##// END OF EJS Templates
phases: introduce phasecache...
Patrick Mezard -
r16657:b6081c2c default
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,3526 +1,3526 b''
1 # mq.py - patch queues for mercurial
1 # mq.py - patch queues for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''manage a stack of patches
8 '''manage a stack of patches
9
9
10 This extension lets you work with a stack of patches in a Mercurial
10 This extension lets you work with a stack of patches in a Mercurial
11 repository. It manages two stacks of patches - all known patches, and
11 repository. It manages two stacks of patches - all known patches, and
12 applied patches (subset of known patches).
12 applied patches (subset of known patches).
13
13
14 Known patches are represented as patch files in the .hg/patches
14 Known patches are represented as patch files in the .hg/patches
15 directory. Applied patches are both patch files and changesets.
15 directory. Applied patches are both patch files and changesets.
16
16
17 Common tasks (use :hg:`help command` for more details)::
17 Common tasks (use :hg:`help command` for more details)::
18
18
19 create new patch qnew
19 create new patch qnew
20 import existing patch qimport
20 import existing patch qimport
21
21
22 print patch series qseries
22 print patch series qseries
23 print applied patches qapplied
23 print applied patches qapplied
24
24
25 add known patch to applied stack qpush
25 add known patch to applied stack qpush
26 remove patch from applied stack qpop
26 remove patch from applied stack qpop
27 refresh contents of top applied patch qrefresh
27 refresh contents of top applied patch qrefresh
28
28
29 By default, mq will automatically use git patches when required to
29 By default, mq will automatically use git patches when required to
30 avoid losing file mode changes, copy records, binary files or empty
30 avoid losing file mode changes, copy records, binary files or empty
31 files creations or deletions. This behaviour can be configured with::
31 files creations or deletions. This behaviour can be configured with::
32
32
33 [mq]
33 [mq]
34 git = auto/keep/yes/no
34 git = auto/keep/yes/no
35
35
36 If set to 'keep', mq will obey the [diff] section configuration while
36 If set to 'keep', mq will obey the [diff] section configuration while
37 preserving existing git patches upon qrefresh. If set to 'yes' or
37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 'no', mq will override the [diff] section and always generate git or
38 'no', mq will override the [diff] section and always generate git or
39 regular patches, possibly losing data in the second case.
39 regular patches, possibly losing data in the second case.
40
40
41 It may be desirable for mq changesets to be kept in the secret phase (see
41 It may be desirable for mq changesets to be kept in the secret phase (see
42 :hg:`help phases`), which can be enabled with the following setting::
42 :hg:`help phases`), which can be enabled with the following setting::
43
43
44 [mq]
44 [mq]
45 secret = True
45 secret = True
46
46
47 You will by default be managing a patch queue named "patches". You can
47 You will by default be managing a patch queue named "patches". You can
48 create other, independent patch queues with the :hg:`qqueue` command.
48 create other, independent patch queues with the :hg:`qqueue` command.
49
49
50 If the working directory contains uncommitted files, qpush, qpop and
50 If the working directory contains uncommitted files, qpush, qpop and
51 qgoto abort immediately. If -f/--force is used, the changes are
51 qgoto abort immediately. If -f/--force is used, the changes are
52 discarded. Setting:
52 discarded. Setting:
53
53
54 [mq]
54 [mq]
55 check = True
55 check = True
56
56
57 make them behave as if -c/--check were passed, and non-conflicting
57 make them behave as if -c/--check were passed, and non-conflicting
58 local changes will be tolerated and preserved. If incompatible options
58 local changes will be tolerated and preserved. If incompatible options
59 such as -f/--force or --exact are passed, this setting is ignored.
59 such as -f/--force or --exact are passed, this setting is ignored.
60 '''
60 '''
61
61
62 from mercurial.i18n import _
62 from mercurial.i18n import _
63 from mercurial.node import bin, hex, short, nullid, nullrev
63 from mercurial.node import bin, hex, short, nullid, nullrev
64 from mercurial.lock import release
64 from mercurial.lock import release
65 from mercurial import commands, cmdutil, hg, scmutil, util, revset
65 from mercurial import commands, cmdutil, hg, scmutil, util, revset
66 from mercurial import repair, extensions, url, error, phases
66 from mercurial import repair, extensions, url, error, phases
67 from mercurial import patch as patchmod
67 from mercurial import patch as patchmod
68 import os, re, errno, shutil
68 import os, re, errno, shutil
69
69
70 commands.norepo += " qclone"
70 commands.norepo += " qclone"
71
71
72 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
72 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
73
73
74 cmdtable = {}
74 cmdtable = {}
75 command = cmdutil.command(cmdtable)
75 command = cmdutil.command(cmdtable)
76
76
77 # Patch names looks like unix-file names.
77 # Patch names looks like unix-file names.
78 # They must be joinable with queue directory and result in the patch path.
78 # They must be joinable with queue directory and result in the patch path.
79 normname = util.normpath
79 normname = util.normpath
80
80
81 class statusentry(object):
81 class statusentry(object):
82 def __init__(self, node, name):
82 def __init__(self, node, name):
83 self.node, self.name = node, name
83 self.node, self.name = node, name
84 def __repr__(self):
84 def __repr__(self):
85 return hex(self.node) + ':' + self.name
85 return hex(self.node) + ':' + self.name
86
86
87 class patchheader(object):
87 class patchheader(object):
88 def __init__(self, pf, plainmode=False):
88 def __init__(self, pf, plainmode=False):
89 def eatdiff(lines):
89 def eatdiff(lines):
90 while lines:
90 while lines:
91 l = lines[-1]
91 l = lines[-1]
92 if (l.startswith("diff -") or
92 if (l.startswith("diff -") or
93 l.startswith("Index:") or
93 l.startswith("Index:") or
94 l.startswith("===========")):
94 l.startswith("===========")):
95 del lines[-1]
95 del lines[-1]
96 else:
96 else:
97 break
97 break
98 def eatempty(lines):
98 def eatempty(lines):
99 while lines:
99 while lines:
100 if not lines[-1].strip():
100 if not lines[-1].strip():
101 del lines[-1]
101 del lines[-1]
102 else:
102 else:
103 break
103 break
104
104
105 message = []
105 message = []
106 comments = []
106 comments = []
107 user = None
107 user = None
108 date = None
108 date = None
109 parent = None
109 parent = None
110 format = None
110 format = None
111 subject = None
111 subject = None
112 branch = None
112 branch = None
113 nodeid = None
113 nodeid = None
114 diffstart = 0
114 diffstart = 0
115
115
116 for line in file(pf):
116 for line in file(pf):
117 line = line.rstrip()
117 line = line.rstrip()
118 if (line.startswith('diff --git')
118 if (line.startswith('diff --git')
119 or (diffstart and line.startswith('+++ '))):
119 or (diffstart and line.startswith('+++ '))):
120 diffstart = 2
120 diffstart = 2
121 break
121 break
122 diffstart = 0 # reset
122 diffstart = 0 # reset
123 if line.startswith("--- "):
123 if line.startswith("--- "):
124 diffstart = 1
124 diffstart = 1
125 continue
125 continue
126 elif format == "hgpatch":
126 elif format == "hgpatch":
127 # parse values when importing the result of an hg export
127 # parse values when importing the result of an hg export
128 if line.startswith("# User "):
128 if line.startswith("# User "):
129 user = line[7:]
129 user = line[7:]
130 elif line.startswith("# Date "):
130 elif line.startswith("# Date "):
131 date = line[7:]
131 date = line[7:]
132 elif line.startswith("# Parent "):
132 elif line.startswith("# Parent "):
133 parent = line[9:].lstrip()
133 parent = line[9:].lstrip()
134 elif line.startswith("# Branch "):
134 elif line.startswith("# Branch "):
135 branch = line[9:]
135 branch = line[9:]
136 elif line.startswith("# Node ID "):
136 elif line.startswith("# Node ID "):
137 nodeid = line[10:]
137 nodeid = line[10:]
138 elif not line.startswith("# ") and line:
138 elif not line.startswith("# ") and line:
139 message.append(line)
139 message.append(line)
140 format = None
140 format = None
141 elif line == '# HG changeset patch':
141 elif line == '# HG changeset patch':
142 message = []
142 message = []
143 format = "hgpatch"
143 format = "hgpatch"
144 elif (format != "tagdone" and (line.startswith("Subject: ") or
144 elif (format != "tagdone" and (line.startswith("Subject: ") or
145 line.startswith("subject: "))):
145 line.startswith("subject: "))):
146 subject = line[9:]
146 subject = line[9:]
147 format = "tag"
147 format = "tag"
148 elif (format != "tagdone" and (line.startswith("From: ") or
148 elif (format != "tagdone" and (line.startswith("From: ") or
149 line.startswith("from: "))):
149 line.startswith("from: "))):
150 user = line[6:]
150 user = line[6:]
151 format = "tag"
151 format = "tag"
152 elif (format != "tagdone" and (line.startswith("Date: ") or
152 elif (format != "tagdone" and (line.startswith("Date: ") or
153 line.startswith("date: "))):
153 line.startswith("date: "))):
154 date = line[6:]
154 date = line[6:]
155 format = "tag"
155 format = "tag"
156 elif format == "tag" and line == "":
156 elif format == "tag" and line == "":
157 # when looking for tags (subject: from: etc) they
157 # when looking for tags (subject: from: etc) they
158 # end once you find a blank line in the source
158 # end once you find a blank line in the source
159 format = "tagdone"
159 format = "tagdone"
160 elif message or line:
160 elif message or line:
161 message.append(line)
161 message.append(line)
162 comments.append(line)
162 comments.append(line)
163
163
164 eatdiff(message)
164 eatdiff(message)
165 eatdiff(comments)
165 eatdiff(comments)
166 # Remember the exact starting line of the patch diffs before consuming
166 # Remember the exact starting line of the patch diffs before consuming
167 # empty lines, for external use by TortoiseHg and others
167 # empty lines, for external use by TortoiseHg and others
168 self.diffstartline = len(comments)
168 self.diffstartline = len(comments)
169 eatempty(message)
169 eatempty(message)
170 eatempty(comments)
170 eatempty(comments)
171
171
172 # make sure message isn't empty
172 # make sure message isn't empty
173 if format and format.startswith("tag") and subject:
173 if format and format.startswith("tag") and subject:
174 message.insert(0, "")
174 message.insert(0, "")
175 message.insert(0, subject)
175 message.insert(0, subject)
176
176
177 self.message = message
177 self.message = message
178 self.comments = comments
178 self.comments = comments
179 self.user = user
179 self.user = user
180 self.date = date
180 self.date = date
181 self.parent = parent
181 self.parent = parent
182 # nodeid and branch are for external use by TortoiseHg and others
182 # nodeid and branch are for external use by TortoiseHg and others
183 self.nodeid = nodeid
183 self.nodeid = nodeid
184 self.branch = branch
184 self.branch = branch
185 self.haspatch = diffstart > 1
185 self.haspatch = diffstart > 1
186 self.plainmode = plainmode
186 self.plainmode = plainmode
187
187
188 def setuser(self, user):
188 def setuser(self, user):
189 if not self.updateheader(['From: ', '# User '], user):
189 if not self.updateheader(['From: ', '# User '], user):
190 try:
190 try:
191 patchheaderat = self.comments.index('# HG changeset patch')
191 patchheaderat = self.comments.index('# HG changeset patch')
192 self.comments.insert(patchheaderat + 1, '# User ' + user)
192 self.comments.insert(patchheaderat + 1, '# User ' + user)
193 except ValueError:
193 except ValueError:
194 if self.plainmode or self._hasheader(['Date: ']):
194 if self.plainmode or self._hasheader(['Date: ']):
195 self.comments = ['From: ' + user] + self.comments
195 self.comments = ['From: ' + user] + self.comments
196 else:
196 else:
197 tmp = ['# HG changeset patch', '# User ' + user, '']
197 tmp = ['# HG changeset patch', '# User ' + user, '']
198 self.comments = tmp + self.comments
198 self.comments = tmp + self.comments
199 self.user = user
199 self.user = user
200
200
201 def setdate(self, date):
201 def setdate(self, date):
202 if not self.updateheader(['Date: ', '# Date '], date):
202 if not self.updateheader(['Date: ', '# Date '], date):
203 try:
203 try:
204 patchheaderat = self.comments.index('# HG changeset patch')
204 patchheaderat = self.comments.index('# HG changeset patch')
205 self.comments.insert(patchheaderat + 1, '# Date ' + date)
205 self.comments.insert(patchheaderat + 1, '# Date ' + date)
206 except ValueError:
206 except ValueError:
207 if self.plainmode or self._hasheader(['From: ']):
207 if self.plainmode or self._hasheader(['From: ']):
208 self.comments = ['Date: ' + date] + self.comments
208 self.comments = ['Date: ' + date] + self.comments
209 else:
209 else:
210 tmp = ['# HG changeset patch', '# Date ' + date, '']
210 tmp = ['# HG changeset patch', '# Date ' + date, '']
211 self.comments = tmp + self.comments
211 self.comments = tmp + self.comments
212 self.date = date
212 self.date = date
213
213
214 def setparent(self, parent):
214 def setparent(self, parent):
215 if not self.updateheader(['# Parent '], parent):
215 if not self.updateheader(['# Parent '], parent):
216 try:
216 try:
217 patchheaderat = self.comments.index('# HG changeset patch')
217 patchheaderat = self.comments.index('# HG changeset patch')
218 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
218 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
219 except ValueError:
219 except ValueError:
220 pass
220 pass
221 self.parent = parent
221 self.parent = parent
222
222
223 def setmessage(self, message):
223 def setmessage(self, message):
224 if self.comments:
224 if self.comments:
225 self._delmsg()
225 self._delmsg()
226 self.message = [message]
226 self.message = [message]
227 self.comments += self.message
227 self.comments += self.message
228
228
229 def updateheader(self, prefixes, new):
229 def updateheader(self, prefixes, new):
230 '''Update all references to a field in the patch header.
230 '''Update all references to a field in the patch header.
231 Return whether the field is present.'''
231 Return whether the field is present.'''
232 res = False
232 res = False
233 for prefix in prefixes:
233 for prefix in prefixes:
234 for i in xrange(len(self.comments)):
234 for i in xrange(len(self.comments)):
235 if self.comments[i].startswith(prefix):
235 if self.comments[i].startswith(prefix):
236 self.comments[i] = prefix + new
236 self.comments[i] = prefix + new
237 res = True
237 res = True
238 break
238 break
239 return res
239 return res
240
240
241 def _hasheader(self, prefixes):
241 def _hasheader(self, prefixes):
242 '''Check if a header starts with any of the given prefixes.'''
242 '''Check if a header starts with any of the given prefixes.'''
243 for prefix in prefixes:
243 for prefix in prefixes:
244 for comment in self.comments:
244 for comment in self.comments:
245 if comment.startswith(prefix):
245 if comment.startswith(prefix):
246 return True
246 return True
247 return False
247 return False
248
248
249 def __str__(self):
249 def __str__(self):
250 if not self.comments:
250 if not self.comments:
251 return ''
251 return ''
252 return '\n'.join(self.comments) + '\n\n'
252 return '\n'.join(self.comments) + '\n\n'
253
253
254 def _delmsg(self):
254 def _delmsg(self):
255 '''Remove existing message, keeping the rest of the comments fields.
255 '''Remove existing message, keeping the rest of the comments fields.
256 If comments contains 'subject: ', message will prepend
256 If comments contains 'subject: ', message will prepend
257 the field and a blank line.'''
257 the field and a blank line.'''
258 if self.message:
258 if self.message:
259 subj = 'subject: ' + self.message[0].lower()
259 subj = 'subject: ' + self.message[0].lower()
260 for i in xrange(len(self.comments)):
260 for i in xrange(len(self.comments)):
261 if subj == self.comments[i].lower():
261 if subj == self.comments[i].lower():
262 del self.comments[i]
262 del self.comments[i]
263 self.message = self.message[2:]
263 self.message = self.message[2:]
264 break
264 break
265 ci = 0
265 ci = 0
266 for mi in self.message:
266 for mi in self.message:
267 while mi != self.comments[ci]:
267 while mi != self.comments[ci]:
268 ci += 1
268 ci += 1
269 del self.comments[ci]
269 del self.comments[ci]
270
270
271 def newcommit(repo, phase, *args, **kwargs):
271 def newcommit(repo, phase, *args, **kwargs):
272 """helper dedicated to ensure a commit respect mq.secret setting
272 """helper dedicated to ensure a commit respect mq.secret setting
273
273
274 It should be used instead of repo.commit inside the mq source for operation
274 It should be used instead of repo.commit inside the mq source for operation
275 creating new changeset.
275 creating new changeset.
276 """
276 """
277 if phase is None:
277 if phase is None:
278 if repo.ui.configbool('mq', 'secret', False):
278 if repo.ui.configbool('mq', 'secret', False):
279 phase = phases.secret
279 phase = phases.secret
280 if phase is not None:
280 if phase is not None:
281 backup = repo.ui.backupconfig('phases', 'new-commit')
281 backup = repo.ui.backupconfig('phases', 'new-commit')
282 # Marking the repository as committing an mq patch can be used
282 # Marking the repository as committing an mq patch can be used
283 # to optimize operations like _branchtags().
283 # to optimize operations like _branchtags().
284 repo._committingpatch = True
284 repo._committingpatch = True
285 try:
285 try:
286 if phase is not None:
286 if phase is not None:
287 repo.ui.setconfig('phases', 'new-commit', phase)
287 repo.ui.setconfig('phases', 'new-commit', phase)
288 return repo.commit(*args, **kwargs)
288 return repo.commit(*args, **kwargs)
289 finally:
289 finally:
290 repo._committingpatch = False
290 repo._committingpatch = False
291 if phase is not None:
291 if phase is not None:
292 repo.ui.restoreconfig(backup)
292 repo.ui.restoreconfig(backup)
293
293
294 class AbortNoCleanup(error.Abort):
294 class AbortNoCleanup(error.Abort):
295 pass
295 pass
296
296
297 class queue(object):
297 class queue(object):
298 def __init__(self, ui, path, patchdir=None):
298 def __init__(self, ui, path, patchdir=None):
299 self.basepath = path
299 self.basepath = path
300 try:
300 try:
301 fh = open(os.path.join(path, 'patches.queue'))
301 fh = open(os.path.join(path, 'patches.queue'))
302 cur = fh.read().rstrip()
302 cur = fh.read().rstrip()
303 fh.close()
303 fh.close()
304 if not cur:
304 if not cur:
305 curpath = os.path.join(path, 'patches')
305 curpath = os.path.join(path, 'patches')
306 else:
306 else:
307 curpath = os.path.join(path, 'patches-' + cur)
307 curpath = os.path.join(path, 'patches-' + cur)
308 except IOError:
308 except IOError:
309 curpath = os.path.join(path, 'patches')
309 curpath = os.path.join(path, 'patches')
310 self.path = patchdir or curpath
310 self.path = patchdir or curpath
311 self.opener = scmutil.opener(self.path)
311 self.opener = scmutil.opener(self.path)
312 self.ui = ui
312 self.ui = ui
313 self.applieddirty = False
313 self.applieddirty = False
314 self.seriesdirty = False
314 self.seriesdirty = False
315 self.added = []
315 self.added = []
316 self.seriespath = "series"
316 self.seriespath = "series"
317 self.statuspath = "status"
317 self.statuspath = "status"
318 self.guardspath = "guards"
318 self.guardspath = "guards"
319 self.activeguards = None
319 self.activeguards = None
320 self.guardsdirty = False
320 self.guardsdirty = False
321 # Handle mq.git as a bool with extended values
321 # Handle mq.git as a bool with extended values
322 try:
322 try:
323 gitmode = ui.configbool('mq', 'git', None)
323 gitmode = ui.configbool('mq', 'git', None)
324 if gitmode is None:
324 if gitmode is None:
325 raise error.ConfigError()
325 raise error.ConfigError()
326 self.gitmode = gitmode and 'yes' or 'no'
326 self.gitmode = gitmode and 'yes' or 'no'
327 except error.ConfigError:
327 except error.ConfigError:
328 self.gitmode = ui.config('mq', 'git', 'auto').lower()
328 self.gitmode = ui.config('mq', 'git', 'auto').lower()
329 self.plainmode = ui.configbool('mq', 'plain', False)
329 self.plainmode = ui.configbool('mq', 'plain', False)
330
330
331 @util.propertycache
331 @util.propertycache
332 def applied(self):
332 def applied(self):
333 def parselines(lines):
333 def parselines(lines):
334 for l in lines:
334 for l in lines:
335 entry = l.split(':', 1)
335 entry = l.split(':', 1)
336 if len(entry) > 1:
336 if len(entry) > 1:
337 n, name = entry
337 n, name = entry
338 yield statusentry(bin(n), name)
338 yield statusentry(bin(n), name)
339 elif l.strip():
339 elif l.strip():
340 self.ui.warn(_('malformated mq status line: %s\n') % entry)
340 self.ui.warn(_('malformated mq status line: %s\n') % entry)
341 # else we ignore empty lines
341 # else we ignore empty lines
342 try:
342 try:
343 lines = self.opener.read(self.statuspath).splitlines()
343 lines = self.opener.read(self.statuspath).splitlines()
344 return list(parselines(lines))
344 return list(parselines(lines))
345 except IOError, e:
345 except IOError, e:
346 if e.errno == errno.ENOENT:
346 if e.errno == errno.ENOENT:
347 return []
347 return []
348 raise
348 raise
349
349
350 @util.propertycache
350 @util.propertycache
351 def fullseries(self):
351 def fullseries(self):
352 try:
352 try:
353 return self.opener.read(self.seriespath).splitlines()
353 return self.opener.read(self.seriespath).splitlines()
354 except IOError, e:
354 except IOError, e:
355 if e.errno == errno.ENOENT:
355 if e.errno == errno.ENOENT:
356 return []
356 return []
357 raise
357 raise
358
358
359 @util.propertycache
359 @util.propertycache
360 def series(self):
360 def series(self):
361 self.parseseries()
361 self.parseseries()
362 return self.series
362 return self.series
363
363
364 @util.propertycache
364 @util.propertycache
365 def seriesguards(self):
365 def seriesguards(self):
366 self.parseseries()
366 self.parseseries()
367 return self.seriesguards
367 return self.seriesguards
368
368
369 def invalidate(self):
369 def invalidate(self):
370 for a in 'applied fullseries series seriesguards'.split():
370 for a in 'applied fullseries series seriesguards'.split():
371 if a in self.__dict__:
371 if a in self.__dict__:
372 delattr(self, a)
372 delattr(self, a)
373 self.applieddirty = False
373 self.applieddirty = False
374 self.seriesdirty = False
374 self.seriesdirty = False
375 self.guardsdirty = False
375 self.guardsdirty = False
376 self.activeguards = None
376 self.activeguards = None
377
377
378 def diffopts(self, opts={}, patchfn=None):
378 def diffopts(self, opts={}, patchfn=None):
379 diffopts = patchmod.diffopts(self.ui, opts)
379 diffopts = patchmod.diffopts(self.ui, opts)
380 if self.gitmode == 'auto':
380 if self.gitmode == 'auto':
381 diffopts.upgrade = True
381 diffopts.upgrade = True
382 elif self.gitmode == 'keep':
382 elif self.gitmode == 'keep':
383 pass
383 pass
384 elif self.gitmode in ('yes', 'no'):
384 elif self.gitmode in ('yes', 'no'):
385 diffopts.git = self.gitmode == 'yes'
385 diffopts.git = self.gitmode == 'yes'
386 else:
386 else:
387 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
387 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
388 ' got %s') % self.gitmode)
388 ' got %s') % self.gitmode)
389 if patchfn:
389 if patchfn:
390 diffopts = self.patchopts(diffopts, patchfn)
390 diffopts = self.patchopts(diffopts, patchfn)
391 return diffopts
391 return diffopts
392
392
393 def patchopts(self, diffopts, *patches):
393 def patchopts(self, diffopts, *patches):
394 """Return a copy of input diff options with git set to true if
394 """Return a copy of input diff options with git set to true if
395 referenced patch is a git patch and should be preserved as such.
395 referenced patch is a git patch and should be preserved as such.
396 """
396 """
397 diffopts = diffopts.copy()
397 diffopts = diffopts.copy()
398 if not diffopts.git and self.gitmode == 'keep':
398 if not diffopts.git and self.gitmode == 'keep':
399 for patchfn in patches:
399 for patchfn in patches:
400 patchf = self.opener(patchfn, 'r')
400 patchf = self.opener(patchfn, 'r')
401 # if the patch was a git patch, refresh it as a git patch
401 # if the patch was a git patch, refresh it as a git patch
402 for line in patchf:
402 for line in patchf:
403 if line.startswith('diff --git'):
403 if line.startswith('diff --git'):
404 diffopts.git = True
404 diffopts.git = True
405 break
405 break
406 patchf.close()
406 patchf.close()
407 return diffopts
407 return diffopts
408
408
409 def join(self, *p):
409 def join(self, *p):
410 return os.path.join(self.path, *p)
410 return os.path.join(self.path, *p)
411
411
412 def findseries(self, patch):
412 def findseries(self, patch):
413 def matchpatch(l):
413 def matchpatch(l):
414 l = l.split('#', 1)[0]
414 l = l.split('#', 1)[0]
415 return l.strip() == patch
415 return l.strip() == patch
416 for index, l in enumerate(self.fullseries):
416 for index, l in enumerate(self.fullseries):
417 if matchpatch(l):
417 if matchpatch(l):
418 return index
418 return index
419 return None
419 return None
420
420
421 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
421 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
422
422
423 def parseseries(self):
423 def parseseries(self):
424 self.series = []
424 self.series = []
425 self.seriesguards = []
425 self.seriesguards = []
426 for l in self.fullseries:
426 for l in self.fullseries:
427 h = l.find('#')
427 h = l.find('#')
428 if h == -1:
428 if h == -1:
429 patch = l
429 patch = l
430 comment = ''
430 comment = ''
431 elif h == 0:
431 elif h == 0:
432 continue
432 continue
433 else:
433 else:
434 patch = l[:h]
434 patch = l[:h]
435 comment = l[h:]
435 comment = l[h:]
436 patch = patch.strip()
436 patch = patch.strip()
437 if patch:
437 if patch:
438 if patch in self.series:
438 if patch in self.series:
439 raise util.Abort(_('%s appears more than once in %s') %
439 raise util.Abort(_('%s appears more than once in %s') %
440 (patch, self.join(self.seriespath)))
440 (patch, self.join(self.seriespath)))
441 self.series.append(patch)
441 self.series.append(patch)
442 self.seriesguards.append(self.guard_re.findall(comment))
442 self.seriesguards.append(self.guard_re.findall(comment))
443
443
444 def checkguard(self, guard):
444 def checkguard(self, guard):
445 if not guard:
445 if not guard:
446 return _('guard cannot be an empty string')
446 return _('guard cannot be an empty string')
447 bad_chars = '# \t\r\n\f'
447 bad_chars = '# \t\r\n\f'
448 first = guard[0]
448 first = guard[0]
449 if first in '-+':
449 if first in '-+':
450 return (_('guard %r starts with invalid character: %r') %
450 return (_('guard %r starts with invalid character: %r') %
451 (guard, first))
451 (guard, first))
452 for c in bad_chars:
452 for c in bad_chars:
453 if c in guard:
453 if c in guard:
454 return _('invalid character in guard %r: %r') % (guard, c)
454 return _('invalid character in guard %r: %r') % (guard, c)
455
455
456 def setactive(self, guards):
456 def setactive(self, guards):
457 for guard in guards:
457 for guard in guards:
458 bad = self.checkguard(guard)
458 bad = self.checkguard(guard)
459 if bad:
459 if bad:
460 raise util.Abort(bad)
460 raise util.Abort(bad)
461 guards = sorted(set(guards))
461 guards = sorted(set(guards))
462 self.ui.debug('active guards: %s\n' % ' '.join(guards))
462 self.ui.debug('active guards: %s\n' % ' '.join(guards))
463 self.activeguards = guards
463 self.activeguards = guards
464 self.guardsdirty = True
464 self.guardsdirty = True
465
465
466 def active(self):
466 def active(self):
467 if self.activeguards is None:
467 if self.activeguards is None:
468 self.activeguards = []
468 self.activeguards = []
469 try:
469 try:
470 guards = self.opener.read(self.guardspath).split()
470 guards = self.opener.read(self.guardspath).split()
471 except IOError, err:
471 except IOError, err:
472 if err.errno != errno.ENOENT:
472 if err.errno != errno.ENOENT:
473 raise
473 raise
474 guards = []
474 guards = []
475 for i, guard in enumerate(guards):
475 for i, guard in enumerate(guards):
476 bad = self.checkguard(guard)
476 bad = self.checkguard(guard)
477 if bad:
477 if bad:
478 self.ui.warn('%s:%d: %s\n' %
478 self.ui.warn('%s:%d: %s\n' %
479 (self.join(self.guardspath), i + 1, bad))
479 (self.join(self.guardspath), i + 1, bad))
480 else:
480 else:
481 self.activeguards.append(guard)
481 self.activeguards.append(guard)
482 return self.activeguards
482 return self.activeguards
483
483
484 def setguards(self, idx, guards):
484 def setguards(self, idx, guards):
485 for g in guards:
485 for g in guards:
486 if len(g) < 2:
486 if len(g) < 2:
487 raise util.Abort(_('guard %r too short') % g)
487 raise util.Abort(_('guard %r too short') % g)
488 if g[0] not in '-+':
488 if g[0] not in '-+':
489 raise util.Abort(_('guard %r starts with invalid char') % g)
489 raise util.Abort(_('guard %r starts with invalid char') % g)
490 bad = self.checkguard(g[1:])
490 bad = self.checkguard(g[1:])
491 if bad:
491 if bad:
492 raise util.Abort(bad)
492 raise util.Abort(bad)
493 drop = self.guard_re.sub('', self.fullseries[idx])
493 drop = self.guard_re.sub('', self.fullseries[idx])
494 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
494 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
495 self.parseseries()
495 self.parseseries()
496 self.seriesdirty = True
496 self.seriesdirty = True
497
497
498 def pushable(self, idx):
498 def pushable(self, idx):
499 if isinstance(idx, str):
499 if isinstance(idx, str):
500 idx = self.series.index(idx)
500 idx = self.series.index(idx)
501 patchguards = self.seriesguards[idx]
501 patchguards = self.seriesguards[idx]
502 if not patchguards:
502 if not patchguards:
503 return True, None
503 return True, None
504 guards = self.active()
504 guards = self.active()
505 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
505 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
506 if exactneg:
506 if exactneg:
507 return False, repr(exactneg[0])
507 return False, repr(exactneg[0])
508 pos = [g for g in patchguards if g[0] == '+']
508 pos = [g for g in patchguards if g[0] == '+']
509 exactpos = [g for g in pos if g[1:] in guards]
509 exactpos = [g for g in pos if g[1:] in guards]
510 if pos:
510 if pos:
511 if exactpos:
511 if exactpos:
512 return True, repr(exactpos[0])
512 return True, repr(exactpos[0])
513 return False, ' '.join(map(repr, pos))
513 return False, ' '.join(map(repr, pos))
514 return True, ''
514 return True, ''
515
515
516 def explainpushable(self, idx, all_patches=False):
516 def explainpushable(self, idx, all_patches=False):
517 write = all_patches and self.ui.write or self.ui.warn
517 write = all_patches and self.ui.write or self.ui.warn
518 if all_patches or self.ui.verbose:
518 if all_patches or self.ui.verbose:
519 if isinstance(idx, str):
519 if isinstance(idx, str):
520 idx = self.series.index(idx)
520 idx = self.series.index(idx)
521 pushable, why = self.pushable(idx)
521 pushable, why = self.pushable(idx)
522 if all_patches and pushable:
522 if all_patches and pushable:
523 if why is None:
523 if why is None:
524 write(_('allowing %s - no guards in effect\n') %
524 write(_('allowing %s - no guards in effect\n') %
525 self.series[idx])
525 self.series[idx])
526 else:
526 else:
527 if not why:
527 if not why:
528 write(_('allowing %s - no matching negative guards\n') %
528 write(_('allowing %s - no matching negative guards\n') %
529 self.series[idx])
529 self.series[idx])
530 else:
530 else:
531 write(_('allowing %s - guarded by %s\n') %
531 write(_('allowing %s - guarded by %s\n') %
532 (self.series[idx], why))
532 (self.series[idx], why))
533 if not pushable:
533 if not pushable:
534 if why:
534 if why:
535 write(_('skipping %s - guarded by %s\n') %
535 write(_('skipping %s - guarded by %s\n') %
536 (self.series[idx], why))
536 (self.series[idx], why))
537 else:
537 else:
538 write(_('skipping %s - no matching guards\n') %
538 write(_('skipping %s - no matching guards\n') %
539 self.series[idx])
539 self.series[idx])
540
540
541 def savedirty(self):
541 def savedirty(self):
542 def writelist(items, path):
542 def writelist(items, path):
543 fp = self.opener(path, 'w')
543 fp = self.opener(path, 'w')
544 for i in items:
544 for i in items:
545 fp.write("%s\n" % i)
545 fp.write("%s\n" % i)
546 fp.close()
546 fp.close()
547 if self.applieddirty:
547 if self.applieddirty:
548 writelist(map(str, self.applied), self.statuspath)
548 writelist(map(str, self.applied), self.statuspath)
549 self.applieddirty = False
549 self.applieddirty = False
550 if self.seriesdirty:
550 if self.seriesdirty:
551 writelist(self.fullseries, self.seriespath)
551 writelist(self.fullseries, self.seriespath)
552 self.seriesdirty = False
552 self.seriesdirty = False
553 if self.guardsdirty:
553 if self.guardsdirty:
554 writelist(self.activeguards, self.guardspath)
554 writelist(self.activeguards, self.guardspath)
555 self.guardsdirty = False
555 self.guardsdirty = False
556 if self.added:
556 if self.added:
557 qrepo = self.qrepo()
557 qrepo = self.qrepo()
558 if qrepo:
558 if qrepo:
559 qrepo[None].add(f for f in self.added if f not in qrepo[None])
559 qrepo[None].add(f for f in self.added if f not in qrepo[None])
560 self.added = []
560 self.added = []
561
561
562 def removeundo(self, repo):
562 def removeundo(self, repo):
563 undo = repo.sjoin('undo')
563 undo = repo.sjoin('undo')
564 if not os.path.exists(undo):
564 if not os.path.exists(undo):
565 return
565 return
566 try:
566 try:
567 os.unlink(undo)
567 os.unlink(undo)
568 except OSError, inst:
568 except OSError, inst:
569 self.ui.warn(_('error removing undo: %s\n') % str(inst))
569 self.ui.warn(_('error removing undo: %s\n') % str(inst))
570
570
571 def backup(self, repo, files, copy=False):
571 def backup(self, repo, files, copy=False):
572 # backup local changes in --force case
572 # backup local changes in --force case
573 for f in sorted(files):
573 for f in sorted(files):
574 absf = repo.wjoin(f)
574 absf = repo.wjoin(f)
575 if os.path.lexists(absf):
575 if os.path.lexists(absf):
576 self.ui.note(_('saving current version of %s as %s\n') %
576 self.ui.note(_('saving current version of %s as %s\n') %
577 (f, f + '.orig'))
577 (f, f + '.orig'))
578 if copy:
578 if copy:
579 util.copyfile(absf, absf + '.orig')
579 util.copyfile(absf, absf + '.orig')
580 else:
580 else:
581 util.rename(absf, absf + '.orig')
581 util.rename(absf, absf + '.orig')
582
582
583 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
583 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
584 fp=None, changes=None, opts={}):
584 fp=None, changes=None, opts={}):
585 stat = opts.get('stat')
585 stat = opts.get('stat')
586 m = scmutil.match(repo[node1], files, opts)
586 m = scmutil.match(repo[node1], files, opts)
587 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
587 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
588 changes, stat, fp)
588 changes, stat, fp)
589
589
590 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
590 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
591 # first try just applying the patch
591 # first try just applying the patch
592 (err, n) = self.apply(repo, [patch], update_status=False,
592 (err, n) = self.apply(repo, [patch], update_status=False,
593 strict=True, merge=rev)
593 strict=True, merge=rev)
594
594
595 if err == 0:
595 if err == 0:
596 return (err, n)
596 return (err, n)
597
597
598 if n is None:
598 if n is None:
599 raise util.Abort(_("apply failed for patch %s") % patch)
599 raise util.Abort(_("apply failed for patch %s") % patch)
600
600
601 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
601 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
602
602
603 # apply failed, strip away that rev and merge.
603 # apply failed, strip away that rev and merge.
604 hg.clean(repo, head)
604 hg.clean(repo, head)
605 self.strip(repo, [n], update=False, backup='strip')
605 self.strip(repo, [n], update=False, backup='strip')
606
606
607 ctx = repo[rev]
607 ctx = repo[rev]
608 ret = hg.merge(repo, rev)
608 ret = hg.merge(repo, rev)
609 if ret:
609 if ret:
610 raise util.Abort(_("update returned %d") % ret)
610 raise util.Abort(_("update returned %d") % ret)
611 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
611 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
612 if n is None:
612 if n is None:
613 raise util.Abort(_("repo commit failed"))
613 raise util.Abort(_("repo commit failed"))
614 try:
614 try:
615 ph = patchheader(mergeq.join(patch), self.plainmode)
615 ph = patchheader(mergeq.join(patch), self.plainmode)
616 except:
616 except:
617 raise util.Abort(_("unable to read %s") % patch)
617 raise util.Abort(_("unable to read %s") % patch)
618
618
619 diffopts = self.patchopts(diffopts, patch)
619 diffopts = self.patchopts(diffopts, patch)
620 patchf = self.opener(patch, "w")
620 patchf = self.opener(patch, "w")
621 comments = str(ph)
621 comments = str(ph)
622 if comments:
622 if comments:
623 patchf.write(comments)
623 patchf.write(comments)
624 self.printdiff(repo, diffopts, head, n, fp=patchf)
624 self.printdiff(repo, diffopts, head, n, fp=patchf)
625 patchf.close()
625 patchf.close()
626 self.removeundo(repo)
626 self.removeundo(repo)
627 return (0, n)
627 return (0, n)
628
628
629 def qparents(self, repo, rev=None):
629 def qparents(self, repo, rev=None):
630 if rev is None:
630 if rev is None:
631 (p1, p2) = repo.dirstate.parents()
631 (p1, p2) = repo.dirstate.parents()
632 if p2 == nullid:
632 if p2 == nullid:
633 return p1
633 return p1
634 if not self.applied:
634 if not self.applied:
635 return None
635 return None
636 return self.applied[-1].node
636 return self.applied[-1].node
637 p1, p2 = repo.changelog.parents(rev)
637 p1, p2 = repo.changelog.parents(rev)
638 if p2 != nullid and p2 in [x.node for x in self.applied]:
638 if p2 != nullid and p2 in [x.node for x in self.applied]:
639 return p2
639 return p2
640 return p1
640 return p1
641
641
642 def mergepatch(self, repo, mergeq, series, diffopts):
642 def mergepatch(self, repo, mergeq, series, diffopts):
643 if not self.applied:
643 if not self.applied:
644 # each of the patches merged in will have two parents. This
644 # each of the patches merged in will have two parents. This
645 # can confuse the qrefresh, qdiff, and strip code because it
645 # can confuse the qrefresh, qdiff, and strip code because it
646 # needs to know which parent is actually in the patch queue.
646 # needs to know which parent is actually in the patch queue.
647 # so, we insert a merge marker with only one parent. This way
647 # so, we insert a merge marker with only one parent. This way
648 # the first patch in the queue is never a merge patch
648 # the first patch in the queue is never a merge patch
649 #
649 #
650 pname = ".hg.patches.merge.marker"
650 pname = ".hg.patches.merge.marker"
651 n = newcommit(repo, None, '[mq]: merge marker', force=True)
651 n = newcommit(repo, None, '[mq]: merge marker', force=True)
652 self.removeundo(repo)
652 self.removeundo(repo)
653 self.applied.append(statusentry(n, pname))
653 self.applied.append(statusentry(n, pname))
654 self.applieddirty = True
654 self.applieddirty = True
655
655
656 head = self.qparents(repo)
656 head = self.qparents(repo)
657
657
658 for patch in series:
658 for patch in series:
659 patch = mergeq.lookup(patch, strict=True)
659 patch = mergeq.lookup(patch, strict=True)
660 if not patch:
660 if not patch:
661 self.ui.warn(_("patch %s does not exist\n") % patch)
661 self.ui.warn(_("patch %s does not exist\n") % patch)
662 return (1, None)
662 return (1, None)
663 pushable, reason = self.pushable(patch)
663 pushable, reason = self.pushable(patch)
664 if not pushable:
664 if not pushable:
665 self.explainpushable(patch, all_patches=True)
665 self.explainpushable(patch, all_patches=True)
666 continue
666 continue
667 info = mergeq.isapplied(patch)
667 info = mergeq.isapplied(patch)
668 if not info:
668 if not info:
669 self.ui.warn(_("patch %s is not applied\n") % patch)
669 self.ui.warn(_("patch %s is not applied\n") % patch)
670 return (1, None)
670 return (1, None)
671 rev = info[1]
671 rev = info[1]
672 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
672 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
673 if head:
673 if head:
674 self.applied.append(statusentry(head, patch))
674 self.applied.append(statusentry(head, patch))
675 self.applieddirty = True
675 self.applieddirty = True
676 if err:
676 if err:
677 return (err, head)
677 return (err, head)
678 self.savedirty()
678 self.savedirty()
679 return (0, head)
679 return (0, head)
680
680
681 def patch(self, repo, patchfile):
681 def patch(self, repo, patchfile):
682 '''Apply patchfile to the working directory.
682 '''Apply patchfile to the working directory.
683 patchfile: name of patch file'''
683 patchfile: name of patch file'''
684 files = set()
684 files = set()
685 try:
685 try:
686 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
686 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
687 files=files, eolmode=None)
687 files=files, eolmode=None)
688 return (True, list(files), fuzz)
688 return (True, list(files), fuzz)
689 except Exception, inst:
689 except Exception, inst:
690 self.ui.note(str(inst) + '\n')
690 self.ui.note(str(inst) + '\n')
691 if not self.ui.verbose:
691 if not self.ui.verbose:
692 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
692 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
693 self.ui.traceback()
693 self.ui.traceback()
694 return (False, list(files), False)
694 return (False, list(files), False)
695
695
696 def apply(self, repo, series, list=False, update_status=True,
696 def apply(self, repo, series, list=False, update_status=True,
697 strict=False, patchdir=None, merge=None, all_files=None,
697 strict=False, patchdir=None, merge=None, all_files=None,
698 tobackup=None, check=False):
698 tobackup=None, check=False):
699 wlock = lock = tr = None
699 wlock = lock = tr = None
700 try:
700 try:
701 wlock = repo.wlock()
701 wlock = repo.wlock()
702 lock = repo.lock()
702 lock = repo.lock()
703 tr = repo.transaction("qpush")
703 tr = repo.transaction("qpush")
704 try:
704 try:
705 ret = self._apply(repo, series, list, update_status,
705 ret = self._apply(repo, series, list, update_status,
706 strict, patchdir, merge, all_files=all_files,
706 strict, patchdir, merge, all_files=all_files,
707 tobackup=tobackup, check=check)
707 tobackup=tobackup, check=check)
708 tr.close()
708 tr.close()
709 self.savedirty()
709 self.savedirty()
710 return ret
710 return ret
711 except AbortNoCleanup:
711 except AbortNoCleanup:
712 tr.close()
712 tr.close()
713 self.savedirty()
713 self.savedirty()
714 return 2, repo.dirstate.p1()
714 return 2, repo.dirstate.p1()
715 except:
715 except:
716 try:
716 try:
717 tr.abort()
717 tr.abort()
718 finally:
718 finally:
719 repo.invalidate()
719 repo.invalidate()
720 repo.dirstate.invalidate()
720 repo.dirstate.invalidate()
721 self.invalidate()
721 self.invalidate()
722 raise
722 raise
723 finally:
723 finally:
724 release(tr, lock, wlock)
724 release(tr, lock, wlock)
725 self.removeundo(repo)
725 self.removeundo(repo)
726
726
727 def _apply(self, repo, series, list=False, update_status=True,
727 def _apply(self, repo, series, list=False, update_status=True,
728 strict=False, patchdir=None, merge=None, all_files=None,
728 strict=False, patchdir=None, merge=None, all_files=None,
729 tobackup=None, check=False):
729 tobackup=None, check=False):
730 """returns (error, hash)
730 """returns (error, hash)
731
731
732 error = 1 for unable to read, 2 for patch failed, 3 for patch
732 error = 1 for unable to read, 2 for patch failed, 3 for patch
733 fuzz. tobackup is None or a set of files to backup before they
733 fuzz. tobackup is None or a set of files to backup before they
734 are modified by a patch.
734 are modified by a patch.
735 """
735 """
736 # TODO unify with commands.py
736 # TODO unify with commands.py
737 if not patchdir:
737 if not patchdir:
738 patchdir = self.path
738 patchdir = self.path
739 err = 0
739 err = 0
740 n = None
740 n = None
741 for patchname in series:
741 for patchname in series:
742 pushable, reason = self.pushable(patchname)
742 pushable, reason = self.pushable(patchname)
743 if not pushable:
743 if not pushable:
744 self.explainpushable(patchname, all_patches=True)
744 self.explainpushable(patchname, all_patches=True)
745 continue
745 continue
746 self.ui.status(_("applying %s\n") % patchname)
746 self.ui.status(_("applying %s\n") % patchname)
747 pf = os.path.join(patchdir, patchname)
747 pf = os.path.join(patchdir, patchname)
748
748
749 try:
749 try:
750 ph = patchheader(self.join(patchname), self.plainmode)
750 ph = patchheader(self.join(patchname), self.plainmode)
751 except IOError:
751 except IOError:
752 self.ui.warn(_("unable to read %s\n") % patchname)
752 self.ui.warn(_("unable to read %s\n") % patchname)
753 err = 1
753 err = 1
754 break
754 break
755
755
756 message = ph.message
756 message = ph.message
757 if not message:
757 if not message:
758 # The commit message should not be translated
758 # The commit message should not be translated
759 message = "imported patch %s\n" % patchname
759 message = "imported patch %s\n" % patchname
760 else:
760 else:
761 if list:
761 if list:
762 # The commit message should not be translated
762 # The commit message should not be translated
763 message.append("\nimported patch %s" % patchname)
763 message.append("\nimported patch %s" % patchname)
764 message = '\n'.join(message)
764 message = '\n'.join(message)
765
765
766 if ph.haspatch:
766 if ph.haspatch:
767 if tobackup:
767 if tobackup:
768 touched = patchmod.changedfiles(self.ui, repo, pf)
768 touched = patchmod.changedfiles(self.ui, repo, pf)
769 touched = set(touched) & tobackup
769 touched = set(touched) & tobackup
770 if touched and check:
770 if touched and check:
771 raise AbortNoCleanup(
771 raise AbortNoCleanup(
772 _("local changes found, refresh first"))
772 _("local changes found, refresh first"))
773 self.backup(repo, touched, copy=True)
773 self.backup(repo, touched, copy=True)
774 tobackup = tobackup - touched
774 tobackup = tobackup - touched
775 (patcherr, files, fuzz) = self.patch(repo, pf)
775 (patcherr, files, fuzz) = self.patch(repo, pf)
776 if all_files is not None:
776 if all_files is not None:
777 all_files.update(files)
777 all_files.update(files)
778 patcherr = not patcherr
778 patcherr = not patcherr
779 else:
779 else:
780 self.ui.warn(_("patch %s is empty\n") % patchname)
780 self.ui.warn(_("patch %s is empty\n") % patchname)
781 patcherr, files, fuzz = 0, [], 0
781 patcherr, files, fuzz = 0, [], 0
782
782
783 if merge and files:
783 if merge and files:
784 # Mark as removed/merged and update dirstate parent info
784 # Mark as removed/merged and update dirstate parent info
785 removed = []
785 removed = []
786 merged = []
786 merged = []
787 for f in files:
787 for f in files:
788 if os.path.lexists(repo.wjoin(f)):
788 if os.path.lexists(repo.wjoin(f)):
789 merged.append(f)
789 merged.append(f)
790 else:
790 else:
791 removed.append(f)
791 removed.append(f)
792 for f in removed:
792 for f in removed:
793 repo.dirstate.remove(f)
793 repo.dirstate.remove(f)
794 for f in merged:
794 for f in merged:
795 repo.dirstate.merge(f)
795 repo.dirstate.merge(f)
796 p1, p2 = repo.dirstate.parents()
796 p1, p2 = repo.dirstate.parents()
797 repo.setparents(p1, merge)
797 repo.setparents(p1, merge)
798
798
799 match = scmutil.matchfiles(repo, files or [])
799 match = scmutil.matchfiles(repo, files or [])
800 oldtip = repo['tip']
800 oldtip = repo['tip']
801 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
801 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
802 force=True)
802 force=True)
803 if repo['tip'] == oldtip:
803 if repo['tip'] == oldtip:
804 raise util.Abort(_("qpush exactly duplicates child changeset"))
804 raise util.Abort(_("qpush exactly duplicates child changeset"))
805 if n is None:
805 if n is None:
806 raise util.Abort(_("repository commit failed"))
806 raise util.Abort(_("repository commit failed"))
807
807
808 if update_status:
808 if update_status:
809 self.applied.append(statusentry(n, patchname))
809 self.applied.append(statusentry(n, patchname))
810
810
811 if patcherr:
811 if patcherr:
812 self.ui.warn(_("patch failed, rejects left in working dir\n"))
812 self.ui.warn(_("patch failed, rejects left in working dir\n"))
813 err = 2
813 err = 2
814 break
814 break
815
815
816 if fuzz and strict:
816 if fuzz and strict:
817 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
817 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
818 err = 3
818 err = 3
819 break
819 break
820 return (err, n)
820 return (err, n)
821
821
822 def _cleanup(self, patches, numrevs, keep=False):
822 def _cleanup(self, patches, numrevs, keep=False):
823 if not keep:
823 if not keep:
824 r = self.qrepo()
824 r = self.qrepo()
825 if r:
825 if r:
826 r[None].forget(patches)
826 r[None].forget(patches)
827 for p in patches:
827 for p in patches:
828 os.unlink(self.join(p))
828 os.unlink(self.join(p))
829
829
830 qfinished = []
830 qfinished = []
831 if numrevs:
831 if numrevs:
832 qfinished = self.applied[:numrevs]
832 qfinished = self.applied[:numrevs]
833 del self.applied[:numrevs]
833 del self.applied[:numrevs]
834 self.applieddirty = True
834 self.applieddirty = True
835
835
836 unknown = []
836 unknown = []
837
837
838 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
838 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
839 reverse=True):
839 reverse=True):
840 if i is not None:
840 if i is not None:
841 del self.fullseries[i]
841 del self.fullseries[i]
842 else:
842 else:
843 unknown.append(p)
843 unknown.append(p)
844
844
845 if unknown:
845 if unknown:
846 if numrevs:
846 if numrevs:
847 rev = dict((entry.name, entry.node) for entry in qfinished)
847 rev = dict((entry.name, entry.node) for entry in qfinished)
848 for p in unknown:
848 for p in unknown:
849 msg = _('revision %s refers to unknown patches: %s\n')
849 msg = _('revision %s refers to unknown patches: %s\n')
850 self.ui.warn(msg % (short(rev[p]), p))
850 self.ui.warn(msg % (short(rev[p]), p))
851 else:
851 else:
852 msg = _('unknown patches: %s\n')
852 msg = _('unknown patches: %s\n')
853 raise util.Abort(''.join(msg % p for p in unknown))
853 raise util.Abort(''.join(msg % p for p in unknown))
854
854
855 self.parseseries()
855 self.parseseries()
856 self.seriesdirty = True
856 self.seriesdirty = True
857 return [entry.node for entry in qfinished]
857 return [entry.node for entry in qfinished]
858
858
859 def _revpatches(self, repo, revs):
859 def _revpatches(self, repo, revs):
860 firstrev = repo[self.applied[0].node].rev()
860 firstrev = repo[self.applied[0].node].rev()
861 patches = []
861 patches = []
862 for i, rev in enumerate(revs):
862 for i, rev in enumerate(revs):
863
863
864 if rev < firstrev:
864 if rev < firstrev:
865 raise util.Abort(_('revision %d is not managed') % rev)
865 raise util.Abort(_('revision %d is not managed') % rev)
866
866
867 ctx = repo[rev]
867 ctx = repo[rev]
868 base = self.applied[i].node
868 base = self.applied[i].node
869 if ctx.node() != base:
869 if ctx.node() != base:
870 msg = _('cannot delete revision %d above applied patches')
870 msg = _('cannot delete revision %d above applied patches')
871 raise util.Abort(msg % rev)
871 raise util.Abort(msg % rev)
872
872
873 patch = self.applied[i].name
873 patch = self.applied[i].name
874 for fmt in ('[mq]: %s', 'imported patch %s'):
874 for fmt in ('[mq]: %s', 'imported patch %s'):
875 if ctx.description() == fmt % patch:
875 if ctx.description() == fmt % patch:
876 msg = _('patch %s finalized without changeset message\n')
876 msg = _('patch %s finalized without changeset message\n')
877 repo.ui.status(msg % patch)
877 repo.ui.status(msg % patch)
878 break
878 break
879
879
880 patches.append(patch)
880 patches.append(patch)
881 return patches
881 return patches
882
882
883 def finish(self, repo, revs):
883 def finish(self, repo, revs):
884 # Manually trigger phase computation to ensure phasedefaults is
884 # Manually trigger phase computation to ensure phasedefaults is
885 # executed before we remove the patches.
885 # executed before we remove the patches.
886 repo._phaserev
886 repo._phasecache
887 patches = self._revpatches(repo, sorted(revs))
887 patches = self._revpatches(repo, sorted(revs))
888 qfinished = self._cleanup(patches, len(patches))
888 qfinished = self._cleanup(patches, len(patches))
889 if qfinished and repo.ui.configbool('mq', 'secret', False):
889 if qfinished and repo.ui.configbool('mq', 'secret', False):
890 # only use this logic when the secret option is added
890 # only use this logic when the secret option is added
891 oldqbase = repo[qfinished[0]]
891 oldqbase = repo[qfinished[0]]
892 tphase = repo.ui.config('phases', 'new-commit', phases.draft)
892 tphase = repo.ui.config('phases', 'new-commit', phases.draft)
893 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
893 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
894 phases.advanceboundary(repo, tphase, qfinished)
894 phases.advanceboundary(repo, tphase, qfinished)
895
895
896 def delete(self, repo, patches, opts):
896 def delete(self, repo, patches, opts):
897 if not patches and not opts.get('rev'):
897 if not patches and not opts.get('rev'):
898 raise util.Abort(_('qdelete requires at least one revision or '
898 raise util.Abort(_('qdelete requires at least one revision or '
899 'patch name'))
899 'patch name'))
900
900
901 realpatches = []
901 realpatches = []
902 for patch in patches:
902 for patch in patches:
903 patch = self.lookup(patch, strict=True)
903 patch = self.lookup(patch, strict=True)
904 info = self.isapplied(patch)
904 info = self.isapplied(patch)
905 if info:
905 if info:
906 raise util.Abort(_("cannot delete applied patch %s") % patch)
906 raise util.Abort(_("cannot delete applied patch %s") % patch)
907 if patch not in self.series:
907 if patch not in self.series:
908 raise util.Abort(_("patch %s not in series file") % patch)
908 raise util.Abort(_("patch %s not in series file") % patch)
909 if patch not in realpatches:
909 if patch not in realpatches:
910 realpatches.append(patch)
910 realpatches.append(patch)
911
911
912 numrevs = 0
912 numrevs = 0
913 if opts.get('rev'):
913 if opts.get('rev'):
914 if not self.applied:
914 if not self.applied:
915 raise util.Abort(_('no patches applied'))
915 raise util.Abort(_('no patches applied'))
916 revs = scmutil.revrange(repo, opts.get('rev'))
916 revs = scmutil.revrange(repo, opts.get('rev'))
917 if len(revs) > 1 and revs[0] > revs[1]:
917 if len(revs) > 1 and revs[0] > revs[1]:
918 revs.reverse()
918 revs.reverse()
919 revpatches = self._revpatches(repo, revs)
919 revpatches = self._revpatches(repo, revs)
920 realpatches += revpatches
920 realpatches += revpatches
921 numrevs = len(revpatches)
921 numrevs = len(revpatches)
922
922
923 self._cleanup(realpatches, numrevs, opts.get('keep'))
923 self._cleanup(realpatches, numrevs, opts.get('keep'))
924
924
925 def checktoppatch(self, repo):
925 def checktoppatch(self, repo):
926 if self.applied:
926 if self.applied:
927 top = self.applied[-1].node
927 top = self.applied[-1].node
928 patch = self.applied[-1].name
928 patch = self.applied[-1].name
929 pp = repo.dirstate.parents()
929 pp = repo.dirstate.parents()
930 if top not in pp:
930 if top not in pp:
931 raise util.Abort(_("working directory revision is not qtip"))
931 raise util.Abort(_("working directory revision is not qtip"))
932 return top, patch
932 return top, patch
933 return None, None
933 return None, None
934
934
935 def checksubstate(self, repo):
935 def checksubstate(self, repo):
936 '''return list of subrepos at a different revision than substate.
936 '''return list of subrepos at a different revision than substate.
937 Abort if any subrepos have uncommitted changes.'''
937 Abort if any subrepos have uncommitted changes.'''
938 inclsubs = []
938 inclsubs = []
939 wctx = repo[None]
939 wctx = repo[None]
940 for s in wctx.substate:
940 for s in wctx.substate:
941 if wctx.sub(s).dirty(True):
941 if wctx.sub(s).dirty(True):
942 raise util.Abort(
942 raise util.Abort(
943 _("uncommitted changes in subrepository %s") % s)
943 _("uncommitted changes in subrepository %s") % s)
944 elif wctx.sub(s).dirty():
944 elif wctx.sub(s).dirty():
945 inclsubs.append(s)
945 inclsubs.append(s)
946 return inclsubs
946 return inclsubs
947
947
948 def localchangesfound(self, refresh=True):
948 def localchangesfound(self, refresh=True):
949 if refresh:
949 if refresh:
950 raise util.Abort(_("local changes found, refresh first"))
950 raise util.Abort(_("local changes found, refresh first"))
951 else:
951 else:
952 raise util.Abort(_("local changes found"))
952 raise util.Abort(_("local changes found"))
953
953
954 def checklocalchanges(self, repo, force=False, refresh=True):
954 def checklocalchanges(self, repo, force=False, refresh=True):
955 m, a, r, d = repo.status()[:4]
955 m, a, r, d = repo.status()[:4]
956 if (m or a or r or d) and not force:
956 if (m or a or r or d) and not force:
957 self.localchangesfound(refresh)
957 self.localchangesfound(refresh)
958 return m, a, r, d
958 return m, a, r, d
959
959
960 _reserved = ('series', 'status', 'guards', '.', '..')
960 _reserved = ('series', 'status', 'guards', '.', '..')
961 def checkreservedname(self, name):
961 def checkreservedname(self, name):
962 if name in self._reserved:
962 if name in self._reserved:
963 raise util.Abort(_('"%s" cannot be used as the name of a patch')
963 raise util.Abort(_('"%s" cannot be used as the name of a patch')
964 % name)
964 % name)
965 for prefix in ('.hg', '.mq'):
965 for prefix in ('.hg', '.mq'):
966 if name.startswith(prefix):
966 if name.startswith(prefix):
967 raise util.Abort(_('patch name cannot begin with "%s"')
967 raise util.Abort(_('patch name cannot begin with "%s"')
968 % prefix)
968 % prefix)
969 for c in ('#', ':'):
969 for c in ('#', ':'):
970 if c in name:
970 if c in name:
971 raise util.Abort(_('"%s" cannot be used in the name of a patch')
971 raise util.Abort(_('"%s" cannot be used in the name of a patch')
972 % c)
972 % c)
973
973
974 def checkpatchname(self, name, force=False):
974 def checkpatchname(self, name, force=False):
975 self.checkreservedname(name)
975 self.checkreservedname(name)
976 if not force and os.path.exists(self.join(name)):
976 if not force and os.path.exists(self.join(name)):
977 if os.path.isdir(self.join(name)):
977 if os.path.isdir(self.join(name)):
978 raise util.Abort(_('"%s" already exists as a directory')
978 raise util.Abort(_('"%s" already exists as a directory')
979 % name)
979 % name)
980 else:
980 else:
981 raise util.Abort(_('patch "%s" already exists') % name)
981 raise util.Abort(_('patch "%s" already exists') % name)
982
982
983 def checkforcecheck(self, check, force):
983 def checkforcecheck(self, check, force):
984 if force and check:
984 if force and check:
985 raise util.Abort(_('cannot use both --force and --check'))
985 raise util.Abort(_('cannot use both --force and --check'))
986
986
987 def new(self, repo, patchfn, *pats, **opts):
987 def new(self, repo, patchfn, *pats, **opts):
988 """options:
988 """options:
989 msg: a string or a no-argument function returning a string
989 msg: a string or a no-argument function returning a string
990 """
990 """
991 msg = opts.get('msg')
991 msg = opts.get('msg')
992 user = opts.get('user')
992 user = opts.get('user')
993 date = opts.get('date')
993 date = opts.get('date')
994 if date:
994 if date:
995 date = util.parsedate(date)
995 date = util.parsedate(date)
996 diffopts = self.diffopts({'git': opts.get('git')})
996 diffopts = self.diffopts({'git': opts.get('git')})
997 if opts.get('checkname', True):
997 if opts.get('checkname', True):
998 self.checkpatchname(patchfn)
998 self.checkpatchname(patchfn)
999 inclsubs = self.checksubstate(repo)
999 inclsubs = self.checksubstate(repo)
1000 if inclsubs:
1000 if inclsubs:
1001 inclsubs.append('.hgsubstate')
1001 inclsubs.append('.hgsubstate')
1002 substatestate = repo.dirstate['.hgsubstate']
1002 substatestate = repo.dirstate['.hgsubstate']
1003 if opts.get('include') or opts.get('exclude') or pats:
1003 if opts.get('include') or opts.get('exclude') or pats:
1004 if inclsubs:
1004 if inclsubs:
1005 pats = list(pats or []) + inclsubs
1005 pats = list(pats or []) + inclsubs
1006 match = scmutil.match(repo[None], pats, opts)
1006 match = scmutil.match(repo[None], pats, opts)
1007 # detect missing files in pats
1007 # detect missing files in pats
1008 def badfn(f, msg):
1008 def badfn(f, msg):
1009 if f != '.hgsubstate': # .hgsubstate is auto-created
1009 if f != '.hgsubstate': # .hgsubstate is auto-created
1010 raise util.Abort('%s: %s' % (f, msg))
1010 raise util.Abort('%s: %s' % (f, msg))
1011 match.bad = badfn
1011 match.bad = badfn
1012 changes = repo.status(match=match)
1012 changes = repo.status(match=match)
1013 m, a, r, d = changes[:4]
1013 m, a, r, d = changes[:4]
1014 else:
1014 else:
1015 changes = self.checklocalchanges(repo, force=True)
1015 changes = self.checklocalchanges(repo, force=True)
1016 m, a, r, d = changes
1016 m, a, r, d = changes
1017 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
1017 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
1018 if len(repo[None].parents()) > 1:
1018 if len(repo[None].parents()) > 1:
1019 raise util.Abort(_('cannot manage merge changesets'))
1019 raise util.Abort(_('cannot manage merge changesets'))
1020 commitfiles = m + a + r
1020 commitfiles = m + a + r
1021 self.checktoppatch(repo)
1021 self.checktoppatch(repo)
1022 insert = self.fullseriesend()
1022 insert = self.fullseriesend()
1023 wlock = repo.wlock()
1023 wlock = repo.wlock()
1024 try:
1024 try:
1025 try:
1025 try:
1026 # if patch file write fails, abort early
1026 # if patch file write fails, abort early
1027 p = self.opener(patchfn, "w")
1027 p = self.opener(patchfn, "w")
1028 except IOError, e:
1028 except IOError, e:
1029 raise util.Abort(_('cannot write patch "%s": %s')
1029 raise util.Abort(_('cannot write patch "%s": %s')
1030 % (patchfn, e.strerror))
1030 % (patchfn, e.strerror))
1031 try:
1031 try:
1032 if self.plainmode:
1032 if self.plainmode:
1033 if user:
1033 if user:
1034 p.write("From: " + user + "\n")
1034 p.write("From: " + user + "\n")
1035 if not date:
1035 if not date:
1036 p.write("\n")
1036 p.write("\n")
1037 if date:
1037 if date:
1038 p.write("Date: %d %d\n\n" % date)
1038 p.write("Date: %d %d\n\n" % date)
1039 else:
1039 else:
1040 p.write("# HG changeset patch\n")
1040 p.write("# HG changeset patch\n")
1041 p.write("# Parent "
1041 p.write("# Parent "
1042 + hex(repo[None].p1().node()) + "\n")
1042 + hex(repo[None].p1().node()) + "\n")
1043 if user:
1043 if user:
1044 p.write("# User " + user + "\n")
1044 p.write("# User " + user + "\n")
1045 if date:
1045 if date:
1046 p.write("# Date %s %s\n\n" % date)
1046 p.write("# Date %s %s\n\n" % date)
1047 if util.safehasattr(msg, '__call__'):
1047 if util.safehasattr(msg, '__call__'):
1048 msg = msg()
1048 msg = msg()
1049 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
1049 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
1050 n = newcommit(repo, None, commitmsg, user, date, match=match,
1050 n = newcommit(repo, None, commitmsg, user, date, match=match,
1051 force=True)
1051 force=True)
1052 if n is None:
1052 if n is None:
1053 raise util.Abort(_("repo commit failed"))
1053 raise util.Abort(_("repo commit failed"))
1054 try:
1054 try:
1055 self.fullseries[insert:insert] = [patchfn]
1055 self.fullseries[insert:insert] = [patchfn]
1056 self.applied.append(statusentry(n, patchfn))
1056 self.applied.append(statusentry(n, patchfn))
1057 self.parseseries()
1057 self.parseseries()
1058 self.seriesdirty = True
1058 self.seriesdirty = True
1059 self.applieddirty = True
1059 self.applieddirty = True
1060 if msg:
1060 if msg:
1061 msg = msg + "\n\n"
1061 msg = msg + "\n\n"
1062 p.write(msg)
1062 p.write(msg)
1063 if commitfiles:
1063 if commitfiles:
1064 parent = self.qparents(repo, n)
1064 parent = self.qparents(repo, n)
1065 if inclsubs:
1065 if inclsubs:
1066 if substatestate in 'a?':
1066 if substatestate in 'a?':
1067 changes[1].append('.hgsubstate')
1067 changes[1].append('.hgsubstate')
1068 elif substatestate in 'r':
1068 elif substatestate in 'r':
1069 changes[2].append('.hgsubstate')
1069 changes[2].append('.hgsubstate')
1070 else: # modified
1070 else: # modified
1071 changes[0].append('.hgsubstate')
1071 changes[0].append('.hgsubstate')
1072 chunks = patchmod.diff(repo, node1=parent, node2=n,
1072 chunks = patchmod.diff(repo, node1=parent, node2=n,
1073 changes=changes, opts=diffopts)
1073 changes=changes, opts=diffopts)
1074 for chunk in chunks:
1074 for chunk in chunks:
1075 p.write(chunk)
1075 p.write(chunk)
1076 p.close()
1076 p.close()
1077 r = self.qrepo()
1077 r = self.qrepo()
1078 if r:
1078 if r:
1079 r[None].add([patchfn])
1079 r[None].add([patchfn])
1080 except:
1080 except:
1081 repo.rollback()
1081 repo.rollback()
1082 raise
1082 raise
1083 except Exception:
1083 except Exception:
1084 patchpath = self.join(patchfn)
1084 patchpath = self.join(patchfn)
1085 try:
1085 try:
1086 os.unlink(patchpath)
1086 os.unlink(patchpath)
1087 except:
1087 except:
1088 self.ui.warn(_('error unlinking %s\n') % patchpath)
1088 self.ui.warn(_('error unlinking %s\n') % patchpath)
1089 raise
1089 raise
1090 self.removeundo(repo)
1090 self.removeundo(repo)
1091 finally:
1091 finally:
1092 release(wlock)
1092 release(wlock)
1093
1093
1094 def strip(self, repo, revs, update=True, backup="all", force=None):
1094 def strip(self, repo, revs, update=True, backup="all", force=None):
1095 wlock = lock = None
1095 wlock = lock = None
1096 try:
1096 try:
1097 wlock = repo.wlock()
1097 wlock = repo.wlock()
1098 lock = repo.lock()
1098 lock = repo.lock()
1099
1099
1100 if update:
1100 if update:
1101 self.checklocalchanges(repo, force=force, refresh=False)
1101 self.checklocalchanges(repo, force=force, refresh=False)
1102 urev = self.qparents(repo, revs[0])
1102 urev = self.qparents(repo, revs[0])
1103 hg.clean(repo, urev)
1103 hg.clean(repo, urev)
1104 repo.dirstate.write()
1104 repo.dirstate.write()
1105
1105
1106 repair.strip(self.ui, repo, revs, backup)
1106 repair.strip(self.ui, repo, revs, backup)
1107 finally:
1107 finally:
1108 release(lock, wlock)
1108 release(lock, wlock)
1109
1109
1110 def isapplied(self, patch):
1110 def isapplied(self, patch):
1111 """returns (index, rev, patch)"""
1111 """returns (index, rev, patch)"""
1112 for i, a in enumerate(self.applied):
1112 for i, a in enumerate(self.applied):
1113 if a.name == patch:
1113 if a.name == patch:
1114 return (i, a.node, a.name)
1114 return (i, a.node, a.name)
1115 return None
1115 return None
1116
1116
1117 # if the exact patch name does not exist, we try a few
1117 # if the exact patch name does not exist, we try a few
1118 # variations. If strict is passed, we try only #1
1118 # variations. If strict is passed, we try only #1
1119 #
1119 #
1120 # 1) a number (as string) to indicate an offset in the series file
1120 # 1) a number (as string) to indicate an offset in the series file
1121 # 2) a unique substring of the patch name was given
1121 # 2) a unique substring of the patch name was given
1122 # 3) patchname[-+]num to indicate an offset in the series file
1122 # 3) patchname[-+]num to indicate an offset in the series file
1123 def lookup(self, patch, strict=False):
1123 def lookup(self, patch, strict=False):
1124 def partialname(s):
1124 def partialname(s):
1125 if s in self.series:
1125 if s in self.series:
1126 return s
1126 return s
1127 matches = [x for x in self.series if s in x]
1127 matches = [x for x in self.series if s in x]
1128 if len(matches) > 1:
1128 if len(matches) > 1:
1129 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1129 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1130 for m in matches:
1130 for m in matches:
1131 self.ui.warn(' %s\n' % m)
1131 self.ui.warn(' %s\n' % m)
1132 return None
1132 return None
1133 if matches:
1133 if matches:
1134 return matches[0]
1134 return matches[0]
1135 if self.series and self.applied:
1135 if self.series and self.applied:
1136 if s == 'qtip':
1136 if s == 'qtip':
1137 return self.series[self.seriesend(True)-1]
1137 return self.series[self.seriesend(True)-1]
1138 if s == 'qbase':
1138 if s == 'qbase':
1139 return self.series[0]
1139 return self.series[0]
1140 return None
1140 return None
1141
1141
1142 if patch in self.series:
1142 if patch in self.series:
1143 return patch
1143 return patch
1144
1144
1145 if not os.path.isfile(self.join(patch)):
1145 if not os.path.isfile(self.join(patch)):
1146 try:
1146 try:
1147 sno = int(patch)
1147 sno = int(patch)
1148 except (ValueError, OverflowError):
1148 except (ValueError, OverflowError):
1149 pass
1149 pass
1150 else:
1150 else:
1151 if -len(self.series) <= sno < len(self.series):
1151 if -len(self.series) <= sno < len(self.series):
1152 return self.series[sno]
1152 return self.series[sno]
1153
1153
1154 if not strict:
1154 if not strict:
1155 res = partialname(patch)
1155 res = partialname(patch)
1156 if res:
1156 if res:
1157 return res
1157 return res
1158 minus = patch.rfind('-')
1158 minus = patch.rfind('-')
1159 if minus >= 0:
1159 if minus >= 0:
1160 res = partialname(patch[:minus])
1160 res = partialname(patch[:minus])
1161 if res:
1161 if res:
1162 i = self.series.index(res)
1162 i = self.series.index(res)
1163 try:
1163 try:
1164 off = int(patch[minus + 1:] or 1)
1164 off = int(patch[minus + 1:] or 1)
1165 except (ValueError, OverflowError):
1165 except (ValueError, OverflowError):
1166 pass
1166 pass
1167 else:
1167 else:
1168 if i - off >= 0:
1168 if i - off >= 0:
1169 return self.series[i - off]
1169 return self.series[i - off]
1170 plus = patch.rfind('+')
1170 plus = patch.rfind('+')
1171 if plus >= 0:
1171 if plus >= 0:
1172 res = partialname(patch[:plus])
1172 res = partialname(patch[:plus])
1173 if res:
1173 if res:
1174 i = self.series.index(res)
1174 i = self.series.index(res)
1175 try:
1175 try:
1176 off = int(patch[plus + 1:] or 1)
1176 off = int(patch[plus + 1:] or 1)
1177 except (ValueError, OverflowError):
1177 except (ValueError, OverflowError):
1178 pass
1178 pass
1179 else:
1179 else:
1180 if i + off < len(self.series):
1180 if i + off < len(self.series):
1181 return self.series[i + off]
1181 return self.series[i + off]
1182 raise util.Abort(_("patch %s not in series") % patch)
1182 raise util.Abort(_("patch %s not in series") % patch)
1183
1183
1184 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1184 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1185 all=False, move=False, exact=False, nobackup=False, check=False):
1185 all=False, move=False, exact=False, nobackup=False, check=False):
1186 self.checkforcecheck(check, force)
1186 self.checkforcecheck(check, force)
1187 diffopts = self.diffopts()
1187 diffopts = self.diffopts()
1188 wlock = repo.wlock()
1188 wlock = repo.wlock()
1189 try:
1189 try:
1190 heads = []
1190 heads = []
1191 for b, ls in repo.branchmap().iteritems():
1191 for b, ls in repo.branchmap().iteritems():
1192 heads += ls
1192 heads += ls
1193 if not heads:
1193 if not heads:
1194 heads = [nullid]
1194 heads = [nullid]
1195 if repo.dirstate.p1() not in heads and not exact:
1195 if repo.dirstate.p1() not in heads and not exact:
1196 self.ui.status(_("(working directory not at a head)\n"))
1196 self.ui.status(_("(working directory not at a head)\n"))
1197
1197
1198 if not self.series:
1198 if not self.series:
1199 self.ui.warn(_('no patches in series\n'))
1199 self.ui.warn(_('no patches in series\n'))
1200 return 0
1200 return 0
1201
1201
1202 # Suppose our series file is: A B C and the current 'top'
1202 # Suppose our series file is: A B C and the current 'top'
1203 # patch is B. qpush C should be performed (moving forward)
1203 # patch is B. qpush C should be performed (moving forward)
1204 # qpush B is a NOP (no change) qpush A is an error (can't
1204 # qpush B is a NOP (no change) qpush A is an error (can't
1205 # go backwards with qpush)
1205 # go backwards with qpush)
1206 if patch:
1206 if patch:
1207 patch = self.lookup(patch)
1207 patch = self.lookup(patch)
1208 info = self.isapplied(patch)
1208 info = self.isapplied(patch)
1209 if info and info[0] >= len(self.applied) - 1:
1209 if info and info[0] >= len(self.applied) - 1:
1210 self.ui.warn(
1210 self.ui.warn(
1211 _('qpush: %s is already at the top\n') % patch)
1211 _('qpush: %s is already at the top\n') % patch)
1212 return 0
1212 return 0
1213
1213
1214 pushable, reason = self.pushable(patch)
1214 pushable, reason = self.pushable(patch)
1215 if pushable:
1215 if pushable:
1216 if self.series.index(patch) < self.seriesend():
1216 if self.series.index(patch) < self.seriesend():
1217 raise util.Abort(
1217 raise util.Abort(
1218 _("cannot push to a previous patch: %s") % patch)
1218 _("cannot push to a previous patch: %s") % patch)
1219 else:
1219 else:
1220 if reason:
1220 if reason:
1221 reason = _('guarded by %s') % reason
1221 reason = _('guarded by %s') % reason
1222 else:
1222 else:
1223 reason = _('no matching guards')
1223 reason = _('no matching guards')
1224 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1224 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1225 return 1
1225 return 1
1226 elif all:
1226 elif all:
1227 patch = self.series[-1]
1227 patch = self.series[-1]
1228 if self.isapplied(patch):
1228 if self.isapplied(patch):
1229 self.ui.warn(_('all patches are currently applied\n'))
1229 self.ui.warn(_('all patches are currently applied\n'))
1230 return 0
1230 return 0
1231
1231
1232 # Following the above example, starting at 'top' of B:
1232 # Following the above example, starting at 'top' of B:
1233 # qpush should be performed (pushes C), but a subsequent
1233 # qpush should be performed (pushes C), but a subsequent
1234 # qpush without an argument is an error (nothing to
1234 # qpush without an argument is an error (nothing to
1235 # apply). This allows a loop of "...while hg qpush..." to
1235 # apply). This allows a loop of "...while hg qpush..." to
1236 # work as it detects an error when done
1236 # work as it detects an error when done
1237 start = self.seriesend()
1237 start = self.seriesend()
1238 if start == len(self.series):
1238 if start == len(self.series):
1239 self.ui.warn(_('patch series already fully applied\n'))
1239 self.ui.warn(_('patch series already fully applied\n'))
1240 return 1
1240 return 1
1241 if not force and not check:
1241 if not force and not check:
1242 self.checklocalchanges(repo, refresh=self.applied)
1242 self.checklocalchanges(repo, refresh=self.applied)
1243
1243
1244 if exact:
1244 if exact:
1245 if check:
1245 if check:
1246 raise util.Abort(
1246 raise util.Abort(
1247 _("cannot use --exact and --check together"))
1247 _("cannot use --exact and --check together"))
1248 if move:
1248 if move:
1249 raise util.Abort(_("cannot use --exact and --move together"))
1249 raise util.Abort(_("cannot use --exact and --move together"))
1250 if self.applied:
1250 if self.applied:
1251 raise util.Abort(_("cannot push --exact with applied patches"))
1251 raise util.Abort(_("cannot push --exact with applied patches"))
1252 root = self.series[start]
1252 root = self.series[start]
1253 target = patchheader(self.join(root), self.plainmode).parent
1253 target = patchheader(self.join(root), self.plainmode).parent
1254 if not target:
1254 if not target:
1255 raise util.Abort(
1255 raise util.Abort(
1256 _("%s does not have a parent recorded") % root)
1256 _("%s does not have a parent recorded") % root)
1257 if not repo[target] == repo['.']:
1257 if not repo[target] == repo['.']:
1258 hg.update(repo, target)
1258 hg.update(repo, target)
1259
1259
1260 if move:
1260 if move:
1261 if not patch:
1261 if not patch:
1262 raise util.Abort(_("please specify the patch to move"))
1262 raise util.Abort(_("please specify the patch to move"))
1263 for fullstart, rpn in enumerate(self.fullseries):
1263 for fullstart, rpn in enumerate(self.fullseries):
1264 # strip markers for patch guards
1264 # strip markers for patch guards
1265 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1265 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1266 break
1266 break
1267 for i, rpn in enumerate(self.fullseries[fullstart:]):
1267 for i, rpn in enumerate(self.fullseries[fullstart:]):
1268 # strip markers for patch guards
1268 # strip markers for patch guards
1269 if self.guard_re.split(rpn, 1)[0] == patch:
1269 if self.guard_re.split(rpn, 1)[0] == patch:
1270 break
1270 break
1271 index = fullstart + i
1271 index = fullstart + i
1272 assert index < len(self.fullseries)
1272 assert index < len(self.fullseries)
1273 fullpatch = self.fullseries[index]
1273 fullpatch = self.fullseries[index]
1274 del self.fullseries[index]
1274 del self.fullseries[index]
1275 self.fullseries.insert(fullstart, fullpatch)
1275 self.fullseries.insert(fullstart, fullpatch)
1276 self.parseseries()
1276 self.parseseries()
1277 self.seriesdirty = True
1277 self.seriesdirty = True
1278
1278
1279 self.applieddirty = True
1279 self.applieddirty = True
1280 if start > 0:
1280 if start > 0:
1281 self.checktoppatch(repo)
1281 self.checktoppatch(repo)
1282 if not patch:
1282 if not patch:
1283 patch = self.series[start]
1283 patch = self.series[start]
1284 end = start + 1
1284 end = start + 1
1285 else:
1285 else:
1286 end = self.series.index(patch, start) + 1
1286 end = self.series.index(patch, start) + 1
1287
1287
1288 tobackup = set()
1288 tobackup = set()
1289 if (not nobackup and force) or check:
1289 if (not nobackup and force) or check:
1290 m, a, r, d = self.checklocalchanges(repo, force=True)
1290 m, a, r, d = self.checklocalchanges(repo, force=True)
1291 if check:
1291 if check:
1292 tobackup.update(m + a + r + d)
1292 tobackup.update(m + a + r + d)
1293 else:
1293 else:
1294 tobackup.update(m + a)
1294 tobackup.update(m + a)
1295
1295
1296 s = self.series[start:end]
1296 s = self.series[start:end]
1297 all_files = set()
1297 all_files = set()
1298 try:
1298 try:
1299 if mergeq:
1299 if mergeq:
1300 ret = self.mergepatch(repo, mergeq, s, diffopts)
1300 ret = self.mergepatch(repo, mergeq, s, diffopts)
1301 else:
1301 else:
1302 ret = self.apply(repo, s, list, all_files=all_files,
1302 ret = self.apply(repo, s, list, all_files=all_files,
1303 tobackup=tobackup, check=check)
1303 tobackup=tobackup, check=check)
1304 except:
1304 except:
1305 self.ui.warn(_('cleaning up working directory...'))
1305 self.ui.warn(_('cleaning up working directory...'))
1306 node = repo.dirstate.p1()
1306 node = repo.dirstate.p1()
1307 hg.revert(repo, node, None)
1307 hg.revert(repo, node, None)
1308 # only remove unknown files that we know we touched or
1308 # only remove unknown files that we know we touched or
1309 # created while patching
1309 # created while patching
1310 for f in all_files:
1310 for f in all_files:
1311 if f not in repo.dirstate:
1311 if f not in repo.dirstate:
1312 try:
1312 try:
1313 util.unlinkpath(repo.wjoin(f))
1313 util.unlinkpath(repo.wjoin(f))
1314 except OSError, inst:
1314 except OSError, inst:
1315 if inst.errno != errno.ENOENT:
1315 if inst.errno != errno.ENOENT:
1316 raise
1316 raise
1317 self.ui.warn(_('done\n'))
1317 self.ui.warn(_('done\n'))
1318 raise
1318 raise
1319
1319
1320 if not self.applied:
1320 if not self.applied:
1321 return ret[0]
1321 return ret[0]
1322 top = self.applied[-1].name
1322 top = self.applied[-1].name
1323 if ret[0] and ret[0] > 1:
1323 if ret[0] and ret[0] > 1:
1324 msg = _("errors during apply, please fix and refresh %s\n")
1324 msg = _("errors during apply, please fix and refresh %s\n")
1325 self.ui.write(msg % top)
1325 self.ui.write(msg % top)
1326 else:
1326 else:
1327 self.ui.write(_("now at: %s\n") % top)
1327 self.ui.write(_("now at: %s\n") % top)
1328 return ret[0]
1328 return ret[0]
1329
1329
1330 finally:
1330 finally:
1331 wlock.release()
1331 wlock.release()
1332
1332
1333 def pop(self, repo, patch=None, force=False, update=True, all=False,
1333 def pop(self, repo, patch=None, force=False, update=True, all=False,
1334 nobackup=False, check=False):
1334 nobackup=False, check=False):
1335 self.checkforcecheck(check, force)
1335 self.checkforcecheck(check, force)
1336 wlock = repo.wlock()
1336 wlock = repo.wlock()
1337 try:
1337 try:
1338 if patch:
1338 if patch:
1339 # index, rev, patch
1339 # index, rev, patch
1340 info = self.isapplied(patch)
1340 info = self.isapplied(patch)
1341 if not info:
1341 if not info:
1342 patch = self.lookup(patch)
1342 patch = self.lookup(patch)
1343 info = self.isapplied(patch)
1343 info = self.isapplied(patch)
1344 if not info:
1344 if not info:
1345 raise util.Abort(_("patch %s is not applied") % patch)
1345 raise util.Abort(_("patch %s is not applied") % patch)
1346
1346
1347 if not self.applied:
1347 if not self.applied:
1348 # Allow qpop -a to work repeatedly,
1348 # Allow qpop -a to work repeatedly,
1349 # but not qpop without an argument
1349 # but not qpop without an argument
1350 self.ui.warn(_("no patches applied\n"))
1350 self.ui.warn(_("no patches applied\n"))
1351 return not all
1351 return not all
1352
1352
1353 if all:
1353 if all:
1354 start = 0
1354 start = 0
1355 elif patch:
1355 elif patch:
1356 start = info[0] + 1
1356 start = info[0] + 1
1357 else:
1357 else:
1358 start = len(self.applied) - 1
1358 start = len(self.applied) - 1
1359
1359
1360 if start >= len(self.applied):
1360 if start >= len(self.applied):
1361 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1361 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1362 return
1362 return
1363
1363
1364 if not update:
1364 if not update:
1365 parents = repo.dirstate.parents()
1365 parents = repo.dirstate.parents()
1366 rr = [x.node for x in self.applied]
1366 rr = [x.node for x in self.applied]
1367 for p in parents:
1367 for p in parents:
1368 if p in rr:
1368 if p in rr:
1369 self.ui.warn(_("qpop: forcing dirstate update\n"))
1369 self.ui.warn(_("qpop: forcing dirstate update\n"))
1370 update = True
1370 update = True
1371 else:
1371 else:
1372 parents = [p.node() for p in repo[None].parents()]
1372 parents = [p.node() for p in repo[None].parents()]
1373 needupdate = False
1373 needupdate = False
1374 for entry in self.applied[start:]:
1374 for entry in self.applied[start:]:
1375 if entry.node in parents:
1375 if entry.node in parents:
1376 needupdate = True
1376 needupdate = True
1377 break
1377 break
1378 update = needupdate
1378 update = needupdate
1379
1379
1380 tobackup = set()
1380 tobackup = set()
1381 if update:
1381 if update:
1382 m, a, r, d = self.checklocalchanges(repo, force=force or check)
1382 m, a, r, d = self.checklocalchanges(repo, force=force or check)
1383 if force:
1383 if force:
1384 if not nobackup:
1384 if not nobackup:
1385 tobackup.update(m + a)
1385 tobackup.update(m + a)
1386 elif check:
1386 elif check:
1387 tobackup.update(m + a + r + d)
1387 tobackup.update(m + a + r + d)
1388
1388
1389 self.applieddirty = True
1389 self.applieddirty = True
1390 end = len(self.applied)
1390 end = len(self.applied)
1391 rev = self.applied[start].node
1391 rev = self.applied[start].node
1392 if update:
1392 if update:
1393 top = self.checktoppatch(repo)[0]
1393 top = self.checktoppatch(repo)[0]
1394
1394
1395 try:
1395 try:
1396 heads = repo.changelog.heads(rev)
1396 heads = repo.changelog.heads(rev)
1397 except error.LookupError:
1397 except error.LookupError:
1398 node = short(rev)
1398 node = short(rev)
1399 raise util.Abort(_('trying to pop unknown node %s') % node)
1399 raise util.Abort(_('trying to pop unknown node %s') % node)
1400
1400
1401 if heads != [self.applied[-1].node]:
1401 if heads != [self.applied[-1].node]:
1402 raise util.Abort(_("popping would remove a revision not "
1402 raise util.Abort(_("popping would remove a revision not "
1403 "managed by this patch queue"))
1403 "managed by this patch queue"))
1404 if not repo[self.applied[-1].node].mutable():
1404 if not repo[self.applied[-1].node].mutable():
1405 raise util.Abort(
1405 raise util.Abort(
1406 _("popping would remove an immutable revision"),
1406 _("popping would remove an immutable revision"),
1407 hint=_('see "hg help phases" for details'))
1407 hint=_('see "hg help phases" for details'))
1408
1408
1409 # we know there are no local changes, so we can make a simplified
1409 # we know there are no local changes, so we can make a simplified
1410 # form of hg.update.
1410 # form of hg.update.
1411 if update:
1411 if update:
1412 qp = self.qparents(repo, rev)
1412 qp = self.qparents(repo, rev)
1413 ctx = repo[qp]
1413 ctx = repo[qp]
1414 m, a, r, d = repo.status(qp, top)[:4]
1414 m, a, r, d = repo.status(qp, top)[:4]
1415 if d:
1415 if d:
1416 raise util.Abort(_("deletions found between repo revs"))
1416 raise util.Abort(_("deletions found between repo revs"))
1417
1417
1418 tobackup = set(a + m + r) & tobackup
1418 tobackup = set(a + m + r) & tobackup
1419 if check and tobackup:
1419 if check and tobackup:
1420 self.localchangesfound()
1420 self.localchangesfound()
1421 self.backup(repo, tobackup)
1421 self.backup(repo, tobackup)
1422
1422
1423 for f in a:
1423 for f in a:
1424 try:
1424 try:
1425 util.unlinkpath(repo.wjoin(f))
1425 util.unlinkpath(repo.wjoin(f))
1426 except OSError, e:
1426 except OSError, e:
1427 if e.errno != errno.ENOENT:
1427 if e.errno != errno.ENOENT:
1428 raise
1428 raise
1429 repo.dirstate.drop(f)
1429 repo.dirstate.drop(f)
1430 for f in m + r:
1430 for f in m + r:
1431 fctx = ctx[f]
1431 fctx = ctx[f]
1432 repo.wwrite(f, fctx.data(), fctx.flags())
1432 repo.wwrite(f, fctx.data(), fctx.flags())
1433 repo.dirstate.normal(f)
1433 repo.dirstate.normal(f)
1434 repo.setparents(qp, nullid)
1434 repo.setparents(qp, nullid)
1435 for patch in reversed(self.applied[start:end]):
1435 for patch in reversed(self.applied[start:end]):
1436 self.ui.status(_("popping %s\n") % patch.name)
1436 self.ui.status(_("popping %s\n") % patch.name)
1437 del self.applied[start:end]
1437 del self.applied[start:end]
1438 self.strip(repo, [rev], update=False, backup='strip')
1438 self.strip(repo, [rev], update=False, backup='strip')
1439 if self.applied:
1439 if self.applied:
1440 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1440 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1441 else:
1441 else:
1442 self.ui.write(_("patch queue now empty\n"))
1442 self.ui.write(_("patch queue now empty\n"))
1443 finally:
1443 finally:
1444 wlock.release()
1444 wlock.release()
1445
1445
1446 def diff(self, repo, pats, opts):
1446 def diff(self, repo, pats, opts):
1447 top, patch = self.checktoppatch(repo)
1447 top, patch = self.checktoppatch(repo)
1448 if not top:
1448 if not top:
1449 self.ui.write(_("no patches applied\n"))
1449 self.ui.write(_("no patches applied\n"))
1450 return
1450 return
1451 qp = self.qparents(repo, top)
1451 qp = self.qparents(repo, top)
1452 if opts.get('reverse'):
1452 if opts.get('reverse'):
1453 node1, node2 = None, qp
1453 node1, node2 = None, qp
1454 else:
1454 else:
1455 node1, node2 = qp, None
1455 node1, node2 = qp, None
1456 diffopts = self.diffopts(opts, patch)
1456 diffopts = self.diffopts(opts, patch)
1457 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1457 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1458
1458
1459 def refresh(self, repo, pats=None, **opts):
1459 def refresh(self, repo, pats=None, **opts):
1460 if not self.applied:
1460 if not self.applied:
1461 self.ui.write(_("no patches applied\n"))
1461 self.ui.write(_("no patches applied\n"))
1462 return 1
1462 return 1
1463 msg = opts.get('msg', '').rstrip()
1463 msg = opts.get('msg', '').rstrip()
1464 newuser = opts.get('user')
1464 newuser = opts.get('user')
1465 newdate = opts.get('date')
1465 newdate = opts.get('date')
1466 if newdate:
1466 if newdate:
1467 newdate = '%d %d' % util.parsedate(newdate)
1467 newdate = '%d %d' % util.parsedate(newdate)
1468 wlock = repo.wlock()
1468 wlock = repo.wlock()
1469
1469
1470 try:
1470 try:
1471 self.checktoppatch(repo)
1471 self.checktoppatch(repo)
1472 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1472 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1473 if repo.changelog.heads(top) != [top]:
1473 if repo.changelog.heads(top) != [top]:
1474 raise util.Abort(_("cannot refresh a revision with children"))
1474 raise util.Abort(_("cannot refresh a revision with children"))
1475 if not repo[top].mutable():
1475 if not repo[top].mutable():
1476 raise util.Abort(_("cannot refresh immutable revision"),
1476 raise util.Abort(_("cannot refresh immutable revision"),
1477 hint=_('see "hg help phases" for details'))
1477 hint=_('see "hg help phases" for details'))
1478
1478
1479 inclsubs = self.checksubstate(repo)
1479 inclsubs = self.checksubstate(repo)
1480
1480
1481 cparents = repo.changelog.parents(top)
1481 cparents = repo.changelog.parents(top)
1482 patchparent = self.qparents(repo, top)
1482 patchparent = self.qparents(repo, top)
1483 ph = patchheader(self.join(patchfn), self.plainmode)
1483 ph = patchheader(self.join(patchfn), self.plainmode)
1484 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1484 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1485 if msg:
1485 if msg:
1486 ph.setmessage(msg)
1486 ph.setmessage(msg)
1487 if newuser:
1487 if newuser:
1488 ph.setuser(newuser)
1488 ph.setuser(newuser)
1489 if newdate:
1489 if newdate:
1490 ph.setdate(newdate)
1490 ph.setdate(newdate)
1491 ph.setparent(hex(patchparent))
1491 ph.setparent(hex(patchparent))
1492
1492
1493 # only commit new patch when write is complete
1493 # only commit new patch when write is complete
1494 patchf = self.opener(patchfn, 'w', atomictemp=True)
1494 patchf = self.opener(patchfn, 'w', atomictemp=True)
1495
1495
1496 comments = str(ph)
1496 comments = str(ph)
1497 if comments:
1497 if comments:
1498 patchf.write(comments)
1498 patchf.write(comments)
1499
1499
1500 # update the dirstate in place, strip off the qtip commit
1500 # update the dirstate in place, strip off the qtip commit
1501 # and then commit.
1501 # and then commit.
1502 #
1502 #
1503 # this should really read:
1503 # this should really read:
1504 # mm, dd, aa = repo.status(top, patchparent)[:3]
1504 # mm, dd, aa = repo.status(top, patchparent)[:3]
1505 # but we do it backwards to take advantage of manifest/chlog
1505 # but we do it backwards to take advantage of manifest/chlog
1506 # caching against the next repo.status call
1506 # caching against the next repo.status call
1507 mm, aa, dd = repo.status(patchparent, top)[:3]
1507 mm, aa, dd = repo.status(patchparent, top)[:3]
1508 changes = repo.changelog.read(top)
1508 changes = repo.changelog.read(top)
1509 man = repo.manifest.read(changes[0])
1509 man = repo.manifest.read(changes[0])
1510 aaa = aa[:]
1510 aaa = aa[:]
1511 matchfn = scmutil.match(repo[None], pats, opts)
1511 matchfn = scmutil.match(repo[None], pats, opts)
1512 # in short mode, we only diff the files included in the
1512 # in short mode, we only diff the files included in the
1513 # patch already plus specified files
1513 # patch already plus specified files
1514 if opts.get('short'):
1514 if opts.get('short'):
1515 # if amending a patch, we start with existing
1515 # if amending a patch, we start with existing
1516 # files plus specified files - unfiltered
1516 # files plus specified files - unfiltered
1517 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1517 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1518 # filter with inc/exl options
1518 # filter with inc/exl options
1519 matchfn = scmutil.match(repo[None], opts=opts)
1519 matchfn = scmutil.match(repo[None], opts=opts)
1520 else:
1520 else:
1521 match = scmutil.matchall(repo)
1521 match = scmutil.matchall(repo)
1522 m, a, r, d = repo.status(match=match)[:4]
1522 m, a, r, d = repo.status(match=match)[:4]
1523 mm = set(mm)
1523 mm = set(mm)
1524 aa = set(aa)
1524 aa = set(aa)
1525 dd = set(dd)
1525 dd = set(dd)
1526
1526
1527 # we might end up with files that were added between
1527 # we might end up with files that were added between
1528 # qtip and the dirstate parent, but then changed in the
1528 # qtip and the dirstate parent, but then changed in the
1529 # local dirstate. in this case, we want them to only
1529 # local dirstate. in this case, we want them to only
1530 # show up in the added section
1530 # show up in the added section
1531 for x in m:
1531 for x in m:
1532 if x not in aa:
1532 if x not in aa:
1533 mm.add(x)
1533 mm.add(x)
1534 # we might end up with files added by the local dirstate that
1534 # we might end up with files added by the local dirstate that
1535 # were deleted by the patch. In this case, they should only
1535 # were deleted by the patch. In this case, they should only
1536 # show up in the changed section.
1536 # show up in the changed section.
1537 for x in a:
1537 for x in a:
1538 if x in dd:
1538 if x in dd:
1539 dd.remove(x)
1539 dd.remove(x)
1540 mm.add(x)
1540 mm.add(x)
1541 else:
1541 else:
1542 aa.add(x)
1542 aa.add(x)
1543 # make sure any files deleted in the local dirstate
1543 # make sure any files deleted in the local dirstate
1544 # are not in the add or change column of the patch
1544 # are not in the add or change column of the patch
1545 forget = []
1545 forget = []
1546 for x in d + r:
1546 for x in d + r:
1547 if x in aa:
1547 if x in aa:
1548 aa.remove(x)
1548 aa.remove(x)
1549 forget.append(x)
1549 forget.append(x)
1550 continue
1550 continue
1551 else:
1551 else:
1552 mm.discard(x)
1552 mm.discard(x)
1553 dd.add(x)
1553 dd.add(x)
1554
1554
1555 m = list(mm)
1555 m = list(mm)
1556 r = list(dd)
1556 r = list(dd)
1557 a = list(aa)
1557 a = list(aa)
1558 c = [filter(matchfn, l) for l in (m, a, r)]
1558 c = [filter(matchfn, l) for l in (m, a, r)]
1559 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1559 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1560 chunks = patchmod.diff(repo, patchparent, match=match,
1560 chunks = patchmod.diff(repo, patchparent, match=match,
1561 changes=c, opts=diffopts)
1561 changes=c, opts=diffopts)
1562 for chunk in chunks:
1562 for chunk in chunks:
1563 patchf.write(chunk)
1563 patchf.write(chunk)
1564
1564
1565 try:
1565 try:
1566 if diffopts.git or diffopts.upgrade:
1566 if diffopts.git or diffopts.upgrade:
1567 copies = {}
1567 copies = {}
1568 for dst in a:
1568 for dst in a:
1569 src = repo.dirstate.copied(dst)
1569 src = repo.dirstate.copied(dst)
1570 # during qfold, the source file for copies may
1570 # during qfold, the source file for copies may
1571 # be removed. Treat this as a simple add.
1571 # be removed. Treat this as a simple add.
1572 if src is not None and src in repo.dirstate:
1572 if src is not None and src in repo.dirstate:
1573 copies.setdefault(src, []).append(dst)
1573 copies.setdefault(src, []).append(dst)
1574 repo.dirstate.add(dst)
1574 repo.dirstate.add(dst)
1575 # remember the copies between patchparent and qtip
1575 # remember the copies between patchparent and qtip
1576 for dst in aaa:
1576 for dst in aaa:
1577 f = repo.file(dst)
1577 f = repo.file(dst)
1578 src = f.renamed(man[dst])
1578 src = f.renamed(man[dst])
1579 if src:
1579 if src:
1580 copies.setdefault(src[0], []).extend(
1580 copies.setdefault(src[0], []).extend(
1581 copies.get(dst, []))
1581 copies.get(dst, []))
1582 if dst in a:
1582 if dst in a:
1583 copies[src[0]].append(dst)
1583 copies[src[0]].append(dst)
1584 # we can't copy a file created by the patch itself
1584 # we can't copy a file created by the patch itself
1585 if dst in copies:
1585 if dst in copies:
1586 del copies[dst]
1586 del copies[dst]
1587 for src, dsts in copies.iteritems():
1587 for src, dsts in copies.iteritems():
1588 for dst in dsts:
1588 for dst in dsts:
1589 repo.dirstate.copy(src, dst)
1589 repo.dirstate.copy(src, dst)
1590 else:
1590 else:
1591 for dst in a:
1591 for dst in a:
1592 repo.dirstate.add(dst)
1592 repo.dirstate.add(dst)
1593 # Drop useless copy information
1593 # Drop useless copy information
1594 for f in list(repo.dirstate.copies()):
1594 for f in list(repo.dirstate.copies()):
1595 repo.dirstate.copy(None, f)
1595 repo.dirstate.copy(None, f)
1596 for f in r:
1596 for f in r:
1597 repo.dirstate.remove(f)
1597 repo.dirstate.remove(f)
1598 # if the patch excludes a modified file, mark that
1598 # if the patch excludes a modified file, mark that
1599 # file with mtime=0 so status can see it.
1599 # file with mtime=0 so status can see it.
1600 mm = []
1600 mm = []
1601 for i in xrange(len(m)-1, -1, -1):
1601 for i in xrange(len(m)-1, -1, -1):
1602 if not matchfn(m[i]):
1602 if not matchfn(m[i]):
1603 mm.append(m[i])
1603 mm.append(m[i])
1604 del m[i]
1604 del m[i]
1605 for f in m:
1605 for f in m:
1606 repo.dirstate.normal(f)
1606 repo.dirstate.normal(f)
1607 for f in mm:
1607 for f in mm:
1608 repo.dirstate.normallookup(f)
1608 repo.dirstate.normallookup(f)
1609 for f in forget:
1609 for f in forget:
1610 repo.dirstate.drop(f)
1610 repo.dirstate.drop(f)
1611
1611
1612 if not msg:
1612 if not msg:
1613 if not ph.message:
1613 if not ph.message:
1614 message = "[mq]: %s\n" % patchfn
1614 message = "[mq]: %s\n" % patchfn
1615 else:
1615 else:
1616 message = "\n".join(ph.message)
1616 message = "\n".join(ph.message)
1617 else:
1617 else:
1618 message = msg
1618 message = msg
1619
1619
1620 user = ph.user or changes[1]
1620 user = ph.user or changes[1]
1621
1621
1622 oldphase = repo[top].phase()
1622 oldphase = repo[top].phase()
1623
1623
1624 # assumes strip can roll itself back if interrupted
1624 # assumes strip can roll itself back if interrupted
1625 repo.setparents(*cparents)
1625 repo.setparents(*cparents)
1626 self.applied.pop()
1626 self.applied.pop()
1627 self.applieddirty = True
1627 self.applieddirty = True
1628 self.strip(repo, [top], update=False,
1628 self.strip(repo, [top], update=False,
1629 backup='strip')
1629 backup='strip')
1630 except:
1630 except:
1631 repo.dirstate.invalidate()
1631 repo.dirstate.invalidate()
1632 raise
1632 raise
1633
1633
1634 try:
1634 try:
1635 # might be nice to attempt to roll back strip after this
1635 # might be nice to attempt to roll back strip after this
1636
1636
1637 # Ensure we create a new changeset in the same phase than
1637 # Ensure we create a new changeset in the same phase than
1638 # the old one.
1638 # the old one.
1639 n = newcommit(repo, oldphase, message, user, ph.date,
1639 n = newcommit(repo, oldphase, message, user, ph.date,
1640 match=match, force=True)
1640 match=match, force=True)
1641 # only write patch after a successful commit
1641 # only write patch after a successful commit
1642 patchf.close()
1642 patchf.close()
1643 self.applied.append(statusentry(n, patchfn))
1643 self.applied.append(statusentry(n, patchfn))
1644 except:
1644 except:
1645 ctx = repo[cparents[0]]
1645 ctx = repo[cparents[0]]
1646 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1646 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1647 self.savedirty()
1647 self.savedirty()
1648 self.ui.warn(_('refresh interrupted while patch was popped! '
1648 self.ui.warn(_('refresh interrupted while patch was popped! '
1649 '(revert --all, qpush to recover)\n'))
1649 '(revert --all, qpush to recover)\n'))
1650 raise
1650 raise
1651 finally:
1651 finally:
1652 wlock.release()
1652 wlock.release()
1653 self.removeundo(repo)
1653 self.removeundo(repo)
1654
1654
1655 def init(self, repo, create=False):
1655 def init(self, repo, create=False):
1656 if not create and os.path.isdir(self.path):
1656 if not create and os.path.isdir(self.path):
1657 raise util.Abort(_("patch queue directory already exists"))
1657 raise util.Abort(_("patch queue directory already exists"))
1658 try:
1658 try:
1659 os.mkdir(self.path)
1659 os.mkdir(self.path)
1660 except OSError, inst:
1660 except OSError, inst:
1661 if inst.errno != errno.EEXIST or not create:
1661 if inst.errno != errno.EEXIST or not create:
1662 raise
1662 raise
1663 if create:
1663 if create:
1664 return self.qrepo(create=True)
1664 return self.qrepo(create=True)
1665
1665
1666 def unapplied(self, repo, patch=None):
1666 def unapplied(self, repo, patch=None):
1667 if patch and patch not in self.series:
1667 if patch and patch not in self.series:
1668 raise util.Abort(_("patch %s is not in series file") % patch)
1668 raise util.Abort(_("patch %s is not in series file") % patch)
1669 if not patch:
1669 if not patch:
1670 start = self.seriesend()
1670 start = self.seriesend()
1671 else:
1671 else:
1672 start = self.series.index(patch) + 1
1672 start = self.series.index(patch) + 1
1673 unapplied = []
1673 unapplied = []
1674 for i in xrange(start, len(self.series)):
1674 for i in xrange(start, len(self.series)):
1675 pushable, reason = self.pushable(i)
1675 pushable, reason = self.pushable(i)
1676 if pushable:
1676 if pushable:
1677 unapplied.append((i, self.series[i]))
1677 unapplied.append((i, self.series[i]))
1678 self.explainpushable(i)
1678 self.explainpushable(i)
1679 return unapplied
1679 return unapplied
1680
1680
1681 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1681 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1682 summary=False):
1682 summary=False):
1683 def displayname(pfx, patchname, state):
1683 def displayname(pfx, patchname, state):
1684 if pfx:
1684 if pfx:
1685 self.ui.write(pfx)
1685 self.ui.write(pfx)
1686 if summary:
1686 if summary:
1687 ph = patchheader(self.join(patchname), self.plainmode)
1687 ph = patchheader(self.join(patchname), self.plainmode)
1688 msg = ph.message and ph.message[0] or ''
1688 msg = ph.message and ph.message[0] or ''
1689 if self.ui.formatted():
1689 if self.ui.formatted():
1690 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1690 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1691 if width > 0:
1691 if width > 0:
1692 msg = util.ellipsis(msg, width)
1692 msg = util.ellipsis(msg, width)
1693 else:
1693 else:
1694 msg = ''
1694 msg = ''
1695 self.ui.write(patchname, label='qseries.' + state)
1695 self.ui.write(patchname, label='qseries.' + state)
1696 self.ui.write(': ')
1696 self.ui.write(': ')
1697 self.ui.write(msg, label='qseries.message.' + state)
1697 self.ui.write(msg, label='qseries.message.' + state)
1698 else:
1698 else:
1699 self.ui.write(patchname, label='qseries.' + state)
1699 self.ui.write(patchname, label='qseries.' + state)
1700 self.ui.write('\n')
1700 self.ui.write('\n')
1701
1701
1702 applied = set([p.name for p in self.applied])
1702 applied = set([p.name for p in self.applied])
1703 if length is None:
1703 if length is None:
1704 length = len(self.series) - start
1704 length = len(self.series) - start
1705 if not missing:
1705 if not missing:
1706 if self.ui.verbose:
1706 if self.ui.verbose:
1707 idxwidth = len(str(start + length - 1))
1707 idxwidth = len(str(start + length - 1))
1708 for i in xrange(start, start + length):
1708 for i in xrange(start, start + length):
1709 patch = self.series[i]
1709 patch = self.series[i]
1710 if patch in applied:
1710 if patch in applied:
1711 char, state = 'A', 'applied'
1711 char, state = 'A', 'applied'
1712 elif self.pushable(i)[0]:
1712 elif self.pushable(i)[0]:
1713 char, state = 'U', 'unapplied'
1713 char, state = 'U', 'unapplied'
1714 else:
1714 else:
1715 char, state = 'G', 'guarded'
1715 char, state = 'G', 'guarded'
1716 pfx = ''
1716 pfx = ''
1717 if self.ui.verbose:
1717 if self.ui.verbose:
1718 pfx = '%*d %s ' % (idxwidth, i, char)
1718 pfx = '%*d %s ' % (idxwidth, i, char)
1719 elif status and status != char:
1719 elif status and status != char:
1720 continue
1720 continue
1721 displayname(pfx, patch, state)
1721 displayname(pfx, patch, state)
1722 else:
1722 else:
1723 msng_list = []
1723 msng_list = []
1724 for root, dirs, files in os.walk(self.path):
1724 for root, dirs, files in os.walk(self.path):
1725 d = root[len(self.path) + 1:]
1725 d = root[len(self.path) + 1:]
1726 for f in files:
1726 for f in files:
1727 fl = os.path.join(d, f)
1727 fl = os.path.join(d, f)
1728 if (fl not in self.series and
1728 if (fl not in self.series and
1729 fl not in (self.statuspath, self.seriespath,
1729 fl not in (self.statuspath, self.seriespath,
1730 self.guardspath)
1730 self.guardspath)
1731 and not fl.startswith('.')):
1731 and not fl.startswith('.')):
1732 msng_list.append(fl)
1732 msng_list.append(fl)
1733 for x in sorted(msng_list):
1733 for x in sorted(msng_list):
1734 pfx = self.ui.verbose and ('D ') or ''
1734 pfx = self.ui.verbose and ('D ') or ''
1735 displayname(pfx, x, 'missing')
1735 displayname(pfx, x, 'missing')
1736
1736
1737 def issaveline(self, l):
1737 def issaveline(self, l):
1738 if l.name == '.hg.patches.save.line':
1738 if l.name == '.hg.patches.save.line':
1739 return True
1739 return True
1740
1740
1741 def qrepo(self, create=False):
1741 def qrepo(self, create=False):
1742 ui = self.ui.copy()
1742 ui = self.ui.copy()
1743 ui.setconfig('paths', 'default', '', overlay=False)
1743 ui.setconfig('paths', 'default', '', overlay=False)
1744 ui.setconfig('paths', 'default-push', '', overlay=False)
1744 ui.setconfig('paths', 'default-push', '', overlay=False)
1745 if create or os.path.isdir(self.join(".hg")):
1745 if create or os.path.isdir(self.join(".hg")):
1746 return hg.repository(ui, path=self.path, create=create)
1746 return hg.repository(ui, path=self.path, create=create)
1747
1747
1748 def restore(self, repo, rev, delete=None, qupdate=None):
1748 def restore(self, repo, rev, delete=None, qupdate=None):
1749 desc = repo[rev].description().strip()
1749 desc = repo[rev].description().strip()
1750 lines = desc.splitlines()
1750 lines = desc.splitlines()
1751 i = 0
1751 i = 0
1752 datastart = None
1752 datastart = None
1753 series = []
1753 series = []
1754 applied = []
1754 applied = []
1755 qpp = None
1755 qpp = None
1756 for i, line in enumerate(lines):
1756 for i, line in enumerate(lines):
1757 if line == 'Patch Data:':
1757 if line == 'Patch Data:':
1758 datastart = i + 1
1758 datastart = i + 1
1759 elif line.startswith('Dirstate:'):
1759 elif line.startswith('Dirstate:'):
1760 l = line.rstrip()
1760 l = line.rstrip()
1761 l = l[10:].split(' ')
1761 l = l[10:].split(' ')
1762 qpp = [bin(x) for x in l]
1762 qpp = [bin(x) for x in l]
1763 elif datastart is not None:
1763 elif datastart is not None:
1764 l = line.rstrip()
1764 l = line.rstrip()
1765 n, name = l.split(':', 1)
1765 n, name = l.split(':', 1)
1766 if n:
1766 if n:
1767 applied.append(statusentry(bin(n), name))
1767 applied.append(statusentry(bin(n), name))
1768 else:
1768 else:
1769 series.append(l)
1769 series.append(l)
1770 if datastart is None:
1770 if datastart is None:
1771 self.ui.warn(_("No saved patch data found\n"))
1771 self.ui.warn(_("No saved patch data found\n"))
1772 return 1
1772 return 1
1773 self.ui.warn(_("restoring status: %s\n") % lines[0])
1773 self.ui.warn(_("restoring status: %s\n") % lines[0])
1774 self.fullseries = series
1774 self.fullseries = series
1775 self.applied = applied
1775 self.applied = applied
1776 self.parseseries()
1776 self.parseseries()
1777 self.seriesdirty = True
1777 self.seriesdirty = True
1778 self.applieddirty = True
1778 self.applieddirty = True
1779 heads = repo.changelog.heads()
1779 heads = repo.changelog.heads()
1780 if delete:
1780 if delete:
1781 if rev not in heads:
1781 if rev not in heads:
1782 self.ui.warn(_("save entry has children, leaving it alone\n"))
1782 self.ui.warn(_("save entry has children, leaving it alone\n"))
1783 else:
1783 else:
1784 self.ui.warn(_("removing save entry %s\n") % short(rev))
1784 self.ui.warn(_("removing save entry %s\n") % short(rev))
1785 pp = repo.dirstate.parents()
1785 pp = repo.dirstate.parents()
1786 if rev in pp:
1786 if rev in pp:
1787 update = True
1787 update = True
1788 else:
1788 else:
1789 update = False
1789 update = False
1790 self.strip(repo, [rev], update=update, backup='strip')
1790 self.strip(repo, [rev], update=update, backup='strip')
1791 if qpp:
1791 if qpp:
1792 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1792 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1793 (short(qpp[0]), short(qpp[1])))
1793 (short(qpp[0]), short(qpp[1])))
1794 if qupdate:
1794 if qupdate:
1795 self.ui.status(_("updating queue directory\n"))
1795 self.ui.status(_("updating queue directory\n"))
1796 r = self.qrepo()
1796 r = self.qrepo()
1797 if not r:
1797 if not r:
1798 self.ui.warn(_("Unable to load queue repository\n"))
1798 self.ui.warn(_("Unable to load queue repository\n"))
1799 return 1
1799 return 1
1800 hg.clean(r, qpp[0])
1800 hg.clean(r, qpp[0])
1801
1801
1802 def save(self, repo, msg=None):
1802 def save(self, repo, msg=None):
1803 if not self.applied:
1803 if not self.applied:
1804 self.ui.warn(_("save: no patches applied, exiting\n"))
1804 self.ui.warn(_("save: no patches applied, exiting\n"))
1805 return 1
1805 return 1
1806 if self.issaveline(self.applied[-1]):
1806 if self.issaveline(self.applied[-1]):
1807 self.ui.warn(_("status is already saved\n"))
1807 self.ui.warn(_("status is already saved\n"))
1808 return 1
1808 return 1
1809
1809
1810 if not msg:
1810 if not msg:
1811 msg = _("hg patches saved state")
1811 msg = _("hg patches saved state")
1812 else:
1812 else:
1813 msg = "hg patches: " + msg.rstrip('\r\n')
1813 msg = "hg patches: " + msg.rstrip('\r\n')
1814 r = self.qrepo()
1814 r = self.qrepo()
1815 if r:
1815 if r:
1816 pp = r.dirstate.parents()
1816 pp = r.dirstate.parents()
1817 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1817 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1818 msg += "\n\nPatch Data:\n"
1818 msg += "\n\nPatch Data:\n"
1819 msg += ''.join('%s\n' % x for x in self.applied)
1819 msg += ''.join('%s\n' % x for x in self.applied)
1820 msg += ''.join(':%s\n' % x for x in self.fullseries)
1820 msg += ''.join(':%s\n' % x for x in self.fullseries)
1821 n = repo.commit(msg, force=True)
1821 n = repo.commit(msg, force=True)
1822 if not n:
1822 if not n:
1823 self.ui.warn(_("repo commit failed\n"))
1823 self.ui.warn(_("repo commit failed\n"))
1824 return 1
1824 return 1
1825 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1825 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1826 self.applieddirty = True
1826 self.applieddirty = True
1827 self.removeundo(repo)
1827 self.removeundo(repo)
1828
1828
1829 def fullseriesend(self):
1829 def fullseriesend(self):
1830 if self.applied:
1830 if self.applied:
1831 p = self.applied[-1].name
1831 p = self.applied[-1].name
1832 end = self.findseries(p)
1832 end = self.findseries(p)
1833 if end is None:
1833 if end is None:
1834 return len(self.fullseries)
1834 return len(self.fullseries)
1835 return end + 1
1835 return end + 1
1836 return 0
1836 return 0
1837
1837
1838 def seriesend(self, all_patches=False):
1838 def seriesend(self, all_patches=False):
1839 """If all_patches is False, return the index of the next pushable patch
1839 """If all_patches is False, return the index of the next pushable patch
1840 in the series, or the series length. If all_patches is True, return the
1840 in the series, or the series length. If all_patches is True, return the
1841 index of the first patch past the last applied one.
1841 index of the first patch past the last applied one.
1842 """
1842 """
1843 end = 0
1843 end = 0
1844 def next(start):
1844 def next(start):
1845 if all_patches or start >= len(self.series):
1845 if all_patches or start >= len(self.series):
1846 return start
1846 return start
1847 for i in xrange(start, len(self.series)):
1847 for i in xrange(start, len(self.series)):
1848 p, reason = self.pushable(i)
1848 p, reason = self.pushable(i)
1849 if p:
1849 if p:
1850 return i
1850 return i
1851 self.explainpushable(i)
1851 self.explainpushable(i)
1852 return len(self.series)
1852 return len(self.series)
1853 if self.applied:
1853 if self.applied:
1854 p = self.applied[-1].name
1854 p = self.applied[-1].name
1855 try:
1855 try:
1856 end = self.series.index(p)
1856 end = self.series.index(p)
1857 except ValueError:
1857 except ValueError:
1858 return 0
1858 return 0
1859 return next(end + 1)
1859 return next(end + 1)
1860 return next(end)
1860 return next(end)
1861
1861
1862 def appliedname(self, index):
1862 def appliedname(self, index):
1863 pname = self.applied[index].name
1863 pname = self.applied[index].name
1864 if not self.ui.verbose:
1864 if not self.ui.verbose:
1865 p = pname
1865 p = pname
1866 else:
1866 else:
1867 p = str(self.series.index(pname)) + " " + pname
1867 p = str(self.series.index(pname)) + " " + pname
1868 return p
1868 return p
1869
1869
1870 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1870 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1871 force=None, git=False):
1871 force=None, git=False):
1872 def checkseries(patchname):
1872 def checkseries(patchname):
1873 if patchname in self.series:
1873 if patchname in self.series:
1874 raise util.Abort(_('patch %s is already in the series file')
1874 raise util.Abort(_('patch %s is already in the series file')
1875 % patchname)
1875 % patchname)
1876
1876
1877 if rev:
1877 if rev:
1878 if files:
1878 if files:
1879 raise util.Abort(_('option "-r" not valid when importing '
1879 raise util.Abort(_('option "-r" not valid when importing '
1880 'files'))
1880 'files'))
1881 rev = scmutil.revrange(repo, rev)
1881 rev = scmutil.revrange(repo, rev)
1882 rev.sort(reverse=True)
1882 rev.sort(reverse=True)
1883 if (len(files) > 1 or len(rev) > 1) and patchname:
1883 if (len(files) > 1 or len(rev) > 1) and patchname:
1884 raise util.Abort(_('option "-n" not valid when importing multiple '
1884 raise util.Abort(_('option "-n" not valid when importing multiple '
1885 'patches'))
1885 'patches'))
1886 imported = []
1886 imported = []
1887 if rev:
1887 if rev:
1888 # If mq patches are applied, we can only import revisions
1888 # If mq patches are applied, we can only import revisions
1889 # that form a linear path to qbase.
1889 # that form a linear path to qbase.
1890 # Otherwise, they should form a linear path to a head.
1890 # Otherwise, they should form a linear path to a head.
1891 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1891 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1892 if len(heads) > 1:
1892 if len(heads) > 1:
1893 raise util.Abort(_('revision %d is the root of more than one '
1893 raise util.Abort(_('revision %d is the root of more than one '
1894 'branch') % rev[-1])
1894 'branch') % rev[-1])
1895 if self.applied:
1895 if self.applied:
1896 base = repo.changelog.node(rev[0])
1896 base = repo.changelog.node(rev[0])
1897 if base in [n.node for n in self.applied]:
1897 if base in [n.node for n in self.applied]:
1898 raise util.Abort(_('revision %d is already managed')
1898 raise util.Abort(_('revision %d is already managed')
1899 % rev[0])
1899 % rev[0])
1900 if heads != [self.applied[-1].node]:
1900 if heads != [self.applied[-1].node]:
1901 raise util.Abort(_('revision %d is not the parent of '
1901 raise util.Abort(_('revision %d is not the parent of '
1902 'the queue') % rev[0])
1902 'the queue') % rev[0])
1903 base = repo.changelog.rev(self.applied[0].node)
1903 base = repo.changelog.rev(self.applied[0].node)
1904 lastparent = repo.changelog.parentrevs(base)[0]
1904 lastparent = repo.changelog.parentrevs(base)[0]
1905 else:
1905 else:
1906 if heads != [repo.changelog.node(rev[0])]:
1906 if heads != [repo.changelog.node(rev[0])]:
1907 raise util.Abort(_('revision %d has unmanaged children')
1907 raise util.Abort(_('revision %d has unmanaged children')
1908 % rev[0])
1908 % rev[0])
1909 lastparent = None
1909 lastparent = None
1910
1910
1911 diffopts = self.diffopts({'git': git})
1911 diffopts = self.diffopts({'git': git})
1912 for r in rev:
1912 for r in rev:
1913 if not repo[r].mutable():
1913 if not repo[r].mutable():
1914 raise util.Abort(_('revision %d is not mutable') % r,
1914 raise util.Abort(_('revision %d is not mutable') % r,
1915 hint=_('see "hg help phases" for details'))
1915 hint=_('see "hg help phases" for details'))
1916 p1, p2 = repo.changelog.parentrevs(r)
1916 p1, p2 = repo.changelog.parentrevs(r)
1917 n = repo.changelog.node(r)
1917 n = repo.changelog.node(r)
1918 if p2 != nullrev:
1918 if p2 != nullrev:
1919 raise util.Abort(_('cannot import merge revision %d') % r)
1919 raise util.Abort(_('cannot import merge revision %d') % r)
1920 if lastparent and lastparent != r:
1920 if lastparent and lastparent != r:
1921 raise util.Abort(_('revision %d is not the parent of %d')
1921 raise util.Abort(_('revision %d is not the parent of %d')
1922 % (r, lastparent))
1922 % (r, lastparent))
1923 lastparent = p1
1923 lastparent = p1
1924
1924
1925 if not patchname:
1925 if not patchname:
1926 patchname = normname('%d.diff' % r)
1926 patchname = normname('%d.diff' % r)
1927 checkseries(patchname)
1927 checkseries(patchname)
1928 self.checkpatchname(patchname, force)
1928 self.checkpatchname(patchname, force)
1929 self.fullseries.insert(0, patchname)
1929 self.fullseries.insert(0, patchname)
1930
1930
1931 patchf = self.opener(patchname, "w")
1931 patchf = self.opener(patchname, "w")
1932 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1932 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1933 patchf.close()
1933 patchf.close()
1934
1934
1935 se = statusentry(n, patchname)
1935 se = statusentry(n, patchname)
1936 self.applied.insert(0, se)
1936 self.applied.insert(0, se)
1937
1937
1938 self.added.append(patchname)
1938 self.added.append(patchname)
1939 imported.append(patchname)
1939 imported.append(patchname)
1940 patchname = None
1940 patchname = None
1941 if rev and repo.ui.configbool('mq', 'secret', False):
1941 if rev and repo.ui.configbool('mq', 'secret', False):
1942 # if we added anything with --rev, we must move the secret root
1942 # if we added anything with --rev, we must move the secret root
1943 phases.retractboundary(repo, phases.secret, [n])
1943 phases.retractboundary(repo, phases.secret, [n])
1944 self.parseseries()
1944 self.parseseries()
1945 self.applieddirty = True
1945 self.applieddirty = True
1946 self.seriesdirty = True
1946 self.seriesdirty = True
1947
1947
1948 for i, filename in enumerate(files):
1948 for i, filename in enumerate(files):
1949 if existing:
1949 if existing:
1950 if filename == '-':
1950 if filename == '-':
1951 raise util.Abort(_('-e is incompatible with import from -'))
1951 raise util.Abort(_('-e is incompatible with import from -'))
1952 filename = normname(filename)
1952 filename = normname(filename)
1953 self.checkreservedname(filename)
1953 self.checkreservedname(filename)
1954 originpath = self.join(filename)
1954 originpath = self.join(filename)
1955 if not os.path.isfile(originpath):
1955 if not os.path.isfile(originpath):
1956 raise util.Abort(_("patch %s does not exist") % filename)
1956 raise util.Abort(_("patch %s does not exist") % filename)
1957
1957
1958 if patchname:
1958 if patchname:
1959 self.checkpatchname(patchname, force)
1959 self.checkpatchname(patchname, force)
1960
1960
1961 self.ui.write(_('renaming %s to %s\n')
1961 self.ui.write(_('renaming %s to %s\n')
1962 % (filename, patchname))
1962 % (filename, patchname))
1963 util.rename(originpath, self.join(patchname))
1963 util.rename(originpath, self.join(patchname))
1964 else:
1964 else:
1965 patchname = filename
1965 patchname = filename
1966
1966
1967 else:
1967 else:
1968 if filename == '-' and not patchname:
1968 if filename == '-' and not patchname:
1969 raise util.Abort(_('need --name to import a patch from -'))
1969 raise util.Abort(_('need --name to import a patch from -'))
1970 elif not patchname:
1970 elif not patchname:
1971 patchname = normname(os.path.basename(filename.rstrip('/')))
1971 patchname = normname(os.path.basename(filename.rstrip('/')))
1972 self.checkpatchname(patchname, force)
1972 self.checkpatchname(patchname, force)
1973 try:
1973 try:
1974 if filename == '-':
1974 if filename == '-':
1975 text = self.ui.fin.read()
1975 text = self.ui.fin.read()
1976 else:
1976 else:
1977 fp = url.open(self.ui, filename)
1977 fp = url.open(self.ui, filename)
1978 text = fp.read()
1978 text = fp.read()
1979 fp.close()
1979 fp.close()
1980 except (OSError, IOError):
1980 except (OSError, IOError):
1981 raise util.Abort(_("unable to read file %s") % filename)
1981 raise util.Abort(_("unable to read file %s") % filename)
1982 patchf = self.opener(patchname, "w")
1982 patchf = self.opener(patchname, "w")
1983 patchf.write(text)
1983 patchf.write(text)
1984 patchf.close()
1984 patchf.close()
1985 if not force:
1985 if not force:
1986 checkseries(patchname)
1986 checkseries(patchname)
1987 if patchname not in self.series:
1987 if patchname not in self.series:
1988 index = self.fullseriesend() + i
1988 index = self.fullseriesend() + i
1989 self.fullseries[index:index] = [patchname]
1989 self.fullseries[index:index] = [patchname]
1990 self.parseseries()
1990 self.parseseries()
1991 self.seriesdirty = True
1991 self.seriesdirty = True
1992 self.ui.warn(_("adding %s to series file\n") % patchname)
1992 self.ui.warn(_("adding %s to series file\n") % patchname)
1993 self.added.append(patchname)
1993 self.added.append(patchname)
1994 imported.append(patchname)
1994 imported.append(patchname)
1995 patchname = None
1995 patchname = None
1996
1996
1997 self.removeundo(repo)
1997 self.removeundo(repo)
1998 return imported
1998 return imported
1999
1999
2000 def fixcheckopts(ui, opts):
2000 def fixcheckopts(ui, opts):
2001 if (not ui.configbool('mq', 'check') or opts.get('force')
2001 if (not ui.configbool('mq', 'check') or opts.get('force')
2002 or opts.get('exact')):
2002 or opts.get('exact')):
2003 return opts
2003 return opts
2004 opts = dict(opts)
2004 opts = dict(opts)
2005 opts['check'] = True
2005 opts['check'] = True
2006 return opts
2006 return opts
2007
2007
2008 @command("qdelete|qremove|qrm",
2008 @command("qdelete|qremove|qrm",
2009 [('k', 'keep', None, _('keep patch file')),
2009 [('k', 'keep', None, _('keep patch file')),
2010 ('r', 'rev', [],
2010 ('r', 'rev', [],
2011 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2011 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2012 _('hg qdelete [-k] [PATCH]...'))
2012 _('hg qdelete [-k] [PATCH]...'))
2013 def delete(ui, repo, *patches, **opts):
2013 def delete(ui, repo, *patches, **opts):
2014 """remove patches from queue
2014 """remove patches from queue
2015
2015
2016 The patches must not be applied, and at least one patch is required. Exact
2016 The patches must not be applied, and at least one patch is required. Exact
2017 patch identifiers must be given. With -k/--keep, the patch files are
2017 patch identifiers must be given. With -k/--keep, the patch files are
2018 preserved in the patch directory.
2018 preserved in the patch directory.
2019
2019
2020 To stop managing a patch and move it into permanent history,
2020 To stop managing a patch and move it into permanent history,
2021 use the :hg:`qfinish` command."""
2021 use the :hg:`qfinish` command."""
2022 q = repo.mq
2022 q = repo.mq
2023 q.delete(repo, patches, opts)
2023 q.delete(repo, patches, opts)
2024 q.savedirty()
2024 q.savedirty()
2025 return 0
2025 return 0
2026
2026
2027 @command("qapplied",
2027 @command("qapplied",
2028 [('1', 'last', None, _('show only the preceding applied patch'))
2028 [('1', 'last', None, _('show only the preceding applied patch'))
2029 ] + seriesopts,
2029 ] + seriesopts,
2030 _('hg qapplied [-1] [-s] [PATCH]'))
2030 _('hg qapplied [-1] [-s] [PATCH]'))
2031 def applied(ui, repo, patch=None, **opts):
2031 def applied(ui, repo, patch=None, **opts):
2032 """print the patches already applied
2032 """print the patches already applied
2033
2033
2034 Returns 0 on success."""
2034 Returns 0 on success."""
2035
2035
2036 q = repo.mq
2036 q = repo.mq
2037
2037
2038 if patch:
2038 if patch:
2039 if patch not in q.series:
2039 if patch not in q.series:
2040 raise util.Abort(_("patch %s is not in series file") % patch)
2040 raise util.Abort(_("patch %s is not in series file") % patch)
2041 end = q.series.index(patch) + 1
2041 end = q.series.index(patch) + 1
2042 else:
2042 else:
2043 end = q.seriesend(True)
2043 end = q.seriesend(True)
2044
2044
2045 if opts.get('last') and not end:
2045 if opts.get('last') and not end:
2046 ui.write(_("no patches applied\n"))
2046 ui.write(_("no patches applied\n"))
2047 return 1
2047 return 1
2048 elif opts.get('last') and end == 1:
2048 elif opts.get('last') and end == 1:
2049 ui.write(_("only one patch applied\n"))
2049 ui.write(_("only one patch applied\n"))
2050 return 1
2050 return 1
2051 elif opts.get('last'):
2051 elif opts.get('last'):
2052 start = end - 2
2052 start = end - 2
2053 end = 1
2053 end = 1
2054 else:
2054 else:
2055 start = 0
2055 start = 0
2056
2056
2057 q.qseries(repo, length=end, start=start, status='A',
2057 q.qseries(repo, length=end, start=start, status='A',
2058 summary=opts.get('summary'))
2058 summary=opts.get('summary'))
2059
2059
2060
2060
2061 @command("qunapplied",
2061 @command("qunapplied",
2062 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2062 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2063 _('hg qunapplied [-1] [-s] [PATCH]'))
2063 _('hg qunapplied [-1] [-s] [PATCH]'))
2064 def unapplied(ui, repo, patch=None, **opts):
2064 def unapplied(ui, repo, patch=None, **opts):
2065 """print the patches not yet applied
2065 """print the patches not yet applied
2066
2066
2067 Returns 0 on success."""
2067 Returns 0 on success."""
2068
2068
2069 q = repo.mq
2069 q = repo.mq
2070 if patch:
2070 if patch:
2071 if patch not in q.series:
2071 if patch not in q.series:
2072 raise util.Abort(_("patch %s is not in series file") % patch)
2072 raise util.Abort(_("patch %s is not in series file") % patch)
2073 start = q.series.index(patch) + 1
2073 start = q.series.index(patch) + 1
2074 else:
2074 else:
2075 start = q.seriesend(True)
2075 start = q.seriesend(True)
2076
2076
2077 if start == len(q.series) and opts.get('first'):
2077 if start == len(q.series) and opts.get('first'):
2078 ui.write(_("all patches applied\n"))
2078 ui.write(_("all patches applied\n"))
2079 return 1
2079 return 1
2080
2080
2081 length = opts.get('first') and 1 or None
2081 length = opts.get('first') and 1 or None
2082 q.qseries(repo, start=start, length=length, status='U',
2082 q.qseries(repo, start=start, length=length, status='U',
2083 summary=opts.get('summary'))
2083 summary=opts.get('summary'))
2084
2084
2085 @command("qimport",
2085 @command("qimport",
2086 [('e', 'existing', None, _('import file in patch directory')),
2086 [('e', 'existing', None, _('import file in patch directory')),
2087 ('n', 'name', '',
2087 ('n', 'name', '',
2088 _('name of patch file'), _('NAME')),
2088 _('name of patch file'), _('NAME')),
2089 ('f', 'force', None, _('overwrite existing files')),
2089 ('f', 'force', None, _('overwrite existing files')),
2090 ('r', 'rev', [],
2090 ('r', 'rev', [],
2091 _('place existing revisions under mq control'), _('REV')),
2091 _('place existing revisions under mq control'), _('REV')),
2092 ('g', 'git', None, _('use git extended diff format')),
2092 ('g', 'git', None, _('use git extended diff format')),
2093 ('P', 'push', None, _('qpush after importing'))],
2093 ('P', 'push', None, _('qpush after importing'))],
2094 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
2094 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
2095 def qimport(ui, repo, *filename, **opts):
2095 def qimport(ui, repo, *filename, **opts):
2096 """import a patch or existing changeset
2096 """import a patch or existing changeset
2097
2097
2098 The patch is inserted into the series after the last applied
2098 The patch is inserted into the series after the last applied
2099 patch. If no patches have been applied, qimport prepends the patch
2099 patch. If no patches have been applied, qimport prepends the patch
2100 to the series.
2100 to the series.
2101
2101
2102 The patch will have the same name as its source file unless you
2102 The patch will have the same name as its source file unless you
2103 give it a new one with -n/--name.
2103 give it a new one with -n/--name.
2104
2104
2105 You can register an existing patch inside the patch directory with
2105 You can register an existing patch inside the patch directory with
2106 the -e/--existing flag.
2106 the -e/--existing flag.
2107
2107
2108 With -f/--force, an existing patch of the same name will be
2108 With -f/--force, an existing patch of the same name will be
2109 overwritten.
2109 overwritten.
2110
2110
2111 An existing changeset may be placed under mq control with -r/--rev
2111 An existing changeset may be placed under mq control with -r/--rev
2112 (e.g. qimport --rev tip -n patch will place tip under mq control).
2112 (e.g. qimport --rev tip -n patch will place tip under mq control).
2113 With -g/--git, patches imported with --rev will use the git diff
2113 With -g/--git, patches imported with --rev will use the git diff
2114 format. See the diffs help topic for information on why this is
2114 format. See the diffs help topic for information on why this is
2115 important for preserving rename/copy information and permission
2115 important for preserving rename/copy information and permission
2116 changes. Use :hg:`qfinish` to remove changesets from mq control.
2116 changes. Use :hg:`qfinish` to remove changesets from mq control.
2117
2117
2118 To import a patch from standard input, pass - as the patch file.
2118 To import a patch from standard input, pass - as the patch file.
2119 When importing from standard input, a patch name must be specified
2119 When importing from standard input, a patch name must be specified
2120 using the --name flag.
2120 using the --name flag.
2121
2121
2122 To import an existing patch while renaming it::
2122 To import an existing patch while renaming it::
2123
2123
2124 hg qimport -e existing-patch -n new-name
2124 hg qimport -e existing-patch -n new-name
2125
2125
2126 Returns 0 if import succeeded.
2126 Returns 0 if import succeeded.
2127 """
2127 """
2128 lock = repo.lock() # cause this may move phase
2128 lock = repo.lock() # cause this may move phase
2129 try:
2129 try:
2130 q = repo.mq
2130 q = repo.mq
2131 try:
2131 try:
2132 imported = q.qimport(
2132 imported = q.qimport(
2133 repo, filename, patchname=opts.get('name'),
2133 repo, filename, patchname=opts.get('name'),
2134 existing=opts.get('existing'), force=opts.get('force'),
2134 existing=opts.get('existing'), force=opts.get('force'),
2135 rev=opts.get('rev'), git=opts.get('git'))
2135 rev=opts.get('rev'), git=opts.get('git'))
2136 finally:
2136 finally:
2137 q.savedirty()
2137 q.savedirty()
2138
2138
2139
2139
2140 if imported and opts.get('push') and not opts.get('rev'):
2140 if imported and opts.get('push') and not opts.get('rev'):
2141 return q.push(repo, imported[-1])
2141 return q.push(repo, imported[-1])
2142 finally:
2142 finally:
2143 lock.release()
2143 lock.release()
2144 return 0
2144 return 0
2145
2145
2146 def qinit(ui, repo, create):
2146 def qinit(ui, repo, create):
2147 """initialize a new queue repository
2147 """initialize a new queue repository
2148
2148
2149 This command also creates a series file for ordering patches, and
2149 This command also creates a series file for ordering patches, and
2150 an mq-specific .hgignore file in the queue repository, to exclude
2150 an mq-specific .hgignore file in the queue repository, to exclude
2151 the status and guards files (these contain mostly transient state).
2151 the status and guards files (these contain mostly transient state).
2152
2152
2153 Returns 0 if initialization succeeded."""
2153 Returns 0 if initialization succeeded."""
2154 q = repo.mq
2154 q = repo.mq
2155 r = q.init(repo, create)
2155 r = q.init(repo, create)
2156 q.savedirty()
2156 q.savedirty()
2157 if r:
2157 if r:
2158 if not os.path.exists(r.wjoin('.hgignore')):
2158 if not os.path.exists(r.wjoin('.hgignore')):
2159 fp = r.wopener('.hgignore', 'w')
2159 fp = r.wopener('.hgignore', 'w')
2160 fp.write('^\\.hg\n')
2160 fp.write('^\\.hg\n')
2161 fp.write('^\\.mq\n')
2161 fp.write('^\\.mq\n')
2162 fp.write('syntax: glob\n')
2162 fp.write('syntax: glob\n')
2163 fp.write('status\n')
2163 fp.write('status\n')
2164 fp.write('guards\n')
2164 fp.write('guards\n')
2165 fp.close()
2165 fp.close()
2166 if not os.path.exists(r.wjoin('series')):
2166 if not os.path.exists(r.wjoin('series')):
2167 r.wopener('series', 'w').close()
2167 r.wopener('series', 'w').close()
2168 r[None].add(['.hgignore', 'series'])
2168 r[None].add(['.hgignore', 'series'])
2169 commands.add(ui, r)
2169 commands.add(ui, r)
2170 return 0
2170 return 0
2171
2171
2172 @command("^qinit",
2172 @command("^qinit",
2173 [('c', 'create-repo', None, _('create queue repository'))],
2173 [('c', 'create-repo', None, _('create queue repository'))],
2174 _('hg qinit [-c]'))
2174 _('hg qinit [-c]'))
2175 def init(ui, repo, **opts):
2175 def init(ui, repo, **opts):
2176 """init a new queue repository (DEPRECATED)
2176 """init a new queue repository (DEPRECATED)
2177
2177
2178 The queue repository is unversioned by default. If
2178 The queue repository is unversioned by default. If
2179 -c/--create-repo is specified, qinit will create a separate nested
2179 -c/--create-repo is specified, qinit will create a separate nested
2180 repository for patches (qinit -c may also be run later to convert
2180 repository for patches (qinit -c may also be run later to convert
2181 an unversioned patch repository into a versioned one). You can use
2181 an unversioned patch repository into a versioned one). You can use
2182 qcommit to commit changes to this queue repository.
2182 qcommit to commit changes to this queue repository.
2183
2183
2184 This command is deprecated. Without -c, it's implied by other relevant
2184 This command is deprecated. Without -c, it's implied by other relevant
2185 commands. With -c, use :hg:`init --mq` instead."""
2185 commands. With -c, use :hg:`init --mq` instead."""
2186 return qinit(ui, repo, create=opts.get('create_repo'))
2186 return qinit(ui, repo, create=opts.get('create_repo'))
2187
2187
2188 @command("qclone",
2188 @command("qclone",
2189 [('', 'pull', None, _('use pull protocol to copy metadata')),
2189 [('', 'pull', None, _('use pull protocol to copy metadata')),
2190 ('U', 'noupdate', None, _('do not update the new working directories')),
2190 ('U', 'noupdate', None, _('do not update the new working directories')),
2191 ('', 'uncompressed', None,
2191 ('', 'uncompressed', None,
2192 _('use uncompressed transfer (fast over LAN)')),
2192 _('use uncompressed transfer (fast over LAN)')),
2193 ('p', 'patches', '',
2193 ('p', 'patches', '',
2194 _('location of source patch repository'), _('REPO')),
2194 _('location of source patch repository'), _('REPO')),
2195 ] + commands.remoteopts,
2195 ] + commands.remoteopts,
2196 _('hg qclone [OPTION]... SOURCE [DEST]'))
2196 _('hg qclone [OPTION]... SOURCE [DEST]'))
2197 def clone(ui, source, dest=None, **opts):
2197 def clone(ui, source, dest=None, **opts):
2198 '''clone main and patch repository at same time
2198 '''clone main and patch repository at same time
2199
2199
2200 If source is local, destination will have no patches applied. If
2200 If source is local, destination will have no patches applied. If
2201 source is remote, this command can not check if patches are
2201 source is remote, this command can not check if patches are
2202 applied in source, so cannot guarantee that patches are not
2202 applied in source, so cannot guarantee that patches are not
2203 applied in destination. If you clone remote repository, be sure
2203 applied in destination. If you clone remote repository, be sure
2204 before that it has no patches applied.
2204 before that it has no patches applied.
2205
2205
2206 Source patch repository is looked for in <src>/.hg/patches by
2206 Source patch repository is looked for in <src>/.hg/patches by
2207 default. Use -p <url> to change.
2207 default. Use -p <url> to change.
2208
2208
2209 The patch directory must be a nested Mercurial repository, as
2209 The patch directory must be a nested Mercurial repository, as
2210 would be created by :hg:`init --mq`.
2210 would be created by :hg:`init --mq`.
2211
2211
2212 Return 0 on success.
2212 Return 0 on success.
2213 '''
2213 '''
2214 def patchdir(repo):
2214 def patchdir(repo):
2215 """compute a patch repo url from a repo object"""
2215 """compute a patch repo url from a repo object"""
2216 url = repo.url()
2216 url = repo.url()
2217 if url.endswith('/'):
2217 if url.endswith('/'):
2218 url = url[:-1]
2218 url = url[:-1]
2219 return url + '/.hg/patches'
2219 return url + '/.hg/patches'
2220
2220
2221 # main repo (destination and sources)
2221 # main repo (destination and sources)
2222 if dest is None:
2222 if dest is None:
2223 dest = hg.defaultdest(source)
2223 dest = hg.defaultdest(source)
2224 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2224 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2225
2225
2226 # patches repo (source only)
2226 # patches repo (source only)
2227 if opts.get('patches'):
2227 if opts.get('patches'):
2228 patchespath = ui.expandpath(opts.get('patches'))
2228 patchespath = ui.expandpath(opts.get('patches'))
2229 else:
2229 else:
2230 patchespath = patchdir(sr)
2230 patchespath = patchdir(sr)
2231 try:
2231 try:
2232 hg.repository(ui, patchespath)
2232 hg.repository(ui, patchespath)
2233 except error.RepoError:
2233 except error.RepoError:
2234 raise util.Abort(_('versioned patch repository not found'
2234 raise util.Abort(_('versioned patch repository not found'
2235 ' (see init --mq)'))
2235 ' (see init --mq)'))
2236 qbase, destrev = None, None
2236 qbase, destrev = None, None
2237 if sr.local():
2237 if sr.local():
2238 if sr.mq.applied and sr[qbase].phase() != phases.secret:
2238 if sr.mq.applied and sr[qbase].phase() != phases.secret:
2239 qbase = sr.mq.applied[0].node
2239 qbase = sr.mq.applied[0].node
2240 if not hg.islocal(dest):
2240 if not hg.islocal(dest):
2241 heads = set(sr.heads())
2241 heads = set(sr.heads())
2242 destrev = list(heads.difference(sr.heads(qbase)))
2242 destrev = list(heads.difference(sr.heads(qbase)))
2243 destrev.append(sr.changelog.parents(qbase)[0])
2243 destrev.append(sr.changelog.parents(qbase)[0])
2244 elif sr.capable('lookup'):
2244 elif sr.capable('lookup'):
2245 try:
2245 try:
2246 qbase = sr.lookup('qbase')
2246 qbase = sr.lookup('qbase')
2247 except error.RepoError:
2247 except error.RepoError:
2248 pass
2248 pass
2249
2249
2250 ui.note(_('cloning main repository\n'))
2250 ui.note(_('cloning main repository\n'))
2251 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2251 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2252 pull=opts.get('pull'),
2252 pull=opts.get('pull'),
2253 rev=destrev,
2253 rev=destrev,
2254 update=False,
2254 update=False,
2255 stream=opts.get('uncompressed'))
2255 stream=opts.get('uncompressed'))
2256
2256
2257 ui.note(_('cloning patch repository\n'))
2257 ui.note(_('cloning patch repository\n'))
2258 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2258 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2259 pull=opts.get('pull'), update=not opts.get('noupdate'),
2259 pull=opts.get('pull'), update=not opts.get('noupdate'),
2260 stream=opts.get('uncompressed'))
2260 stream=opts.get('uncompressed'))
2261
2261
2262 if dr.local():
2262 if dr.local():
2263 if qbase:
2263 if qbase:
2264 ui.note(_('stripping applied patches from destination '
2264 ui.note(_('stripping applied patches from destination '
2265 'repository\n'))
2265 'repository\n'))
2266 dr.mq.strip(dr, [qbase], update=False, backup=None)
2266 dr.mq.strip(dr, [qbase], update=False, backup=None)
2267 if not opts.get('noupdate'):
2267 if not opts.get('noupdate'):
2268 ui.note(_('updating destination repository\n'))
2268 ui.note(_('updating destination repository\n'))
2269 hg.update(dr, dr.changelog.tip())
2269 hg.update(dr, dr.changelog.tip())
2270
2270
2271 @command("qcommit|qci",
2271 @command("qcommit|qci",
2272 commands.table["^commit|ci"][1],
2272 commands.table["^commit|ci"][1],
2273 _('hg qcommit [OPTION]... [FILE]...'))
2273 _('hg qcommit [OPTION]... [FILE]...'))
2274 def commit(ui, repo, *pats, **opts):
2274 def commit(ui, repo, *pats, **opts):
2275 """commit changes in the queue repository (DEPRECATED)
2275 """commit changes in the queue repository (DEPRECATED)
2276
2276
2277 This command is deprecated; use :hg:`commit --mq` instead."""
2277 This command is deprecated; use :hg:`commit --mq` instead."""
2278 q = repo.mq
2278 q = repo.mq
2279 r = q.qrepo()
2279 r = q.qrepo()
2280 if not r:
2280 if not r:
2281 raise util.Abort('no queue repository')
2281 raise util.Abort('no queue repository')
2282 commands.commit(r.ui, r, *pats, **opts)
2282 commands.commit(r.ui, r, *pats, **opts)
2283
2283
2284 @command("qseries",
2284 @command("qseries",
2285 [('m', 'missing', None, _('print patches not in series')),
2285 [('m', 'missing', None, _('print patches not in series')),
2286 ] + seriesopts,
2286 ] + seriesopts,
2287 _('hg qseries [-ms]'))
2287 _('hg qseries [-ms]'))
2288 def series(ui, repo, **opts):
2288 def series(ui, repo, **opts):
2289 """print the entire series file
2289 """print the entire series file
2290
2290
2291 Returns 0 on success."""
2291 Returns 0 on success."""
2292 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2292 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2293 return 0
2293 return 0
2294
2294
2295 @command("qtop", seriesopts, _('hg qtop [-s]'))
2295 @command("qtop", seriesopts, _('hg qtop [-s]'))
2296 def top(ui, repo, **opts):
2296 def top(ui, repo, **opts):
2297 """print the name of the current patch
2297 """print the name of the current patch
2298
2298
2299 Returns 0 on success."""
2299 Returns 0 on success."""
2300 q = repo.mq
2300 q = repo.mq
2301 t = q.applied and q.seriesend(True) or 0
2301 t = q.applied and q.seriesend(True) or 0
2302 if t:
2302 if t:
2303 q.qseries(repo, start=t - 1, length=1, status='A',
2303 q.qseries(repo, start=t - 1, length=1, status='A',
2304 summary=opts.get('summary'))
2304 summary=opts.get('summary'))
2305 else:
2305 else:
2306 ui.write(_("no patches applied\n"))
2306 ui.write(_("no patches applied\n"))
2307 return 1
2307 return 1
2308
2308
2309 @command("qnext", seriesopts, _('hg qnext [-s]'))
2309 @command("qnext", seriesopts, _('hg qnext [-s]'))
2310 def next(ui, repo, **opts):
2310 def next(ui, repo, **opts):
2311 """print the name of the next pushable patch
2311 """print the name of the next pushable patch
2312
2312
2313 Returns 0 on success."""
2313 Returns 0 on success."""
2314 q = repo.mq
2314 q = repo.mq
2315 end = q.seriesend()
2315 end = q.seriesend()
2316 if end == len(q.series):
2316 if end == len(q.series):
2317 ui.write(_("all patches applied\n"))
2317 ui.write(_("all patches applied\n"))
2318 return 1
2318 return 1
2319 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2319 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2320
2320
2321 @command("qprev", seriesopts, _('hg qprev [-s]'))
2321 @command("qprev", seriesopts, _('hg qprev [-s]'))
2322 def prev(ui, repo, **opts):
2322 def prev(ui, repo, **opts):
2323 """print the name of the preceding applied patch
2323 """print the name of the preceding applied patch
2324
2324
2325 Returns 0 on success."""
2325 Returns 0 on success."""
2326 q = repo.mq
2326 q = repo.mq
2327 l = len(q.applied)
2327 l = len(q.applied)
2328 if l == 1:
2328 if l == 1:
2329 ui.write(_("only one patch applied\n"))
2329 ui.write(_("only one patch applied\n"))
2330 return 1
2330 return 1
2331 if not l:
2331 if not l:
2332 ui.write(_("no patches applied\n"))
2332 ui.write(_("no patches applied\n"))
2333 return 1
2333 return 1
2334 idx = q.series.index(q.applied[-2].name)
2334 idx = q.series.index(q.applied[-2].name)
2335 q.qseries(repo, start=idx, length=1, status='A',
2335 q.qseries(repo, start=idx, length=1, status='A',
2336 summary=opts.get('summary'))
2336 summary=opts.get('summary'))
2337
2337
2338 def setupheaderopts(ui, opts):
2338 def setupheaderopts(ui, opts):
2339 if not opts.get('user') and opts.get('currentuser'):
2339 if not opts.get('user') and opts.get('currentuser'):
2340 opts['user'] = ui.username()
2340 opts['user'] = ui.username()
2341 if not opts.get('date') and opts.get('currentdate'):
2341 if not opts.get('date') and opts.get('currentdate'):
2342 opts['date'] = "%d %d" % util.makedate()
2342 opts['date'] = "%d %d" % util.makedate()
2343
2343
2344 @command("^qnew",
2344 @command("^qnew",
2345 [('e', 'edit', None, _('edit commit message')),
2345 [('e', 'edit', None, _('edit commit message')),
2346 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2346 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2347 ('g', 'git', None, _('use git extended diff format')),
2347 ('g', 'git', None, _('use git extended diff format')),
2348 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2348 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2349 ('u', 'user', '',
2349 ('u', 'user', '',
2350 _('add "From: <USER>" to patch'), _('USER')),
2350 _('add "From: <USER>" to patch'), _('USER')),
2351 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2351 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2352 ('d', 'date', '',
2352 ('d', 'date', '',
2353 _('add "Date: <DATE>" to patch'), _('DATE'))
2353 _('add "Date: <DATE>" to patch'), _('DATE'))
2354 ] + commands.walkopts + commands.commitopts,
2354 ] + commands.walkopts + commands.commitopts,
2355 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2355 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2356 def new(ui, repo, patch, *args, **opts):
2356 def new(ui, repo, patch, *args, **opts):
2357 """create a new patch
2357 """create a new patch
2358
2358
2359 qnew creates a new patch on top of the currently-applied patch (if
2359 qnew creates a new patch on top of the currently-applied patch (if
2360 any). The patch will be initialized with any outstanding changes
2360 any). The patch will be initialized with any outstanding changes
2361 in the working directory. You may also use -I/--include,
2361 in the working directory. You may also use -I/--include,
2362 -X/--exclude, and/or a list of files after the patch name to add
2362 -X/--exclude, and/or a list of files after the patch name to add
2363 only changes to matching files to the new patch, leaving the rest
2363 only changes to matching files to the new patch, leaving the rest
2364 as uncommitted modifications.
2364 as uncommitted modifications.
2365
2365
2366 -u/--user and -d/--date can be used to set the (given) user and
2366 -u/--user and -d/--date can be used to set the (given) user and
2367 date, respectively. -U/--currentuser and -D/--currentdate set user
2367 date, respectively. -U/--currentuser and -D/--currentdate set user
2368 to current user and date to current date.
2368 to current user and date to current date.
2369
2369
2370 -e/--edit, -m/--message or -l/--logfile set the patch header as
2370 -e/--edit, -m/--message or -l/--logfile set the patch header as
2371 well as the commit message. If none is specified, the header is
2371 well as the commit message. If none is specified, the header is
2372 empty and the commit message is '[mq]: PATCH'.
2372 empty and the commit message is '[mq]: PATCH'.
2373
2373
2374 Use the -g/--git option to keep the patch in the git extended diff
2374 Use the -g/--git option to keep the patch in the git extended diff
2375 format. Read the diffs help topic for more information on why this
2375 format. Read the diffs help topic for more information on why this
2376 is important for preserving permission changes and copy/rename
2376 is important for preserving permission changes and copy/rename
2377 information.
2377 information.
2378
2378
2379 Returns 0 on successful creation of a new patch.
2379 Returns 0 on successful creation of a new patch.
2380 """
2380 """
2381 msg = cmdutil.logmessage(ui, opts)
2381 msg = cmdutil.logmessage(ui, opts)
2382 def getmsg():
2382 def getmsg():
2383 return ui.edit(msg, opts.get('user') or ui.username())
2383 return ui.edit(msg, opts.get('user') or ui.username())
2384 q = repo.mq
2384 q = repo.mq
2385 opts['msg'] = msg
2385 opts['msg'] = msg
2386 if opts.get('edit'):
2386 if opts.get('edit'):
2387 opts['msg'] = getmsg
2387 opts['msg'] = getmsg
2388 else:
2388 else:
2389 opts['msg'] = msg
2389 opts['msg'] = msg
2390 setupheaderopts(ui, opts)
2390 setupheaderopts(ui, opts)
2391 q.new(repo, patch, *args, **opts)
2391 q.new(repo, patch, *args, **opts)
2392 q.savedirty()
2392 q.savedirty()
2393 return 0
2393 return 0
2394
2394
2395 @command("^qrefresh",
2395 @command("^qrefresh",
2396 [('e', 'edit', None, _('edit commit message')),
2396 [('e', 'edit', None, _('edit commit message')),
2397 ('g', 'git', None, _('use git extended diff format')),
2397 ('g', 'git', None, _('use git extended diff format')),
2398 ('s', 'short', None,
2398 ('s', 'short', None,
2399 _('refresh only files already in the patch and specified files')),
2399 _('refresh only files already in the patch and specified files')),
2400 ('U', 'currentuser', None,
2400 ('U', 'currentuser', None,
2401 _('add/update author field in patch with current user')),
2401 _('add/update author field in patch with current user')),
2402 ('u', 'user', '',
2402 ('u', 'user', '',
2403 _('add/update author field in patch with given user'), _('USER')),
2403 _('add/update author field in patch with given user'), _('USER')),
2404 ('D', 'currentdate', None,
2404 ('D', 'currentdate', None,
2405 _('add/update date field in patch with current date')),
2405 _('add/update date field in patch with current date')),
2406 ('d', 'date', '',
2406 ('d', 'date', '',
2407 _('add/update date field in patch with given date'), _('DATE'))
2407 _('add/update date field in patch with given date'), _('DATE'))
2408 ] + commands.walkopts + commands.commitopts,
2408 ] + commands.walkopts + commands.commitopts,
2409 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2409 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2410 def refresh(ui, repo, *pats, **opts):
2410 def refresh(ui, repo, *pats, **opts):
2411 """update the current patch
2411 """update the current patch
2412
2412
2413 If any file patterns are provided, the refreshed patch will
2413 If any file patterns are provided, the refreshed patch will
2414 contain only the modifications that match those patterns; the
2414 contain only the modifications that match those patterns; the
2415 remaining modifications will remain in the working directory.
2415 remaining modifications will remain in the working directory.
2416
2416
2417 If -s/--short is specified, files currently included in the patch
2417 If -s/--short is specified, files currently included in the patch
2418 will be refreshed just like matched files and remain in the patch.
2418 will be refreshed just like matched files and remain in the patch.
2419
2419
2420 If -e/--edit is specified, Mercurial will start your configured editor for
2420 If -e/--edit is specified, Mercurial will start your configured editor for
2421 you to enter a message. In case qrefresh fails, you will find a backup of
2421 you to enter a message. In case qrefresh fails, you will find a backup of
2422 your message in ``.hg/last-message.txt``.
2422 your message in ``.hg/last-message.txt``.
2423
2423
2424 hg add/remove/copy/rename work as usual, though you might want to
2424 hg add/remove/copy/rename work as usual, though you might want to
2425 use git-style patches (-g/--git or [diff] git=1) to track copies
2425 use git-style patches (-g/--git or [diff] git=1) to track copies
2426 and renames. See the diffs help topic for more information on the
2426 and renames. See the diffs help topic for more information on the
2427 git diff format.
2427 git diff format.
2428
2428
2429 Returns 0 on success.
2429 Returns 0 on success.
2430 """
2430 """
2431 q = repo.mq
2431 q = repo.mq
2432 message = cmdutil.logmessage(ui, opts)
2432 message = cmdutil.logmessage(ui, opts)
2433 if opts.get('edit'):
2433 if opts.get('edit'):
2434 if not q.applied:
2434 if not q.applied:
2435 ui.write(_("no patches applied\n"))
2435 ui.write(_("no patches applied\n"))
2436 return 1
2436 return 1
2437 if message:
2437 if message:
2438 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2438 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2439 patch = q.applied[-1].name
2439 patch = q.applied[-1].name
2440 ph = patchheader(q.join(patch), q.plainmode)
2440 ph = patchheader(q.join(patch), q.plainmode)
2441 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2441 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2442 # We don't want to lose the patch message if qrefresh fails (issue2062)
2442 # We don't want to lose the patch message if qrefresh fails (issue2062)
2443 repo.savecommitmessage(message)
2443 repo.savecommitmessage(message)
2444 setupheaderopts(ui, opts)
2444 setupheaderopts(ui, opts)
2445 wlock = repo.wlock()
2445 wlock = repo.wlock()
2446 try:
2446 try:
2447 ret = q.refresh(repo, pats, msg=message, **opts)
2447 ret = q.refresh(repo, pats, msg=message, **opts)
2448 q.savedirty()
2448 q.savedirty()
2449 return ret
2449 return ret
2450 finally:
2450 finally:
2451 wlock.release()
2451 wlock.release()
2452
2452
2453 @command("^qdiff",
2453 @command("^qdiff",
2454 commands.diffopts + commands.diffopts2 + commands.walkopts,
2454 commands.diffopts + commands.diffopts2 + commands.walkopts,
2455 _('hg qdiff [OPTION]... [FILE]...'))
2455 _('hg qdiff [OPTION]... [FILE]...'))
2456 def diff(ui, repo, *pats, **opts):
2456 def diff(ui, repo, *pats, **opts):
2457 """diff of the current patch and subsequent modifications
2457 """diff of the current patch and subsequent modifications
2458
2458
2459 Shows a diff which includes the current patch as well as any
2459 Shows a diff which includes the current patch as well as any
2460 changes which have been made in the working directory since the
2460 changes which have been made in the working directory since the
2461 last refresh (thus showing what the current patch would become
2461 last refresh (thus showing what the current patch would become
2462 after a qrefresh).
2462 after a qrefresh).
2463
2463
2464 Use :hg:`diff` if you only want to see the changes made since the
2464 Use :hg:`diff` if you only want to see the changes made since the
2465 last qrefresh, or :hg:`export qtip` if you want to see changes
2465 last qrefresh, or :hg:`export qtip` if you want to see changes
2466 made by the current patch without including changes made since the
2466 made by the current patch without including changes made since the
2467 qrefresh.
2467 qrefresh.
2468
2468
2469 Returns 0 on success.
2469 Returns 0 on success.
2470 """
2470 """
2471 repo.mq.diff(repo, pats, opts)
2471 repo.mq.diff(repo, pats, opts)
2472 return 0
2472 return 0
2473
2473
2474 @command('qfold',
2474 @command('qfold',
2475 [('e', 'edit', None, _('edit patch header')),
2475 [('e', 'edit', None, _('edit patch header')),
2476 ('k', 'keep', None, _('keep folded patch files')),
2476 ('k', 'keep', None, _('keep folded patch files')),
2477 ] + commands.commitopts,
2477 ] + commands.commitopts,
2478 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2478 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2479 def fold(ui, repo, *files, **opts):
2479 def fold(ui, repo, *files, **opts):
2480 """fold the named patches into the current patch
2480 """fold the named patches into the current patch
2481
2481
2482 Patches must not yet be applied. Each patch will be successively
2482 Patches must not yet be applied. Each patch will be successively
2483 applied to the current patch in the order given. If all the
2483 applied to the current patch in the order given. If all the
2484 patches apply successfully, the current patch will be refreshed
2484 patches apply successfully, the current patch will be refreshed
2485 with the new cumulative patch, and the folded patches will be
2485 with the new cumulative patch, and the folded patches will be
2486 deleted. With -k/--keep, the folded patch files will not be
2486 deleted. With -k/--keep, the folded patch files will not be
2487 removed afterwards.
2487 removed afterwards.
2488
2488
2489 The header for each folded patch will be concatenated with the
2489 The header for each folded patch will be concatenated with the
2490 current patch header, separated by a line of ``* * *``.
2490 current patch header, separated by a line of ``* * *``.
2491
2491
2492 Returns 0 on success."""
2492 Returns 0 on success."""
2493 q = repo.mq
2493 q = repo.mq
2494 if not files:
2494 if not files:
2495 raise util.Abort(_('qfold requires at least one patch name'))
2495 raise util.Abort(_('qfold requires at least one patch name'))
2496 if not q.checktoppatch(repo)[0]:
2496 if not q.checktoppatch(repo)[0]:
2497 raise util.Abort(_('no patches applied'))
2497 raise util.Abort(_('no patches applied'))
2498 q.checklocalchanges(repo)
2498 q.checklocalchanges(repo)
2499
2499
2500 message = cmdutil.logmessage(ui, opts)
2500 message = cmdutil.logmessage(ui, opts)
2501 if opts.get('edit'):
2501 if opts.get('edit'):
2502 if message:
2502 if message:
2503 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2503 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2504
2504
2505 parent = q.lookup('qtip')
2505 parent = q.lookup('qtip')
2506 patches = []
2506 patches = []
2507 messages = []
2507 messages = []
2508 for f in files:
2508 for f in files:
2509 p = q.lookup(f)
2509 p = q.lookup(f)
2510 if p in patches or p == parent:
2510 if p in patches or p == parent:
2511 ui.warn(_('Skipping already folded patch %s\n') % p)
2511 ui.warn(_('Skipping already folded patch %s\n') % p)
2512 if q.isapplied(p):
2512 if q.isapplied(p):
2513 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2513 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2514 patches.append(p)
2514 patches.append(p)
2515
2515
2516 for p in patches:
2516 for p in patches:
2517 if not message:
2517 if not message:
2518 ph = patchheader(q.join(p), q.plainmode)
2518 ph = patchheader(q.join(p), q.plainmode)
2519 if ph.message:
2519 if ph.message:
2520 messages.append(ph.message)
2520 messages.append(ph.message)
2521 pf = q.join(p)
2521 pf = q.join(p)
2522 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2522 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2523 if not patchsuccess:
2523 if not patchsuccess:
2524 raise util.Abort(_('error folding patch %s') % p)
2524 raise util.Abort(_('error folding patch %s') % p)
2525
2525
2526 if not message:
2526 if not message:
2527 ph = patchheader(q.join(parent), q.plainmode)
2527 ph = patchheader(q.join(parent), q.plainmode)
2528 message, user = ph.message, ph.user
2528 message, user = ph.message, ph.user
2529 for msg in messages:
2529 for msg in messages:
2530 message.append('* * *')
2530 message.append('* * *')
2531 message.extend(msg)
2531 message.extend(msg)
2532 message = '\n'.join(message)
2532 message = '\n'.join(message)
2533
2533
2534 if opts.get('edit'):
2534 if opts.get('edit'):
2535 message = ui.edit(message, user or ui.username())
2535 message = ui.edit(message, user or ui.username())
2536
2536
2537 diffopts = q.patchopts(q.diffopts(), *patches)
2537 diffopts = q.patchopts(q.diffopts(), *patches)
2538 wlock = repo.wlock()
2538 wlock = repo.wlock()
2539 try:
2539 try:
2540 q.refresh(repo, msg=message, git=diffopts.git)
2540 q.refresh(repo, msg=message, git=diffopts.git)
2541 q.delete(repo, patches, opts)
2541 q.delete(repo, patches, opts)
2542 q.savedirty()
2542 q.savedirty()
2543 finally:
2543 finally:
2544 wlock.release()
2544 wlock.release()
2545
2545
2546 @command("qgoto",
2546 @command("qgoto",
2547 [('c', 'check', None, _('tolerate non-conflicting local changes')),
2547 [('c', 'check', None, _('tolerate non-conflicting local changes')),
2548 ('f', 'force', None, _('overwrite any local changes')),
2548 ('f', 'force', None, _('overwrite any local changes')),
2549 ('', 'no-backup', None, _('do not save backup copies of files'))],
2549 ('', 'no-backup', None, _('do not save backup copies of files'))],
2550 _('hg qgoto [OPTION]... PATCH'))
2550 _('hg qgoto [OPTION]... PATCH'))
2551 def goto(ui, repo, patch, **opts):
2551 def goto(ui, repo, patch, **opts):
2552 '''push or pop patches until named patch is at top of stack
2552 '''push or pop patches until named patch is at top of stack
2553
2553
2554 Returns 0 on success.'''
2554 Returns 0 on success.'''
2555 opts = fixcheckopts(ui, opts)
2555 opts = fixcheckopts(ui, opts)
2556 q = repo.mq
2556 q = repo.mq
2557 patch = q.lookup(patch)
2557 patch = q.lookup(patch)
2558 nobackup = opts.get('no_backup')
2558 nobackup = opts.get('no_backup')
2559 check = opts.get('check')
2559 check = opts.get('check')
2560 if q.isapplied(patch):
2560 if q.isapplied(patch):
2561 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2561 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2562 check=check)
2562 check=check)
2563 else:
2563 else:
2564 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2564 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2565 check=check)
2565 check=check)
2566 q.savedirty()
2566 q.savedirty()
2567 return ret
2567 return ret
2568
2568
2569 @command("qguard",
2569 @command("qguard",
2570 [('l', 'list', None, _('list all patches and guards')),
2570 [('l', 'list', None, _('list all patches and guards')),
2571 ('n', 'none', None, _('drop all guards'))],
2571 ('n', 'none', None, _('drop all guards'))],
2572 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2572 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2573 def guard(ui, repo, *args, **opts):
2573 def guard(ui, repo, *args, **opts):
2574 '''set or print guards for a patch
2574 '''set or print guards for a patch
2575
2575
2576 Guards control whether a patch can be pushed. A patch with no
2576 Guards control whether a patch can be pushed. A patch with no
2577 guards is always pushed. A patch with a positive guard ("+foo") is
2577 guards is always pushed. A patch with a positive guard ("+foo") is
2578 pushed only if the :hg:`qselect` command has activated it. A patch with
2578 pushed only if the :hg:`qselect` command has activated it. A patch with
2579 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2579 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2580 has activated it.
2580 has activated it.
2581
2581
2582 With no arguments, print the currently active guards.
2582 With no arguments, print the currently active guards.
2583 With arguments, set guards for the named patch.
2583 With arguments, set guards for the named patch.
2584
2584
2585 .. note::
2585 .. note::
2586 Specifying negative guards now requires '--'.
2586 Specifying negative guards now requires '--'.
2587
2587
2588 To set guards on another patch::
2588 To set guards on another patch::
2589
2589
2590 hg qguard other.patch -- +2.6.17 -stable
2590 hg qguard other.patch -- +2.6.17 -stable
2591
2591
2592 Returns 0 on success.
2592 Returns 0 on success.
2593 '''
2593 '''
2594 def status(idx):
2594 def status(idx):
2595 guards = q.seriesguards[idx] or ['unguarded']
2595 guards = q.seriesguards[idx] or ['unguarded']
2596 if q.series[idx] in applied:
2596 if q.series[idx] in applied:
2597 state = 'applied'
2597 state = 'applied'
2598 elif q.pushable(idx)[0]:
2598 elif q.pushable(idx)[0]:
2599 state = 'unapplied'
2599 state = 'unapplied'
2600 else:
2600 else:
2601 state = 'guarded'
2601 state = 'guarded'
2602 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2602 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2603 ui.write('%s: ' % ui.label(q.series[idx], label))
2603 ui.write('%s: ' % ui.label(q.series[idx], label))
2604
2604
2605 for i, guard in enumerate(guards):
2605 for i, guard in enumerate(guards):
2606 if guard.startswith('+'):
2606 if guard.startswith('+'):
2607 ui.write(guard, label='qguard.positive')
2607 ui.write(guard, label='qguard.positive')
2608 elif guard.startswith('-'):
2608 elif guard.startswith('-'):
2609 ui.write(guard, label='qguard.negative')
2609 ui.write(guard, label='qguard.negative')
2610 else:
2610 else:
2611 ui.write(guard, label='qguard.unguarded')
2611 ui.write(guard, label='qguard.unguarded')
2612 if i != len(guards) - 1:
2612 if i != len(guards) - 1:
2613 ui.write(' ')
2613 ui.write(' ')
2614 ui.write('\n')
2614 ui.write('\n')
2615 q = repo.mq
2615 q = repo.mq
2616 applied = set(p.name for p in q.applied)
2616 applied = set(p.name for p in q.applied)
2617 patch = None
2617 patch = None
2618 args = list(args)
2618 args = list(args)
2619 if opts.get('list'):
2619 if opts.get('list'):
2620 if args or opts.get('none'):
2620 if args or opts.get('none'):
2621 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2621 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2622 for i in xrange(len(q.series)):
2622 for i in xrange(len(q.series)):
2623 status(i)
2623 status(i)
2624 return
2624 return
2625 if not args or args[0][0:1] in '-+':
2625 if not args or args[0][0:1] in '-+':
2626 if not q.applied:
2626 if not q.applied:
2627 raise util.Abort(_('no patches applied'))
2627 raise util.Abort(_('no patches applied'))
2628 patch = q.applied[-1].name
2628 patch = q.applied[-1].name
2629 if patch is None and args[0][0:1] not in '-+':
2629 if patch is None and args[0][0:1] not in '-+':
2630 patch = args.pop(0)
2630 patch = args.pop(0)
2631 if patch is None:
2631 if patch is None:
2632 raise util.Abort(_('no patch to work with'))
2632 raise util.Abort(_('no patch to work with'))
2633 if args or opts.get('none'):
2633 if args or opts.get('none'):
2634 idx = q.findseries(patch)
2634 idx = q.findseries(patch)
2635 if idx is None:
2635 if idx is None:
2636 raise util.Abort(_('no patch named %s') % patch)
2636 raise util.Abort(_('no patch named %s') % patch)
2637 q.setguards(idx, args)
2637 q.setguards(idx, args)
2638 q.savedirty()
2638 q.savedirty()
2639 else:
2639 else:
2640 status(q.series.index(q.lookup(patch)))
2640 status(q.series.index(q.lookup(patch)))
2641
2641
2642 @command("qheader", [], _('hg qheader [PATCH]'))
2642 @command("qheader", [], _('hg qheader [PATCH]'))
2643 def header(ui, repo, patch=None):
2643 def header(ui, repo, patch=None):
2644 """print the header of the topmost or specified patch
2644 """print the header of the topmost or specified patch
2645
2645
2646 Returns 0 on success."""
2646 Returns 0 on success."""
2647 q = repo.mq
2647 q = repo.mq
2648
2648
2649 if patch:
2649 if patch:
2650 patch = q.lookup(patch)
2650 patch = q.lookup(patch)
2651 else:
2651 else:
2652 if not q.applied:
2652 if not q.applied:
2653 ui.write(_('no patches applied\n'))
2653 ui.write(_('no patches applied\n'))
2654 return 1
2654 return 1
2655 patch = q.lookup('qtip')
2655 patch = q.lookup('qtip')
2656 ph = patchheader(q.join(patch), q.plainmode)
2656 ph = patchheader(q.join(patch), q.plainmode)
2657
2657
2658 ui.write('\n'.join(ph.message) + '\n')
2658 ui.write('\n'.join(ph.message) + '\n')
2659
2659
2660 def lastsavename(path):
2660 def lastsavename(path):
2661 (directory, base) = os.path.split(path)
2661 (directory, base) = os.path.split(path)
2662 names = os.listdir(directory)
2662 names = os.listdir(directory)
2663 namere = re.compile("%s.([0-9]+)" % base)
2663 namere = re.compile("%s.([0-9]+)" % base)
2664 maxindex = None
2664 maxindex = None
2665 maxname = None
2665 maxname = None
2666 for f in names:
2666 for f in names:
2667 m = namere.match(f)
2667 m = namere.match(f)
2668 if m:
2668 if m:
2669 index = int(m.group(1))
2669 index = int(m.group(1))
2670 if maxindex is None or index > maxindex:
2670 if maxindex is None or index > maxindex:
2671 maxindex = index
2671 maxindex = index
2672 maxname = f
2672 maxname = f
2673 if maxname:
2673 if maxname:
2674 return (os.path.join(directory, maxname), maxindex)
2674 return (os.path.join(directory, maxname), maxindex)
2675 return (None, None)
2675 return (None, None)
2676
2676
2677 def savename(path):
2677 def savename(path):
2678 (last, index) = lastsavename(path)
2678 (last, index) = lastsavename(path)
2679 if last is None:
2679 if last is None:
2680 index = 0
2680 index = 0
2681 newpath = path + ".%d" % (index + 1)
2681 newpath = path + ".%d" % (index + 1)
2682 return newpath
2682 return newpath
2683
2683
2684 @command("^qpush",
2684 @command("^qpush",
2685 [('c', 'check', None, _('tolerate non-conflicting local changes')),
2685 [('c', 'check', None, _('tolerate non-conflicting local changes')),
2686 ('f', 'force', None, _('apply on top of local changes')),
2686 ('f', 'force', None, _('apply on top of local changes')),
2687 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2687 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2688 ('l', 'list', None, _('list patch name in commit text')),
2688 ('l', 'list', None, _('list patch name in commit text')),
2689 ('a', 'all', None, _('apply all patches')),
2689 ('a', 'all', None, _('apply all patches')),
2690 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2690 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2691 ('n', 'name', '',
2691 ('n', 'name', '',
2692 _('merge queue name (DEPRECATED)'), _('NAME')),
2692 _('merge queue name (DEPRECATED)'), _('NAME')),
2693 ('', 'move', None,
2693 ('', 'move', None,
2694 _('reorder patch series and apply only the patch')),
2694 _('reorder patch series and apply only the patch')),
2695 ('', 'no-backup', None, _('do not save backup copies of files'))],
2695 ('', 'no-backup', None, _('do not save backup copies of files'))],
2696 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2696 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2697 def push(ui, repo, patch=None, **opts):
2697 def push(ui, repo, patch=None, **opts):
2698 """push the next patch onto the stack
2698 """push the next patch onto the stack
2699
2699
2700 By default, abort if the working directory contains uncommitted
2700 By default, abort if the working directory contains uncommitted
2701 changes. With -c/--check, abort only if the uncommitted files
2701 changes. With -c/--check, abort only if the uncommitted files
2702 overlap with patched files. With -f/--force, backup and patch over
2702 overlap with patched files. With -f/--force, backup and patch over
2703 uncommitted changes.
2703 uncommitted changes.
2704
2704
2705 Return 0 on success.
2705 Return 0 on success.
2706 """
2706 """
2707 q = repo.mq
2707 q = repo.mq
2708 mergeq = None
2708 mergeq = None
2709
2709
2710 opts = fixcheckopts(ui, opts)
2710 opts = fixcheckopts(ui, opts)
2711 if opts.get('merge'):
2711 if opts.get('merge'):
2712 if opts.get('name'):
2712 if opts.get('name'):
2713 newpath = repo.join(opts.get('name'))
2713 newpath = repo.join(opts.get('name'))
2714 else:
2714 else:
2715 newpath, i = lastsavename(q.path)
2715 newpath, i = lastsavename(q.path)
2716 if not newpath:
2716 if not newpath:
2717 ui.warn(_("no saved queues found, please use -n\n"))
2717 ui.warn(_("no saved queues found, please use -n\n"))
2718 return 1
2718 return 1
2719 mergeq = queue(ui, repo.path, newpath)
2719 mergeq = queue(ui, repo.path, newpath)
2720 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2720 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2721 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2721 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2722 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2722 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2723 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2723 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2724 check=opts.get('check'))
2724 check=opts.get('check'))
2725 return ret
2725 return ret
2726
2726
2727 @command("^qpop",
2727 @command("^qpop",
2728 [('a', 'all', None, _('pop all patches')),
2728 [('a', 'all', None, _('pop all patches')),
2729 ('n', 'name', '',
2729 ('n', 'name', '',
2730 _('queue name to pop (DEPRECATED)'), _('NAME')),
2730 _('queue name to pop (DEPRECATED)'), _('NAME')),
2731 ('c', 'check', None, _('tolerate non-conflicting local changes')),
2731 ('c', 'check', None, _('tolerate non-conflicting local changes')),
2732 ('f', 'force', None, _('forget any local changes to patched files')),
2732 ('f', 'force', None, _('forget any local changes to patched files')),
2733 ('', 'no-backup', None, _('do not save backup copies of files'))],
2733 ('', 'no-backup', None, _('do not save backup copies of files'))],
2734 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2734 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2735 def pop(ui, repo, patch=None, **opts):
2735 def pop(ui, repo, patch=None, **opts):
2736 """pop the current patch off the stack
2736 """pop the current patch off the stack
2737
2737
2738 Without argument, pops off the top of the patch stack. If given a
2738 Without argument, pops off the top of the patch stack. If given a
2739 patch name, keeps popping off patches until the named patch is at
2739 patch name, keeps popping off patches until the named patch is at
2740 the top of the stack.
2740 the top of the stack.
2741
2741
2742 By default, abort if the working directory contains uncommitted
2742 By default, abort if the working directory contains uncommitted
2743 changes. With -c/--check, abort only if the uncommitted files
2743 changes. With -c/--check, abort only if the uncommitted files
2744 overlap with patched files. With -f/--force, backup and discard
2744 overlap with patched files. With -f/--force, backup and discard
2745 changes made to such files.
2745 changes made to such files.
2746
2746
2747 Return 0 on success.
2747 Return 0 on success.
2748 """
2748 """
2749 opts = fixcheckopts(ui, opts)
2749 opts = fixcheckopts(ui, opts)
2750 localupdate = True
2750 localupdate = True
2751 if opts.get('name'):
2751 if opts.get('name'):
2752 q = queue(ui, repo.path, repo.join(opts.get('name')))
2752 q = queue(ui, repo.path, repo.join(opts.get('name')))
2753 ui.warn(_('using patch queue: %s\n') % q.path)
2753 ui.warn(_('using patch queue: %s\n') % q.path)
2754 localupdate = False
2754 localupdate = False
2755 else:
2755 else:
2756 q = repo.mq
2756 q = repo.mq
2757 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2757 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2758 all=opts.get('all'), nobackup=opts.get('no_backup'),
2758 all=opts.get('all'), nobackup=opts.get('no_backup'),
2759 check=opts.get('check'))
2759 check=opts.get('check'))
2760 q.savedirty()
2760 q.savedirty()
2761 return ret
2761 return ret
2762
2762
2763 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2763 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2764 def rename(ui, repo, patch, name=None, **opts):
2764 def rename(ui, repo, patch, name=None, **opts):
2765 """rename a patch
2765 """rename a patch
2766
2766
2767 With one argument, renames the current patch to PATCH1.
2767 With one argument, renames the current patch to PATCH1.
2768 With two arguments, renames PATCH1 to PATCH2.
2768 With two arguments, renames PATCH1 to PATCH2.
2769
2769
2770 Returns 0 on success."""
2770 Returns 0 on success."""
2771 q = repo.mq
2771 q = repo.mq
2772 if not name:
2772 if not name:
2773 name = patch
2773 name = patch
2774 patch = None
2774 patch = None
2775
2775
2776 if patch:
2776 if patch:
2777 patch = q.lookup(patch)
2777 patch = q.lookup(patch)
2778 else:
2778 else:
2779 if not q.applied:
2779 if not q.applied:
2780 ui.write(_('no patches applied\n'))
2780 ui.write(_('no patches applied\n'))
2781 return
2781 return
2782 patch = q.lookup('qtip')
2782 patch = q.lookup('qtip')
2783 absdest = q.join(name)
2783 absdest = q.join(name)
2784 if os.path.isdir(absdest):
2784 if os.path.isdir(absdest):
2785 name = normname(os.path.join(name, os.path.basename(patch)))
2785 name = normname(os.path.join(name, os.path.basename(patch)))
2786 absdest = q.join(name)
2786 absdest = q.join(name)
2787 q.checkpatchname(name)
2787 q.checkpatchname(name)
2788
2788
2789 ui.note(_('renaming %s to %s\n') % (patch, name))
2789 ui.note(_('renaming %s to %s\n') % (patch, name))
2790 i = q.findseries(patch)
2790 i = q.findseries(patch)
2791 guards = q.guard_re.findall(q.fullseries[i])
2791 guards = q.guard_re.findall(q.fullseries[i])
2792 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2792 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2793 q.parseseries()
2793 q.parseseries()
2794 q.seriesdirty = True
2794 q.seriesdirty = True
2795
2795
2796 info = q.isapplied(patch)
2796 info = q.isapplied(patch)
2797 if info:
2797 if info:
2798 q.applied[info[0]] = statusentry(info[1], name)
2798 q.applied[info[0]] = statusentry(info[1], name)
2799 q.applieddirty = True
2799 q.applieddirty = True
2800
2800
2801 destdir = os.path.dirname(absdest)
2801 destdir = os.path.dirname(absdest)
2802 if not os.path.isdir(destdir):
2802 if not os.path.isdir(destdir):
2803 os.makedirs(destdir)
2803 os.makedirs(destdir)
2804 util.rename(q.join(patch), absdest)
2804 util.rename(q.join(patch), absdest)
2805 r = q.qrepo()
2805 r = q.qrepo()
2806 if r and patch in r.dirstate:
2806 if r and patch in r.dirstate:
2807 wctx = r[None]
2807 wctx = r[None]
2808 wlock = r.wlock()
2808 wlock = r.wlock()
2809 try:
2809 try:
2810 if r.dirstate[patch] == 'a':
2810 if r.dirstate[patch] == 'a':
2811 r.dirstate.drop(patch)
2811 r.dirstate.drop(patch)
2812 r.dirstate.add(name)
2812 r.dirstate.add(name)
2813 else:
2813 else:
2814 wctx.copy(patch, name)
2814 wctx.copy(patch, name)
2815 wctx.forget([patch])
2815 wctx.forget([patch])
2816 finally:
2816 finally:
2817 wlock.release()
2817 wlock.release()
2818
2818
2819 q.savedirty()
2819 q.savedirty()
2820
2820
2821 @command("qrestore",
2821 @command("qrestore",
2822 [('d', 'delete', None, _('delete save entry')),
2822 [('d', 'delete', None, _('delete save entry')),
2823 ('u', 'update', None, _('update queue working directory'))],
2823 ('u', 'update', None, _('update queue working directory'))],
2824 _('hg qrestore [-d] [-u] REV'))
2824 _('hg qrestore [-d] [-u] REV'))
2825 def restore(ui, repo, rev, **opts):
2825 def restore(ui, repo, rev, **opts):
2826 """restore the queue state saved by a revision (DEPRECATED)
2826 """restore the queue state saved by a revision (DEPRECATED)
2827
2827
2828 This command is deprecated, use :hg:`rebase` instead."""
2828 This command is deprecated, use :hg:`rebase` instead."""
2829 rev = repo.lookup(rev)
2829 rev = repo.lookup(rev)
2830 q = repo.mq
2830 q = repo.mq
2831 q.restore(repo, rev, delete=opts.get('delete'),
2831 q.restore(repo, rev, delete=opts.get('delete'),
2832 qupdate=opts.get('update'))
2832 qupdate=opts.get('update'))
2833 q.savedirty()
2833 q.savedirty()
2834 return 0
2834 return 0
2835
2835
2836 @command("qsave",
2836 @command("qsave",
2837 [('c', 'copy', None, _('copy patch directory')),
2837 [('c', 'copy', None, _('copy patch directory')),
2838 ('n', 'name', '',
2838 ('n', 'name', '',
2839 _('copy directory name'), _('NAME')),
2839 _('copy directory name'), _('NAME')),
2840 ('e', 'empty', None, _('clear queue status file')),
2840 ('e', 'empty', None, _('clear queue status file')),
2841 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2841 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2842 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2842 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2843 def save(ui, repo, **opts):
2843 def save(ui, repo, **opts):
2844 """save current queue state (DEPRECATED)
2844 """save current queue state (DEPRECATED)
2845
2845
2846 This command is deprecated, use :hg:`rebase` instead."""
2846 This command is deprecated, use :hg:`rebase` instead."""
2847 q = repo.mq
2847 q = repo.mq
2848 message = cmdutil.logmessage(ui, opts)
2848 message = cmdutil.logmessage(ui, opts)
2849 ret = q.save(repo, msg=message)
2849 ret = q.save(repo, msg=message)
2850 if ret:
2850 if ret:
2851 return ret
2851 return ret
2852 q.savedirty() # save to .hg/patches before copying
2852 q.savedirty() # save to .hg/patches before copying
2853 if opts.get('copy'):
2853 if opts.get('copy'):
2854 path = q.path
2854 path = q.path
2855 if opts.get('name'):
2855 if opts.get('name'):
2856 newpath = os.path.join(q.basepath, opts.get('name'))
2856 newpath = os.path.join(q.basepath, opts.get('name'))
2857 if os.path.exists(newpath):
2857 if os.path.exists(newpath):
2858 if not os.path.isdir(newpath):
2858 if not os.path.isdir(newpath):
2859 raise util.Abort(_('destination %s exists and is not '
2859 raise util.Abort(_('destination %s exists and is not '
2860 'a directory') % newpath)
2860 'a directory') % newpath)
2861 if not opts.get('force'):
2861 if not opts.get('force'):
2862 raise util.Abort(_('destination %s exists, '
2862 raise util.Abort(_('destination %s exists, '
2863 'use -f to force') % newpath)
2863 'use -f to force') % newpath)
2864 else:
2864 else:
2865 newpath = savename(path)
2865 newpath = savename(path)
2866 ui.warn(_("copy %s to %s\n") % (path, newpath))
2866 ui.warn(_("copy %s to %s\n") % (path, newpath))
2867 util.copyfiles(path, newpath)
2867 util.copyfiles(path, newpath)
2868 if opts.get('empty'):
2868 if opts.get('empty'):
2869 del q.applied[:]
2869 del q.applied[:]
2870 q.applieddirty = True
2870 q.applieddirty = True
2871 q.savedirty()
2871 q.savedirty()
2872 return 0
2872 return 0
2873
2873
2874 @command("strip",
2874 @command("strip",
2875 [
2875 [
2876 ('r', 'rev', [], _('strip specified revision (optional, '
2876 ('r', 'rev', [], _('strip specified revision (optional, '
2877 'can specify revisions without this '
2877 'can specify revisions without this '
2878 'option)'), _('REV')),
2878 'option)'), _('REV')),
2879 ('f', 'force', None, _('force removal of changesets, discard '
2879 ('f', 'force', None, _('force removal of changesets, discard '
2880 'uncommitted changes (no backup)')),
2880 'uncommitted changes (no backup)')),
2881 ('b', 'backup', None, _('bundle only changesets with local revision'
2881 ('b', 'backup', None, _('bundle only changesets with local revision'
2882 ' number greater than REV which are not'
2882 ' number greater than REV which are not'
2883 ' descendants of REV (DEPRECATED)')),
2883 ' descendants of REV (DEPRECATED)')),
2884 ('', 'no-backup', None, _('no backups')),
2884 ('', 'no-backup', None, _('no backups')),
2885 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2885 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2886 ('n', '', None, _('ignored (DEPRECATED)')),
2886 ('n', '', None, _('ignored (DEPRECATED)')),
2887 ('k', 'keep', None, _("do not modify working copy during strip"))],
2887 ('k', 'keep', None, _("do not modify working copy during strip"))],
2888 _('hg strip [-k] [-f] [-n] REV...'))
2888 _('hg strip [-k] [-f] [-n] REV...'))
2889 def strip(ui, repo, *revs, **opts):
2889 def strip(ui, repo, *revs, **opts):
2890 """strip changesets and all their descendants from the repository
2890 """strip changesets and all their descendants from the repository
2891
2891
2892 The strip command removes the specified changesets and all their
2892 The strip command removes the specified changesets and all their
2893 descendants. If the working directory has uncommitted changes, the
2893 descendants. If the working directory has uncommitted changes, the
2894 operation is aborted unless the --force flag is supplied, in which
2894 operation is aborted unless the --force flag is supplied, in which
2895 case changes will be discarded.
2895 case changes will be discarded.
2896
2896
2897 If a parent of the working directory is stripped, then the working
2897 If a parent of the working directory is stripped, then the working
2898 directory will automatically be updated to the most recent
2898 directory will automatically be updated to the most recent
2899 available ancestor of the stripped parent after the operation
2899 available ancestor of the stripped parent after the operation
2900 completes.
2900 completes.
2901
2901
2902 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2902 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2903 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2903 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2904 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2904 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2905 where BUNDLE is the bundle file created by the strip. Note that
2905 where BUNDLE is the bundle file created by the strip. Note that
2906 the local revision numbers will in general be different after the
2906 the local revision numbers will in general be different after the
2907 restore.
2907 restore.
2908
2908
2909 Use the --no-backup option to discard the backup bundle once the
2909 Use the --no-backup option to discard the backup bundle once the
2910 operation completes.
2910 operation completes.
2911
2911
2912 Return 0 on success.
2912 Return 0 on success.
2913 """
2913 """
2914 backup = 'all'
2914 backup = 'all'
2915 if opts.get('backup'):
2915 if opts.get('backup'):
2916 backup = 'strip'
2916 backup = 'strip'
2917 elif opts.get('no_backup') or opts.get('nobackup'):
2917 elif opts.get('no_backup') or opts.get('nobackup'):
2918 backup = 'none'
2918 backup = 'none'
2919
2919
2920 cl = repo.changelog
2920 cl = repo.changelog
2921 revs = list(revs) + opts.get('rev')
2921 revs = list(revs) + opts.get('rev')
2922 revs = set(scmutil.revrange(repo, revs))
2922 revs = set(scmutil.revrange(repo, revs))
2923 if not revs:
2923 if not revs:
2924 raise util.Abort(_('empty revision set'))
2924 raise util.Abort(_('empty revision set'))
2925
2925
2926 descendants = set(cl.descendants(*revs))
2926 descendants = set(cl.descendants(*revs))
2927 strippedrevs = revs.union(descendants)
2927 strippedrevs = revs.union(descendants)
2928 roots = revs.difference(descendants)
2928 roots = revs.difference(descendants)
2929
2929
2930 update = False
2930 update = False
2931 # if one of the wdir parent is stripped we'll need
2931 # if one of the wdir parent is stripped we'll need
2932 # to update away to an earlier revision
2932 # to update away to an earlier revision
2933 for p in repo.dirstate.parents():
2933 for p in repo.dirstate.parents():
2934 if p != nullid and cl.rev(p) in strippedrevs:
2934 if p != nullid and cl.rev(p) in strippedrevs:
2935 update = True
2935 update = True
2936 break
2936 break
2937
2937
2938 rootnodes = set(cl.node(r) for r in roots)
2938 rootnodes = set(cl.node(r) for r in roots)
2939
2939
2940 q = repo.mq
2940 q = repo.mq
2941 if q.applied:
2941 if q.applied:
2942 # refresh queue state if we're about to strip
2942 # refresh queue state if we're about to strip
2943 # applied patches
2943 # applied patches
2944 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2944 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2945 q.applieddirty = True
2945 q.applieddirty = True
2946 start = 0
2946 start = 0
2947 end = len(q.applied)
2947 end = len(q.applied)
2948 for i, statusentry in enumerate(q.applied):
2948 for i, statusentry in enumerate(q.applied):
2949 if statusentry.node in rootnodes:
2949 if statusentry.node in rootnodes:
2950 # if one of the stripped roots is an applied
2950 # if one of the stripped roots is an applied
2951 # patch, only part of the queue is stripped
2951 # patch, only part of the queue is stripped
2952 start = i
2952 start = i
2953 break
2953 break
2954 del q.applied[start:end]
2954 del q.applied[start:end]
2955 q.savedirty()
2955 q.savedirty()
2956
2956
2957 revs = list(rootnodes)
2957 revs = list(rootnodes)
2958 if update and opts.get('keep'):
2958 if update and opts.get('keep'):
2959 wlock = repo.wlock()
2959 wlock = repo.wlock()
2960 try:
2960 try:
2961 urev = repo.mq.qparents(repo, revs[0])
2961 urev = repo.mq.qparents(repo, revs[0])
2962 repo.dirstate.rebuild(urev, repo[urev].manifest())
2962 repo.dirstate.rebuild(urev, repo[urev].manifest())
2963 repo.dirstate.write()
2963 repo.dirstate.write()
2964 update = False
2964 update = False
2965 finally:
2965 finally:
2966 wlock.release()
2966 wlock.release()
2967
2967
2968 repo.mq.strip(repo, revs, backup=backup, update=update,
2968 repo.mq.strip(repo, revs, backup=backup, update=update,
2969 force=opts.get('force'))
2969 force=opts.get('force'))
2970 return 0
2970 return 0
2971
2971
2972 @command("qselect",
2972 @command("qselect",
2973 [('n', 'none', None, _('disable all guards')),
2973 [('n', 'none', None, _('disable all guards')),
2974 ('s', 'series', None, _('list all guards in series file')),
2974 ('s', 'series', None, _('list all guards in series file')),
2975 ('', 'pop', None, _('pop to before first guarded applied patch')),
2975 ('', 'pop', None, _('pop to before first guarded applied patch')),
2976 ('', 'reapply', None, _('pop, then reapply patches'))],
2976 ('', 'reapply', None, _('pop, then reapply patches'))],
2977 _('hg qselect [OPTION]... [GUARD]...'))
2977 _('hg qselect [OPTION]... [GUARD]...'))
2978 def select(ui, repo, *args, **opts):
2978 def select(ui, repo, *args, **opts):
2979 '''set or print guarded patches to push
2979 '''set or print guarded patches to push
2980
2980
2981 Use the :hg:`qguard` command to set or print guards on patch, then use
2981 Use the :hg:`qguard` command to set or print guards on patch, then use
2982 qselect to tell mq which guards to use. A patch will be pushed if
2982 qselect to tell mq which guards to use. A patch will be pushed if
2983 it has no guards or any positive guards match the currently
2983 it has no guards or any positive guards match the currently
2984 selected guard, but will not be pushed if any negative guards
2984 selected guard, but will not be pushed if any negative guards
2985 match the current guard. For example::
2985 match the current guard. For example::
2986
2986
2987 qguard foo.patch -- -stable (negative guard)
2987 qguard foo.patch -- -stable (negative guard)
2988 qguard bar.patch +stable (positive guard)
2988 qguard bar.patch +stable (positive guard)
2989 qselect stable
2989 qselect stable
2990
2990
2991 This activates the "stable" guard. mq will skip foo.patch (because
2991 This activates the "stable" guard. mq will skip foo.patch (because
2992 it has a negative match) but push bar.patch (because it has a
2992 it has a negative match) but push bar.patch (because it has a
2993 positive match).
2993 positive match).
2994
2994
2995 With no arguments, prints the currently active guards.
2995 With no arguments, prints the currently active guards.
2996 With one argument, sets the active guard.
2996 With one argument, sets the active guard.
2997
2997
2998 Use -n/--none to deactivate guards (no other arguments needed).
2998 Use -n/--none to deactivate guards (no other arguments needed).
2999 When no guards are active, patches with positive guards are
2999 When no guards are active, patches with positive guards are
3000 skipped and patches with negative guards are pushed.
3000 skipped and patches with negative guards are pushed.
3001
3001
3002 qselect can change the guards on applied patches. It does not pop
3002 qselect can change the guards on applied patches. It does not pop
3003 guarded patches by default. Use --pop to pop back to the last
3003 guarded patches by default. Use --pop to pop back to the last
3004 applied patch that is not guarded. Use --reapply (which implies
3004 applied patch that is not guarded. Use --reapply (which implies
3005 --pop) to push back to the current patch afterwards, but skip
3005 --pop) to push back to the current patch afterwards, but skip
3006 guarded patches.
3006 guarded patches.
3007
3007
3008 Use -s/--series to print a list of all guards in the series file
3008 Use -s/--series to print a list of all guards in the series file
3009 (no other arguments needed). Use -v for more information.
3009 (no other arguments needed). Use -v for more information.
3010
3010
3011 Returns 0 on success.'''
3011 Returns 0 on success.'''
3012
3012
3013 q = repo.mq
3013 q = repo.mq
3014 guards = q.active()
3014 guards = q.active()
3015 if args or opts.get('none'):
3015 if args or opts.get('none'):
3016 old_unapplied = q.unapplied(repo)
3016 old_unapplied = q.unapplied(repo)
3017 old_guarded = [i for i in xrange(len(q.applied)) if
3017 old_guarded = [i for i in xrange(len(q.applied)) if
3018 not q.pushable(i)[0]]
3018 not q.pushable(i)[0]]
3019 q.setactive(args)
3019 q.setactive(args)
3020 q.savedirty()
3020 q.savedirty()
3021 if not args:
3021 if not args:
3022 ui.status(_('guards deactivated\n'))
3022 ui.status(_('guards deactivated\n'))
3023 if not opts.get('pop') and not opts.get('reapply'):
3023 if not opts.get('pop') and not opts.get('reapply'):
3024 unapplied = q.unapplied(repo)
3024 unapplied = q.unapplied(repo)
3025 guarded = [i for i in xrange(len(q.applied))
3025 guarded = [i for i in xrange(len(q.applied))
3026 if not q.pushable(i)[0]]
3026 if not q.pushable(i)[0]]
3027 if len(unapplied) != len(old_unapplied):
3027 if len(unapplied) != len(old_unapplied):
3028 ui.status(_('number of unguarded, unapplied patches has '
3028 ui.status(_('number of unguarded, unapplied patches has '
3029 'changed from %d to %d\n') %
3029 'changed from %d to %d\n') %
3030 (len(old_unapplied), len(unapplied)))
3030 (len(old_unapplied), len(unapplied)))
3031 if len(guarded) != len(old_guarded):
3031 if len(guarded) != len(old_guarded):
3032 ui.status(_('number of guarded, applied patches has changed '
3032 ui.status(_('number of guarded, applied patches has changed '
3033 'from %d to %d\n') %
3033 'from %d to %d\n') %
3034 (len(old_guarded), len(guarded)))
3034 (len(old_guarded), len(guarded)))
3035 elif opts.get('series'):
3035 elif opts.get('series'):
3036 guards = {}
3036 guards = {}
3037 noguards = 0
3037 noguards = 0
3038 for gs in q.seriesguards:
3038 for gs in q.seriesguards:
3039 if not gs:
3039 if not gs:
3040 noguards += 1
3040 noguards += 1
3041 for g in gs:
3041 for g in gs:
3042 guards.setdefault(g, 0)
3042 guards.setdefault(g, 0)
3043 guards[g] += 1
3043 guards[g] += 1
3044 if ui.verbose:
3044 if ui.verbose:
3045 guards['NONE'] = noguards
3045 guards['NONE'] = noguards
3046 guards = guards.items()
3046 guards = guards.items()
3047 guards.sort(key=lambda x: x[0][1:])
3047 guards.sort(key=lambda x: x[0][1:])
3048 if guards:
3048 if guards:
3049 ui.note(_('guards in series file:\n'))
3049 ui.note(_('guards in series file:\n'))
3050 for guard, count in guards:
3050 for guard, count in guards:
3051 ui.note('%2d ' % count)
3051 ui.note('%2d ' % count)
3052 ui.write(guard, '\n')
3052 ui.write(guard, '\n')
3053 else:
3053 else:
3054 ui.note(_('no guards in series file\n'))
3054 ui.note(_('no guards in series file\n'))
3055 else:
3055 else:
3056 if guards:
3056 if guards:
3057 ui.note(_('active guards:\n'))
3057 ui.note(_('active guards:\n'))
3058 for g in guards:
3058 for g in guards:
3059 ui.write(g, '\n')
3059 ui.write(g, '\n')
3060 else:
3060 else:
3061 ui.write(_('no active guards\n'))
3061 ui.write(_('no active guards\n'))
3062 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
3062 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
3063 popped = False
3063 popped = False
3064 if opts.get('pop') or opts.get('reapply'):
3064 if opts.get('pop') or opts.get('reapply'):
3065 for i in xrange(len(q.applied)):
3065 for i in xrange(len(q.applied)):
3066 pushable, reason = q.pushable(i)
3066 pushable, reason = q.pushable(i)
3067 if not pushable:
3067 if not pushable:
3068 ui.status(_('popping guarded patches\n'))
3068 ui.status(_('popping guarded patches\n'))
3069 popped = True
3069 popped = True
3070 if i == 0:
3070 if i == 0:
3071 q.pop(repo, all=True)
3071 q.pop(repo, all=True)
3072 else:
3072 else:
3073 q.pop(repo, str(i - 1))
3073 q.pop(repo, str(i - 1))
3074 break
3074 break
3075 if popped:
3075 if popped:
3076 try:
3076 try:
3077 if reapply:
3077 if reapply:
3078 ui.status(_('reapplying unguarded patches\n'))
3078 ui.status(_('reapplying unguarded patches\n'))
3079 q.push(repo, reapply)
3079 q.push(repo, reapply)
3080 finally:
3080 finally:
3081 q.savedirty()
3081 q.savedirty()
3082
3082
3083 @command("qfinish",
3083 @command("qfinish",
3084 [('a', 'applied', None, _('finish all applied changesets'))],
3084 [('a', 'applied', None, _('finish all applied changesets'))],
3085 _('hg qfinish [-a] [REV]...'))
3085 _('hg qfinish [-a] [REV]...'))
3086 def finish(ui, repo, *revrange, **opts):
3086 def finish(ui, repo, *revrange, **opts):
3087 """move applied patches into repository history
3087 """move applied patches into repository history
3088
3088
3089 Finishes the specified revisions (corresponding to applied
3089 Finishes the specified revisions (corresponding to applied
3090 patches) by moving them out of mq control into regular repository
3090 patches) by moving them out of mq control into regular repository
3091 history.
3091 history.
3092
3092
3093 Accepts a revision range or the -a/--applied option. If --applied
3093 Accepts a revision range or the -a/--applied option. If --applied
3094 is specified, all applied mq revisions are removed from mq
3094 is specified, all applied mq revisions are removed from mq
3095 control. Otherwise, the given revisions must be at the base of the
3095 control. Otherwise, the given revisions must be at the base of the
3096 stack of applied patches.
3096 stack of applied patches.
3097
3097
3098 This can be especially useful if your changes have been applied to
3098 This can be especially useful if your changes have been applied to
3099 an upstream repository, or if you are about to push your changes
3099 an upstream repository, or if you are about to push your changes
3100 to upstream.
3100 to upstream.
3101
3101
3102 Returns 0 on success.
3102 Returns 0 on success.
3103 """
3103 """
3104 if not opts.get('applied') and not revrange:
3104 if not opts.get('applied') and not revrange:
3105 raise util.Abort(_('no revisions specified'))
3105 raise util.Abort(_('no revisions specified'))
3106 elif opts.get('applied'):
3106 elif opts.get('applied'):
3107 revrange = ('qbase::qtip',) + revrange
3107 revrange = ('qbase::qtip',) + revrange
3108
3108
3109 q = repo.mq
3109 q = repo.mq
3110 if not q.applied:
3110 if not q.applied:
3111 ui.status(_('no patches applied\n'))
3111 ui.status(_('no patches applied\n'))
3112 return 0
3112 return 0
3113
3113
3114 revs = scmutil.revrange(repo, revrange)
3114 revs = scmutil.revrange(repo, revrange)
3115 if repo['.'].rev() in revs and repo[None].files():
3115 if repo['.'].rev() in revs and repo[None].files():
3116 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3116 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3117 # queue.finish may changes phases but leave the responsability to lock the
3117 # queue.finish may changes phases but leave the responsability to lock the
3118 # repo to the caller to avoid deadlock with wlock. This command code is
3118 # repo to the caller to avoid deadlock with wlock. This command code is
3119 # responsability for this locking.
3119 # responsability for this locking.
3120 lock = repo.lock()
3120 lock = repo.lock()
3121 try:
3121 try:
3122 q.finish(repo, revs)
3122 q.finish(repo, revs)
3123 q.savedirty()
3123 q.savedirty()
3124 finally:
3124 finally:
3125 lock.release()
3125 lock.release()
3126 return 0
3126 return 0
3127
3127
3128 @command("qqueue",
3128 @command("qqueue",
3129 [('l', 'list', False, _('list all available queues')),
3129 [('l', 'list', False, _('list all available queues')),
3130 ('', 'active', False, _('print name of active queue')),
3130 ('', 'active', False, _('print name of active queue')),
3131 ('c', 'create', False, _('create new queue')),
3131 ('c', 'create', False, _('create new queue')),
3132 ('', 'rename', False, _('rename active queue')),
3132 ('', 'rename', False, _('rename active queue')),
3133 ('', 'delete', False, _('delete reference to queue')),
3133 ('', 'delete', False, _('delete reference to queue')),
3134 ('', 'purge', False, _('delete queue, and remove patch dir')),
3134 ('', 'purge', False, _('delete queue, and remove patch dir')),
3135 ],
3135 ],
3136 _('[OPTION] [QUEUE]'))
3136 _('[OPTION] [QUEUE]'))
3137 def qqueue(ui, repo, name=None, **opts):
3137 def qqueue(ui, repo, name=None, **opts):
3138 '''manage multiple patch queues
3138 '''manage multiple patch queues
3139
3139
3140 Supports switching between different patch queues, as well as creating
3140 Supports switching between different patch queues, as well as creating
3141 new patch queues and deleting existing ones.
3141 new patch queues and deleting existing ones.
3142
3142
3143 Omitting a queue name or specifying -l/--list will show you the registered
3143 Omitting a queue name or specifying -l/--list will show you the registered
3144 queues - by default the "normal" patches queue is registered. The currently
3144 queues - by default the "normal" patches queue is registered. The currently
3145 active queue will be marked with "(active)". Specifying --active will print
3145 active queue will be marked with "(active)". Specifying --active will print
3146 only the name of the active queue.
3146 only the name of the active queue.
3147
3147
3148 To create a new queue, use -c/--create. The queue is automatically made
3148 To create a new queue, use -c/--create. The queue is automatically made
3149 active, except in the case where there are applied patches from the
3149 active, except in the case where there are applied patches from the
3150 currently active queue in the repository. Then the queue will only be
3150 currently active queue in the repository. Then the queue will only be
3151 created and switching will fail.
3151 created and switching will fail.
3152
3152
3153 To delete an existing queue, use --delete. You cannot delete the currently
3153 To delete an existing queue, use --delete. You cannot delete the currently
3154 active queue.
3154 active queue.
3155
3155
3156 Returns 0 on success.
3156 Returns 0 on success.
3157 '''
3157 '''
3158 q = repo.mq
3158 q = repo.mq
3159 _defaultqueue = 'patches'
3159 _defaultqueue = 'patches'
3160 _allqueues = 'patches.queues'
3160 _allqueues = 'patches.queues'
3161 _activequeue = 'patches.queue'
3161 _activequeue = 'patches.queue'
3162
3162
3163 def _getcurrent():
3163 def _getcurrent():
3164 cur = os.path.basename(q.path)
3164 cur = os.path.basename(q.path)
3165 if cur.startswith('patches-'):
3165 if cur.startswith('patches-'):
3166 cur = cur[8:]
3166 cur = cur[8:]
3167 return cur
3167 return cur
3168
3168
3169 def _noqueues():
3169 def _noqueues():
3170 try:
3170 try:
3171 fh = repo.opener(_allqueues, 'r')
3171 fh = repo.opener(_allqueues, 'r')
3172 fh.close()
3172 fh.close()
3173 except IOError:
3173 except IOError:
3174 return True
3174 return True
3175
3175
3176 return False
3176 return False
3177
3177
3178 def _getqueues():
3178 def _getqueues():
3179 current = _getcurrent()
3179 current = _getcurrent()
3180
3180
3181 try:
3181 try:
3182 fh = repo.opener(_allqueues, 'r')
3182 fh = repo.opener(_allqueues, 'r')
3183 queues = [queue.strip() for queue in fh if queue.strip()]
3183 queues = [queue.strip() for queue in fh if queue.strip()]
3184 fh.close()
3184 fh.close()
3185 if current not in queues:
3185 if current not in queues:
3186 queues.append(current)
3186 queues.append(current)
3187 except IOError:
3187 except IOError:
3188 queues = [_defaultqueue]
3188 queues = [_defaultqueue]
3189
3189
3190 return sorted(queues)
3190 return sorted(queues)
3191
3191
3192 def _setactive(name):
3192 def _setactive(name):
3193 if q.applied:
3193 if q.applied:
3194 raise util.Abort(_('patches applied - cannot set new queue active'))
3194 raise util.Abort(_('patches applied - cannot set new queue active'))
3195 _setactivenocheck(name)
3195 _setactivenocheck(name)
3196
3196
3197 def _setactivenocheck(name):
3197 def _setactivenocheck(name):
3198 fh = repo.opener(_activequeue, 'w')
3198 fh = repo.opener(_activequeue, 'w')
3199 if name != 'patches':
3199 if name != 'patches':
3200 fh.write(name)
3200 fh.write(name)
3201 fh.close()
3201 fh.close()
3202
3202
3203 def _addqueue(name):
3203 def _addqueue(name):
3204 fh = repo.opener(_allqueues, 'a')
3204 fh = repo.opener(_allqueues, 'a')
3205 fh.write('%s\n' % (name,))
3205 fh.write('%s\n' % (name,))
3206 fh.close()
3206 fh.close()
3207
3207
3208 def _queuedir(name):
3208 def _queuedir(name):
3209 if name == 'patches':
3209 if name == 'patches':
3210 return repo.join('patches')
3210 return repo.join('patches')
3211 else:
3211 else:
3212 return repo.join('patches-' + name)
3212 return repo.join('patches-' + name)
3213
3213
3214 def _validname(name):
3214 def _validname(name):
3215 for n in name:
3215 for n in name:
3216 if n in ':\\/.':
3216 if n in ':\\/.':
3217 return False
3217 return False
3218 return True
3218 return True
3219
3219
3220 def _delete(name):
3220 def _delete(name):
3221 if name not in existing:
3221 if name not in existing:
3222 raise util.Abort(_('cannot delete queue that does not exist'))
3222 raise util.Abort(_('cannot delete queue that does not exist'))
3223
3223
3224 current = _getcurrent()
3224 current = _getcurrent()
3225
3225
3226 if name == current:
3226 if name == current:
3227 raise util.Abort(_('cannot delete currently active queue'))
3227 raise util.Abort(_('cannot delete currently active queue'))
3228
3228
3229 fh = repo.opener('patches.queues.new', 'w')
3229 fh = repo.opener('patches.queues.new', 'w')
3230 for queue in existing:
3230 for queue in existing:
3231 if queue == name:
3231 if queue == name:
3232 continue
3232 continue
3233 fh.write('%s\n' % (queue,))
3233 fh.write('%s\n' % (queue,))
3234 fh.close()
3234 fh.close()
3235 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3235 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3236
3236
3237 if not name or opts.get('list') or opts.get('active'):
3237 if not name or opts.get('list') or opts.get('active'):
3238 current = _getcurrent()
3238 current = _getcurrent()
3239 if opts.get('active'):
3239 if opts.get('active'):
3240 ui.write('%s\n' % (current,))
3240 ui.write('%s\n' % (current,))
3241 return
3241 return
3242 for queue in _getqueues():
3242 for queue in _getqueues():
3243 ui.write('%s' % (queue,))
3243 ui.write('%s' % (queue,))
3244 if queue == current and not ui.quiet:
3244 if queue == current and not ui.quiet:
3245 ui.write(_(' (active)\n'))
3245 ui.write(_(' (active)\n'))
3246 else:
3246 else:
3247 ui.write('\n')
3247 ui.write('\n')
3248 return
3248 return
3249
3249
3250 if not _validname(name):
3250 if not _validname(name):
3251 raise util.Abort(
3251 raise util.Abort(
3252 _('invalid queue name, may not contain the characters ":\\/."'))
3252 _('invalid queue name, may not contain the characters ":\\/."'))
3253
3253
3254 existing = _getqueues()
3254 existing = _getqueues()
3255
3255
3256 if opts.get('create'):
3256 if opts.get('create'):
3257 if name in existing:
3257 if name in existing:
3258 raise util.Abort(_('queue "%s" already exists') % name)
3258 raise util.Abort(_('queue "%s" already exists') % name)
3259 if _noqueues():
3259 if _noqueues():
3260 _addqueue(_defaultqueue)
3260 _addqueue(_defaultqueue)
3261 _addqueue(name)
3261 _addqueue(name)
3262 _setactive(name)
3262 _setactive(name)
3263 elif opts.get('rename'):
3263 elif opts.get('rename'):
3264 current = _getcurrent()
3264 current = _getcurrent()
3265 if name == current:
3265 if name == current:
3266 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3266 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3267 if name in existing:
3267 if name in existing:
3268 raise util.Abort(_('queue "%s" already exists') % name)
3268 raise util.Abort(_('queue "%s" already exists') % name)
3269
3269
3270 olddir = _queuedir(current)
3270 olddir = _queuedir(current)
3271 newdir = _queuedir(name)
3271 newdir = _queuedir(name)
3272
3272
3273 if os.path.exists(newdir):
3273 if os.path.exists(newdir):
3274 raise util.Abort(_('non-queue directory "%s" already exists') %
3274 raise util.Abort(_('non-queue directory "%s" already exists') %
3275 newdir)
3275 newdir)
3276
3276
3277 fh = repo.opener('patches.queues.new', 'w')
3277 fh = repo.opener('patches.queues.new', 'w')
3278 for queue in existing:
3278 for queue in existing:
3279 if queue == current:
3279 if queue == current:
3280 fh.write('%s\n' % (name,))
3280 fh.write('%s\n' % (name,))
3281 if os.path.exists(olddir):
3281 if os.path.exists(olddir):
3282 util.rename(olddir, newdir)
3282 util.rename(olddir, newdir)
3283 else:
3283 else:
3284 fh.write('%s\n' % (queue,))
3284 fh.write('%s\n' % (queue,))
3285 fh.close()
3285 fh.close()
3286 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3286 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3287 _setactivenocheck(name)
3287 _setactivenocheck(name)
3288 elif opts.get('delete'):
3288 elif opts.get('delete'):
3289 _delete(name)
3289 _delete(name)
3290 elif opts.get('purge'):
3290 elif opts.get('purge'):
3291 if name in existing:
3291 if name in existing:
3292 _delete(name)
3292 _delete(name)
3293 qdir = _queuedir(name)
3293 qdir = _queuedir(name)
3294 if os.path.exists(qdir):
3294 if os.path.exists(qdir):
3295 shutil.rmtree(qdir)
3295 shutil.rmtree(qdir)
3296 else:
3296 else:
3297 if name not in existing:
3297 if name not in existing:
3298 raise util.Abort(_('use --create to create a new queue'))
3298 raise util.Abort(_('use --create to create a new queue'))
3299 _setactive(name)
3299 _setactive(name)
3300
3300
3301 def mqphasedefaults(repo, roots):
3301 def mqphasedefaults(repo, roots):
3302 """callback used to set mq changeset as secret when no phase data exists"""
3302 """callback used to set mq changeset as secret when no phase data exists"""
3303 if repo.mq.applied:
3303 if repo.mq.applied:
3304 if repo.ui.configbool('mq', 'secret', False):
3304 if repo.ui.configbool('mq', 'secret', False):
3305 mqphase = phases.secret
3305 mqphase = phases.secret
3306 else:
3306 else:
3307 mqphase = phases.draft
3307 mqphase = phases.draft
3308 qbase = repo[repo.mq.applied[0].node]
3308 qbase = repo[repo.mq.applied[0].node]
3309 roots[mqphase].add(qbase.node())
3309 roots[mqphase].add(qbase.node())
3310 return roots
3310 return roots
3311
3311
3312 def reposetup(ui, repo):
3312 def reposetup(ui, repo):
3313 class mqrepo(repo.__class__):
3313 class mqrepo(repo.__class__):
3314 @util.propertycache
3314 @util.propertycache
3315 def mq(self):
3315 def mq(self):
3316 return queue(self.ui, self.path)
3316 return queue(self.ui, self.path)
3317
3317
3318 def abortifwdirpatched(self, errmsg, force=False):
3318 def abortifwdirpatched(self, errmsg, force=False):
3319 if self.mq.applied and not force:
3319 if self.mq.applied and not force:
3320 parents = self.dirstate.parents()
3320 parents = self.dirstate.parents()
3321 patches = [s.node for s in self.mq.applied]
3321 patches = [s.node for s in self.mq.applied]
3322 if parents[0] in patches or parents[1] in patches:
3322 if parents[0] in patches or parents[1] in patches:
3323 raise util.Abort(errmsg)
3323 raise util.Abort(errmsg)
3324
3324
3325 def commit(self, text="", user=None, date=None, match=None,
3325 def commit(self, text="", user=None, date=None, match=None,
3326 force=False, editor=False, extra={}):
3326 force=False, editor=False, extra={}):
3327 self.abortifwdirpatched(
3327 self.abortifwdirpatched(
3328 _('cannot commit over an applied mq patch'),
3328 _('cannot commit over an applied mq patch'),
3329 force)
3329 force)
3330
3330
3331 return super(mqrepo, self).commit(text, user, date, match, force,
3331 return super(mqrepo, self).commit(text, user, date, match, force,
3332 editor, extra)
3332 editor, extra)
3333
3333
3334 def checkpush(self, force, revs):
3334 def checkpush(self, force, revs):
3335 if self.mq.applied and not force:
3335 if self.mq.applied and not force:
3336 outapplied = [e.node for e in self.mq.applied]
3336 outapplied = [e.node for e in self.mq.applied]
3337 if revs:
3337 if revs:
3338 # Assume applied patches have no non-patch descendants and
3338 # Assume applied patches have no non-patch descendants and
3339 # are not on remote already. Filtering any changeset not
3339 # are not on remote already. Filtering any changeset not
3340 # pushed.
3340 # pushed.
3341 heads = set(revs)
3341 heads = set(revs)
3342 for node in reversed(outapplied):
3342 for node in reversed(outapplied):
3343 if node in heads:
3343 if node in heads:
3344 break
3344 break
3345 else:
3345 else:
3346 outapplied.pop()
3346 outapplied.pop()
3347 # looking for pushed and shared changeset
3347 # looking for pushed and shared changeset
3348 for node in outapplied:
3348 for node in outapplied:
3349 if repo[node].phase() < phases.secret:
3349 if repo[node].phase() < phases.secret:
3350 raise util.Abort(_('source has mq patches applied'))
3350 raise util.Abort(_('source has mq patches applied'))
3351 # no non-secret patches pushed
3351 # no non-secret patches pushed
3352 super(mqrepo, self).checkpush(force, revs)
3352 super(mqrepo, self).checkpush(force, revs)
3353
3353
3354 def _findtags(self):
3354 def _findtags(self):
3355 '''augment tags from base class with patch tags'''
3355 '''augment tags from base class with patch tags'''
3356 result = super(mqrepo, self)._findtags()
3356 result = super(mqrepo, self)._findtags()
3357
3357
3358 q = self.mq
3358 q = self.mq
3359 if not q.applied:
3359 if not q.applied:
3360 return result
3360 return result
3361
3361
3362 mqtags = [(patch.node, patch.name) for patch in q.applied]
3362 mqtags = [(patch.node, patch.name) for patch in q.applied]
3363
3363
3364 try:
3364 try:
3365 self.changelog.rev(mqtags[-1][0])
3365 self.changelog.rev(mqtags[-1][0])
3366 except error.LookupError:
3366 except error.LookupError:
3367 self.ui.warn(_('mq status file refers to unknown node %s\n')
3367 self.ui.warn(_('mq status file refers to unknown node %s\n')
3368 % short(mqtags[-1][0]))
3368 % short(mqtags[-1][0]))
3369 return result
3369 return result
3370
3370
3371 mqtags.append((mqtags[-1][0], 'qtip'))
3371 mqtags.append((mqtags[-1][0], 'qtip'))
3372 mqtags.append((mqtags[0][0], 'qbase'))
3372 mqtags.append((mqtags[0][0], 'qbase'))
3373 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3373 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3374 tags = result[0]
3374 tags = result[0]
3375 for patch in mqtags:
3375 for patch in mqtags:
3376 if patch[1] in tags:
3376 if patch[1] in tags:
3377 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3377 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3378 % patch[1])
3378 % patch[1])
3379 else:
3379 else:
3380 tags[patch[1]] = patch[0]
3380 tags[patch[1]] = patch[0]
3381
3381
3382 return result
3382 return result
3383
3383
3384 def _branchtags(self, partial, lrev):
3384 def _branchtags(self, partial, lrev):
3385 q = self.mq
3385 q = self.mq
3386 cl = self.changelog
3386 cl = self.changelog
3387 qbase = None
3387 qbase = None
3388 if not q.applied:
3388 if not q.applied:
3389 if getattr(self, '_committingpatch', False):
3389 if getattr(self, '_committingpatch', False):
3390 # Committing a new patch, must be tip
3390 # Committing a new patch, must be tip
3391 qbase = len(cl) - 1
3391 qbase = len(cl) - 1
3392 else:
3392 else:
3393 qbasenode = q.applied[0].node
3393 qbasenode = q.applied[0].node
3394 try:
3394 try:
3395 qbase = cl.rev(qbasenode)
3395 qbase = cl.rev(qbasenode)
3396 except error.LookupError:
3396 except error.LookupError:
3397 self.ui.warn(_('mq status file refers to unknown node %s\n')
3397 self.ui.warn(_('mq status file refers to unknown node %s\n')
3398 % short(qbasenode))
3398 % short(qbasenode))
3399 if qbase is None:
3399 if qbase is None:
3400 return super(mqrepo, self)._branchtags(partial, lrev)
3400 return super(mqrepo, self)._branchtags(partial, lrev)
3401
3401
3402 start = lrev + 1
3402 start = lrev + 1
3403 if start < qbase:
3403 if start < qbase:
3404 # update the cache (excluding the patches) and save it
3404 # update the cache (excluding the patches) and save it
3405 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3405 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3406 self._updatebranchcache(partial, ctxgen)
3406 self._updatebranchcache(partial, ctxgen)
3407 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3407 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3408 start = qbase
3408 start = qbase
3409 # if start = qbase, the cache is as updated as it should be.
3409 # if start = qbase, the cache is as updated as it should be.
3410 # if start > qbase, the cache includes (part of) the patches.
3410 # if start > qbase, the cache includes (part of) the patches.
3411 # we might as well use it, but we won't save it.
3411 # we might as well use it, but we won't save it.
3412
3412
3413 # update the cache up to the tip
3413 # update the cache up to the tip
3414 ctxgen = (self[r] for r in xrange(start, len(cl)))
3414 ctxgen = (self[r] for r in xrange(start, len(cl)))
3415 self._updatebranchcache(partial, ctxgen)
3415 self._updatebranchcache(partial, ctxgen)
3416
3416
3417 return partial
3417 return partial
3418
3418
3419 if repo.local():
3419 if repo.local():
3420 repo.__class__ = mqrepo
3420 repo.__class__ = mqrepo
3421
3421
3422 repo._phasedefaults.append(mqphasedefaults)
3422 repo._phasedefaults.append(mqphasedefaults)
3423
3423
3424 def mqimport(orig, ui, repo, *args, **kwargs):
3424 def mqimport(orig, ui, repo, *args, **kwargs):
3425 if (util.safehasattr(repo, 'abortifwdirpatched')
3425 if (util.safehasattr(repo, 'abortifwdirpatched')
3426 and not kwargs.get('no_commit', False)):
3426 and not kwargs.get('no_commit', False)):
3427 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3427 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3428 kwargs.get('force'))
3428 kwargs.get('force'))
3429 return orig(ui, repo, *args, **kwargs)
3429 return orig(ui, repo, *args, **kwargs)
3430
3430
3431 def mqinit(orig, ui, *args, **kwargs):
3431 def mqinit(orig, ui, *args, **kwargs):
3432 mq = kwargs.pop('mq', None)
3432 mq = kwargs.pop('mq', None)
3433
3433
3434 if not mq:
3434 if not mq:
3435 return orig(ui, *args, **kwargs)
3435 return orig(ui, *args, **kwargs)
3436
3436
3437 if args:
3437 if args:
3438 repopath = args[0]
3438 repopath = args[0]
3439 if not hg.islocal(repopath):
3439 if not hg.islocal(repopath):
3440 raise util.Abort(_('only a local queue repository '
3440 raise util.Abort(_('only a local queue repository '
3441 'may be initialized'))
3441 'may be initialized'))
3442 else:
3442 else:
3443 repopath = cmdutil.findrepo(os.getcwd())
3443 repopath = cmdutil.findrepo(os.getcwd())
3444 if not repopath:
3444 if not repopath:
3445 raise util.Abort(_('there is no Mercurial repository here '
3445 raise util.Abort(_('there is no Mercurial repository here '
3446 '(.hg not found)'))
3446 '(.hg not found)'))
3447 repo = hg.repository(ui, repopath)
3447 repo = hg.repository(ui, repopath)
3448 return qinit(ui, repo, True)
3448 return qinit(ui, repo, True)
3449
3449
3450 def mqcommand(orig, ui, repo, *args, **kwargs):
3450 def mqcommand(orig, ui, repo, *args, **kwargs):
3451 """Add --mq option to operate on patch repository instead of main"""
3451 """Add --mq option to operate on patch repository instead of main"""
3452
3452
3453 # some commands do not like getting unknown options
3453 # some commands do not like getting unknown options
3454 mq = kwargs.pop('mq', None)
3454 mq = kwargs.pop('mq', None)
3455
3455
3456 if not mq:
3456 if not mq:
3457 return orig(ui, repo, *args, **kwargs)
3457 return orig(ui, repo, *args, **kwargs)
3458
3458
3459 q = repo.mq
3459 q = repo.mq
3460 r = q.qrepo()
3460 r = q.qrepo()
3461 if not r:
3461 if not r:
3462 raise util.Abort(_('no queue repository'))
3462 raise util.Abort(_('no queue repository'))
3463 return orig(r.ui, r, *args, **kwargs)
3463 return orig(r.ui, r, *args, **kwargs)
3464
3464
3465 def summary(orig, ui, repo, *args, **kwargs):
3465 def summary(orig, ui, repo, *args, **kwargs):
3466 r = orig(ui, repo, *args, **kwargs)
3466 r = orig(ui, repo, *args, **kwargs)
3467 q = repo.mq
3467 q = repo.mq
3468 m = []
3468 m = []
3469 a, u = len(q.applied), len(q.unapplied(repo))
3469 a, u = len(q.applied), len(q.unapplied(repo))
3470 if a:
3470 if a:
3471 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3471 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3472 if u:
3472 if u:
3473 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3473 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3474 if m:
3474 if m:
3475 ui.write("mq: %s\n" % ', '.join(m))
3475 ui.write("mq: %s\n" % ', '.join(m))
3476 else:
3476 else:
3477 ui.note(_("mq: (empty queue)\n"))
3477 ui.note(_("mq: (empty queue)\n"))
3478 return r
3478 return r
3479
3479
3480 def revsetmq(repo, subset, x):
3480 def revsetmq(repo, subset, x):
3481 """``mq()``
3481 """``mq()``
3482 Changesets managed by MQ.
3482 Changesets managed by MQ.
3483 """
3483 """
3484 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3484 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3485 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3485 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3486 return [r for r in subset if r in applied]
3486 return [r for r in subset if r in applied]
3487
3487
3488 def extsetup(ui):
3488 def extsetup(ui):
3489 revset.symbols['mq'] = revsetmq
3489 revset.symbols['mq'] = revsetmq
3490
3490
3491 # tell hggettext to extract docstrings from these functions:
3491 # tell hggettext to extract docstrings from these functions:
3492 i18nfunctions = [revsetmq]
3492 i18nfunctions = [revsetmq]
3493
3493
3494 def uisetup(ui):
3494 def uisetup(ui):
3495 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3495 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3496
3496
3497 extensions.wrapcommand(commands.table, 'import', mqimport)
3497 extensions.wrapcommand(commands.table, 'import', mqimport)
3498 extensions.wrapcommand(commands.table, 'summary', summary)
3498 extensions.wrapcommand(commands.table, 'summary', summary)
3499
3499
3500 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3500 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3501 entry[1].extend(mqopt)
3501 entry[1].extend(mqopt)
3502
3502
3503 nowrap = set(commands.norepo.split(" "))
3503 nowrap = set(commands.norepo.split(" "))
3504
3504
3505 def dotable(cmdtable):
3505 def dotable(cmdtable):
3506 for cmd in cmdtable.keys():
3506 for cmd in cmdtable.keys():
3507 cmd = cmdutil.parsealiases(cmd)[0]
3507 cmd = cmdutil.parsealiases(cmd)[0]
3508 if cmd in nowrap:
3508 if cmd in nowrap:
3509 continue
3509 continue
3510 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3510 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3511 entry[1].extend(mqopt)
3511 entry[1].extend(mqopt)
3512
3512
3513 dotable(commands.table)
3513 dotable(commands.table)
3514
3514
3515 for extname, extmodule in extensions.extensions():
3515 for extname, extmodule in extensions.extensions():
3516 if extmodule.__file__ != __file__:
3516 if extmodule.__file__ != __file__:
3517 dotable(getattr(extmodule, 'cmdtable', {}))
3517 dotable(getattr(extmodule, 'cmdtable', {}))
3518
3518
3519
3519
3520 colortable = {'qguard.negative': 'red',
3520 colortable = {'qguard.negative': 'red',
3521 'qguard.positive': 'yellow',
3521 'qguard.positive': 'yellow',
3522 'qguard.unguarded': 'green',
3522 'qguard.unguarded': 'green',
3523 'qseries.applied': 'blue bold underline',
3523 'qseries.applied': 'blue bold underline',
3524 'qseries.guarded': 'black bold',
3524 'qseries.guarded': 'black bold',
3525 'qseries.missing': 'red bold',
3525 'qseries.missing': 'red bold',
3526 'qseries.unapplied': 'black bold'}
3526 'qseries.unapplied': 'black bold'}
@@ -1,5752 +1,5752 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, url, encoding, templatekw, discovery
13 import patch, help, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge
18 import dagparser, context, simplemerge
19 import random, setdiscovery, treediscovery, dagutil, pvec
19 import random, setdiscovery, treediscovery, dagutil, pvec
20 import phases
20 import phases
21
21
22 table = {}
22 table = {}
23
23
24 command = cmdutil.command(table)
24 command = cmdutil.command(table)
25
25
26 # common command options
26 # common command options
27
27
28 globalopts = [
28 globalopts = [
29 ('R', 'repository', '',
29 ('R', 'repository', '',
30 _('repository root directory or name of overlay bundle file'),
30 _('repository root directory or name of overlay bundle file'),
31 _('REPO')),
31 _('REPO')),
32 ('', 'cwd', '',
32 ('', 'cwd', '',
33 _('change working directory'), _('DIR')),
33 _('change working directory'), _('DIR')),
34 ('y', 'noninteractive', None,
34 ('y', 'noninteractive', None,
35 _('do not prompt, automatically pick the first choice for all prompts')),
35 _('do not prompt, automatically pick the first choice for all prompts')),
36 ('q', 'quiet', None, _('suppress output')),
36 ('q', 'quiet', None, _('suppress output')),
37 ('v', 'verbose', None, _('enable additional output')),
37 ('v', 'verbose', None, _('enable additional output')),
38 ('', 'config', [],
38 ('', 'config', [],
39 _('set/override config option (use \'section.name=value\')'),
39 _('set/override config option (use \'section.name=value\')'),
40 _('CONFIG')),
40 _('CONFIG')),
41 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debug', None, _('enable debugging output')),
42 ('', 'debugger', None, _('start debugger')),
42 ('', 'debugger', None, _('start debugger')),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
44 _('ENCODE')),
44 _('ENCODE')),
45 ('', 'encodingmode', encoding.encodingmode,
45 ('', 'encodingmode', encoding.encodingmode,
46 _('set the charset encoding mode'), _('MODE')),
46 _('set the charset encoding mode'), _('MODE')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
48 ('', 'time', None, _('time how long the command takes')),
48 ('', 'time', None, _('time how long the command takes')),
49 ('', 'profile', None, _('print command execution profile')),
49 ('', 'profile', None, _('print command execution profile')),
50 ('', 'version', None, _('output version information and exit')),
50 ('', 'version', None, _('output version information and exit')),
51 ('h', 'help', None, _('display help and exit')),
51 ('h', 'help', None, _('display help and exit')),
52 ]
52 ]
53
53
54 dryrunopts = [('n', 'dry-run', None,
54 dryrunopts = [('n', 'dry-run', None,
55 _('do not perform actions, just print output'))]
55 _('do not perform actions, just print output'))]
56
56
57 remoteopts = [
57 remoteopts = [
58 ('e', 'ssh', '',
58 ('e', 'ssh', '',
59 _('specify ssh command to use'), _('CMD')),
59 _('specify ssh command to use'), _('CMD')),
60 ('', 'remotecmd', '',
60 ('', 'remotecmd', '',
61 _('specify hg command to run on the remote side'), _('CMD')),
61 _('specify hg command to run on the remote side'), _('CMD')),
62 ('', 'insecure', None,
62 ('', 'insecure', None,
63 _('do not verify server certificate (ignoring web.cacerts config)')),
63 _('do not verify server certificate (ignoring web.cacerts config)')),
64 ]
64 ]
65
65
66 walkopts = [
66 walkopts = [
67 ('I', 'include', [],
67 ('I', 'include', [],
68 _('include names matching the given patterns'), _('PATTERN')),
68 _('include names matching the given patterns'), _('PATTERN')),
69 ('X', 'exclude', [],
69 ('X', 'exclude', [],
70 _('exclude names matching the given patterns'), _('PATTERN')),
70 _('exclude names matching the given patterns'), _('PATTERN')),
71 ]
71 ]
72
72
73 commitopts = [
73 commitopts = [
74 ('m', 'message', '',
74 ('m', 'message', '',
75 _('use text as commit message'), _('TEXT')),
75 _('use text as commit message'), _('TEXT')),
76 ('l', 'logfile', '',
76 ('l', 'logfile', '',
77 _('read commit message from file'), _('FILE')),
77 _('read commit message from file'), _('FILE')),
78 ]
78 ]
79
79
80 commitopts2 = [
80 commitopts2 = [
81 ('d', 'date', '',
81 ('d', 'date', '',
82 _('record the specified date as commit date'), _('DATE')),
82 _('record the specified date as commit date'), _('DATE')),
83 ('u', 'user', '',
83 ('u', 'user', '',
84 _('record the specified user as committer'), _('USER')),
84 _('record the specified user as committer'), _('USER')),
85 ]
85 ]
86
86
87 templateopts = [
87 templateopts = [
88 ('', 'style', '',
88 ('', 'style', '',
89 _('display using template map file'), _('STYLE')),
89 _('display using template map file'), _('STYLE')),
90 ('', 'template', '',
90 ('', 'template', '',
91 _('display with template'), _('TEMPLATE')),
91 _('display with template'), _('TEMPLATE')),
92 ]
92 ]
93
93
94 logopts = [
94 logopts = [
95 ('p', 'patch', None, _('show patch')),
95 ('p', 'patch', None, _('show patch')),
96 ('g', 'git', None, _('use git extended diff format')),
96 ('g', 'git', None, _('use git extended diff format')),
97 ('l', 'limit', '',
97 ('l', 'limit', '',
98 _('limit number of changes displayed'), _('NUM')),
98 _('limit number of changes displayed'), _('NUM')),
99 ('M', 'no-merges', None, _('do not show merges')),
99 ('M', 'no-merges', None, _('do not show merges')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
101 ] + templateopts
101 ] + templateopts
102
102
103 diffopts = [
103 diffopts = [
104 ('a', 'text', None, _('treat all files as text')),
104 ('a', 'text', None, _('treat all files as text')),
105 ('g', 'git', None, _('use git extended diff format')),
105 ('g', 'git', None, _('use git extended diff format')),
106 ('', 'nodates', None, _('omit dates from diff headers'))
106 ('', 'nodates', None, _('omit dates from diff headers'))
107 ]
107 ]
108
108
109 diffwsopts = [
109 diffwsopts = [
110 ('w', 'ignore-all-space', None,
110 ('w', 'ignore-all-space', None,
111 _('ignore white space when comparing lines')),
111 _('ignore white space when comparing lines')),
112 ('b', 'ignore-space-change', None,
112 ('b', 'ignore-space-change', None,
113 _('ignore changes in the amount of white space')),
113 _('ignore changes in the amount of white space')),
114 ('B', 'ignore-blank-lines', None,
114 ('B', 'ignore-blank-lines', None,
115 _('ignore changes whose lines are all blank')),
115 _('ignore changes whose lines are all blank')),
116 ]
116 ]
117
117
118 diffopts2 = [
118 diffopts2 = [
119 ('p', 'show-function', None, _('show which function each change is in')),
119 ('p', 'show-function', None, _('show which function each change is in')),
120 ('', 'reverse', None, _('produce a diff that undoes the changes')),
120 ('', 'reverse', None, _('produce a diff that undoes the changes')),
121 ] + diffwsopts + [
121 ] + diffwsopts + [
122 ('U', 'unified', '',
122 ('U', 'unified', '',
123 _('number of lines of context to show'), _('NUM')),
123 _('number of lines of context to show'), _('NUM')),
124 ('', 'stat', None, _('output diffstat-style summary of changes')),
124 ('', 'stat', None, _('output diffstat-style summary of changes')),
125 ]
125 ]
126
126
127 mergetoolopts = [
127 mergetoolopts = [
128 ('t', 'tool', '', _('specify merge tool')),
128 ('t', 'tool', '', _('specify merge tool')),
129 ]
129 ]
130
130
131 similarityopts = [
131 similarityopts = [
132 ('s', 'similarity', '',
132 ('s', 'similarity', '',
133 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
133 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
134 ]
134 ]
135
135
136 subrepoopts = [
136 subrepoopts = [
137 ('S', 'subrepos', None,
137 ('S', 'subrepos', None,
138 _('recurse into subrepositories'))
138 _('recurse into subrepositories'))
139 ]
139 ]
140
140
141 # Commands start here, listed alphabetically
141 # Commands start here, listed alphabetically
142
142
143 @command('^add',
143 @command('^add',
144 walkopts + subrepoopts + dryrunopts,
144 walkopts + subrepoopts + dryrunopts,
145 _('[OPTION]... [FILE]...'))
145 _('[OPTION]... [FILE]...'))
146 def add(ui, repo, *pats, **opts):
146 def add(ui, repo, *pats, **opts):
147 """add the specified files on the next commit
147 """add the specified files on the next commit
148
148
149 Schedule files to be version controlled and added to the
149 Schedule files to be version controlled and added to the
150 repository.
150 repository.
151
151
152 The files will be added to the repository at the next commit. To
152 The files will be added to the repository at the next commit. To
153 undo an add before that, see :hg:`forget`.
153 undo an add before that, see :hg:`forget`.
154
154
155 If no names are given, add all files to the repository.
155 If no names are given, add all files to the repository.
156
156
157 .. container:: verbose
157 .. container:: verbose
158
158
159 An example showing how new (unknown) files are added
159 An example showing how new (unknown) files are added
160 automatically by :hg:`add`::
160 automatically by :hg:`add`::
161
161
162 $ ls
162 $ ls
163 foo.c
163 foo.c
164 $ hg status
164 $ hg status
165 ? foo.c
165 ? foo.c
166 $ hg add
166 $ hg add
167 adding foo.c
167 adding foo.c
168 $ hg status
168 $ hg status
169 A foo.c
169 A foo.c
170
170
171 Returns 0 if all files are successfully added.
171 Returns 0 if all files are successfully added.
172 """
172 """
173
173
174 m = scmutil.match(repo[None], pats, opts)
174 m = scmutil.match(repo[None], pats, opts)
175 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
175 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
176 opts.get('subrepos'), prefix="", explicitonly=False)
176 opts.get('subrepos'), prefix="", explicitonly=False)
177 return rejected and 1 or 0
177 return rejected and 1 or 0
178
178
179 @command('addremove',
179 @command('addremove',
180 similarityopts + walkopts + dryrunopts,
180 similarityopts + walkopts + dryrunopts,
181 _('[OPTION]... [FILE]...'))
181 _('[OPTION]... [FILE]...'))
182 def addremove(ui, repo, *pats, **opts):
182 def addremove(ui, repo, *pats, **opts):
183 """add all new files, delete all missing files
183 """add all new files, delete all missing files
184
184
185 Add all new files and remove all missing files from the
185 Add all new files and remove all missing files from the
186 repository.
186 repository.
187
187
188 New files are ignored if they match any of the patterns in
188 New files are ignored if they match any of the patterns in
189 ``.hgignore``. As with add, these changes take effect at the next
189 ``.hgignore``. As with add, these changes take effect at the next
190 commit.
190 commit.
191
191
192 Use the -s/--similarity option to detect renamed files. With a
192 Use the -s/--similarity option to detect renamed files. With a
193 parameter greater than 0, this compares every removed file with
193 parameter greater than 0, this compares every removed file with
194 every added file and records those similar enough as renames. This
194 every added file and records those similar enough as renames. This
195 option takes a percentage between 0 (disabled) and 100 (files must
195 option takes a percentage between 0 (disabled) and 100 (files must
196 be identical) as its parameter. Detecting renamed files this way
196 be identical) as its parameter. Detecting renamed files this way
197 can be expensive. After using this option, :hg:`status -C` can be
197 can be expensive. After using this option, :hg:`status -C` can be
198 used to check which files were identified as moved or renamed.
198 used to check which files were identified as moved or renamed.
199 If this option is not specified, only renames of identical files
199 If this option is not specified, only renames of identical files
200 are detected.
200 are detected.
201
201
202 Returns 0 if all files are successfully added.
202 Returns 0 if all files are successfully added.
203 """
203 """
204 try:
204 try:
205 sim = float(opts.get('similarity') or 100)
205 sim = float(opts.get('similarity') or 100)
206 except ValueError:
206 except ValueError:
207 raise util.Abort(_('similarity must be a number'))
207 raise util.Abort(_('similarity must be a number'))
208 if sim < 0 or sim > 100:
208 if sim < 0 or sim > 100:
209 raise util.Abort(_('similarity must be between 0 and 100'))
209 raise util.Abort(_('similarity must be between 0 and 100'))
210 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
210 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
211
211
212 @command('^annotate|blame',
212 @command('^annotate|blame',
213 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
213 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
214 ('', 'follow', None,
214 ('', 'follow', None,
215 _('follow copies/renames and list the filename (DEPRECATED)')),
215 _('follow copies/renames and list the filename (DEPRECATED)')),
216 ('', 'no-follow', None, _("don't follow copies and renames")),
216 ('', 'no-follow', None, _("don't follow copies and renames")),
217 ('a', 'text', None, _('treat all files as text')),
217 ('a', 'text', None, _('treat all files as text')),
218 ('u', 'user', None, _('list the author (long with -v)')),
218 ('u', 'user', None, _('list the author (long with -v)')),
219 ('f', 'file', None, _('list the filename')),
219 ('f', 'file', None, _('list the filename')),
220 ('d', 'date', None, _('list the date (short with -q)')),
220 ('d', 'date', None, _('list the date (short with -q)')),
221 ('n', 'number', None, _('list the revision number (default)')),
221 ('n', 'number', None, _('list the revision number (default)')),
222 ('c', 'changeset', None, _('list the changeset')),
222 ('c', 'changeset', None, _('list the changeset')),
223 ('l', 'line-number', None, _('show line number at the first appearance'))
223 ('l', 'line-number', None, _('show line number at the first appearance'))
224 ] + diffwsopts + walkopts,
224 ] + diffwsopts + walkopts,
225 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
225 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
226 def annotate(ui, repo, *pats, **opts):
226 def annotate(ui, repo, *pats, **opts):
227 """show changeset information by line for each file
227 """show changeset information by line for each file
228
228
229 List changes in files, showing the revision id responsible for
229 List changes in files, showing the revision id responsible for
230 each line
230 each line
231
231
232 This command is useful for discovering when a change was made and
232 This command is useful for discovering when a change was made and
233 by whom.
233 by whom.
234
234
235 Without the -a/--text option, annotate will avoid processing files
235 Without the -a/--text option, annotate will avoid processing files
236 it detects as binary. With -a, annotate will annotate the file
236 it detects as binary. With -a, annotate will annotate the file
237 anyway, although the results will probably be neither useful
237 anyway, although the results will probably be neither useful
238 nor desirable.
238 nor desirable.
239
239
240 Returns 0 on success.
240 Returns 0 on success.
241 """
241 """
242 if opts.get('follow'):
242 if opts.get('follow'):
243 # --follow is deprecated and now just an alias for -f/--file
243 # --follow is deprecated and now just an alias for -f/--file
244 # to mimic the behavior of Mercurial before version 1.5
244 # to mimic the behavior of Mercurial before version 1.5
245 opts['file'] = True
245 opts['file'] = True
246
246
247 datefunc = ui.quiet and util.shortdate or util.datestr
247 datefunc = ui.quiet and util.shortdate or util.datestr
248 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
248 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
249
249
250 if not pats:
250 if not pats:
251 raise util.Abort(_('at least one filename or pattern is required'))
251 raise util.Abort(_('at least one filename or pattern is required'))
252
252
253 hexfn = ui.debugflag and hex or short
253 hexfn = ui.debugflag and hex or short
254
254
255 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
255 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
256 ('number', ' ', lambda x: str(x[0].rev())),
256 ('number', ' ', lambda x: str(x[0].rev())),
257 ('changeset', ' ', lambda x: hexfn(x[0].node())),
257 ('changeset', ' ', lambda x: hexfn(x[0].node())),
258 ('date', ' ', getdate),
258 ('date', ' ', getdate),
259 ('file', ' ', lambda x: x[0].path()),
259 ('file', ' ', lambda x: x[0].path()),
260 ('line_number', ':', lambda x: str(x[1])),
260 ('line_number', ':', lambda x: str(x[1])),
261 ]
261 ]
262
262
263 if (not opts.get('user') and not opts.get('changeset')
263 if (not opts.get('user') and not opts.get('changeset')
264 and not opts.get('date') and not opts.get('file')):
264 and not opts.get('date') and not opts.get('file')):
265 opts['number'] = True
265 opts['number'] = True
266
266
267 linenumber = opts.get('line_number') is not None
267 linenumber = opts.get('line_number') is not None
268 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
268 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
269 raise util.Abort(_('at least one of -n/-c is required for -l'))
269 raise util.Abort(_('at least one of -n/-c is required for -l'))
270
270
271 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
271 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
272 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
272 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
273
273
274 def bad(x, y):
274 def bad(x, y):
275 raise util.Abort("%s: %s" % (x, y))
275 raise util.Abort("%s: %s" % (x, y))
276
276
277 ctx = scmutil.revsingle(repo, opts.get('rev'))
277 ctx = scmutil.revsingle(repo, opts.get('rev'))
278 m = scmutil.match(ctx, pats, opts)
278 m = scmutil.match(ctx, pats, opts)
279 m.bad = bad
279 m.bad = bad
280 follow = not opts.get('no_follow')
280 follow = not opts.get('no_follow')
281 diffopts = patch.diffopts(ui, opts, section='annotate')
281 diffopts = patch.diffopts(ui, opts, section='annotate')
282 for abs in ctx.walk(m):
282 for abs in ctx.walk(m):
283 fctx = ctx[abs]
283 fctx = ctx[abs]
284 if not opts.get('text') and util.binary(fctx.data()):
284 if not opts.get('text') and util.binary(fctx.data()):
285 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
285 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
286 continue
286 continue
287
287
288 lines = fctx.annotate(follow=follow, linenumber=linenumber,
288 lines = fctx.annotate(follow=follow, linenumber=linenumber,
289 diffopts=diffopts)
289 diffopts=diffopts)
290 pieces = []
290 pieces = []
291
291
292 for f, sep in funcmap:
292 for f, sep in funcmap:
293 l = [f(n) for n, dummy in lines]
293 l = [f(n) for n, dummy in lines]
294 if l:
294 if l:
295 sized = [(x, encoding.colwidth(x)) for x in l]
295 sized = [(x, encoding.colwidth(x)) for x in l]
296 ml = max([w for x, w in sized])
296 ml = max([w for x, w in sized])
297 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
297 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
298 for x, w in sized])
298 for x, w in sized])
299
299
300 if pieces:
300 if pieces:
301 for p, l in zip(zip(*pieces), lines):
301 for p, l in zip(zip(*pieces), lines):
302 ui.write("%s: %s" % ("".join(p), l[1]))
302 ui.write("%s: %s" % ("".join(p), l[1]))
303
303
304 if lines and not lines[-1][1].endswith('\n'):
304 if lines and not lines[-1][1].endswith('\n'):
305 ui.write('\n')
305 ui.write('\n')
306
306
307 @command('archive',
307 @command('archive',
308 [('', 'no-decode', None, _('do not pass files through decoders')),
308 [('', 'no-decode', None, _('do not pass files through decoders')),
309 ('p', 'prefix', '', _('directory prefix for files in archive'),
309 ('p', 'prefix', '', _('directory prefix for files in archive'),
310 _('PREFIX')),
310 _('PREFIX')),
311 ('r', 'rev', '', _('revision to distribute'), _('REV')),
311 ('r', 'rev', '', _('revision to distribute'), _('REV')),
312 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
312 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
313 ] + subrepoopts + walkopts,
313 ] + subrepoopts + walkopts,
314 _('[OPTION]... DEST'))
314 _('[OPTION]... DEST'))
315 def archive(ui, repo, dest, **opts):
315 def archive(ui, repo, dest, **opts):
316 '''create an unversioned archive of a repository revision
316 '''create an unversioned archive of a repository revision
317
317
318 By default, the revision used is the parent of the working
318 By default, the revision used is the parent of the working
319 directory; use -r/--rev to specify a different revision.
319 directory; use -r/--rev to specify a different revision.
320
320
321 The archive type is automatically detected based on file
321 The archive type is automatically detected based on file
322 extension (or override using -t/--type).
322 extension (or override using -t/--type).
323
323
324 .. container:: verbose
324 .. container:: verbose
325
325
326 Examples:
326 Examples:
327
327
328 - create a zip file containing the 1.0 release::
328 - create a zip file containing the 1.0 release::
329
329
330 hg archive -r 1.0 project-1.0.zip
330 hg archive -r 1.0 project-1.0.zip
331
331
332 - create a tarball excluding .hg files::
332 - create a tarball excluding .hg files::
333
333
334 hg archive project.tar.gz -X ".hg*"
334 hg archive project.tar.gz -X ".hg*"
335
335
336 Valid types are:
336 Valid types are:
337
337
338 :``files``: a directory full of files (default)
338 :``files``: a directory full of files (default)
339 :``tar``: tar archive, uncompressed
339 :``tar``: tar archive, uncompressed
340 :``tbz2``: tar archive, compressed using bzip2
340 :``tbz2``: tar archive, compressed using bzip2
341 :``tgz``: tar archive, compressed using gzip
341 :``tgz``: tar archive, compressed using gzip
342 :``uzip``: zip archive, uncompressed
342 :``uzip``: zip archive, uncompressed
343 :``zip``: zip archive, compressed using deflate
343 :``zip``: zip archive, compressed using deflate
344
344
345 The exact name of the destination archive or directory is given
345 The exact name of the destination archive or directory is given
346 using a format string; see :hg:`help export` for details.
346 using a format string; see :hg:`help export` for details.
347
347
348 Each member added to an archive file has a directory prefix
348 Each member added to an archive file has a directory prefix
349 prepended. Use -p/--prefix to specify a format string for the
349 prepended. Use -p/--prefix to specify a format string for the
350 prefix. The default is the basename of the archive, with suffixes
350 prefix. The default is the basename of the archive, with suffixes
351 removed.
351 removed.
352
352
353 Returns 0 on success.
353 Returns 0 on success.
354 '''
354 '''
355
355
356 ctx = scmutil.revsingle(repo, opts.get('rev'))
356 ctx = scmutil.revsingle(repo, opts.get('rev'))
357 if not ctx:
357 if not ctx:
358 raise util.Abort(_('no working directory: please specify a revision'))
358 raise util.Abort(_('no working directory: please specify a revision'))
359 node = ctx.node()
359 node = ctx.node()
360 dest = cmdutil.makefilename(repo, dest, node)
360 dest = cmdutil.makefilename(repo, dest, node)
361 if os.path.realpath(dest) == repo.root:
361 if os.path.realpath(dest) == repo.root:
362 raise util.Abort(_('repository root cannot be destination'))
362 raise util.Abort(_('repository root cannot be destination'))
363
363
364 kind = opts.get('type') or archival.guesskind(dest) or 'files'
364 kind = opts.get('type') or archival.guesskind(dest) or 'files'
365 prefix = opts.get('prefix')
365 prefix = opts.get('prefix')
366
366
367 if dest == '-':
367 if dest == '-':
368 if kind == 'files':
368 if kind == 'files':
369 raise util.Abort(_('cannot archive plain files to stdout'))
369 raise util.Abort(_('cannot archive plain files to stdout'))
370 dest = cmdutil.makefileobj(repo, dest)
370 dest = cmdutil.makefileobj(repo, dest)
371 if not prefix:
371 if not prefix:
372 prefix = os.path.basename(repo.root) + '-%h'
372 prefix = os.path.basename(repo.root) + '-%h'
373
373
374 prefix = cmdutil.makefilename(repo, prefix, node)
374 prefix = cmdutil.makefilename(repo, prefix, node)
375 matchfn = scmutil.match(ctx, [], opts)
375 matchfn = scmutil.match(ctx, [], opts)
376 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
376 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
377 matchfn, prefix, subrepos=opts.get('subrepos'))
377 matchfn, prefix, subrepos=opts.get('subrepos'))
378
378
379 @command('backout',
379 @command('backout',
380 [('', 'merge', None, _('merge with old dirstate parent after backout')),
380 [('', 'merge', None, _('merge with old dirstate parent after backout')),
381 ('', 'parent', '',
381 ('', 'parent', '',
382 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
382 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
383 ('r', 'rev', '', _('revision to backout'), _('REV')),
383 ('r', 'rev', '', _('revision to backout'), _('REV')),
384 ] + mergetoolopts + walkopts + commitopts + commitopts2,
384 ] + mergetoolopts + walkopts + commitopts + commitopts2,
385 _('[OPTION]... [-r] REV'))
385 _('[OPTION]... [-r] REV'))
386 def backout(ui, repo, node=None, rev=None, **opts):
386 def backout(ui, repo, node=None, rev=None, **opts):
387 '''reverse effect of earlier changeset
387 '''reverse effect of earlier changeset
388
388
389 Prepare a new changeset with the effect of REV undone in the
389 Prepare a new changeset with the effect of REV undone in the
390 current working directory.
390 current working directory.
391
391
392 If REV is the parent of the working directory, then this new changeset
392 If REV is the parent of the working directory, then this new changeset
393 is committed automatically. Otherwise, hg needs to merge the
393 is committed automatically. Otherwise, hg needs to merge the
394 changes and the merged result is left uncommitted.
394 changes and the merged result is left uncommitted.
395
395
396 .. note::
396 .. note::
397 backout cannot be used to fix either an unwanted or
397 backout cannot be used to fix either an unwanted or
398 incorrect merge.
398 incorrect merge.
399
399
400 .. container:: verbose
400 .. container:: verbose
401
401
402 By default, the pending changeset will have one parent,
402 By default, the pending changeset will have one parent,
403 maintaining a linear history. With --merge, the pending
403 maintaining a linear history. With --merge, the pending
404 changeset will instead have two parents: the old parent of the
404 changeset will instead have two parents: the old parent of the
405 working directory and a new child of REV that simply undoes REV.
405 working directory and a new child of REV that simply undoes REV.
406
406
407 Before version 1.7, the behavior without --merge was equivalent
407 Before version 1.7, the behavior without --merge was equivalent
408 to specifying --merge followed by :hg:`update --clean .` to
408 to specifying --merge followed by :hg:`update --clean .` to
409 cancel the merge and leave the child of REV as a head to be
409 cancel the merge and leave the child of REV as a head to be
410 merged separately.
410 merged separately.
411
411
412 See :hg:`help dates` for a list of formats valid for -d/--date.
412 See :hg:`help dates` for a list of formats valid for -d/--date.
413
413
414 Returns 0 on success.
414 Returns 0 on success.
415 '''
415 '''
416 if rev and node:
416 if rev and node:
417 raise util.Abort(_("please specify just one revision"))
417 raise util.Abort(_("please specify just one revision"))
418
418
419 if not rev:
419 if not rev:
420 rev = node
420 rev = node
421
421
422 if not rev:
422 if not rev:
423 raise util.Abort(_("please specify a revision to backout"))
423 raise util.Abort(_("please specify a revision to backout"))
424
424
425 date = opts.get('date')
425 date = opts.get('date')
426 if date:
426 if date:
427 opts['date'] = util.parsedate(date)
427 opts['date'] = util.parsedate(date)
428
428
429 cmdutil.bailifchanged(repo)
429 cmdutil.bailifchanged(repo)
430 node = scmutil.revsingle(repo, rev).node()
430 node = scmutil.revsingle(repo, rev).node()
431
431
432 op1, op2 = repo.dirstate.parents()
432 op1, op2 = repo.dirstate.parents()
433 a = repo.changelog.ancestor(op1, node)
433 a = repo.changelog.ancestor(op1, node)
434 if a != node:
434 if a != node:
435 raise util.Abort(_('cannot backout change on a different branch'))
435 raise util.Abort(_('cannot backout change on a different branch'))
436
436
437 p1, p2 = repo.changelog.parents(node)
437 p1, p2 = repo.changelog.parents(node)
438 if p1 == nullid:
438 if p1 == nullid:
439 raise util.Abort(_('cannot backout a change with no parents'))
439 raise util.Abort(_('cannot backout a change with no parents'))
440 if p2 != nullid:
440 if p2 != nullid:
441 if not opts.get('parent'):
441 if not opts.get('parent'):
442 raise util.Abort(_('cannot backout a merge changeset'))
442 raise util.Abort(_('cannot backout a merge changeset'))
443 p = repo.lookup(opts['parent'])
443 p = repo.lookup(opts['parent'])
444 if p not in (p1, p2):
444 if p not in (p1, p2):
445 raise util.Abort(_('%s is not a parent of %s') %
445 raise util.Abort(_('%s is not a parent of %s') %
446 (short(p), short(node)))
446 (short(p), short(node)))
447 parent = p
447 parent = p
448 else:
448 else:
449 if opts.get('parent'):
449 if opts.get('parent'):
450 raise util.Abort(_('cannot use --parent on non-merge changeset'))
450 raise util.Abort(_('cannot use --parent on non-merge changeset'))
451 parent = p1
451 parent = p1
452
452
453 # the backout should appear on the same branch
453 # the backout should appear on the same branch
454 wlock = repo.wlock()
454 wlock = repo.wlock()
455 try:
455 try:
456 branch = repo.dirstate.branch()
456 branch = repo.dirstate.branch()
457 hg.clean(repo, node, show_stats=False)
457 hg.clean(repo, node, show_stats=False)
458 repo.dirstate.setbranch(branch)
458 repo.dirstate.setbranch(branch)
459 revert_opts = opts.copy()
459 revert_opts = opts.copy()
460 revert_opts['date'] = None
460 revert_opts['date'] = None
461 revert_opts['all'] = True
461 revert_opts['all'] = True
462 revert_opts['rev'] = hex(parent)
462 revert_opts['rev'] = hex(parent)
463 revert_opts['no_backup'] = None
463 revert_opts['no_backup'] = None
464 revert(ui, repo, **revert_opts)
464 revert(ui, repo, **revert_opts)
465 if not opts.get('merge') and op1 != node:
465 if not opts.get('merge') and op1 != node:
466 try:
466 try:
467 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
467 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
468 return hg.update(repo, op1)
468 return hg.update(repo, op1)
469 finally:
469 finally:
470 ui.setconfig('ui', 'forcemerge', '')
470 ui.setconfig('ui', 'forcemerge', '')
471
471
472 commit_opts = opts.copy()
472 commit_opts = opts.copy()
473 commit_opts['addremove'] = False
473 commit_opts['addremove'] = False
474 if not commit_opts['message'] and not commit_opts['logfile']:
474 if not commit_opts['message'] and not commit_opts['logfile']:
475 # we don't translate commit messages
475 # we don't translate commit messages
476 commit_opts['message'] = "Backed out changeset %s" % short(node)
476 commit_opts['message'] = "Backed out changeset %s" % short(node)
477 commit_opts['force_editor'] = True
477 commit_opts['force_editor'] = True
478 commit(ui, repo, **commit_opts)
478 commit(ui, repo, **commit_opts)
479 def nice(node):
479 def nice(node):
480 return '%d:%s' % (repo.changelog.rev(node), short(node))
480 return '%d:%s' % (repo.changelog.rev(node), short(node))
481 ui.status(_('changeset %s backs out changeset %s\n') %
481 ui.status(_('changeset %s backs out changeset %s\n') %
482 (nice(repo.changelog.tip()), nice(node)))
482 (nice(repo.changelog.tip()), nice(node)))
483 if opts.get('merge') and op1 != node:
483 if opts.get('merge') and op1 != node:
484 hg.clean(repo, op1, show_stats=False)
484 hg.clean(repo, op1, show_stats=False)
485 ui.status(_('merging with changeset %s\n')
485 ui.status(_('merging with changeset %s\n')
486 % nice(repo.changelog.tip()))
486 % nice(repo.changelog.tip()))
487 try:
487 try:
488 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
488 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
489 return hg.merge(repo, hex(repo.changelog.tip()))
489 return hg.merge(repo, hex(repo.changelog.tip()))
490 finally:
490 finally:
491 ui.setconfig('ui', 'forcemerge', '')
491 ui.setconfig('ui', 'forcemerge', '')
492 finally:
492 finally:
493 wlock.release()
493 wlock.release()
494 return 0
494 return 0
495
495
496 @command('bisect',
496 @command('bisect',
497 [('r', 'reset', False, _('reset bisect state')),
497 [('r', 'reset', False, _('reset bisect state')),
498 ('g', 'good', False, _('mark changeset good')),
498 ('g', 'good', False, _('mark changeset good')),
499 ('b', 'bad', False, _('mark changeset bad')),
499 ('b', 'bad', False, _('mark changeset bad')),
500 ('s', 'skip', False, _('skip testing changeset')),
500 ('s', 'skip', False, _('skip testing changeset')),
501 ('e', 'extend', False, _('extend the bisect range')),
501 ('e', 'extend', False, _('extend the bisect range')),
502 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
502 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
503 ('U', 'noupdate', False, _('do not update to target'))],
503 ('U', 'noupdate', False, _('do not update to target'))],
504 _("[-gbsr] [-U] [-c CMD] [REV]"))
504 _("[-gbsr] [-U] [-c CMD] [REV]"))
505 def bisect(ui, repo, rev=None, extra=None, command=None,
505 def bisect(ui, repo, rev=None, extra=None, command=None,
506 reset=None, good=None, bad=None, skip=None, extend=None,
506 reset=None, good=None, bad=None, skip=None, extend=None,
507 noupdate=None):
507 noupdate=None):
508 """subdivision search of changesets
508 """subdivision search of changesets
509
509
510 This command helps to find changesets which introduce problems. To
510 This command helps to find changesets which introduce problems. To
511 use, mark the earliest changeset you know exhibits the problem as
511 use, mark the earliest changeset you know exhibits the problem as
512 bad, then mark the latest changeset which is free from the problem
512 bad, then mark the latest changeset which is free from the problem
513 as good. Bisect will update your working directory to a revision
513 as good. Bisect will update your working directory to a revision
514 for testing (unless the -U/--noupdate option is specified). Once
514 for testing (unless the -U/--noupdate option is specified). Once
515 you have performed tests, mark the working directory as good or
515 you have performed tests, mark the working directory as good or
516 bad, and bisect will either update to another candidate changeset
516 bad, and bisect will either update to another candidate changeset
517 or announce that it has found the bad revision.
517 or announce that it has found the bad revision.
518
518
519 As a shortcut, you can also use the revision argument to mark a
519 As a shortcut, you can also use the revision argument to mark a
520 revision as good or bad without checking it out first.
520 revision as good or bad without checking it out first.
521
521
522 If you supply a command, it will be used for automatic bisection.
522 If you supply a command, it will be used for automatic bisection.
523 The environment variable HG_NODE will contain the ID of the
523 The environment variable HG_NODE will contain the ID of the
524 changeset being tested. The exit status of the command will be
524 changeset being tested. The exit status of the command will be
525 used to mark revisions as good or bad: status 0 means good, 125
525 used to mark revisions as good or bad: status 0 means good, 125
526 means to skip the revision, 127 (command not found) will abort the
526 means to skip the revision, 127 (command not found) will abort the
527 bisection, and any other non-zero exit status means the revision
527 bisection, and any other non-zero exit status means the revision
528 is bad.
528 is bad.
529
529
530 .. container:: verbose
530 .. container:: verbose
531
531
532 Some examples:
532 Some examples:
533
533
534 - start a bisection with known bad revision 12, and good revision 34::
534 - start a bisection with known bad revision 12, and good revision 34::
535
535
536 hg bisect --bad 34
536 hg bisect --bad 34
537 hg bisect --good 12
537 hg bisect --good 12
538
538
539 - advance the current bisection by marking current revision as good or
539 - advance the current bisection by marking current revision as good or
540 bad::
540 bad::
541
541
542 hg bisect --good
542 hg bisect --good
543 hg bisect --bad
543 hg bisect --bad
544
544
545 - mark the current revision, or a known revision, to be skipped (eg. if
545 - mark the current revision, or a known revision, to be skipped (eg. if
546 that revision is not usable because of another issue)::
546 that revision is not usable because of another issue)::
547
547
548 hg bisect --skip
548 hg bisect --skip
549 hg bisect --skip 23
549 hg bisect --skip 23
550
550
551 - forget the current bisection::
551 - forget the current bisection::
552
552
553 hg bisect --reset
553 hg bisect --reset
554
554
555 - use 'make && make tests' to automatically find the first broken
555 - use 'make && make tests' to automatically find the first broken
556 revision::
556 revision::
557
557
558 hg bisect --reset
558 hg bisect --reset
559 hg bisect --bad 34
559 hg bisect --bad 34
560 hg bisect --good 12
560 hg bisect --good 12
561 hg bisect --command 'make && make tests'
561 hg bisect --command 'make && make tests'
562
562
563 - see all changesets whose states are already known in the current
563 - see all changesets whose states are already known in the current
564 bisection::
564 bisection::
565
565
566 hg log -r "bisect(pruned)"
566 hg log -r "bisect(pruned)"
567
567
568 - see the changeset currently being bisected (especially useful
568 - see the changeset currently being bisected (especially useful
569 if running with -U/--noupdate)::
569 if running with -U/--noupdate)::
570
570
571 hg log -r "bisect(current)"
571 hg log -r "bisect(current)"
572
572
573 - see all changesets that took part in the current bisection::
573 - see all changesets that took part in the current bisection::
574
574
575 hg log -r "bisect(range)"
575 hg log -r "bisect(range)"
576
576
577 - with the graphlog extension, you can even get a nice graph::
577 - with the graphlog extension, you can even get a nice graph::
578
578
579 hg log --graph -r "bisect(range)"
579 hg log --graph -r "bisect(range)"
580
580
581 See :hg:`help revsets` for more about the `bisect()` keyword.
581 See :hg:`help revsets` for more about the `bisect()` keyword.
582
582
583 Returns 0 on success.
583 Returns 0 on success.
584 """
584 """
585 def extendbisectrange(nodes, good):
585 def extendbisectrange(nodes, good):
586 # bisect is incomplete when it ends on a merge node and
586 # bisect is incomplete when it ends on a merge node and
587 # one of the parent was not checked.
587 # one of the parent was not checked.
588 parents = repo[nodes[0]].parents()
588 parents = repo[nodes[0]].parents()
589 if len(parents) > 1:
589 if len(parents) > 1:
590 side = good and state['bad'] or state['good']
590 side = good and state['bad'] or state['good']
591 num = len(set(i.node() for i in parents) & set(side))
591 num = len(set(i.node() for i in parents) & set(side))
592 if num == 1:
592 if num == 1:
593 return parents[0].ancestor(parents[1])
593 return parents[0].ancestor(parents[1])
594 return None
594 return None
595
595
596 def print_result(nodes, good):
596 def print_result(nodes, good):
597 displayer = cmdutil.show_changeset(ui, repo, {})
597 displayer = cmdutil.show_changeset(ui, repo, {})
598 if len(nodes) == 1:
598 if len(nodes) == 1:
599 # narrowed it down to a single revision
599 # narrowed it down to a single revision
600 if good:
600 if good:
601 ui.write(_("The first good revision is:\n"))
601 ui.write(_("The first good revision is:\n"))
602 else:
602 else:
603 ui.write(_("The first bad revision is:\n"))
603 ui.write(_("The first bad revision is:\n"))
604 displayer.show(repo[nodes[0]])
604 displayer.show(repo[nodes[0]])
605 extendnode = extendbisectrange(nodes, good)
605 extendnode = extendbisectrange(nodes, good)
606 if extendnode is not None:
606 if extendnode is not None:
607 ui.write(_('Not all ancestors of this changeset have been'
607 ui.write(_('Not all ancestors of this changeset have been'
608 ' checked.\nUse bisect --extend to continue the '
608 ' checked.\nUse bisect --extend to continue the '
609 'bisection from\nthe common ancestor, %s.\n')
609 'bisection from\nthe common ancestor, %s.\n')
610 % extendnode)
610 % extendnode)
611 else:
611 else:
612 # multiple possible revisions
612 # multiple possible revisions
613 if good:
613 if good:
614 ui.write(_("Due to skipped revisions, the first "
614 ui.write(_("Due to skipped revisions, the first "
615 "good revision could be any of:\n"))
615 "good revision could be any of:\n"))
616 else:
616 else:
617 ui.write(_("Due to skipped revisions, the first "
617 ui.write(_("Due to skipped revisions, the first "
618 "bad revision could be any of:\n"))
618 "bad revision could be any of:\n"))
619 for n in nodes:
619 for n in nodes:
620 displayer.show(repo[n])
620 displayer.show(repo[n])
621 displayer.close()
621 displayer.close()
622
622
623 def check_state(state, interactive=True):
623 def check_state(state, interactive=True):
624 if not state['good'] or not state['bad']:
624 if not state['good'] or not state['bad']:
625 if (good or bad or skip or reset) and interactive:
625 if (good or bad or skip or reset) and interactive:
626 return
626 return
627 if not state['good']:
627 if not state['good']:
628 raise util.Abort(_('cannot bisect (no known good revisions)'))
628 raise util.Abort(_('cannot bisect (no known good revisions)'))
629 else:
629 else:
630 raise util.Abort(_('cannot bisect (no known bad revisions)'))
630 raise util.Abort(_('cannot bisect (no known bad revisions)'))
631 return True
631 return True
632
632
633 # backward compatibility
633 # backward compatibility
634 if rev in "good bad reset init".split():
634 if rev in "good bad reset init".split():
635 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
635 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
636 cmd, rev, extra = rev, extra, None
636 cmd, rev, extra = rev, extra, None
637 if cmd == "good":
637 if cmd == "good":
638 good = True
638 good = True
639 elif cmd == "bad":
639 elif cmd == "bad":
640 bad = True
640 bad = True
641 else:
641 else:
642 reset = True
642 reset = True
643 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
643 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
644 raise util.Abort(_('incompatible arguments'))
644 raise util.Abort(_('incompatible arguments'))
645
645
646 if reset:
646 if reset:
647 p = repo.join("bisect.state")
647 p = repo.join("bisect.state")
648 if os.path.exists(p):
648 if os.path.exists(p):
649 os.unlink(p)
649 os.unlink(p)
650 return
650 return
651
651
652 state = hbisect.load_state(repo)
652 state = hbisect.load_state(repo)
653
653
654 if command:
654 if command:
655 changesets = 1
655 changesets = 1
656 try:
656 try:
657 node = state['current'][0]
657 node = state['current'][0]
658 except LookupError:
658 except LookupError:
659 if noupdate:
659 if noupdate:
660 raise util.Abort(_('current bisect revision is unknown - '
660 raise util.Abort(_('current bisect revision is unknown - '
661 'start a new bisect to fix'))
661 'start a new bisect to fix'))
662 node, p2 = repo.dirstate.parents()
662 node, p2 = repo.dirstate.parents()
663 if p2 != nullid:
663 if p2 != nullid:
664 raise util.Abort(_('current bisect revision is a merge'))
664 raise util.Abort(_('current bisect revision is a merge'))
665 try:
665 try:
666 while changesets:
666 while changesets:
667 # update state
667 # update state
668 state['current'] = [node]
668 state['current'] = [node]
669 hbisect.save_state(repo, state)
669 hbisect.save_state(repo, state)
670 status = util.system(command,
670 status = util.system(command,
671 environ={'HG_NODE': hex(node)},
671 environ={'HG_NODE': hex(node)},
672 out=ui.fout)
672 out=ui.fout)
673 if status == 125:
673 if status == 125:
674 transition = "skip"
674 transition = "skip"
675 elif status == 0:
675 elif status == 0:
676 transition = "good"
676 transition = "good"
677 # status < 0 means process was killed
677 # status < 0 means process was killed
678 elif status == 127:
678 elif status == 127:
679 raise util.Abort(_("failed to execute %s") % command)
679 raise util.Abort(_("failed to execute %s") % command)
680 elif status < 0:
680 elif status < 0:
681 raise util.Abort(_("%s killed") % command)
681 raise util.Abort(_("%s killed") % command)
682 else:
682 else:
683 transition = "bad"
683 transition = "bad"
684 ctx = scmutil.revsingle(repo, rev, node)
684 ctx = scmutil.revsingle(repo, rev, node)
685 rev = None # clear for future iterations
685 rev = None # clear for future iterations
686 state[transition].append(ctx.node())
686 state[transition].append(ctx.node())
687 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
687 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
688 check_state(state, interactive=False)
688 check_state(state, interactive=False)
689 # bisect
689 # bisect
690 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
690 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
691 # update to next check
691 # update to next check
692 node = nodes[0]
692 node = nodes[0]
693 if not noupdate:
693 if not noupdate:
694 cmdutil.bailifchanged(repo)
694 cmdutil.bailifchanged(repo)
695 hg.clean(repo, node, show_stats=False)
695 hg.clean(repo, node, show_stats=False)
696 finally:
696 finally:
697 state['current'] = [node]
697 state['current'] = [node]
698 hbisect.save_state(repo, state)
698 hbisect.save_state(repo, state)
699 print_result(nodes, good)
699 print_result(nodes, good)
700 return
700 return
701
701
702 # update state
702 # update state
703
703
704 if rev:
704 if rev:
705 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
705 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
706 else:
706 else:
707 nodes = [repo.lookup('.')]
707 nodes = [repo.lookup('.')]
708
708
709 if good or bad or skip:
709 if good or bad or skip:
710 if good:
710 if good:
711 state['good'] += nodes
711 state['good'] += nodes
712 elif bad:
712 elif bad:
713 state['bad'] += nodes
713 state['bad'] += nodes
714 elif skip:
714 elif skip:
715 state['skip'] += nodes
715 state['skip'] += nodes
716 hbisect.save_state(repo, state)
716 hbisect.save_state(repo, state)
717
717
718 if not check_state(state):
718 if not check_state(state):
719 return
719 return
720
720
721 # actually bisect
721 # actually bisect
722 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
722 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
723 if extend:
723 if extend:
724 if not changesets:
724 if not changesets:
725 extendnode = extendbisectrange(nodes, good)
725 extendnode = extendbisectrange(nodes, good)
726 if extendnode is not None:
726 if extendnode is not None:
727 ui.write(_("Extending search to changeset %d:%s\n"
727 ui.write(_("Extending search to changeset %d:%s\n"
728 % (extendnode.rev(), extendnode)))
728 % (extendnode.rev(), extendnode)))
729 state['current'] = [extendnode.node()]
729 state['current'] = [extendnode.node()]
730 hbisect.save_state(repo, state)
730 hbisect.save_state(repo, state)
731 if noupdate:
731 if noupdate:
732 return
732 return
733 cmdutil.bailifchanged(repo)
733 cmdutil.bailifchanged(repo)
734 return hg.clean(repo, extendnode.node())
734 return hg.clean(repo, extendnode.node())
735 raise util.Abort(_("nothing to extend"))
735 raise util.Abort(_("nothing to extend"))
736
736
737 if changesets == 0:
737 if changesets == 0:
738 print_result(nodes, good)
738 print_result(nodes, good)
739 else:
739 else:
740 assert len(nodes) == 1 # only a single node can be tested next
740 assert len(nodes) == 1 # only a single node can be tested next
741 node = nodes[0]
741 node = nodes[0]
742 # compute the approximate number of remaining tests
742 # compute the approximate number of remaining tests
743 tests, size = 0, 2
743 tests, size = 0, 2
744 while size <= changesets:
744 while size <= changesets:
745 tests, size = tests + 1, size * 2
745 tests, size = tests + 1, size * 2
746 rev = repo.changelog.rev(node)
746 rev = repo.changelog.rev(node)
747 ui.write(_("Testing changeset %d:%s "
747 ui.write(_("Testing changeset %d:%s "
748 "(%d changesets remaining, ~%d tests)\n")
748 "(%d changesets remaining, ~%d tests)\n")
749 % (rev, short(node), changesets, tests))
749 % (rev, short(node), changesets, tests))
750 state['current'] = [node]
750 state['current'] = [node]
751 hbisect.save_state(repo, state)
751 hbisect.save_state(repo, state)
752 if not noupdate:
752 if not noupdate:
753 cmdutil.bailifchanged(repo)
753 cmdutil.bailifchanged(repo)
754 return hg.clean(repo, node)
754 return hg.clean(repo, node)
755
755
756 @command('bookmarks',
756 @command('bookmarks',
757 [('f', 'force', False, _('force')),
757 [('f', 'force', False, _('force')),
758 ('r', 'rev', '', _('revision'), _('REV')),
758 ('r', 'rev', '', _('revision'), _('REV')),
759 ('d', 'delete', False, _('delete a given bookmark')),
759 ('d', 'delete', False, _('delete a given bookmark')),
760 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
760 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
761 ('i', 'inactive', False, _('mark a bookmark inactive'))],
761 ('i', 'inactive', False, _('mark a bookmark inactive'))],
762 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
762 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
763 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
763 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
764 rename=None, inactive=False):
764 rename=None, inactive=False):
765 '''track a line of development with movable markers
765 '''track a line of development with movable markers
766
766
767 Bookmarks are pointers to certain commits that move when committing.
767 Bookmarks are pointers to certain commits that move when committing.
768 Bookmarks are local. They can be renamed, copied and deleted. It is
768 Bookmarks are local. They can be renamed, copied and deleted. It is
769 possible to use :hg:`merge NAME` to merge from a given bookmark, and
769 possible to use :hg:`merge NAME` to merge from a given bookmark, and
770 :hg:`update NAME` to update to a given bookmark.
770 :hg:`update NAME` to update to a given bookmark.
771
771
772 You can use :hg:`bookmark NAME` to set a bookmark on the working
772 You can use :hg:`bookmark NAME` to set a bookmark on the working
773 directory's parent revision with the given name. If you specify
773 directory's parent revision with the given name. If you specify
774 a revision using -r REV (where REV may be an existing bookmark),
774 a revision using -r REV (where REV may be an existing bookmark),
775 the bookmark is assigned to that revision.
775 the bookmark is assigned to that revision.
776
776
777 Bookmarks can be pushed and pulled between repositories (see :hg:`help
777 Bookmarks can be pushed and pulled between repositories (see :hg:`help
778 push` and :hg:`help pull`). This requires both the local and remote
778 push` and :hg:`help pull`). This requires both the local and remote
779 repositories to support bookmarks. For versions prior to 1.8, this means
779 repositories to support bookmarks. For versions prior to 1.8, this means
780 the bookmarks extension must be enabled.
780 the bookmarks extension must be enabled.
781
781
782 With -i/--inactive, the new bookmark will not be made the active
782 With -i/--inactive, the new bookmark will not be made the active
783 bookmark. If -r/--rev is given, the new bookmark will not be made
783 bookmark. If -r/--rev is given, the new bookmark will not be made
784 active even if -i/--inactive is not given. If no NAME is given, the
784 active even if -i/--inactive is not given. If no NAME is given, the
785 current active bookmark will be marked inactive.
785 current active bookmark will be marked inactive.
786 '''
786 '''
787 hexfn = ui.debugflag and hex or short
787 hexfn = ui.debugflag and hex or short
788 marks = repo._bookmarks
788 marks = repo._bookmarks
789 cur = repo.changectx('.').node()
789 cur = repo.changectx('.').node()
790
790
791 if delete:
791 if delete:
792 if mark is None:
792 if mark is None:
793 raise util.Abort(_("bookmark name required"))
793 raise util.Abort(_("bookmark name required"))
794 if mark not in marks:
794 if mark not in marks:
795 raise util.Abort(_("bookmark '%s' does not exist") % mark)
795 raise util.Abort(_("bookmark '%s' does not exist") % mark)
796 if mark == repo._bookmarkcurrent:
796 if mark == repo._bookmarkcurrent:
797 bookmarks.setcurrent(repo, None)
797 bookmarks.setcurrent(repo, None)
798 del marks[mark]
798 del marks[mark]
799 bookmarks.write(repo)
799 bookmarks.write(repo)
800 return
800 return
801
801
802 if rename:
802 if rename:
803 if rename not in marks:
803 if rename not in marks:
804 raise util.Abort(_("bookmark '%s' does not exist") % rename)
804 raise util.Abort(_("bookmark '%s' does not exist") % rename)
805 if mark in marks and not force:
805 if mark in marks and not force:
806 raise util.Abort(_("bookmark '%s' already exists "
806 raise util.Abort(_("bookmark '%s' already exists "
807 "(use -f to force)") % mark)
807 "(use -f to force)") % mark)
808 if mark is None:
808 if mark is None:
809 raise util.Abort(_("new bookmark name required"))
809 raise util.Abort(_("new bookmark name required"))
810 marks[mark] = marks[rename]
810 marks[mark] = marks[rename]
811 if repo._bookmarkcurrent == rename and not inactive:
811 if repo._bookmarkcurrent == rename and not inactive:
812 bookmarks.setcurrent(repo, mark)
812 bookmarks.setcurrent(repo, mark)
813 del marks[rename]
813 del marks[rename]
814 bookmarks.write(repo)
814 bookmarks.write(repo)
815 return
815 return
816
816
817 if mark is not None:
817 if mark is not None:
818 if "\n" in mark:
818 if "\n" in mark:
819 raise util.Abort(_("bookmark name cannot contain newlines"))
819 raise util.Abort(_("bookmark name cannot contain newlines"))
820 mark = mark.strip()
820 mark = mark.strip()
821 if not mark:
821 if not mark:
822 raise util.Abort(_("bookmark names cannot consist entirely of "
822 raise util.Abort(_("bookmark names cannot consist entirely of "
823 "whitespace"))
823 "whitespace"))
824 if inactive and mark == repo._bookmarkcurrent:
824 if inactive and mark == repo._bookmarkcurrent:
825 bookmarks.setcurrent(repo, None)
825 bookmarks.setcurrent(repo, None)
826 return
826 return
827 if mark in marks and not force:
827 if mark in marks and not force:
828 raise util.Abort(_("bookmark '%s' already exists "
828 raise util.Abort(_("bookmark '%s' already exists "
829 "(use -f to force)") % mark)
829 "(use -f to force)") % mark)
830 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
830 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
831 and not force):
831 and not force):
832 raise util.Abort(
832 raise util.Abort(
833 _("a bookmark cannot have the name of an existing branch"))
833 _("a bookmark cannot have the name of an existing branch"))
834 if rev:
834 if rev:
835 marks[mark] = repo.lookup(rev)
835 marks[mark] = repo.lookup(rev)
836 else:
836 else:
837 marks[mark] = cur
837 marks[mark] = cur
838 if not inactive and cur == marks[mark]:
838 if not inactive and cur == marks[mark]:
839 bookmarks.setcurrent(repo, mark)
839 bookmarks.setcurrent(repo, mark)
840 bookmarks.write(repo)
840 bookmarks.write(repo)
841 return
841 return
842
842
843 if mark is None:
843 if mark is None:
844 if rev:
844 if rev:
845 raise util.Abort(_("bookmark name required"))
845 raise util.Abort(_("bookmark name required"))
846 if len(marks) == 0:
846 if len(marks) == 0:
847 ui.status(_("no bookmarks set\n"))
847 ui.status(_("no bookmarks set\n"))
848 else:
848 else:
849 for bmark, n in sorted(marks.iteritems()):
849 for bmark, n in sorted(marks.iteritems()):
850 current = repo._bookmarkcurrent
850 current = repo._bookmarkcurrent
851 if bmark == current and n == cur:
851 if bmark == current and n == cur:
852 prefix, label = '*', 'bookmarks.current'
852 prefix, label = '*', 'bookmarks.current'
853 else:
853 else:
854 prefix, label = ' ', ''
854 prefix, label = ' ', ''
855
855
856 if ui.quiet:
856 if ui.quiet:
857 ui.write("%s\n" % bmark, label=label)
857 ui.write("%s\n" % bmark, label=label)
858 else:
858 else:
859 ui.write(" %s %-25s %d:%s\n" % (
859 ui.write(" %s %-25s %d:%s\n" % (
860 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
860 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
861 label=label)
861 label=label)
862 return
862 return
863
863
864 @command('branch',
864 @command('branch',
865 [('f', 'force', None,
865 [('f', 'force', None,
866 _('set branch name even if it shadows an existing branch')),
866 _('set branch name even if it shadows an existing branch')),
867 ('C', 'clean', None, _('reset branch name to parent branch name'))],
867 ('C', 'clean', None, _('reset branch name to parent branch name'))],
868 _('[-fC] [NAME]'))
868 _('[-fC] [NAME]'))
869 def branch(ui, repo, label=None, **opts):
869 def branch(ui, repo, label=None, **opts):
870 """set or show the current branch name
870 """set or show the current branch name
871
871
872 .. note::
872 .. note::
873 Branch names are permanent and global. Use :hg:`bookmark` to create a
873 Branch names are permanent and global. Use :hg:`bookmark` to create a
874 light-weight bookmark instead. See :hg:`help glossary` for more
874 light-weight bookmark instead. See :hg:`help glossary` for more
875 information about named branches and bookmarks.
875 information about named branches and bookmarks.
876
876
877 With no argument, show the current branch name. With one argument,
877 With no argument, show the current branch name. With one argument,
878 set the working directory branch name (the branch will not exist
878 set the working directory branch name (the branch will not exist
879 in the repository until the next commit). Standard practice
879 in the repository until the next commit). Standard practice
880 recommends that primary development take place on the 'default'
880 recommends that primary development take place on the 'default'
881 branch.
881 branch.
882
882
883 Unless -f/--force is specified, branch will not let you set a
883 Unless -f/--force is specified, branch will not let you set a
884 branch name that already exists, even if it's inactive.
884 branch name that already exists, even if it's inactive.
885
885
886 Use -C/--clean to reset the working directory branch to that of
886 Use -C/--clean to reset the working directory branch to that of
887 the parent of the working directory, negating a previous branch
887 the parent of the working directory, negating a previous branch
888 change.
888 change.
889
889
890 Use the command :hg:`update` to switch to an existing branch. Use
890 Use the command :hg:`update` to switch to an existing branch. Use
891 :hg:`commit --close-branch` to mark this branch as closed.
891 :hg:`commit --close-branch` to mark this branch as closed.
892
892
893 Returns 0 on success.
893 Returns 0 on success.
894 """
894 """
895 if not opts.get('clean') and not label:
895 if not opts.get('clean') and not label:
896 ui.write("%s\n" % repo.dirstate.branch())
896 ui.write("%s\n" % repo.dirstate.branch())
897 return
897 return
898
898
899 wlock = repo.wlock()
899 wlock = repo.wlock()
900 try:
900 try:
901 if opts.get('clean'):
901 if opts.get('clean'):
902 label = repo[None].p1().branch()
902 label = repo[None].p1().branch()
903 repo.dirstate.setbranch(label)
903 repo.dirstate.setbranch(label)
904 ui.status(_('reset working directory to branch %s\n') % label)
904 ui.status(_('reset working directory to branch %s\n') % label)
905 elif label:
905 elif label:
906 if not opts.get('force') and label in repo.branchtags():
906 if not opts.get('force') and label in repo.branchtags():
907 if label not in [p.branch() for p in repo.parents()]:
907 if label not in [p.branch() for p in repo.parents()]:
908 raise util.Abort(_('a branch of the same name already'
908 raise util.Abort(_('a branch of the same name already'
909 ' exists'),
909 ' exists'),
910 # i18n: "it" refers to an existing branch
910 # i18n: "it" refers to an existing branch
911 hint=_("use 'hg update' to switch to it"))
911 hint=_("use 'hg update' to switch to it"))
912 repo.dirstate.setbranch(label)
912 repo.dirstate.setbranch(label)
913 ui.status(_('marked working directory as branch %s\n') % label)
913 ui.status(_('marked working directory as branch %s\n') % label)
914 ui.status(_('(branches are permanent and global, '
914 ui.status(_('(branches are permanent and global, '
915 'did you want a bookmark?)\n'))
915 'did you want a bookmark?)\n'))
916 finally:
916 finally:
917 wlock.release()
917 wlock.release()
918
918
919 @command('branches',
919 @command('branches',
920 [('a', 'active', False, _('show only branches that have unmerged heads')),
920 [('a', 'active', False, _('show only branches that have unmerged heads')),
921 ('c', 'closed', False, _('show normal and closed branches'))],
921 ('c', 'closed', False, _('show normal and closed branches'))],
922 _('[-ac]'))
922 _('[-ac]'))
923 def branches(ui, repo, active=False, closed=False):
923 def branches(ui, repo, active=False, closed=False):
924 """list repository named branches
924 """list repository named branches
925
925
926 List the repository's named branches, indicating which ones are
926 List the repository's named branches, indicating which ones are
927 inactive. If -c/--closed is specified, also list branches which have
927 inactive. If -c/--closed is specified, also list branches which have
928 been marked closed (see :hg:`commit --close-branch`).
928 been marked closed (see :hg:`commit --close-branch`).
929
929
930 If -a/--active is specified, only show active branches. A branch
930 If -a/--active is specified, only show active branches. A branch
931 is considered active if it contains repository heads.
931 is considered active if it contains repository heads.
932
932
933 Use the command :hg:`update` to switch to an existing branch.
933 Use the command :hg:`update` to switch to an existing branch.
934
934
935 Returns 0.
935 Returns 0.
936 """
936 """
937
937
938 hexfunc = ui.debugflag and hex or short
938 hexfunc = ui.debugflag and hex or short
939 activebranches = [repo[n].branch() for n in repo.heads()]
939 activebranches = [repo[n].branch() for n in repo.heads()]
940 def testactive(tag, node):
940 def testactive(tag, node):
941 realhead = tag in activebranches
941 realhead = tag in activebranches
942 open = node in repo.branchheads(tag, closed=False)
942 open = node in repo.branchheads(tag, closed=False)
943 return realhead and open
943 return realhead and open
944 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
944 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
945 for tag, node in repo.branchtags().items()],
945 for tag, node in repo.branchtags().items()],
946 reverse=True)
946 reverse=True)
947
947
948 for isactive, node, tag in branches:
948 for isactive, node, tag in branches:
949 if (not active) or isactive:
949 if (not active) or isactive:
950 hn = repo.lookup(node)
950 hn = repo.lookup(node)
951 if isactive:
951 if isactive:
952 label = 'branches.active'
952 label = 'branches.active'
953 notice = ''
953 notice = ''
954 elif hn not in repo.branchheads(tag, closed=False):
954 elif hn not in repo.branchheads(tag, closed=False):
955 if not closed:
955 if not closed:
956 continue
956 continue
957 label = 'branches.closed'
957 label = 'branches.closed'
958 notice = _(' (closed)')
958 notice = _(' (closed)')
959 else:
959 else:
960 label = 'branches.inactive'
960 label = 'branches.inactive'
961 notice = _(' (inactive)')
961 notice = _(' (inactive)')
962 if tag == repo.dirstate.branch():
962 if tag == repo.dirstate.branch():
963 label = 'branches.current'
963 label = 'branches.current'
964 rev = str(node).rjust(31 - encoding.colwidth(tag))
964 rev = str(node).rjust(31 - encoding.colwidth(tag))
965 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
965 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
966 tag = ui.label(tag, label)
966 tag = ui.label(tag, label)
967 if ui.quiet:
967 if ui.quiet:
968 ui.write("%s\n" % tag)
968 ui.write("%s\n" % tag)
969 else:
969 else:
970 ui.write("%s %s%s\n" % (tag, rev, notice))
970 ui.write("%s %s%s\n" % (tag, rev, notice))
971
971
972 @command('bundle',
972 @command('bundle',
973 [('f', 'force', None, _('run even when the destination is unrelated')),
973 [('f', 'force', None, _('run even when the destination is unrelated')),
974 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
974 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
975 _('REV')),
975 _('REV')),
976 ('b', 'branch', [], _('a specific branch you would like to bundle'),
976 ('b', 'branch', [], _('a specific branch you would like to bundle'),
977 _('BRANCH')),
977 _('BRANCH')),
978 ('', 'base', [],
978 ('', 'base', [],
979 _('a base changeset assumed to be available at the destination'),
979 _('a base changeset assumed to be available at the destination'),
980 _('REV')),
980 _('REV')),
981 ('a', 'all', None, _('bundle all changesets in the repository')),
981 ('a', 'all', None, _('bundle all changesets in the repository')),
982 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
982 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
983 ] + remoteopts,
983 ] + remoteopts,
984 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
984 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
985 def bundle(ui, repo, fname, dest=None, **opts):
985 def bundle(ui, repo, fname, dest=None, **opts):
986 """create a changegroup file
986 """create a changegroup file
987
987
988 Generate a compressed changegroup file collecting changesets not
988 Generate a compressed changegroup file collecting changesets not
989 known to be in another repository.
989 known to be in another repository.
990
990
991 If you omit the destination repository, then hg assumes the
991 If you omit the destination repository, then hg assumes the
992 destination will have all the nodes you specify with --base
992 destination will have all the nodes you specify with --base
993 parameters. To create a bundle containing all changesets, use
993 parameters. To create a bundle containing all changesets, use
994 -a/--all (or --base null).
994 -a/--all (or --base null).
995
995
996 You can change compression method with the -t/--type option.
996 You can change compression method with the -t/--type option.
997 The available compression methods are: none, bzip2, and
997 The available compression methods are: none, bzip2, and
998 gzip (by default, bundles are compressed using bzip2).
998 gzip (by default, bundles are compressed using bzip2).
999
999
1000 The bundle file can then be transferred using conventional means
1000 The bundle file can then be transferred using conventional means
1001 and applied to another repository with the unbundle or pull
1001 and applied to another repository with the unbundle or pull
1002 command. This is useful when direct push and pull are not
1002 command. This is useful when direct push and pull are not
1003 available or when exporting an entire repository is undesirable.
1003 available or when exporting an entire repository is undesirable.
1004
1004
1005 Applying bundles preserves all changeset contents including
1005 Applying bundles preserves all changeset contents including
1006 permissions, copy/rename information, and revision history.
1006 permissions, copy/rename information, and revision history.
1007
1007
1008 Returns 0 on success, 1 if no changes found.
1008 Returns 0 on success, 1 if no changes found.
1009 """
1009 """
1010 revs = None
1010 revs = None
1011 if 'rev' in opts:
1011 if 'rev' in opts:
1012 revs = scmutil.revrange(repo, opts['rev'])
1012 revs = scmutil.revrange(repo, opts['rev'])
1013
1013
1014 bundletype = opts.get('type', 'bzip2').lower()
1014 bundletype = opts.get('type', 'bzip2').lower()
1015 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1015 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1016 bundletype = btypes.get(bundletype)
1016 bundletype = btypes.get(bundletype)
1017 if bundletype not in changegroup.bundletypes:
1017 if bundletype not in changegroup.bundletypes:
1018 raise util.Abort(_('unknown bundle type specified with --type'))
1018 raise util.Abort(_('unknown bundle type specified with --type'))
1019
1019
1020 if opts.get('all'):
1020 if opts.get('all'):
1021 base = ['null']
1021 base = ['null']
1022 else:
1022 else:
1023 base = scmutil.revrange(repo, opts.get('base'))
1023 base = scmutil.revrange(repo, opts.get('base'))
1024 if base:
1024 if base:
1025 if dest:
1025 if dest:
1026 raise util.Abort(_("--base is incompatible with specifying "
1026 raise util.Abort(_("--base is incompatible with specifying "
1027 "a destination"))
1027 "a destination"))
1028 common = [repo.lookup(rev) for rev in base]
1028 common = [repo.lookup(rev) for rev in base]
1029 heads = revs and map(repo.lookup, revs) or revs
1029 heads = revs and map(repo.lookup, revs) or revs
1030 cg = repo.getbundle('bundle', heads=heads, common=common)
1030 cg = repo.getbundle('bundle', heads=heads, common=common)
1031 outgoing = None
1031 outgoing = None
1032 else:
1032 else:
1033 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1033 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1034 dest, branches = hg.parseurl(dest, opts.get('branch'))
1034 dest, branches = hg.parseurl(dest, opts.get('branch'))
1035 other = hg.peer(repo, opts, dest)
1035 other = hg.peer(repo, opts, dest)
1036 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1036 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1037 heads = revs and map(repo.lookup, revs) or revs
1037 heads = revs and map(repo.lookup, revs) or revs
1038 outgoing = discovery.findcommonoutgoing(repo, other,
1038 outgoing = discovery.findcommonoutgoing(repo, other,
1039 onlyheads=heads,
1039 onlyheads=heads,
1040 force=opts.get('force'))
1040 force=opts.get('force'))
1041 cg = repo.getlocalbundle('bundle', outgoing)
1041 cg = repo.getlocalbundle('bundle', outgoing)
1042 if not cg:
1042 if not cg:
1043 scmutil.nochangesfound(ui, outgoing and outgoing.excluded)
1043 scmutil.nochangesfound(ui, outgoing and outgoing.excluded)
1044 return 1
1044 return 1
1045
1045
1046 changegroup.writebundle(cg, fname, bundletype)
1046 changegroup.writebundle(cg, fname, bundletype)
1047
1047
1048 @command('cat',
1048 @command('cat',
1049 [('o', 'output', '',
1049 [('o', 'output', '',
1050 _('print output to file with formatted name'), _('FORMAT')),
1050 _('print output to file with formatted name'), _('FORMAT')),
1051 ('r', 'rev', '', _('print the given revision'), _('REV')),
1051 ('r', 'rev', '', _('print the given revision'), _('REV')),
1052 ('', 'decode', None, _('apply any matching decode filter')),
1052 ('', 'decode', None, _('apply any matching decode filter')),
1053 ] + walkopts,
1053 ] + walkopts,
1054 _('[OPTION]... FILE...'))
1054 _('[OPTION]... FILE...'))
1055 def cat(ui, repo, file1, *pats, **opts):
1055 def cat(ui, repo, file1, *pats, **opts):
1056 """output the current or given revision of files
1056 """output the current or given revision of files
1057
1057
1058 Print the specified files as they were at the given revision. If
1058 Print the specified files as they were at the given revision. If
1059 no revision is given, the parent of the working directory is used,
1059 no revision is given, the parent of the working directory is used,
1060 or tip if no revision is checked out.
1060 or tip if no revision is checked out.
1061
1061
1062 Output may be to a file, in which case the name of the file is
1062 Output may be to a file, in which case the name of the file is
1063 given using a format string. The formatting rules are the same as
1063 given using a format string. The formatting rules are the same as
1064 for the export command, with the following additions:
1064 for the export command, with the following additions:
1065
1065
1066 :``%s``: basename of file being printed
1066 :``%s``: basename of file being printed
1067 :``%d``: dirname of file being printed, or '.' if in repository root
1067 :``%d``: dirname of file being printed, or '.' if in repository root
1068 :``%p``: root-relative path name of file being printed
1068 :``%p``: root-relative path name of file being printed
1069
1069
1070 Returns 0 on success.
1070 Returns 0 on success.
1071 """
1071 """
1072 ctx = scmutil.revsingle(repo, opts.get('rev'))
1072 ctx = scmutil.revsingle(repo, opts.get('rev'))
1073 err = 1
1073 err = 1
1074 m = scmutil.match(ctx, (file1,) + pats, opts)
1074 m = scmutil.match(ctx, (file1,) + pats, opts)
1075 for abs in ctx.walk(m):
1075 for abs in ctx.walk(m):
1076 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1076 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1077 pathname=abs)
1077 pathname=abs)
1078 data = ctx[abs].data()
1078 data = ctx[abs].data()
1079 if opts.get('decode'):
1079 if opts.get('decode'):
1080 data = repo.wwritedata(abs, data)
1080 data = repo.wwritedata(abs, data)
1081 fp.write(data)
1081 fp.write(data)
1082 fp.close()
1082 fp.close()
1083 err = 0
1083 err = 0
1084 return err
1084 return err
1085
1085
1086 @command('^clone',
1086 @command('^clone',
1087 [('U', 'noupdate', None,
1087 [('U', 'noupdate', None,
1088 _('the clone will include an empty working copy (only a repository)')),
1088 _('the clone will include an empty working copy (only a repository)')),
1089 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1089 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1090 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1090 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1091 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1091 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1092 ('', 'pull', None, _('use pull protocol to copy metadata')),
1092 ('', 'pull', None, _('use pull protocol to copy metadata')),
1093 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1093 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1094 ] + remoteopts,
1094 ] + remoteopts,
1095 _('[OPTION]... SOURCE [DEST]'))
1095 _('[OPTION]... SOURCE [DEST]'))
1096 def clone(ui, source, dest=None, **opts):
1096 def clone(ui, source, dest=None, **opts):
1097 """make a copy of an existing repository
1097 """make a copy of an existing repository
1098
1098
1099 Create a copy of an existing repository in a new directory.
1099 Create a copy of an existing repository in a new directory.
1100
1100
1101 If no destination directory name is specified, it defaults to the
1101 If no destination directory name is specified, it defaults to the
1102 basename of the source.
1102 basename of the source.
1103
1103
1104 The location of the source is added to the new repository's
1104 The location of the source is added to the new repository's
1105 ``.hg/hgrc`` file, as the default to be used for future pulls.
1105 ``.hg/hgrc`` file, as the default to be used for future pulls.
1106
1106
1107 Only local paths and ``ssh://`` URLs are supported as
1107 Only local paths and ``ssh://`` URLs are supported as
1108 destinations. For ``ssh://`` destinations, no working directory or
1108 destinations. For ``ssh://`` destinations, no working directory or
1109 ``.hg/hgrc`` will be created on the remote side.
1109 ``.hg/hgrc`` will be created on the remote side.
1110
1110
1111 To pull only a subset of changesets, specify one or more revisions
1111 To pull only a subset of changesets, specify one or more revisions
1112 identifiers with -r/--rev or branches with -b/--branch. The
1112 identifiers with -r/--rev or branches with -b/--branch. The
1113 resulting clone will contain only the specified changesets and
1113 resulting clone will contain only the specified changesets and
1114 their ancestors. These options (or 'clone src#rev dest') imply
1114 their ancestors. These options (or 'clone src#rev dest') imply
1115 --pull, even for local source repositories. Note that specifying a
1115 --pull, even for local source repositories. Note that specifying a
1116 tag will include the tagged changeset but not the changeset
1116 tag will include the tagged changeset but not the changeset
1117 containing the tag.
1117 containing the tag.
1118
1118
1119 To check out a particular version, use -u/--update, or
1119 To check out a particular version, use -u/--update, or
1120 -U/--noupdate to create a clone with no working directory.
1120 -U/--noupdate to create a clone with no working directory.
1121
1121
1122 .. container:: verbose
1122 .. container:: verbose
1123
1123
1124 For efficiency, hardlinks are used for cloning whenever the
1124 For efficiency, hardlinks are used for cloning whenever the
1125 source and destination are on the same filesystem (note this
1125 source and destination are on the same filesystem (note this
1126 applies only to the repository data, not to the working
1126 applies only to the repository data, not to the working
1127 directory). Some filesystems, such as AFS, implement hardlinking
1127 directory). Some filesystems, such as AFS, implement hardlinking
1128 incorrectly, but do not report errors. In these cases, use the
1128 incorrectly, but do not report errors. In these cases, use the
1129 --pull option to avoid hardlinking.
1129 --pull option to avoid hardlinking.
1130
1130
1131 In some cases, you can clone repositories and the working
1131 In some cases, you can clone repositories and the working
1132 directory using full hardlinks with ::
1132 directory using full hardlinks with ::
1133
1133
1134 $ cp -al REPO REPOCLONE
1134 $ cp -al REPO REPOCLONE
1135
1135
1136 This is the fastest way to clone, but it is not always safe. The
1136 This is the fastest way to clone, but it is not always safe. The
1137 operation is not atomic (making sure REPO is not modified during
1137 operation is not atomic (making sure REPO is not modified during
1138 the operation is up to you) and you have to make sure your
1138 the operation is up to you) and you have to make sure your
1139 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1139 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1140 so). Also, this is not compatible with certain extensions that
1140 so). Also, this is not compatible with certain extensions that
1141 place their metadata under the .hg directory, such as mq.
1141 place their metadata under the .hg directory, such as mq.
1142
1142
1143 Mercurial will update the working directory to the first applicable
1143 Mercurial will update the working directory to the first applicable
1144 revision from this list:
1144 revision from this list:
1145
1145
1146 a) null if -U or the source repository has no changesets
1146 a) null if -U or the source repository has no changesets
1147 b) if -u . and the source repository is local, the first parent of
1147 b) if -u . and the source repository is local, the first parent of
1148 the source repository's working directory
1148 the source repository's working directory
1149 c) the changeset specified with -u (if a branch name, this means the
1149 c) the changeset specified with -u (if a branch name, this means the
1150 latest head of that branch)
1150 latest head of that branch)
1151 d) the changeset specified with -r
1151 d) the changeset specified with -r
1152 e) the tipmost head specified with -b
1152 e) the tipmost head specified with -b
1153 f) the tipmost head specified with the url#branch source syntax
1153 f) the tipmost head specified with the url#branch source syntax
1154 g) the tipmost head of the default branch
1154 g) the tipmost head of the default branch
1155 h) tip
1155 h) tip
1156
1156
1157 Examples:
1157 Examples:
1158
1158
1159 - clone a remote repository to a new directory named hg/::
1159 - clone a remote repository to a new directory named hg/::
1160
1160
1161 hg clone http://selenic.com/hg
1161 hg clone http://selenic.com/hg
1162
1162
1163 - create a lightweight local clone::
1163 - create a lightweight local clone::
1164
1164
1165 hg clone project/ project-feature/
1165 hg clone project/ project-feature/
1166
1166
1167 - clone from an absolute path on an ssh server (note double-slash)::
1167 - clone from an absolute path on an ssh server (note double-slash)::
1168
1168
1169 hg clone ssh://user@server//home/projects/alpha/
1169 hg clone ssh://user@server//home/projects/alpha/
1170
1170
1171 - do a high-speed clone over a LAN while checking out a
1171 - do a high-speed clone over a LAN while checking out a
1172 specified version::
1172 specified version::
1173
1173
1174 hg clone --uncompressed http://server/repo -u 1.5
1174 hg clone --uncompressed http://server/repo -u 1.5
1175
1175
1176 - create a repository without changesets after a particular revision::
1176 - create a repository without changesets after a particular revision::
1177
1177
1178 hg clone -r 04e544 experimental/ good/
1178 hg clone -r 04e544 experimental/ good/
1179
1179
1180 - clone (and track) a particular named branch::
1180 - clone (and track) a particular named branch::
1181
1181
1182 hg clone http://selenic.com/hg#stable
1182 hg clone http://selenic.com/hg#stable
1183
1183
1184 See :hg:`help urls` for details on specifying URLs.
1184 See :hg:`help urls` for details on specifying URLs.
1185
1185
1186 Returns 0 on success.
1186 Returns 0 on success.
1187 """
1187 """
1188 if opts.get('noupdate') and opts.get('updaterev'):
1188 if opts.get('noupdate') and opts.get('updaterev'):
1189 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1189 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1190
1190
1191 r = hg.clone(ui, opts, source, dest,
1191 r = hg.clone(ui, opts, source, dest,
1192 pull=opts.get('pull'),
1192 pull=opts.get('pull'),
1193 stream=opts.get('uncompressed'),
1193 stream=opts.get('uncompressed'),
1194 rev=opts.get('rev'),
1194 rev=opts.get('rev'),
1195 update=opts.get('updaterev') or not opts.get('noupdate'),
1195 update=opts.get('updaterev') or not opts.get('noupdate'),
1196 branch=opts.get('branch'))
1196 branch=opts.get('branch'))
1197
1197
1198 return r is None
1198 return r is None
1199
1199
1200 @command('^commit|ci',
1200 @command('^commit|ci',
1201 [('A', 'addremove', None,
1201 [('A', 'addremove', None,
1202 _('mark new/missing files as added/removed before committing')),
1202 _('mark new/missing files as added/removed before committing')),
1203 ('', 'close-branch', None,
1203 ('', 'close-branch', None,
1204 _('mark a branch as closed, hiding it from the branch list')),
1204 _('mark a branch as closed, hiding it from the branch list')),
1205 ('', 'amend', None, _('amend the parent of the working dir')),
1205 ('', 'amend', None, _('amend the parent of the working dir')),
1206 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1206 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1207 _('[OPTION]... [FILE]...'))
1207 _('[OPTION]... [FILE]...'))
1208 def commit(ui, repo, *pats, **opts):
1208 def commit(ui, repo, *pats, **opts):
1209 """commit the specified files or all outstanding changes
1209 """commit the specified files or all outstanding changes
1210
1210
1211 Commit changes to the given files into the repository. Unlike a
1211 Commit changes to the given files into the repository. Unlike a
1212 centralized SCM, this operation is a local operation. See
1212 centralized SCM, this operation is a local operation. See
1213 :hg:`push` for a way to actively distribute your changes.
1213 :hg:`push` for a way to actively distribute your changes.
1214
1214
1215 If a list of files is omitted, all changes reported by :hg:`status`
1215 If a list of files is omitted, all changes reported by :hg:`status`
1216 will be committed.
1216 will be committed.
1217
1217
1218 If you are committing the result of a merge, do not provide any
1218 If you are committing the result of a merge, do not provide any
1219 filenames or -I/-X filters.
1219 filenames or -I/-X filters.
1220
1220
1221 If no commit message is specified, Mercurial starts your
1221 If no commit message is specified, Mercurial starts your
1222 configured editor where you can enter a message. In case your
1222 configured editor where you can enter a message. In case your
1223 commit fails, you will find a backup of your message in
1223 commit fails, you will find a backup of your message in
1224 ``.hg/last-message.txt``.
1224 ``.hg/last-message.txt``.
1225
1225
1226 The --amend flag can be used to amend the parent of the
1226 The --amend flag can be used to amend the parent of the
1227 working directory with a new commit that contains the changes
1227 working directory with a new commit that contains the changes
1228 in the parent in addition to those currently reported by :hg:`status`,
1228 in the parent in addition to those currently reported by :hg:`status`,
1229 if there are any. The old commit is stored in a backup bundle in
1229 if there are any. The old commit is stored in a backup bundle in
1230 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1230 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1231 on how to restore it).
1231 on how to restore it).
1232
1232
1233 Message, user and date are taken from the amended commit unless
1233 Message, user and date are taken from the amended commit unless
1234 specified. When a message isn't specified on the command line,
1234 specified. When a message isn't specified on the command line,
1235 the editor will open with the message of the amended commit.
1235 the editor will open with the message of the amended commit.
1236
1236
1237 It is not possible to amend public changesets (see :hg:`help phases`)
1237 It is not possible to amend public changesets (see :hg:`help phases`)
1238 or changesets that have children.
1238 or changesets that have children.
1239
1239
1240 See :hg:`help dates` for a list of formats valid for -d/--date.
1240 See :hg:`help dates` for a list of formats valid for -d/--date.
1241
1241
1242 Returns 0 on success, 1 if nothing changed.
1242 Returns 0 on success, 1 if nothing changed.
1243 """
1243 """
1244 if opts.get('subrepos'):
1244 if opts.get('subrepos'):
1245 # Let --subrepos on the command line overide config setting.
1245 # Let --subrepos on the command line overide config setting.
1246 ui.setconfig('ui', 'commitsubrepos', True)
1246 ui.setconfig('ui', 'commitsubrepos', True)
1247
1247
1248 extra = {}
1248 extra = {}
1249 if opts.get('close_branch'):
1249 if opts.get('close_branch'):
1250 if repo['.'].node() not in repo.branchheads():
1250 if repo['.'].node() not in repo.branchheads():
1251 # The topo heads set is included in the branch heads set of the
1251 # The topo heads set is included in the branch heads set of the
1252 # current branch, so it's sufficient to test branchheads
1252 # current branch, so it's sufficient to test branchheads
1253 raise util.Abort(_('can only close branch heads'))
1253 raise util.Abort(_('can only close branch heads'))
1254 extra['close'] = 1
1254 extra['close'] = 1
1255
1255
1256 branch = repo[None].branch()
1256 branch = repo[None].branch()
1257 bheads = repo.branchheads(branch)
1257 bheads = repo.branchheads(branch)
1258
1258
1259 if opts.get('amend'):
1259 if opts.get('amend'):
1260 if ui.configbool('ui', 'commitsubrepos'):
1260 if ui.configbool('ui', 'commitsubrepos'):
1261 raise util.Abort(_('cannot amend recursively'))
1261 raise util.Abort(_('cannot amend recursively'))
1262
1262
1263 old = repo['.']
1263 old = repo['.']
1264 if old.phase() == phases.public:
1264 if old.phase() == phases.public:
1265 raise util.Abort(_('cannot amend public changesets'))
1265 raise util.Abort(_('cannot amend public changesets'))
1266 if len(old.parents()) > 1:
1266 if len(old.parents()) > 1:
1267 raise util.Abort(_('cannot amend merge changesets'))
1267 raise util.Abort(_('cannot amend merge changesets'))
1268 if len(repo[None].parents()) > 1:
1268 if len(repo[None].parents()) > 1:
1269 raise util.Abort(_('cannot amend while merging'))
1269 raise util.Abort(_('cannot amend while merging'))
1270 if old.children():
1270 if old.children():
1271 raise util.Abort(_('cannot amend changeset with children'))
1271 raise util.Abort(_('cannot amend changeset with children'))
1272
1272
1273 e = cmdutil.commiteditor
1273 e = cmdutil.commiteditor
1274 if opts.get('force_editor'):
1274 if opts.get('force_editor'):
1275 e = cmdutil.commitforceeditor
1275 e = cmdutil.commitforceeditor
1276
1276
1277 def commitfunc(ui, repo, message, match, opts):
1277 def commitfunc(ui, repo, message, match, opts):
1278 editor = e
1278 editor = e
1279 # message contains text from -m or -l, if it's empty,
1279 # message contains text from -m or -l, if it's empty,
1280 # open the editor with the old message
1280 # open the editor with the old message
1281 if not message:
1281 if not message:
1282 message = old.description()
1282 message = old.description()
1283 editor = cmdutil.commitforceeditor
1283 editor = cmdutil.commitforceeditor
1284 return repo.commit(message,
1284 return repo.commit(message,
1285 opts.get('user') or old.user(),
1285 opts.get('user') or old.user(),
1286 opts.get('date') or old.date(),
1286 opts.get('date') or old.date(),
1287 match,
1287 match,
1288 editor=editor,
1288 editor=editor,
1289 extra=extra)
1289 extra=extra)
1290
1290
1291 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1291 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1292 if node == old.node():
1292 if node == old.node():
1293 ui.status(_("nothing changed\n"))
1293 ui.status(_("nothing changed\n"))
1294 return 1
1294 return 1
1295 else:
1295 else:
1296 e = cmdutil.commiteditor
1296 e = cmdutil.commiteditor
1297 if opts.get('force_editor'):
1297 if opts.get('force_editor'):
1298 e = cmdutil.commitforceeditor
1298 e = cmdutil.commitforceeditor
1299
1299
1300 def commitfunc(ui, repo, message, match, opts):
1300 def commitfunc(ui, repo, message, match, opts):
1301 return repo.commit(message, opts.get('user'), opts.get('date'),
1301 return repo.commit(message, opts.get('user'), opts.get('date'),
1302 match, editor=e, extra=extra)
1302 match, editor=e, extra=extra)
1303
1303
1304 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1304 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1305
1305
1306 if not node:
1306 if not node:
1307 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1307 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1308 if stat[3]:
1308 if stat[3]:
1309 ui.status(_("nothing changed (%d missing files, see "
1309 ui.status(_("nothing changed (%d missing files, see "
1310 "'hg status')\n") % len(stat[3]))
1310 "'hg status')\n") % len(stat[3]))
1311 else:
1311 else:
1312 ui.status(_("nothing changed\n"))
1312 ui.status(_("nothing changed\n"))
1313 return 1
1313 return 1
1314
1314
1315 ctx = repo[node]
1315 ctx = repo[node]
1316 parents = ctx.parents()
1316 parents = ctx.parents()
1317
1317
1318 if (not opts.get('amend') and bheads and node not in bheads and not
1318 if (not opts.get('amend') and bheads and node not in bheads and not
1319 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1319 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1320 ui.status(_('created new head\n'))
1320 ui.status(_('created new head\n'))
1321 # The message is not printed for initial roots. For the other
1321 # The message is not printed for initial roots. For the other
1322 # changesets, it is printed in the following situations:
1322 # changesets, it is printed in the following situations:
1323 #
1323 #
1324 # Par column: for the 2 parents with ...
1324 # Par column: for the 2 parents with ...
1325 # N: null or no parent
1325 # N: null or no parent
1326 # B: parent is on another named branch
1326 # B: parent is on another named branch
1327 # C: parent is a regular non head changeset
1327 # C: parent is a regular non head changeset
1328 # H: parent was a branch head of the current branch
1328 # H: parent was a branch head of the current branch
1329 # Msg column: whether we print "created new head" message
1329 # Msg column: whether we print "created new head" message
1330 # In the following, it is assumed that there already exists some
1330 # In the following, it is assumed that there already exists some
1331 # initial branch heads of the current branch, otherwise nothing is
1331 # initial branch heads of the current branch, otherwise nothing is
1332 # printed anyway.
1332 # printed anyway.
1333 #
1333 #
1334 # Par Msg Comment
1334 # Par Msg Comment
1335 # NN y additional topo root
1335 # NN y additional topo root
1336 #
1336 #
1337 # BN y additional branch root
1337 # BN y additional branch root
1338 # CN y additional topo head
1338 # CN y additional topo head
1339 # HN n usual case
1339 # HN n usual case
1340 #
1340 #
1341 # BB y weird additional branch root
1341 # BB y weird additional branch root
1342 # CB y branch merge
1342 # CB y branch merge
1343 # HB n merge with named branch
1343 # HB n merge with named branch
1344 #
1344 #
1345 # CC y additional head from merge
1345 # CC y additional head from merge
1346 # CH n merge with a head
1346 # CH n merge with a head
1347 #
1347 #
1348 # HH n head merge: head count decreases
1348 # HH n head merge: head count decreases
1349
1349
1350 if not opts.get('close_branch'):
1350 if not opts.get('close_branch'):
1351 for r in parents:
1351 for r in parents:
1352 if r.extra().get('close') and r.branch() == branch:
1352 if r.extra().get('close') and r.branch() == branch:
1353 ui.status(_('reopening closed branch head %d\n') % r)
1353 ui.status(_('reopening closed branch head %d\n') % r)
1354
1354
1355 if ui.debugflag:
1355 if ui.debugflag:
1356 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1356 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1357 elif ui.verbose:
1357 elif ui.verbose:
1358 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1358 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1359
1359
1360 @command('copy|cp',
1360 @command('copy|cp',
1361 [('A', 'after', None, _('record a copy that has already occurred')),
1361 [('A', 'after', None, _('record a copy that has already occurred')),
1362 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1362 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1363 ] + walkopts + dryrunopts,
1363 ] + walkopts + dryrunopts,
1364 _('[OPTION]... [SOURCE]... DEST'))
1364 _('[OPTION]... [SOURCE]... DEST'))
1365 def copy(ui, repo, *pats, **opts):
1365 def copy(ui, repo, *pats, **opts):
1366 """mark files as copied for the next commit
1366 """mark files as copied for the next commit
1367
1367
1368 Mark dest as having copies of source files. If dest is a
1368 Mark dest as having copies of source files. If dest is a
1369 directory, copies are put in that directory. If dest is a file,
1369 directory, copies are put in that directory. If dest is a file,
1370 the source must be a single file.
1370 the source must be a single file.
1371
1371
1372 By default, this command copies the contents of files as they
1372 By default, this command copies the contents of files as they
1373 exist in the working directory. If invoked with -A/--after, the
1373 exist in the working directory. If invoked with -A/--after, the
1374 operation is recorded, but no copying is performed.
1374 operation is recorded, but no copying is performed.
1375
1375
1376 This command takes effect with the next commit. To undo a copy
1376 This command takes effect with the next commit. To undo a copy
1377 before that, see :hg:`revert`.
1377 before that, see :hg:`revert`.
1378
1378
1379 Returns 0 on success, 1 if errors are encountered.
1379 Returns 0 on success, 1 if errors are encountered.
1380 """
1380 """
1381 wlock = repo.wlock(False)
1381 wlock = repo.wlock(False)
1382 try:
1382 try:
1383 return cmdutil.copy(ui, repo, pats, opts)
1383 return cmdutil.copy(ui, repo, pats, opts)
1384 finally:
1384 finally:
1385 wlock.release()
1385 wlock.release()
1386
1386
1387 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1387 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1388 def debugancestor(ui, repo, *args):
1388 def debugancestor(ui, repo, *args):
1389 """find the ancestor revision of two revisions in a given index"""
1389 """find the ancestor revision of two revisions in a given index"""
1390 if len(args) == 3:
1390 if len(args) == 3:
1391 index, rev1, rev2 = args
1391 index, rev1, rev2 = args
1392 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1392 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1393 lookup = r.lookup
1393 lookup = r.lookup
1394 elif len(args) == 2:
1394 elif len(args) == 2:
1395 if not repo:
1395 if not repo:
1396 raise util.Abort(_("there is no Mercurial repository here "
1396 raise util.Abort(_("there is no Mercurial repository here "
1397 "(.hg not found)"))
1397 "(.hg not found)"))
1398 rev1, rev2 = args
1398 rev1, rev2 = args
1399 r = repo.changelog
1399 r = repo.changelog
1400 lookup = repo.lookup
1400 lookup = repo.lookup
1401 else:
1401 else:
1402 raise util.Abort(_('either two or three arguments required'))
1402 raise util.Abort(_('either two or three arguments required'))
1403 a = r.ancestor(lookup(rev1), lookup(rev2))
1403 a = r.ancestor(lookup(rev1), lookup(rev2))
1404 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1404 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1405
1405
1406 @command('debugbuilddag',
1406 @command('debugbuilddag',
1407 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1407 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1408 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1408 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1409 ('n', 'new-file', None, _('add new file at each rev'))],
1409 ('n', 'new-file', None, _('add new file at each rev'))],
1410 _('[OPTION]... [TEXT]'))
1410 _('[OPTION]... [TEXT]'))
1411 def debugbuilddag(ui, repo, text=None,
1411 def debugbuilddag(ui, repo, text=None,
1412 mergeable_file=False,
1412 mergeable_file=False,
1413 overwritten_file=False,
1413 overwritten_file=False,
1414 new_file=False):
1414 new_file=False):
1415 """builds a repo with a given DAG from scratch in the current empty repo
1415 """builds a repo with a given DAG from scratch in the current empty repo
1416
1416
1417 The description of the DAG is read from stdin if not given on the
1417 The description of the DAG is read from stdin if not given on the
1418 command line.
1418 command line.
1419
1419
1420 Elements:
1420 Elements:
1421
1421
1422 - "+n" is a linear run of n nodes based on the current default parent
1422 - "+n" is a linear run of n nodes based on the current default parent
1423 - "." is a single node based on the current default parent
1423 - "." is a single node based on the current default parent
1424 - "$" resets the default parent to null (implied at the start);
1424 - "$" resets the default parent to null (implied at the start);
1425 otherwise the default parent is always the last node created
1425 otherwise the default parent is always the last node created
1426 - "<p" sets the default parent to the backref p
1426 - "<p" sets the default parent to the backref p
1427 - "*p" is a fork at parent p, which is a backref
1427 - "*p" is a fork at parent p, which is a backref
1428 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1428 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1429 - "/p2" is a merge of the preceding node and p2
1429 - "/p2" is a merge of the preceding node and p2
1430 - ":tag" defines a local tag for the preceding node
1430 - ":tag" defines a local tag for the preceding node
1431 - "@branch" sets the named branch for subsequent nodes
1431 - "@branch" sets the named branch for subsequent nodes
1432 - "#...\\n" is a comment up to the end of the line
1432 - "#...\\n" is a comment up to the end of the line
1433
1433
1434 Whitespace between the above elements is ignored.
1434 Whitespace between the above elements is ignored.
1435
1435
1436 A backref is either
1436 A backref is either
1437
1437
1438 - a number n, which references the node curr-n, where curr is the current
1438 - a number n, which references the node curr-n, where curr is the current
1439 node, or
1439 node, or
1440 - the name of a local tag you placed earlier using ":tag", or
1440 - the name of a local tag you placed earlier using ":tag", or
1441 - empty to denote the default parent.
1441 - empty to denote the default parent.
1442
1442
1443 All string valued-elements are either strictly alphanumeric, or must
1443 All string valued-elements are either strictly alphanumeric, or must
1444 be enclosed in double quotes ("..."), with "\\" as escape character.
1444 be enclosed in double quotes ("..."), with "\\" as escape character.
1445 """
1445 """
1446
1446
1447 if text is None:
1447 if text is None:
1448 ui.status(_("reading DAG from stdin\n"))
1448 ui.status(_("reading DAG from stdin\n"))
1449 text = ui.fin.read()
1449 text = ui.fin.read()
1450
1450
1451 cl = repo.changelog
1451 cl = repo.changelog
1452 if len(cl) > 0:
1452 if len(cl) > 0:
1453 raise util.Abort(_('repository is not empty'))
1453 raise util.Abort(_('repository is not empty'))
1454
1454
1455 # determine number of revs in DAG
1455 # determine number of revs in DAG
1456 total = 0
1456 total = 0
1457 for type, data in dagparser.parsedag(text):
1457 for type, data in dagparser.parsedag(text):
1458 if type == 'n':
1458 if type == 'n':
1459 total += 1
1459 total += 1
1460
1460
1461 if mergeable_file:
1461 if mergeable_file:
1462 linesperrev = 2
1462 linesperrev = 2
1463 # make a file with k lines per rev
1463 # make a file with k lines per rev
1464 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1464 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1465 initialmergedlines.append("")
1465 initialmergedlines.append("")
1466
1466
1467 tags = []
1467 tags = []
1468
1468
1469 lock = tr = None
1469 lock = tr = None
1470 try:
1470 try:
1471 lock = repo.lock()
1471 lock = repo.lock()
1472 tr = repo.transaction("builddag")
1472 tr = repo.transaction("builddag")
1473
1473
1474 at = -1
1474 at = -1
1475 atbranch = 'default'
1475 atbranch = 'default'
1476 nodeids = []
1476 nodeids = []
1477 id = 0
1477 id = 0
1478 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1478 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1479 for type, data in dagparser.parsedag(text):
1479 for type, data in dagparser.parsedag(text):
1480 if type == 'n':
1480 if type == 'n':
1481 ui.note('node %s\n' % str(data))
1481 ui.note('node %s\n' % str(data))
1482 id, ps = data
1482 id, ps = data
1483
1483
1484 files = []
1484 files = []
1485 fctxs = {}
1485 fctxs = {}
1486
1486
1487 p2 = None
1487 p2 = None
1488 if mergeable_file:
1488 if mergeable_file:
1489 fn = "mf"
1489 fn = "mf"
1490 p1 = repo[ps[0]]
1490 p1 = repo[ps[0]]
1491 if len(ps) > 1:
1491 if len(ps) > 1:
1492 p2 = repo[ps[1]]
1492 p2 = repo[ps[1]]
1493 pa = p1.ancestor(p2)
1493 pa = p1.ancestor(p2)
1494 base, local, other = [x[fn].data() for x in pa, p1, p2]
1494 base, local, other = [x[fn].data() for x in pa, p1, p2]
1495 m3 = simplemerge.Merge3Text(base, local, other)
1495 m3 = simplemerge.Merge3Text(base, local, other)
1496 ml = [l.strip() for l in m3.merge_lines()]
1496 ml = [l.strip() for l in m3.merge_lines()]
1497 ml.append("")
1497 ml.append("")
1498 elif at > 0:
1498 elif at > 0:
1499 ml = p1[fn].data().split("\n")
1499 ml = p1[fn].data().split("\n")
1500 else:
1500 else:
1501 ml = initialmergedlines
1501 ml = initialmergedlines
1502 ml[id * linesperrev] += " r%i" % id
1502 ml[id * linesperrev] += " r%i" % id
1503 mergedtext = "\n".join(ml)
1503 mergedtext = "\n".join(ml)
1504 files.append(fn)
1504 files.append(fn)
1505 fctxs[fn] = context.memfilectx(fn, mergedtext)
1505 fctxs[fn] = context.memfilectx(fn, mergedtext)
1506
1506
1507 if overwritten_file:
1507 if overwritten_file:
1508 fn = "of"
1508 fn = "of"
1509 files.append(fn)
1509 files.append(fn)
1510 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1510 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1511
1511
1512 if new_file:
1512 if new_file:
1513 fn = "nf%i" % id
1513 fn = "nf%i" % id
1514 files.append(fn)
1514 files.append(fn)
1515 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1515 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1516 if len(ps) > 1:
1516 if len(ps) > 1:
1517 if not p2:
1517 if not p2:
1518 p2 = repo[ps[1]]
1518 p2 = repo[ps[1]]
1519 for fn in p2:
1519 for fn in p2:
1520 if fn.startswith("nf"):
1520 if fn.startswith("nf"):
1521 files.append(fn)
1521 files.append(fn)
1522 fctxs[fn] = p2[fn]
1522 fctxs[fn] = p2[fn]
1523
1523
1524 def fctxfn(repo, cx, path):
1524 def fctxfn(repo, cx, path):
1525 return fctxs.get(path)
1525 return fctxs.get(path)
1526
1526
1527 if len(ps) == 0 or ps[0] < 0:
1527 if len(ps) == 0 or ps[0] < 0:
1528 pars = [None, None]
1528 pars = [None, None]
1529 elif len(ps) == 1:
1529 elif len(ps) == 1:
1530 pars = [nodeids[ps[0]], None]
1530 pars = [nodeids[ps[0]], None]
1531 else:
1531 else:
1532 pars = [nodeids[p] for p in ps]
1532 pars = [nodeids[p] for p in ps]
1533 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1533 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1534 date=(id, 0),
1534 date=(id, 0),
1535 user="debugbuilddag",
1535 user="debugbuilddag",
1536 extra={'branch': atbranch})
1536 extra={'branch': atbranch})
1537 nodeid = repo.commitctx(cx)
1537 nodeid = repo.commitctx(cx)
1538 nodeids.append(nodeid)
1538 nodeids.append(nodeid)
1539 at = id
1539 at = id
1540 elif type == 'l':
1540 elif type == 'l':
1541 id, name = data
1541 id, name = data
1542 ui.note('tag %s\n' % name)
1542 ui.note('tag %s\n' % name)
1543 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1543 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1544 elif type == 'a':
1544 elif type == 'a':
1545 ui.note('branch %s\n' % data)
1545 ui.note('branch %s\n' % data)
1546 atbranch = data
1546 atbranch = data
1547 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1547 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1548 tr.close()
1548 tr.close()
1549
1549
1550 if tags:
1550 if tags:
1551 repo.opener.write("localtags", "".join(tags))
1551 repo.opener.write("localtags", "".join(tags))
1552 finally:
1552 finally:
1553 ui.progress(_('building'), None)
1553 ui.progress(_('building'), None)
1554 release(tr, lock)
1554 release(tr, lock)
1555
1555
1556 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1556 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1557 def debugbundle(ui, bundlepath, all=None, **opts):
1557 def debugbundle(ui, bundlepath, all=None, **opts):
1558 """lists the contents of a bundle"""
1558 """lists the contents of a bundle"""
1559 f = url.open(ui, bundlepath)
1559 f = url.open(ui, bundlepath)
1560 try:
1560 try:
1561 gen = changegroup.readbundle(f, bundlepath)
1561 gen = changegroup.readbundle(f, bundlepath)
1562 if all:
1562 if all:
1563 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1563 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1564
1564
1565 def showchunks(named):
1565 def showchunks(named):
1566 ui.write("\n%s\n" % named)
1566 ui.write("\n%s\n" % named)
1567 chain = None
1567 chain = None
1568 while True:
1568 while True:
1569 chunkdata = gen.deltachunk(chain)
1569 chunkdata = gen.deltachunk(chain)
1570 if not chunkdata:
1570 if not chunkdata:
1571 break
1571 break
1572 node = chunkdata['node']
1572 node = chunkdata['node']
1573 p1 = chunkdata['p1']
1573 p1 = chunkdata['p1']
1574 p2 = chunkdata['p2']
1574 p2 = chunkdata['p2']
1575 cs = chunkdata['cs']
1575 cs = chunkdata['cs']
1576 deltabase = chunkdata['deltabase']
1576 deltabase = chunkdata['deltabase']
1577 delta = chunkdata['delta']
1577 delta = chunkdata['delta']
1578 ui.write("%s %s %s %s %s %s\n" %
1578 ui.write("%s %s %s %s %s %s\n" %
1579 (hex(node), hex(p1), hex(p2),
1579 (hex(node), hex(p1), hex(p2),
1580 hex(cs), hex(deltabase), len(delta)))
1580 hex(cs), hex(deltabase), len(delta)))
1581 chain = node
1581 chain = node
1582
1582
1583 chunkdata = gen.changelogheader()
1583 chunkdata = gen.changelogheader()
1584 showchunks("changelog")
1584 showchunks("changelog")
1585 chunkdata = gen.manifestheader()
1585 chunkdata = gen.manifestheader()
1586 showchunks("manifest")
1586 showchunks("manifest")
1587 while True:
1587 while True:
1588 chunkdata = gen.filelogheader()
1588 chunkdata = gen.filelogheader()
1589 if not chunkdata:
1589 if not chunkdata:
1590 break
1590 break
1591 fname = chunkdata['filename']
1591 fname = chunkdata['filename']
1592 showchunks(fname)
1592 showchunks(fname)
1593 else:
1593 else:
1594 chunkdata = gen.changelogheader()
1594 chunkdata = gen.changelogheader()
1595 chain = None
1595 chain = None
1596 while True:
1596 while True:
1597 chunkdata = gen.deltachunk(chain)
1597 chunkdata = gen.deltachunk(chain)
1598 if not chunkdata:
1598 if not chunkdata:
1599 break
1599 break
1600 node = chunkdata['node']
1600 node = chunkdata['node']
1601 ui.write("%s\n" % hex(node))
1601 ui.write("%s\n" % hex(node))
1602 chain = node
1602 chain = node
1603 finally:
1603 finally:
1604 f.close()
1604 f.close()
1605
1605
1606 @command('debugcheckstate', [], '')
1606 @command('debugcheckstate', [], '')
1607 def debugcheckstate(ui, repo):
1607 def debugcheckstate(ui, repo):
1608 """validate the correctness of the current dirstate"""
1608 """validate the correctness of the current dirstate"""
1609 parent1, parent2 = repo.dirstate.parents()
1609 parent1, parent2 = repo.dirstate.parents()
1610 m1 = repo[parent1].manifest()
1610 m1 = repo[parent1].manifest()
1611 m2 = repo[parent2].manifest()
1611 m2 = repo[parent2].manifest()
1612 errors = 0
1612 errors = 0
1613 for f in repo.dirstate:
1613 for f in repo.dirstate:
1614 state = repo.dirstate[f]
1614 state = repo.dirstate[f]
1615 if state in "nr" and f not in m1:
1615 if state in "nr" and f not in m1:
1616 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1616 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1617 errors += 1
1617 errors += 1
1618 if state in "a" and f in m1:
1618 if state in "a" and f in m1:
1619 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1619 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1620 errors += 1
1620 errors += 1
1621 if state in "m" and f not in m1 and f not in m2:
1621 if state in "m" and f not in m1 and f not in m2:
1622 ui.warn(_("%s in state %s, but not in either manifest\n") %
1622 ui.warn(_("%s in state %s, but not in either manifest\n") %
1623 (f, state))
1623 (f, state))
1624 errors += 1
1624 errors += 1
1625 for f in m1:
1625 for f in m1:
1626 state = repo.dirstate[f]
1626 state = repo.dirstate[f]
1627 if state not in "nrm":
1627 if state not in "nrm":
1628 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1628 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1629 errors += 1
1629 errors += 1
1630 if errors:
1630 if errors:
1631 error = _(".hg/dirstate inconsistent with current parent's manifest")
1631 error = _(".hg/dirstate inconsistent with current parent's manifest")
1632 raise util.Abort(error)
1632 raise util.Abort(error)
1633
1633
1634 @command('debugcommands', [], _('[COMMAND]'))
1634 @command('debugcommands', [], _('[COMMAND]'))
1635 def debugcommands(ui, cmd='', *args):
1635 def debugcommands(ui, cmd='', *args):
1636 """list all available commands and options"""
1636 """list all available commands and options"""
1637 for cmd, vals in sorted(table.iteritems()):
1637 for cmd, vals in sorted(table.iteritems()):
1638 cmd = cmd.split('|')[0].strip('^')
1638 cmd = cmd.split('|')[0].strip('^')
1639 opts = ', '.join([i[1] for i in vals[1]])
1639 opts = ', '.join([i[1] for i in vals[1]])
1640 ui.write('%s: %s\n' % (cmd, opts))
1640 ui.write('%s: %s\n' % (cmd, opts))
1641
1641
1642 @command('debugcomplete',
1642 @command('debugcomplete',
1643 [('o', 'options', None, _('show the command options'))],
1643 [('o', 'options', None, _('show the command options'))],
1644 _('[-o] CMD'))
1644 _('[-o] CMD'))
1645 def debugcomplete(ui, cmd='', **opts):
1645 def debugcomplete(ui, cmd='', **opts):
1646 """returns the completion list associated with the given command"""
1646 """returns the completion list associated with the given command"""
1647
1647
1648 if opts.get('options'):
1648 if opts.get('options'):
1649 options = []
1649 options = []
1650 otables = [globalopts]
1650 otables = [globalopts]
1651 if cmd:
1651 if cmd:
1652 aliases, entry = cmdutil.findcmd(cmd, table, False)
1652 aliases, entry = cmdutil.findcmd(cmd, table, False)
1653 otables.append(entry[1])
1653 otables.append(entry[1])
1654 for t in otables:
1654 for t in otables:
1655 for o in t:
1655 for o in t:
1656 if "(DEPRECATED)" in o[3]:
1656 if "(DEPRECATED)" in o[3]:
1657 continue
1657 continue
1658 if o[0]:
1658 if o[0]:
1659 options.append('-%s' % o[0])
1659 options.append('-%s' % o[0])
1660 options.append('--%s' % o[1])
1660 options.append('--%s' % o[1])
1661 ui.write("%s\n" % "\n".join(options))
1661 ui.write("%s\n" % "\n".join(options))
1662 return
1662 return
1663
1663
1664 cmdlist = cmdutil.findpossible(cmd, table)
1664 cmdlist = cmdutil.findpossible(cmd, table)
1665 if ui.verbose:
1665 if ui.verbose:
1666 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1666 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1667 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1667 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1668
1668
1669 @command('debugdag',
1669 @command('debugdag',
1670 [('t', 'tags', None, _('use tags as labels')),
1670 [('t', 'tags', None, _('use tags as labels')),
1671 ('b', 'branches', None, _('annotate with branch names')),
1671 ('b', 'branches', None, _('annotate with branch names')),
1672 ('', 'dots', None, _('use dots for runs')),
1672 ('', 'dots', None, _('use dots for runs')),
1673 ('s', 'spaces', None, _('separate elements by spaces'))],
1673 ('s', 'spaces', None, _('separate elements by spaces'))],
1674 _('[OPTION]... [FILE [REV]...]'))
1674 _('[OPTION]... [FILE [REV]...]'))
1675 def debugdag(ui, repo, file_=None, *revs, **opts):
1675 def debugdag(ui, repo, file_=None, *revs, **opts):
1676 """format the changelog or an index DAG as a concise textual description
1676 """format the changelog or an index DAG as a concise textual description
1677
1677
1678 If you pass a revlog index, the revlog's DAG is emitted. If you list
1678 If you pass a revlog index, the revlog's DAG is emitted. If you list
1679 revision numbers, they get labelled in the output as rN.
1679 revision numbers, they get labelled in the output as rN.
1680
1680
1681 Otherwise, the changelog DAG of the current repo is emitted.
1681 Otherwise, the changelog DAG of the current repo is emitted.
1682 """
1682 """
1683 spaces = opts.get('spaces')
1683 spaces = opts.get('spaces')
1684 dots = opts.get('dots')
1684 dots = opts.get('dots')
1685 if file_:
1685 if file_:
1686 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1686 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1687 revs = set((int(r) for r in revs))
1687 revs = set((int(r) for r in revs))
1688 def events():
1688 def events():
1689 for r in rlog:
1689 for r in rlog:
1690 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1690 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1691 if r in revs:
1691 if r in revs:
1692 yield 'l', (r, "r%i" % r)
1692 yield 'l', (r, "r%i" % r)
1693 elif repo:
1693 elif repo:
1694 cl = repo.changelog
1694 cl = repo.changelog
1695 tags = opts.get('tags')
1695 tags = opts.get('tags')
1696 branches = opts.get('branches')
1696 branches = opts.get('branches')
1697 if tags:
1697 if tags:
1698 labels = {}
1698 labels = {}
1699 for l, n in repo.tags().items():
1699 for l, n in repo.tags().items():
1700 labels.setdefault(cl.rev(n), []).append(l)
1700 labels.setdefault(cl.rev(n), []).append(l)
1701 def events():
1701 def events():
1702 b = "default"
1702 b = "default"
1703 for r in cl:
1703 for r in cl:
1704 if branches:
1704 if branches:
1705 newb = cl.read(cl.node(r))[5]['branch']
1705 newb = cl.read(cl.node(r))[5]['branch']
1706 if newb != b:
1706 if newb != b:
1707 yield 'a', newb
1707 yield 'a', newb
1708 b = newb
1708 b = newb
1709 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1709 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1710 if tags:
1710 if tags:
1711 ls = labels.get(r)
1711 ls = labels.get(r)
1712 if ls:
1712 if ls:
1713 for l in ls:
1713 for l in ls:
1714 yield 'l', (r, l)
1714 yield 'l', (r, l)
1715 else:
1715 else:
1716 raise util.Abort(_('need repo for changelog dag'))
1716 raise util.Abort(_('need repo for changelog dag'))
1717
1717
1718 for line in dagparser.dagtextlines(events(),
1718 for line in dagparser.dagtextlines(events(),
1719 addspaces=spaces,
1719 addspaces=spaces,
1720 wraplabels=True,
1720 wraplabels=True,
1721 wrapannotations=True,
1721 wrapannotations=True,
1722 wrapnonlinear=dots,
1722 wrapnonlinear=dots,
1723 usedots=dots,
1723 usedots=dots,
1724 maxlinewidth=70):
1724 maxlinewidth=70):
1725 ui.write(line)
1725 ui.write(line)
1726 ui.write("\n")
1726 ui.write("\n")
1727
1727
1728 @command('debugdata',
1728 @command('debugdata',
1729 [('c', 'changelog', False, _('open changelog')),
1729 [('c', 'changelog', False, _('open changelog')),
1730 ('m', 'manifest', False, _('open manifest'))],
1730 ('m', 'manifest', False, _('open manifest'))],
1731 _('-c|-m|FILE REV'))
1731 _('-c|-m|FILE REV'))
1732 def debugdata(ui, repo, file_, rev = None, **opts):
1732 def debugdata(ui, repo, file_, rev = None, **opts):
1733 """dump the contents of a data file revision"""
1733 """dump the contents of a data file revision"""
1734 if opts.get('changelog') or opts.get('manifest'):
1734 if opts.get('changelog') or opts.get('manifest'):
1735 file_, rev = None, file_
1735 file_, rev = None, file_
1736 elif rev is None:
1736 elif rev is None:
1737 raise error.CommandError('debugdata', _('invalid arguments'))
1737 raise error.CommandError('debugdata', _('invalid arguments'))
1738 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1738 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1739 try:
1739 try:
1740 ui.write(r.revision(r.lookup(rev)))
1740 ui.write(r.revision(r.lookup(rev)))
1741 except KeyError:
1741 except KeyError:
1742 raise util.Abort(_('invalid revision identifier %s') % rev)
1742 raise util.Abort(_('invalid revision identifier %s') % rev)
1743
1743
1744 @command('debugdate',
1744 @command('debugdate',
1745 [('e', 'extended', None, _('try extended date formats'))],
1745 [('e', 'extended', None, _('try extended date formats'))],
1746 _('[-e] DATE [RANGE]'))
1746 _('[-e] DATE [RANGE]'))
1747 def debugdate(ui, date, range=None, **opts):
1747 def debugdate(ui, date, range=None, **opts):
1748 """parse and display a date"""
1748 """parse and display a date"""
1749 if opts["extended"]:
1749 if opts["extended"]:
1750 d = util.parsedate(date, util.extendeddateformats)
1750 d = util.parsedate(date, util.extendeddateformats)
1751 else:
1751 else:
1752 d = util.parsedate(date)
1752 d = util.parsedate(date)
1753 ui.write("internal: %s %s\n" % d)
1753 ui.write("internal: %s %s\n" % d)
1754 ui.write("standard: %s\n" % util.datestr(d))
1754 ui.write("standard: %s\n" % util.datestr(d))
1755 if range:
1755 if range:
1756 m = util.matchdate(range)
1756 m = util.matchdate(range)
1757 ui.write("match: %s\n" % m(d[0]))
1757 ui.write("match: %s\n" % m(d[0]))
1758
1758
1759 @command('debugdiscovery',
1759 @command('debugdiscovery',
1760 [('', 'old', None, _('use old-style discovery')),
1760 [('', 'old', None, _('use old-style discovery')),
1761 ('', 'nonheads', None,
1761 ('', 'nonheads', None,
1762 _('use old-style discovery with non-heads included')),
1762 _('use old-style discovery with non-heads included')),
1763 ] + remoteopts,
1763 ] + remoteopts,
1764 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1764 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1765 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1765 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1766 """runs the changeset discovery protocol in isolation"""
1766 """runs the changeset discovery protocol in isolation"""
1767 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1767 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1768 remote = hg.peer(repo, opts, remoteurl)
1768 remote = hg.peer(repo, opts, remoteurl)
1769 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1769 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1770
1770
1771 # make sure tests are repeatable
1771 # make sure tests are repeatable
1772 random.seed(12323)
1772 random.seed(12323)
1773
1773
1774 def doit(localheads, remoteheads):
1774 def doit(localheads, remoteheads):
1775 if opts.get('old'):
1775 if opts.get('old'):
1776 if localheads:
1776 if localheads:
1777 raise util.Abort('cannot use localheads with old style discovery')
1777 raise util.Abort('cannot use localheads with old style discovery')
1778 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1778 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1779 force=True)
1779 force=True)
1780 common = set(common)
1780 common = set(common)
1781 if not opts.get('nonheads'):
1781 if not opts.get('nonheads'):
1782 ui.write("unpruned common: %s\n" % " ".join([short(n)
1782 ui.write("unpruned common: %s\n" % " ".join([short(n)
1783 for n in common]))
1783 for n in common]))
1784 dag = dagutil.revlogdag(repo.changelog)
1784 dag = dagutil.revlogdag(repo.changelog)
1785 all = dag.ancestorset(dag.internalizeall(common))
1785 all = dag.ancestorset(dag.internalizeall(common))
1786 common = dag.externalizeall(dag.headsetofconnecteds(all))
1786 common = dag.externalizeall(dag.headsetofconnecteds(all))
1787 else:
1787 else:
1788 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1788 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1789 common = set(common)
1789 common = set(common)
1790 rheads = set(hds)
1790 rheads = set(hds)
1791 lheads = set(repo.heads())
1791 lheads = set(repo.heads())
1792 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1792 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1793 if lheads <= common:
1793 if lheads <= common:
1794 ui.write("local is subset\n")
1794 ui.write("local is subset\n")
1795 elif rheads <= common:
1795 elif rheads <= common:
1796 ui.write("remote is subset\n")
1796 ui.write("remote is subset\n")
1797
1797
1798 serverlogs = opts.get('serverlog')
1798 serverlogs = opts.get('serverlog')
1799 if serverlogs:
1799 if serverlogs:
1800 for filename in serverlogs:
1800 for filename in serverlogs:
1801 logfile = open(filename, 'r')
1801 logfile = open(filename, 'r')
1802 try:
1802 try:
1803 line = logfile.readline()
1803 line = logfile.readline()
1804 while line:
1804 while line:
1805 parts = line.strip().split(';')
1805 parts = line.strip().split(';')
1806 op = parts[1]
1806 op = parts[1]
1807 if op == 'cg':
1807 if op == 'cg':
1808 pass
1808 pass
1809 elif op == 'cgss':
1809 elif op == 'cgss':
1810 doit(parts[2].split(' '), parts[3].split(' '))
1810 doit(parts[2].split(' '), parts[3].split(' '))
1811 elif op == 'unb':
1811 elif op == 'unb':
1812 doit(parts[3].split(' '), parts[2].split(' '))
1812 doit(parts[3].split(' '), parts[2].split(' '))
1813 line = logfile.readline()
1813 line = logfile.readline()
1814 finally:
1814 finally:
1815 logfile.close()
1815 logfile.close()
1816
1816
1817 else:
1817 else:
1818 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1818 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1819 opts.get('remote_head'))
1819 opts.get('remote_head'))
1820 localrevs = opts.get('local_head')
1820 localrevs = opts.get('local_head')
1821 doit(localrevs, remoterevs)
1821 doit(localrevs, remoterevs)
1822
1822
1823 @command('debugfileset', [], ('REVSPEC'))
1823 @command('debugfileset', [], ('REVSPEC'))
1824 def debugfileset(ui, repo, expr):
1824 def debugfileset(ui, repo, expr):
1825 '''parse and apply a fileset specification'''
1825 '''parse and apply a fileset specification'''
1826 if ui.verbose:
1826 if ui.verbose:
1827 tree = fileset.parse(expr)[0]
1827 tree = fileset.parse(expr)[0]
1828 ui.note(tree, "\n")
1828 ui.note(tree, "\n")
1829
1829
1830 for f in fileset.getfileset(repo[None], expr):
1830 for f in fileset.getfileset(repo[None], expr):
1831 ui.write("%s\n" % f)
1831 ui.write("%s\n" % f)
1832
1832
1833 @command('debugfsinfo', [], _('[PATH]'))
1833 @command('debugfsinfo', [], _('[PATH]'))
1834 def debugfsinfo(ui, path = "."):
1834 def debugfsinfo(ui, path = "."):
1835 """show information detected about current filesystem"""
1835 """show information detected about current filesystem"""
1836 util.writefile('.debugfsinfo', '')
1836 util.writefile('.debugfsinfo', '')
1837 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1837 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1838 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1838 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1839 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1839 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1840 and 'yes' or 'no'))
1840 and 'yes' or 'no'))
1841 os.unlink('.debugfsinfo')
1841 os.unlink('.debugfsinfo')
1842
1842
1843 @command('debuggetbundle',
1843 @command('debuggetbundle',
1844 [('H', 'head', [], _('id of head node'), _('ID')),
1844 [('H', 'head', [], _('id of head node'), _('ID')),
1845 ('C', 'common', [], _('id of common node'), _('ID')),
1845 ('C', 'common', [], _('id of common node'), _('ID')),
1846 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1846 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1847 _('REPO FILE [-H|-C ID]...'))
1847 _('REPO FILE [-H|-C ID]...'))
1848 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1848 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1849 """retrieves a bundle from a repo
1849 """retrieves a bundle from a repo
1850
1850
1851 Every ID must be a full-length hex node id string. Saves the bundle to the
1851 Every ID must be a full-length hex node id string. Saves the bundle to the
1852 given file.
1852 given file.
1853 """
1853 """
1854 repo = hg.peer(ui, opts, repopath)
1854 repo = hg.peer(ui, opts, repopath)
1855 if not repo.capable('getbundle'):
1855 if not repo.capable('getbundle'):
1856 raise util.Abort("getbundle() not supported by target repository")
1856 raise util.Abort("getbundle() not supported by target repository")
1857 args = {}
1857 args = {}
1858 if common:
1858 if common:
1859 args['common'] = [bin(s) for s in common]
1859 args['common'] = [bin(s) for s in common]
1860 if head:
1860 if head:
1861 args['heads'] = [bin(s) for s in head]
1861 args['heads'] = [bin(s) for s in head]
1862 bundle = repo.getbundle('debug', **args)
1862 bundle = repo.getbundle('debug', **args)
1863
1863
1864 bundletype = opts.get('type', 'bzip2').lower()
1864 bundletype = opts.get('type', 'bzip2').lower()
1865 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1865 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1866 bundletype = btypes.get(bundletype)
1866 bundletype = btypes.get(bundletype)
1867 if bundletype not in changegroup.bundletypes:
1867 if bundletype not in changegroup.bundletypes:
1868 raise util.Abort(_('unknown bundle type specified with --type'))
1868 raise util.Abort(_('unknown bundle type specified with --type'))
1869 changegroup.writebundle(bundle, bundlepath, bundletype)
1869 changegroup.writebundle(bundle, bundlepath, bundletype)
1870
1870
1871 @command('debugignore', [], '')
1871 @command('debugignore', [], '')
1872 def debugignore(ui, repo, *values, **opts):
1872 def debugignore(ui, repo, *values, **opts):
1873 """display the combined ignore pattern"""
1873 """display the combined ignore pattern"""
1874 ignore = repo.dirstate._ignore
1874 ignore = repo.dirstate._ignore
1875 includepat = getattr(ignore, 'includepat', None)
1875 includepat = getattr(ignore, 'includepat', None)
1876 if includepat is not None:
1876 if includepat is not None:
1877 ui.write("%s\n" % includepat)
1877 ui.write("%s\n" % includepat)
1878 else:
1878 else:
1879 raise util.Abort(_("no ignore patterns found"))
1879 raise util.Abort(_("no ignore patterns found"))
1880
1880
1881 @command('debugindex',
1881 @command('debugindex',
1882 [('c', 'changelog', False, _('open changelog')),
1882 [('c', 'changelog', False, _('open changelog')),
1883 ('m', 'manifest', False, _('open manifest')),
1883 ('m', 'manifest', False, _('open manifest')),
1884 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1884 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1885 _('[-f FORMAT] -c|-m|FILE'))
1885 _('[-f FORMAT] -c|-m|FILE'))
1886 def debugindex(ui, repo, file_ = None, **opts):
1886 def debugindex(ui, repo, file_ = None, **opts):
1887 """dump the contents of an index file"""
1887 """dump the contents of an index file"""
1888 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1888 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1889 format = opts.get('format', 0)
1889 format = opts.get('format', 0)
1890 if format not in (0, 1):
1890 if format not in (0, 1):
1891 raise util.Abort(_("unknown format %d") % format)
1891 raise util.Abort(_("unknown format %d") % format)
1892
1892
1893 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1893 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1894 if generaldelta:
1894 if generaldelta:
1895 basehdr = ' delta'
1895 basehdr = ' delta'
1896 else:
1896 else:
1897 basehdr = ' base'
1897 basehdr = ' base'
1898
1898
1899 if format == 0:
1899 if format == 0:
1900 ui.write(" rev offset length " + basehdr + " linkrev"
1900 ui.write(" rev offset length " + basehdr + " linkrev"
1901 " nodeid p1 p2\n")
1901 " nodeid p1 p2\n")
1902 elif format == 1:
1902 elif format == 1:
1903 ui.write(" rev flag offset length"
1903 ui.write(" rev flag offset length"
1904 " size " + basehdr + " link p1 p2 nodeid\n")
1904 " size " + basehdr + " link p1 p2 nodeid\n")
1905
1905
1906 for i in r:
1906 for i in r:
1907 node = r.node(i)
1907 node = r.node(i)
1908 if generaldelta:
1908 if generaldelta:
1909 base = r.deltaparent(i)
1909 base = r.deltaparent(i)
1910 else:
1910 else:
1911 base = r.chainbase(i)
1911 base = r.chainbase(i)
1912 if format == 0:
1912 if format == 0:
1913 try:
1913 try:
1914 pp = r.parents(node)
1914 pp = r.parents(node)
1915 except:
1915 except:
1916 pp = [nullid, nullid]
1916 pp = [nullid, nullid]
1917 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1917 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1918 i, r.start(i), r.length(i), base, r.linkrev(i),
1918 i, r.start(i), r.length(i), base, r.linkrev(i),
1919 short(node), short(pp[0]), short(pp[1])))
1919 short(node), short(pp[0]), short(pp[1])))
1920 elif format == 1:
1920 elif format == 1:
1921 pr = r.parentrevs(i)
1921 pr = r.parentrevs(i)
1922 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1922 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1923 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1923 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1924 base, r.linkrev(i), pr[0], pr[1], short(node)))
1924 base, r.linkrev(i), pr[0], pr[1], short(node)))
1925
1925
1926 @command('debugindexdot', [], _('FILE'))
1926 @command('debugindexdot', [], _('FILE'))
1927 def debugindexdot(ui, repo, file_):
1927 def debugindexdot(ui, repo, file_):
1928 """dump an index DAG as a graphviz dot file"""
1928 """dump an index DAG as a graphviz dot file"""
1929 r = None
1929 r = None
1930 if repo:
1930 if repo:
1931 filelog = repo.file(file_)
1931 filelog = repo.file(file_)
1932 if len(filelog):
1932 if len(filelog):
1933 r = filelog
1933 r = filelog
1934 if not r:
1934 if not r:
1935 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1935 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1936 ui.write("digraph G {\n")
1936 ui.write("digraph G {\n")
1937 for i in r:
1937 for i in r:
1938 node = r.node(i)
1938 node = r.node(i)
1939 pp = r.parents(node)
1939 pp = r.parents(node)
1940 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1940 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1941 if pp[1] != nullid:
1941 if pp[1] != nullid:
1942 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1942 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1943 ui.write("}\n")
1943 ui.write("}\n")
1944
1944
1945 @command('debuginstall', [], '')
1945 @command('debuginstall', [], '')
1946 def debuginstall(ui):
1946 def debuginstall(ui):
1947 '''test Mercurial installation
1947 '''test Mercurial installation
1948
1948
1949 Returns 0 on success.
1949 Returns 0 on success.
1950 '''
1950 '''
1951
1951
1952 def writetemp(contents):
1952 def writetemp(contents):
1953 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1953 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1954 f = os.fdopen(fd, "wb")
1954 f = os.fdopen(fd, "wb")
1955 f.write(contents)
1955 f.write(contents)
1956 f.close()
1956 f.close()
1957 return name
1957 return name
1958
1958
1959 problems = 0
1959 problems = 0
1960
1960
1961 # encoding
1961 # encoding
1962 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1962 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1963 try:
1963 try:
1964 encoding.fromlocal("test")
1964 encoding.fromlocal("test")
1965 except util.Abort, inst:
1965 except util.Abort, inst:
1966 ui.write(" %s\n" % inst)
1966 ui.write(" %s\n" % inst)
1967 ui.write(_(" (check that your locale is properly set)\n"))
1967 ui.write(_(" (check that your locale is properly set)\n"))
1968 problems += 1
1968 problems += 1
1969
1969
1970 # compiled modules
1970 # compiled modules
1971 ui.status(_("Checking installed modules (%s)...\n")
1971 ui.status(_("Checking installed modules (%s)...\n")
1972 % os.path.dirname(__file__))
1972 % os.path.dirname(__file__))
1973 try:
1973 try:
1974 import bdiff, mpatch, base85, osutil
1974 import bdiff, mpatch, base85, osutil
1975 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1975 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1976 except Exception, inst:
1976 except Exception, inst:
1977 ui.write(" %s\n" % inst)
1977 ui.write(" %s\n" % inst)
1978 ui.write(_(" One or more extensions could not be found"))
1978 ui.write(_(" One or more extensions could not be found"))
1979 ui.write(_(" (check that you compiled the extensions)\n"))
1979 ui.write(_(" (check that you compiled the extensions)\n"))
1980 problems += 1
1980 problems += 1
1981
1981
1982 # templates
1982 # templates
1983 import templater
1983 import templater
1984 p = templater.templatepath()
1984 p = templater.templatepath()
1985 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1985 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1986 try:
1986 try:
1987 templater.templater(templater.templatepath("map-cmdline.default"))
1987 templater.templater(templater.templatepath("map-cmdline.default"))
1988 except Exception, inst:
1988 except Exception, inst:
1989 ui.write(" %s\n" % inst)
1989 ui.write(" %s\n" % inst)
1990 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1990 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1991 problems += 1
1991 problems += 1
1992
1992
1993 # editor
1993 # editor
1994 ui.status(_("Checking commit editor...\n"))
1994 ui.status(_("Checking commit editor...\n"))
1995 editor = ui.geteditor()
1995 editor = ui.geteditor()
1996 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1996 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1997 if not cmdpath:
1997 if not cmdpath:
1998 if editor == 'vi':
1998 if editor == 'vi':
1999 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1999 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2000 ui.write(_(" (specify a commit editor in your configuration"
2000 ui.write(_(" (specify a commit editor in your configuration"
2001 " file)\n"))
2001 " file)\n"))
2002 else:
2002 else:
2003 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2003 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2004 ui.write(_(" (specify a commit editor in your configuration"
2004 ui.write(_(" (specify a commit editor in your configuration"
2005 " file)\n"))
2005 " file)\n"))
2006 problems += 1
2006 problems += 1
2007
2007
2008 # check username
2008 # check username
2009 ui.status(_("Checking username...\n"))
2009 ui.status(_("Checking username...\n"))
2010 try:
2010 try:
2011 ui.username()
2011 ui.username()
2012 except util.Abort, e:
2012 except util.Abort, e:
2013 ui.write(" %s\n" % e)
2013 ui.write(" %s\n" % e)
2014 ui.write(_(" (specify a username in your configuration file)\n"))
2014 ui.write(_(" (specify a username in your configuration file)\n"))
2015 problems += 1
2015 problems += 1
2016
2016
2017 if not problems:
2017 if not problems:
2018 ui.status(_("No problems detected\n"))
2018 ui.status(_("No problems detected\n"))
2019 else:
2019 else:
2020 ui.write(_("%s problems detected,"
2020 ui.write(_("%s problems detected,"
2021 " please check your install!\n") % problems)
2021 " please check your install!\n") % problems)
2022
2022
2023 return problems
2023 return problems
2024
2024
2025 @command('debugknown', [], _('REPO ID...'))
2025 @command('debugknown', [], _('REPO ID...'))
2026 def debugknown(ui, repopath, *ids, **opts):
2026 def debugknown(ui, repopath, *ids, **opts):
2027 """test whether node ids are known to a repo
2027 """test whether node ids are known to a repo
2028
2028
2029 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
2029 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
2030 indicating unknown/known.
2030 indicating unknown/known.
2031 """
2031 """
2032 repo = hg.peer(ui, opts, repopath)
2032 repo = hg.peer(ui, opts, repopath)
2033 if not repo.capable('known'):
2033 if not repo.capable('known'):
2034 raise util.Abort("known() not supported by target repository")
2034 raise util.Abort("known() not supported by target repository")
2035 flags = repo.known([bin(s) for s in ids])
2035 flags = repo.known([bin(s) for s in ids])
2036 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2036 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2037
2037
2038 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2038 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2039 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2039 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2040 '''access the pushkey key/value protocol
2040 '''access the pushkey key/value protocol
2041
2041
2042 With two args, list the keys in the given namespace.
2042 With two args, list the keys in the given namespace.
2043
2043
2044 With five args, set a key to new if it currently is set to old.
2044 With five args, set a key to new if it currently is set to old.
2045 Reports success or failure.
2045 Reports success or failure.
2046 '''
2046 '''
2047
2047
2048 target = hg.peer(ui, {}, repopath)
2048 target = hg.peer(ui, {}, repopath)
2049 if keyinfo:
2049 if keyinfo:
2050 key, old, new = keyinfo
2050 key, old, new = keyinfo
2051 r = target.pushkey(namespace, key, old, new)
2051 r = target.pushkey(namespace, key, old, new)
2052 ui.status(str(r) + '\n')
2052 ui.status(str(r) + '\n')
2053 return not r
2053 return not r
2054 else:
2054 else:
2055 for k, v in target.listkeys(namespace).iteritems():
2055 for k, v in target.listkeys(namespace).iteritems():
2056 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2056 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2057 v.encode('string-escape')))
2057 v.encode('string-escape')))
2058
2058
2059 @command('debugpvec', [], _('A B'))
2059 @command('debugpvec', [], _('A B'))
2060 def debugpvec(ui, repo, a, b=None):
2060 def debugpvec(ui, repo, a, b=None):
2061 ca = scmutil.revsingle(repo, a)
2061 ca = scmutil.revsingle(repo, a)
2062 cb = scmutil.revsingle(repo, b)
2062 cb = scmutil.revsingle(repo, b)
2063 pa = pvec.ctxpvec(ca)
2063 pa = pvec.ctxpvec(ca)
2064 pb = pvec.ctxpvec(cb)
2064 pb = pvec.ctxpvec(cb)
2065 if pa == pb:
2065 if pa == pb:
2066 rel = "="
2066 rel = "="
2067 elif pa > pb:
2067 elif pa > pb:
2068 rel = ">"
2068 rel = ">"
2069 elif pa < pb:
2069 elif pa < pb:
2070 rel = "<"
2070 rel = "<"
2071 elif pa | pb:
2071 elif pa | pb:
2072 rel = "|"
2072 rel = "|"
2073 ui.write(_("a: %s\n") % pa)
2073 ui.write(_("a: %s\n") % pa)
2074 ui.write(_("b: %s\n") % pb)
2074 ui.write(_("b: %s\n") % pb)
2075 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2075 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2076 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2076 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2077 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2077 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2078 pa.distance(pb), rel))
2078 pa.distance(pb), rel))
2079
2079
2080 @command('debugrebuildstate',
2080 @command('debugrebuildstate',
2081 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2081 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2082 _('[-r REV] [REV]'))
2082 _('[-r REV] [REV]'))
2083 def debugrebuildstate(ui, repo, rev="tip"):
2083 def debugrebuildstate(ui, repo, rev="tip"):
2084 """rebuild the dirstate as it would look like for the given revision"""
2084 """rebuild the dirstate as it would look like for the given revision"""
2085 ctx = scmutil.revsingle(repo, rev)
2085 ctx = scmutil.revsingle(repo, rev)
2086 wlock = repo.wlock()
2086 wlock = repo.wlock()
2087 try:
2087 try:
2088 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2088 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2089 finally:
2089 finally:
2090 wlock.release()
2090 wlock.release()
2091
2091
2092 @command('debugrename',
2092 @command('debugrename',
2093 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2093 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2094 _('[-r REV] FILE'))
2094 _('[-r REV] FILE'))
2095 def debugrename(ui, repo, file1, *pats, **opts):
2095 def debugrename(ui, repo, file1, *pats, **opts):
2096 """dump rename information"""
2096 """dump rename information"""
2097
2097
2098 ctx = scmutil.revsingle(repo, opts.get('rev'))
2098 ctx = scmutil.revsingle(repo, opts.get('rev'))
2099 m = scmutil.match(ctx, (file1,) + pats, opts)
2099 m = scmutil.match(ctx, (file1,) + pats, opts)
2100 for abs in ctx.walk(m):
2100 for abs in ctx.walk(m):
2101 fctx = ctx[abs]
2101 fctx = ctx[abs]
2102 o = fctx.filelog().renamed(fctx.filenode())
2102 o = fctx.filelog().renamed(fctx.filenode())
2103 rel = m.rel(abs)
2103 rel = m.rel(abs)
2104 if o:
2104 if o:
2105 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2105 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2106 else:
2106 else:
2107 ui.write(_("%s not renamed\n") % rel)
2107 ui.write(_("%s not renamed\n") % rel)
2108
2108
2109 @command('debugrevlog',
2109 @command('debugrevlog',
2110 [('c', 'changelog', False, _('open changelog')),
2110 [('c', 'changelog', False, _('open changelog')),
2111 ('m', 'manifest', False, _('open manifest')),
2111 ('m', 'manifest', False, _('open manifest')),
2112 ('d', 'dump', False, _('dump index data'))],
2112 ('d', 'dump', False, _('dump index data'))],
2113 _('-c|-m|FILE'))
2113 _('-c|-m|FILE'))
2114 def debugrevlog(ui, repo, file_ = None, **opts):
2114 def debugrevlog(ui, repo, file_ = None, **opts):
2115 """show data and statistics about a revlog"""
2115 """show data and statistics about a revlog"""
2116 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2116 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2117
2117
2118 if opts.get("dump"):
2118 if opts.get("dump"):
2119 numrevs = len(r)
2119 numrevs = len(r)
2120 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2120 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2121 " rawsize totalsize compression heads\n")
2121 " rawsize totalsize compression heads\n")
2122 ts = 0
2122 ts = 0
2123 heads = set()
2123 heads = set()
2124 for rev in xrange(numrevs):
2124 for rev in xrange(numrevs):
2125 dbase = r.deltaparent(rev)
2125 dbase = r.deltaparent(rev)
2126 if dbase == -1:
2126 if dbase == -1:
2127 dbase = rev
2127 dbase = rev
2128 cbase = r.chainbase(rev)
2128 cbase = r.chainbase(rev)
2129 p1, p2 = r.parentrevs(rev)
2129 p1, p2 = r.parentrevs(rev)
2130 rs = r.rawsize(rev)
2130 rs = r.rawsize(rev)
2131 ts = ts + rs
2131 ts = ts + rs
2132 heads -= set(r.parentrevs(rev))
2132 heads -= set(r.parentrevs(rev))
2133 heads.add(rev)
2133 heads.add(rev)
2134 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2134 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2135 (rev, p1, p2, r.start(rev), r.end(rev),
2135 (rev, p1, p2, r.start(rev), r.end(rev),
2136 r.start(dbase), r.start(cbase),
2136 r.start(dbase), r.start(cbase),
2137 r.start(p1), r.start(p2),
2137 r.start(p1), r.start(p2),
2138 rs, ts, ts / r.end(rev), len(heads)))
2138 rs, ts, ts / r.end(rev), len(heads)))
2139 return 0
2139 return 0
2140
2140
2141 v = r.version
2141 v = r.version
2142 format = v & 0xFFFF
2142 format = v & 0xFFFF
2143 flags = []
2143 flags = []
2144 gdelta = False
2144 gdelta = False
2145 if v & revlog.REVLOGNGINLINEDATA:
2145 if v & revlog.REVLOGNGINLINEDATA:
2146 flags.append('inline')
2146 flags.append('inline')
2147 if v & revlog.REVLOGGENERALDELTA:
2147 if v & revlog.REVLOGGENERALDELTA:
2148 gdelta = True
2148 gdelta = True
2149 flags.append('generaldelta')
2149 flags.append('generaldelta')
2150 if not flags:
2150 if not flags:
2151 flags = ['(none)']
2151 flags = ['(none)']
2152
2152
2153 nummerges = 0
2153 nummerges = 0
2154 numfull = 0
2154 numfull = 0
2155 numprev = 0
2155 numprev = 0
2156 nump1 = 0
2156 nump1 = 0
2157 nump2 = 0
2157 nump2 = 0
2158 numother = 0
2158 numother = 0
2159 nump1prev = 0
2159 nump1prev = 0
2160 nump2prev = 0
2160 nump2prev = 0
2161 chainlengths = []
2161 chainlengths = []
2162
2162
2163 datasize = [None, 0, 0L]
2163 datasize = [None, 0, 0L]
2164 fullsize = [None, 0, 0L]
2164 fullsize = [None, 0, 0L]
2165 deltasize = [None, 0, 0L]
2165 deltasize = [None, 0, 0L]
2166
2166
2167 def addsize(size, l):
2167 def addsize(size, l):
2168 if l[0] is None or size < l[0]:
2168 if l[0] is None or size < l[0]:
2169 l[0] = size
2169 l[0] = size
2170 if size > l[1]:
2170 if size > l[1]:
2171 l[1] = size
2171 l[1] = size
2172 l[2] += size
2172 l[2] += size
2173
2173
2174 numrevs = len(r)
2174 numrevs = len(r)
2175 for rev in xrange(numrevs):
2175 for rev in xrange(numrevs):
2176 p1, p2 = r.parentrevs(rev)
2176 p1, p2 = r.parentrevs(rev)
2177 delta = r.deltaparent(rev)
2177 delta = r.deltaparent(rev)
2178 if format > 0:
2178 if format > 0:
2179 addsize(r.rawsize(rev), datasize)
2179 addsize(r.rawsize(rev), datasize)
2180 if p2 != nullrev:
2180 if p2 != nullrev:
2181 nummerges += 1
2181 nummerges += 1
2182 size = r.length(rev)
2182 size = r.length(rev)
2183 if delta == nullrev:
2183 if delta == nullrev:
2184 chainlengths.append(0)
2184 chainlengths.append(0)
2185 numfull += 1
2185 numfull += 1
2186 addsize(size, fullsize)
2186 addsize(size, fullsize)
2187 else:
2187 else:
2188 chainlengths.append(chainlengths[delta] + 1)
2188 chainlengths.append(chainlengths[delta] + 1)
2189 addsize(size, deltasize)
2189 addsize(size, deltasize)
2190 if delta == rev - 1:
2190 if delta == rev - 1:
2191 numprev += 1
2191 numprev += 1
2192 if delta == p1:
2192 if delta == p1:
2193 nump1prev += 1
2193 nump1prev += 1
2194 elif delta == p2:
2194 elif delta == p2:
2195 nump2prev += 1
2195 nump2prev += 1
2196 elif delta == p1:
2196 elif delta == p1:
2197 nump1 += 1
2197 nump1 += 1
2198 elif delta == p2:
2198 elif delta == p2:
2199 nump2 += 1
2199 nump2 += 1
2200 elif delta != nullrev:
2200 elif delta != nullrev:
2201 numother += 1
2201 numother += 1
2202
2202
2203 numdeltas = numrevs - numfull
2203 numdeltas = numrevs - numfull
2204 numoprev = numprev - nump1prev - nump2prev
2204 numoprev = numprev - nump1prev - nump2prev
2205 totalrawsize = datasize[2]
2205 totalrawsize = datasize[2]
2206 datasize[2] /= numrevs
2206 datasize[2] /= numrevs
2207 fulltotal = fullsize[2]
2207 fulltotal = fullsize[2]
2208 fullsize[2] /= numfull
2208 fullsize[2] /= numfull
2209 deltatotal = deltasize[2]
2209 deltatotal = deltasize[2]
2210 deltasize[2] /= numrevs - numfull
2210 deltasize[2] /= numrevs - numfull
2211 totalsize = fulltotal + deltatotal
2211 totalsize = fulltotal + deltatotal
2212 avgchainlen = sum(chainlengths) / numrevs
2212 avgchainlen = sum(chainlengths) / numrevs
2213 compratio = totalrawsize / totalsize
2213 compratio = totalrawsize / totalsize
2214
2214
2215 basedfmtstr = '%%%dd\n'
2215 basedfmtstr = '%%%dd\n'
2216 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2216 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2217
2217
2218 def dfmtstr(max):
2218 def dfmtstr(max):
2219 return basedfmtstr % len(str(max))
2219 return basedfmtstr % len(str(max))
2220 def pcfmtstr(max, padding=0):
2220 def pcfmtstr(max, padding=0):
2221 return basepcfmtstr % (len(str(max)), ' ' * padding)
2221 return basepcfmtstr % (len(str(max)), ' ' * padding)
2222
2222
2223 def pcfmt(value, total):
2223 def pcfmt(value, total):
2224 return (value, 100 * float(value) / total)
2224 return (value, 100 * float(value) / total)
2225
2225
2226 ui.write('format : %d\n' % format)
2226 ui.write('format : %d\n' % format)
2227 ui.write('flags : %s\n' % ', '.join(flags))
2227 ui.write('flags : %s\n' % ', '.join(flags))
2228
2228
2229 ui.write('\n')
2229 ui.write('\n')
2230 fmt = pcfmtstr(totalsize)
2230 fmt = pcfmtstr(totalsize)
2231 fmt2 = dfmtstr(totalsize)
2231 fmt2 = dfmtstr(totalsize)
2232 ui.write('revisions : ' + fmt2 % numrevs)
2232 ui.write('revisions : ' + fmt2 % numrevs)
2233 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2233 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2234 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2234 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2235 ui.write('revisions : ' + fmt2 % numrevs)
2235 ui.write('revisions : ' + fmt2 % numrevs)
2236 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2236 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2237 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2237 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2238 ui.write('revision size : ' + fmt2 % totalsize)
2238 ui.write('revision size : ' + fmt2 % totalsize)
2239 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2239 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2240 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2240 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2241
2241
2242 ui.write('\n')
2242 ui.write('\n')
2243 fmt = dfmtstr(max(avgchainlen, compratio))
2243 fmt = dfmtstr(max(avgchainlen, compratio))
2244 ui.write('avg chain length : ' + fmt % avgchainlen)
2244 ui.write('avg chain length : ' + fmt % avgchainlen)
2245 ui.write('compression ratio : ' + fmt % compratio)
2245 ui.write('compression ratio : ' + fmt % compratio)
2246
2246
2247 if format > 0:
2247 if format > 0:
2248 ui.write('\n')
2248 ui.write('\n')
2249 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2249 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2250 % tuple(datasize))
2250 % tuple(datasize))
2251 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2251 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2252 % tuple(fullsize))
2252 % tuple(fullsize))
2253 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2253 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2254 % tuple(deltasize))
2254 % tuple(deltasize))
2255
2255
2256 if numdeltas > 0:
2256 if numdeltas > 0:
2257 ui.write('\n')
2257 ui.write('\n')
2258 fmt = pcfmtstr(numdeltas)
2258 fmt = pcfmtstr(numdeltas)
2259 fmt2 = pcfmtstr(numdeltas, 4)
2259 fmt2 = pcfmtstr(numdeltas, 4)
2260 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2260 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2261 if numprev > 0:
2261 if numprev > 0:
2262 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2262 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2263 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2263 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2264 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2264 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2265 if gdelta:
2265 if gdelta:
2266 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2266 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2267 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2267 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2268 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2268 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2269
2269
2270 @command('debugrevspec', [], ('REVSPEC'))
2270 @command('debugrevspec', [], ('REVSPEC'))
2271 def debugrevspec(ui, repo, expr):
2271 def debugrevspec(ui, repo, expr):
2272 """parse and apply a revision specification
2272 """parse and apply a revision specification
2273
2273
2274 Use --verbose to print the parsed tree before and after aliases
2274 Use --verbose to print the parsed tree before and after aliases
2275 expansion.
2275 expansion.
2276 """
2276 """
2277 if ui.verbose:
2277 if ui.verbose:
2278 tree = revset.parse(expr)[0]
2278 tree = revset.parse(expr)[0]
2279 ui.note(revset.prettyformat(tree), "\n")
2279 ui.note(revset.prettyformat(tree), "\n")
2280 newtree = revset.findaliases(ui, tree)
2280 newtree = revset.findaliases(ui, tree)
2281 if newtree != tree:
2281 if newtree != tree:
2282 ui.note(revset.prettyformat(newtree), "\n")
2282 ui.note(revset.prettyformat(newtree), "\n")
2283 func = revset.match(ui, expr)
2283 func = revset.match(ui, expr)
2284 for c in func(repo, range(len(repo))):
2284 for c in func(repo, range(len(repo))):
2285 ui.write("%s\n" % c)
2285 ui.write("%s\n" % c)
2286
2286
2287 @command('debugsetparents', [], _('REV1 [REV2]'))
2287 @command('debugsetparents', [], _('REV1 [REV2]'))
2288 def debugsetparents(ui, repo, rev1, rev2=None):
2288 def debugsetparents(ui, repo, rev1, rev2=None):
2289 """manually set the parents of the current working directory
2289 """manually set the parents of the current working directory
2290
2290
2291 This is useful for writing repository conversion tools, but should
2291 This is useful for writing repository conversion tools, but should
2292 be used with care.
2292 be used with care.
2293
2293
2294 Returns 0 on success.
2294 Returns 0 on success.
2295 """
2295 """
2296
2296
2297 r1 = scmutil.revsingle(repo, rev1).node()
2297 r1 = scmutil.revsingle(repo, rev1).node()
2298 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2298 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2299
2299
2300 wlock = repo.wlock()
2300 wlock = repo.wlock()
2301 try:
2301 try:
2302 repo.setparents(r1, r2)
2302 repo.setparents(r1, r2)
2303 finally:
2303 finally:
2304 wlock.release()
2304 wlock.release()
2305
2305
2306 @command('debugstate',
2306 @command('debugstate',
2307 [('', 'nodates', None, _('do not display the saved mtime')),
2307 [('', 'nodates', None, _('do not display the saved mtime')),
2308 ('', 'datesort', None, _('sort by saved mtime'))],
2308 ('', 'datesort', None, _('sort by saved mtime'))],
2309 _('[OPTION]...'))
2309 _('[OPTION]...'))
2310 def debugstate(ui, repo, nodates=None, datesort=None):
2310 def debugstate(ui, repo, nodates=None, datesort=None):
2311 """show the contents of the current dirstate"""
2311 """show the contents of the current dirstate"""
2312 timestr = ""
2312 timestr = ""
2313 showdate = not nodates
2313 showdate = not nodates
2314 if datesort:
2314 if datesort:
2315 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2315 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2316 else:
2316 else:
2317 keyfunc = None # sort by filename
2317 keyfunc = None # sort by filename
2318 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2318 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2319 if showdate:
2319 if showdate:
2320 if ent[3] == -1:
2320 if ent[3] == -1:
2321 # Pad or slice to locale representation
2321 # Pad or slice to locale representation
2322 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2322 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2323 time.localtime(0)))
2323 time.localtime(0)))
2324 timestr = 'unset'
2324 timestr = 'unset'
2325 timestr = (timestr[:locale_len] +
2325 timestr = (timestr[:locale_len] +
2326 ' ' * (locale_len - len(timestr)))
2326 ' ' * (locale_len - len(timestr)))
2327 else:
2327 else:
2328 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2328 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2329 time.localtime(ent[3]))
2329 time.localtime(ent[3]))
2330 if ent[1] & 020000:
2330 if ent[1] & 020000:
2331 mode = 'lnk'
2331 mode = 'lnk'
2332 else:
2332 else:
2333 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2333 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2334 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2334 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2335 for f in repo.dirstate.copies():
2335 for f in repo.dirstate.copies():
2336 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2336 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2337
2337
2338 @command('debugsub',
2338 @command('debugsub',
2339 [('r', 'rev', '',
2339 [('r', 'rev', '',
2340 _('revision to check'), _('REV'))],
2340 _('revision to check'), _('REV'))],
2341 _('[-r REV] [REV]'))
2341 _('[-r REV] [REV]'))
2342 def debugsub(ui, repo, rev=None):
2342 def debugsub(ui, repo, rev=None):
2343 ctx = scmutil.revsingle(repo, rev, None)
2343 ctx = scmutil.revsingle(repo, rev, None)
2344 for k, v in sorted(ctx.substate.items()):
2344 for k, v in sorted(ctx.substate.items()):
2345 ui.write('path %s\n' % k)
2345 ui.write('path %s\n' % k)
2346 ui.write(' source %s\n' % v[0])
2346 ui.write(' source %s\n' % v[0])
2347 ui.write(' revision %s\n' % v[1])
2347 ui.write(' revision %s\n' % v[1])
2348
2348
2349 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2349 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2350 def debugwalk(ui, repo, *pats, **opts):
2350 def debugwalk(ui, repo, *pats, **opts):
2351 """show how files match on given patterns"""
2351 """show how files match on given patterns"""
2352 m = scmutil.match(repo[None], pats, opts)
2352 m = scmutil.match(repo[None], pats, opts)
2353 items = list(repo.walk(m))
2353 items = list(repo.walk(m))
2354 if not items:
2354 if not items:
2355 return
2355 return
2356 fmt = 'f %%-%ds %%-%ds %%s' % (
2356 fmt = 'f %%-%ds %%-%ds %%s' % (
2357 max([len(abs) for abs in items]),
2357 max([len(abs) for abs in items]),
2358 max([len(m.rel(abs)) for abs in items]))
2358 max([len(m.rel(abs)) for abs in items]))
2359 for abs in items:
2359 for abs in items:
2360 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2360 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2361 ui.write("%s\n" % line.rstrip())
2361 ui.write("%s\n" % line.rstrip())
2362
2362
2363 @command('debugwireargs',
2363 @command('debugwireargs',
2364 [('', 'three', '', 'three'),
2364 [('', 'three', '', 'three'),
2365 ('', 'four', '', 'four'),
2365 ('', 'four', '', 'four'),
2366 ('', 'five', '', 'five'),
2366 ('', 'five', '', 'five'),
2367 ] + remoteopts,
2367 ] + remoteopts,
2368 _('REPO [OPTIONS]... [ONE [TWO]]'))
2368 _('REPO [OPTIONS]... [ONE [TWO]]'))
2369 def debugwireargs(ui, repopath, *vals, **opts):
2369 def debugwireargs(ui, repopath, *vals, **opts):
2370 repo = hg.peer(ui, opts, repopath)
2370 repo = hg.peer(ui, opts, repopath)
2371 for opt in remoteopts:
2371 for opt in remoteopts:
2372 del opts[opt[1]]
2372 del opts[opt[1]]
2373 args = {}
2373 args = {}
2374 for k, v in opts.iteritems():
2374 for k, v in opts.iteritems():
2375 if v:
2375 if v:
2376 args[k] = v
2376 args[k] = v
2377 # run twice to check that we don't mess up the stream for the next command
2377 # run twice to check that we don't mess up the stream for the next command
2378 res1 = repo.debugwireargs(*vals, **args)
2378 res1 = repo.debugwireargs(*vals, **args)
2379 res2 = repo.debugwireargs(*vals, **args)
2379 res2 = repo.debugwireargs(*vals, **args)
2380 ui.write("%s\n" % res1)
2380 ui.write("%s\n" % res1)
2381 if res1 != res2:
2381 if res1 != res2:
2382 ui.warn("%s\n" % res2)
2382 ui.warn("%s\n" % res2)
2383
2383
2384 @command('^diff',
2384 @command('^diff',
2385 [('r', 'rev', [], _('revision'), _('REV')),
2385 [('r', 'rev', [], _('revision'), _('REV')),
2386 ('c', 'change', '', _('change made by revision'), _('REV'))
2386 ('c', 'change', '', _('change made by revision'), _('REV'))
2387 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2387 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2388 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2388 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2389 def diff(ui, repo, *pats, **opts):
2389 def diff(ui, repo, *pats, **opts):
2390 """diff repository (or selected files)
2390 """diff repository (or selected files)
2391
2391
2392 Show differences between revisions for the specified files.
2392 Show differences between revisions for the specified files.
2393
2393
2394 Differences between files are shown using the unified diff format.
2394 Differences between files are shown using the unified diff format.
2395
2395
2396 .. note::
2396 .. note::
2397 diff may generate unexpected results for merges, as it will
2397 diff may generate unexpected results for merges, as it will
2398 default to comparing against the working directory's first
2398 default to comparing against the working directory's first
2399 parent changeset if no revisions are specified.
2399 parent changeset if no revisions are specified.
2400
2400
2401 When two revision arguments are given, then changes are shown
2401 When two revision arguments are given, then changes are shown
2402 between those revisions. If only one revision is specified then
2402 between those revisions. If only one revision is specified then
2403 that revision is compared to the working directory, and, when no
2403 that revision is compared to the working directory, and, when no
2404 revisions are specified, the working directory files are compared
2404 revisions are specified, the working directory files are compared
2405 to its parent.
2405 to its parent.
2406
2406
2407 Alternatively you can specify -c/--change with a revision to see
2407 Alternatively you can specify -c/--change with a revision to see
2408 the changes in that changeset relative to its first parent.
2408 the changes in that changeset relative to its first parent.
2409
2409
2410 Without the -a/--text option, diff will avoid generating diffs of
2410 Without the -a/--text option, diff will avoid generating diffs of
2411 files it detects as binary. With -a, diff will generate a diff
2411 files it detects as binary. With -a, diff will generate a diff
2412 anyway, probably with undesirable results.
2412 anyway, probably with undesirable results.
2413
2413
2414 Use the -g/--git option to generate diffs in the git extended diff
2414 Use the -g/--git option to generate diffs in the git extended diff
2415 format. For more information, read :hg:`help diffs`.
2415 format. For more information, read :hg:`help diffs`.
2416
2416
2417 .. container:: verbose
2417 .. container:: verbose
2418
2418
2419 Examples:
2419 Examples:
2420
2420
2421 - compare a file in the current working directory to its parent::
2421 - compare a file in the current working directory to its parent::
2422
2422
2423 hg diff foo.c
2423 hg diff foo.c
2424
2424
2425 - compare two historical versions of a directory, with rename info::
2425 - compare two historical versions of a directory, with rename info::
2426
2426
2427 hg diff --git -r 1.0:1.2 lib/
2427 hg diff --git -r 1.0:1.2 lib/
2428
2428
2429 - get change stats relative to the last change on some date::
2429 - get change stats relative to the last change on some date::
2430
2430
2431 hg diff --stat -r "date('may 2')"
2431 hg diff --stat -r "date('may 2')"
2432
2432
2433 - diff all newly-added files that contain a keyword::
2433 - diff all newly-added files that contain a keyword::
2434
2434
2435 hg diff "set:added() and grep(GNU)"
2435 hg diff "set:added() and grep(GNU)"
2436
2436
2437 - compare a revision and its parents::
2437 - compare a revision and its parents::
2438
2438
2439 hg diff -c 9353 # compare against first parent
2439 hg diff -c 9353 # compare against first parent
2440 hg diff -r 9353^:9353 # same using revset syntax
2440 hg diff -r 9353^:9353 # same using revset syntax
2441 hg diff -r 9353^2:9353 # compare against the second parent
2441 hg diff -r 9353^2:9353 # compare against the second parent
2442
2442
2443 Returns 0 on success.
2443 Returns 0 on success.
2444 """
2444 """
2445
2445
2446 revs = opts.get('rev')
2446 revs = opts.get('rev')
2447 change = opts.get('change')
2447 change = opts.get('change')
2448 stat = opts.get('stat')
2448 stat = opts.get('stat')
2449 reverse = opts.get('reverse')
2449 reverse = opts.get('reverse')
2450
2450
2451 if revs and change:
2451 if revs and change:
2452 msg = _('cannot specify --rev and --change at the same time')
2452 msg = _('cannot specify --rev and --change at the same time')
2453 raise util.Abort(msg)
2453 raise util.Abort(msg)
2454 elif change:
2454 elif change:
2455 node2 = scmutil.revsingle(repo, change, None).node()
2455 node2 = scmutil.revsingle(repo, change, None).node()
2456 node1 = repo[node2].p1().node()
2456 node1 = repo[node2].p1().node()
2457 else:
2457 else:
2458 node1, node2 = scmutil.revpair(repo, revs)
2458 node1, node2 = scmutil.revpair(repo, revs)
2459
2459
2460 if reverse:
2460 if reverse:
2461 node1, node2 = node2, node1
2461 node1, node2 = node2, node1
2462
2462
2463 diffopts = patch.diffopts(ui, opts)
2463 diffopts = patch.diffopts(ui, opts)
2464 m = scmutil.match(repo[node2], pats, opts)
2464 m = scmutil.match(repo[node2], pats, opts)
2465 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2465 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2466 listsubrepos=opts.get('subrepos'))
2466 listsubrepos=opts.get('subrepos'))
2467
2467
2468 @command('^export',
2468 @command('^export',
2469 [('o', 'output', '',
2469 [('o', 'output', '',
2470 _('print output to file with formatted name'), _('FORMAT')),
2470 _('print output to file with formatted name'), _('FORMAT')),
2471 ('', 'switch-parent', None, _('diff against the second parent')),
2471 ('', 'switch-parent', None, _('diff against the second parent')),
2472 ('r', 'rev', [], _('revisions to export'), _('REV')),
2472 ('r', 'rev', [], _('revisions to export'), _('REV')),
2473 ] + diffopts,
2473 ] + diffopts,
2474 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2474 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2475 def export(ui, repo, *changesets, **opts):
2475 def export(ui, repo, *changesets, **opts):
2476 """dump the header and diffs for one or more changesets
2476 """dump the header and diffs for one or more changesets
2477
2477
2478 Print the changeset header and diffs for one or more revisions.
2478 Print the changeset header and diffs for one or more revisions.
2479
2479
2480 The information shown in the changeset header is: author, date,
2480 The information shown in the changeset header is: author, date,
2481 branch name (if non-default), changeset hash, parent(s) and commit
2481 branch name (if non-default), changeset hash, parent(s) and commit
2482 comment.
2482 comment.
2483
2483
2484 .. note::
2484 .. note::
2485 export may generate unexpected diff output for merge
2485 export may generate unexpected diff output for merge
2486 changesets, as it will compare the merge changeset against its
2486 changesets, as it will compare the merge changeset against its
2487 first parent only.
2487 first parent only.
2488
2488
2489 Output may be to a file, in which case the name of the file is
2489 Output may be to a file, in which case the name of the file is
2490 given using a format string. The formatting rules are as follows:
2490 given using a format string. The formatting rules are as follows:
2491
2491
2492 :``%%``: literal "%" character
2492 :``%%``: literal "%" character
2493 :``%H``: changeset hash (40 hexadecimal digits)
2493 :``%H``: changeset hash (40 hexadecimal digits)
2494 :``%N``: number of patches being generated
2494 :``%N``: number of patches being generated
2495 :``%R``: changeset revision number
2495 :``%R``: changeset revision number
2496 :``%b``: basename of the exporting repository
2496 :``%b``: basename of the exporting repository
2497 :``%h``: short-form changeset hash (12 hexadecimal digits)
2497 :``%h``: short-form changeset hash (12 hexadecimal digits)
2498 :``%m``: first line of the commit message (only alphanumeric characters)
2498 :``%m``: first line of the commit message (only alphanumeric characters)
2499 :``%n``: zero-padded sequence number, starting at 1
2499 :``%n``: zero-padded sequence number, starting at 1
2500 :``%r``: zero-padded changeset revision number
2500 :``%r``: zero-padded changeset revision number
2501
2501
2502 Without the -a/--text option, export will avoid generating diffs
2502 Without the -a/--text option, export will avoid generating diffs
2503 of files it detects as binary. With -a, export will generate a
2503 of files it detects as binary. With -a, export will generate a
2504 diff anyway, probably with undesirable results.
2504 diff anyway, probably with undesirable results.
2505
2505
2506 Use the -g/--git option to generate diffs in the git extended diff
2506 Use the -g/--git option to generate diffs in the git extended diff
2507 format. See :hg:`help diffs` for more information.
2507 format. See :hg:`help diffs` for more information.
2508
2508
2509 With the --switch-parent option, the diff will be against the
2509 With the --switch-parent option, the diff will be against the
2510 second parent. It can be useful to review a merge.
2510 second parent. It can be useful to review a merge.
2511
2511
2512 .. container:: verbose
2512 .. container:: verbose
2513
2513
2514 Examples:
2514 Examples:
2515
2515
2516 - use export and import to transplant a bugfix to the current
2516 - use export and import to transplant a bugfix to the current
2517 branch::
2517 branch::
2518
2518
2519 hg export -r 9353 | hg import -
2519 hg export -r 9353 | hg import -
2520
2520
2521 - export all the changesets between two revisions to a file with
2521 - export all the changesets between two revisions to a file with
2522 rename information::
2522 rename information::
2523
2523
2524 hg export --git -r 123:150 > changes.txt
2524 hg export --git -r 123:150 > changes.txt
2525
2525
2526 - split outgoing changes into a series of patches with
2526 - split outgoing changes into a series of patches with
2527 descriptive names::
2527 descriptive names::
2528
2528
2529 hg export -r "outgoing()" -o "%n-%m.patch"
2529 hg export -r "outgoing()" -o "%n-%m.patch"
2530
2530
2531 Returns 0 on success.
2531 Returns 0 on success.
2532 """
2532 """
2533 changesets += tuple(opts.get('rev', []))
2533 changesets += tuple(opts.get('rev', []))
2534 revs = scmutil.revrange(repo, changesets)
2534 revs = scmutil.revrange(repo, changesets)
2535 if not revs:
2535 if not revs:
2536 raise util.Abort(_("export requires at least one changeset"))
2536 raise util.Abort(_("export requires at least one changeset"))
2537 if len(revs) > 1:
2537 if len(revs) > 1:
2538 ui.note(_('exporting patches:\n'))
2538 ui.note(_('exporting patches:\n'))
2539 else:
2539 else:
2540 ui.note(_('exporting patch:\n'))
2540 ui.note(_('exporting patch:\n'))
2541 cmdutil.export(repo, revs, template=opts.get('output'),
2541 cmdutil.export(repo, revs, template=opts.get('output'),
2542 switch_parent=opts.get('switch_parent'),
2542 switch_parent=opts.get('switch_parent'),
2543 opts=patch.diffopts(ui, opts))
2543 opts=patch.diffopts(ui, opts))
2544
2544
2545 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2545 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2546 def forget(ui, repo, *pats, **opts):
2546 def forget(ui, repo, *pats, **opts):
2547 """forget the specified files on the next commit
2547 """forget the specified files on the next commit
2548
2548
2549 Mark the specified files so they will no longer be tracked
2549 Mark the specified files so they will no longer be tracked
2550 after the next commit.
2550 after the next commit.
2551
2551
2552 This only removes files from the current branch, not from the
2552 This only removes files from the current branch, not from the
2553 entire project history, and it does not delete them from the
2553 entire project history, and it does not delete them from the
2554 working directory.
2554 working directory.
2555
2555
2556 To undo a forget before the next commit, see :hg:`add`.
2556 To undo a forget before the next commit, see :hg:`add`.
2557
2557
2558 .. container:: verbose
2558 .. container:: verbose
2559
2559
2560 Examples:
2560 Examples:
2561
2561
2562 - forget newly-added binary files::
2562 - forget newly-added binary files::
2563
2563
2564 hg forget "set:added() and binary()"
2564 hg forget "set:added() and binary()"
2565
2565
2566 - forget files that would be excluded by .hgignore::
2566 - forget files that would be excluded by .hgignore::
2567
2567
2568 hg forget "set:hgignore()"
2568 hg forget "set:hgignore()"
2569
2569
2570 Returns 0 on success.
2570 Returns 0 on success.
2571 """
2571 """
2572
2572
2573 if not pats:
2573 if not pats:
2574 raise util.Abort(_('no files specified'))
2574 raise util.Abort(_('no files specified'))
2575
2575
2576 m = scmutil.match(repo[None], pats, opts)
2576 m = scmutil.match(repo[None], pats, opts)
2577 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2577 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2578 return rejected and 1 or 0
2578 return rejected and 1 or 0
2579
2579
2580 @command(
2580 @command(
2581 'graft',
2581 'graft',
2582 [('c', 'continue', False, _('resume interrupted graft')),
2582 [('c', 'continue', False, _('resume interrupted graft')),
2583 ('e', 'edit', False, _('invoke editor on commit messages')),
2583 ('e', 'edit', False, _('invoke editor on commit messages')),
2584 ('D', 'currentdate', False,
2584 ('D', 'currentdate', False,
2585 _('record the current date as commit date')),
2585 _('record the current date as commit date')),
2586 ('U', 'currentuser', False,
2586 ('U', 'currentuser', False,
2587 _('record the current user as committer'), _('DATE'))]
2587 _('record the current user as committer'), _('DATE'))]
2588 + commitopts2 + mergetoolopts + dryrunopts,
2588 + commitopts2 + mergetoolopts + dryrunopts,
2589 _('[OPTION]... REVISION...'))
2589 _('[OPTION]... REVISION...'))
2590 def graft(ui, repo, *revs, **opts):
2590 def graft(ui, repo, *revs, **opts):
2591 '''copy changes from other branches onto the current branch
2591 '''copy changes from other branches onto the current branch
2592
2592
2593 This command uses Mercurial's merge logic to copy individual
2593 This command uses Mercurial's merge logic to copy individual
2594 changes from other branches without merging branches in the
2594 changes from other branches without merging branches in the
2595 history graph. This is sometimes known as 'backporting' or
2595 history graph. This is sometimes known as 'backporting' or
2596 'cherry-picking'. By default, graft will copy user, date, and
2596 'cherry-picking'. By default, graft will copy user, date, and
2597 description from the source changesets.
2597 description from the source changesets.
2598
2598
2599 Changesets that are ancestors of the current revision, that have
2599 Changesets that are ancestors of the current revision, that have
2600 already been grafted, or that are merges will be skipped.
2600 already been grafted, or that are merges will be skipped.
2601
2601
2602 If a graft merge results in conflicts, the graft process is
2602 If a graft merge results in conflicts, the graft process is
2603 interrupted so that the current merge can be manually resolved.
2603 interrupted so that the current merge can be manually resolved.
2604 Once all conflicts are addressed, the graft process can be
2604 Once all conflicts are addressed, the graft process can be
2605 continued with the -c/--continue option.
2605 continued with the -c/--continue option.
2606
2606
2607 .. note::
2607 .. note::
2608 The -c/--continue option does not reapply earlier options.
2608 The -c/--continue option does not reapply earlier options.
2609
2609
2610 .. container:: verbose
2610 .. container:: verbose
2611
2611
2612 Examples:
2612 Examples:
2613
2613
2614 - copy a single change to the stable branch and edit its description::
2614 - copy a single change to the stable branch and edit its description::
2615
2615
2616 hg update stable
2616 hg update stable
2617 hg graft --edit 9393
2617 hg graft --edit 9393
2618
2618
2619 - graft a range of changesets with one exception, updating dates::
2619 - graft a range of changesets with one exception, updating dates::
2620
2620
2621 hg graft -D "2085::2093 and not 2091"
2621 hg graft -D "2085::2093 and not 2091"
2622
2622
2623 - continue a graft after resolving conflicts::
2623 - continue a graft after resolving conflicts::
2624
2624
2625 hg graft -c
2625 hg graft -c
2626
2626
2627 - show the source of a grafted changeset::
2627 - show the source of a grafted changeset::
2628
2628
2629 hg log --debug -r tip
2629 hg log --debug -r tip
2630
2630
2631 Returns 0 on successful completion.
2631 Returns 0 on successful completion.
2632 '''
2632 '''
2633
2633
2634 if not opts.get('user') and opts.get('currentuser'):
2634 if not opts.get('user') and opts.get('currentuser'):
2635 opts['user'] = ui.username()
2635 opts['user'] = ui.username()
2636 if not opts.get('date') and opts.get('currentdate'):
2636 if not opts.get('date') and opts.get('currentdate'):
2637 opts['date'] = "%d %d" % util.makedate()
2637 opts['date'] = "%d %d" % util.makedate()
2638
2638
2639 editor = None
2639 editor = None
2640 if opts.get('edit'):
2640 if opts.get('edit'):
2641 editor = cmdutil.commitforceeditor
2641 editor = cmdutil.commitforceeditor
2642
2642
2643 cont = False
2643 cont = False
2644 if opts['continue']:
2644 if opts['continue']:
2645 cont = True
2645 cont = True
2646 if revs:
2646 if revs:
2647 raise util.Abort(_("can't specify --continue and revisions"))
2647 raise util.Abort(_("can't specify --continue and revisions"))
2648 # read in unfinished revisions
2648 # read in unfinished revisions
2649 try:
2649 try:
2650 nodes = repo.opener.read('graftstate').splitlines()
2650 nodes = repo.opener.read('graftstate').splitlines()
2651 revs = [repo[node].rev() for node in nodes]
2651 revs = [repo[node].rev() for node in nodes]
2652 except IOError, inst:
2652 except IOError, inst:
2653 if inst.errno != errno.ENOENT:
2653 if inst.errno != errno.ENOENT:
2654 raise
2654 raise
2655 raise util.Abort(_("no graft state found, can't continue"))
2655 raise util.Abort(_("no graft state found, can't continue"))
2656 else:
2656 else:
2657 cmdutil.bailifchanged(repo)
2657 cmdutil.bailifchanged(repo)
2658 if not revs:
2658 if not revs:
2659 raise util.Abort(_('no revisions specified'))
2659 raise util.Abort(_('no revisions specified'))
2660 revs = scmutil.revrange(repo, revs)
2660 revs = scmutil.revrange(repo, revs)
2661
2661
2662 # check for merges
2662 # check for merges
2663 for rev in repo.revs('%ld and merge()', revs):
2663 for rev in repo.revs('%ld and merge()', revs):
2664 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2664 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2665 revs.remove(rev)
2665 revs.remove(rev)
2666 if not revs:
2666 if not revs:
2667 return -1
2667 return -1
2668
2668
2669 # check for ancestors of dest branch
2669 # check for ancestors of dest branch
2670 for rev in repo.revs('::. and %ld', revs):
2670 for rev in repo.revs('::. and %ld', revs):
2671 ui.warn(_('skipping ancestor revision %s\n') % rev)
2671 ui.warn(_('skipping ancestor revision %s\n') % rev)
2672 revs.remove(rev)
2672 revs.remove(rev)
2673 if not revs:
2673 if not revs:
2674 return -1
2674 return -1
2675
2675
2676 # analyze revs for earlier grafts
2676 # analyze revs for earlier grafts
2677 ids = {}
2677 ids = {}
2678 for ctx in repo.set("%ld", revs):
2678 for ctx in repo.set("%ld", revs):
2679 ids[ctx.hex()] = ctx.rev()
2679 ids[ctx.hex()] = ctx.rev()
2680 n = ctx.extra().get('source')
2680 n = ctx.extra().get('source')
2681 if n:
2681 if n:
2682 ids[n] = ctx.rev()
2682 ids[n] = ctx.rev()
2683
2683
2684 # check ancestors for earlier grafts
2684 # check ancestors for earlier grafts
2685 ui.debug('scanning for duplicate grafts\n')
2685 ui.debug('scanning for duplicate grafts\n')
2686 for ctx in repo.set("::. - ::%ld", revs):
2686 for ctx in repo.set("::. - ::%ld", revs):
2687 n = ctx.extra().get('source')
2687 n = ctx.extra().get('source')
2688 if n in ids:
2688 if n in ids:
2689 r = repo[n].rev()
2689 r = repo[n].rev()
2690 if r in revs:
2690 if r in revs:
2691 ui.warn(_('skipping already grafted revision %s\n') % r)
2691 ui.warn(_('skipping already grafted revision %s\n') % r)
2692 revs.remove(r)
2692 revs.remove(r)
2693 elif ids[n] in revs:
2693 elif ids[n] in revs:
2694 ui.warn(_('skipping already grafted revision %s '
2694 ui.warn(_('skipping already grafted revision %s '
2695 '(same origin %d)\n') % (ids[n], r))
2695 '(same origin %d)\n') % (ids[n], r))
2696 revs.remove(ids[n])
2696 revs.remove(ids[n])
2697 elif ctx.hex() in ids:
2697 elif ctx.hex() in ids:
2698 r = ids[ctx.hex()]
2698 r = ids[ctx.hex()]
2699 ui.warn(_('skipping already grafted revision %s '
2699 ui.warn(_('skipping already grafted revision %s '
2700 '(was grafted from %d)\n') % (r, ctx.rev()))
2700 '(was grafted from %d)\n') % (r, ctx.rev()))
2701 revs.remove(r)
2701 revs.remove(r)
2702 if not revs:
2702 if not revs:
2703 return -1
2703 return -1
2704
2704
2705 wlock = repo.wlock()
2705 wlock = repo.wlock()
2706 try:
2706 try:
2707 for pos, ctx in enumerate(repo.set("%ld", revs)):
2707 for pos, ctx in enumerate(repo.set("%ld", revs)):
2708 current = repo['.']
2708 current = repo['.']
2709
2709
2710 ui.status(_('grafting revision %s\n') % ctx.rev())
2710 ui.status(_('grafting revision %s\n') % ctx.rev())
2711 if opts.get('dry_run'):
2711 if opts.get('dry_run'):
2712 continue
2712 continue
2713
2713
2714 # we don't merge the first commit when continuing
2714 # we don't merge the first commit when continuing
2715 if not cont:
2715 if not cont:
2716 # perform the graft merge with p1(rev) as 'ancestor'
2716 # perform the graft merge with p1(rev) as 'ancestor'
2717 try:
2717 try:
2718 # ui.forcemerge is an internal variable, do not document
2718 # ui.forcemerge is an internal variable, do not document
2719 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2719 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2720 stats = mergemod.update(repo, ctx.node(), True, True, False,
2720 stats = mergemod.update(repo, ctx.node(), True, True, False,
2721 ctx.p1().node())
2721 ctx.p1().node())
2722 finally:
2722 finally:
2723 ui.setconfig('ui', 'forcemerge', '')
2723 ui.setconfig('ui', 'forcemerge', '')
2724 # drop the second merge parent
2724 # drop the second merge parent
2725 repo.setparents(current.node(), nullid)
2725 repo.setparents(current.node(), nullid)
2726 repo.dirstate.write()
2726 repo.dirstate.write()
2727 # fix up dirstate for copies and renames
2727 # fix up dirstate for copies and renames
2728 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2728 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2729 # report any conflicts
2729 # report any conflicts
2730 if stats and stats[3] > 0:
2730 if stats and stats[3] > 0:
2731 # write out state for --continue
2731 # write out state for --continue
2732 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2732 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2733 repo.opener.write('graftstate', ''.join(nodelines))
2733 repo.opener.write('graftstate', ''.join(nodelines))
2734 raise util.Abort(
2734 raise util.Abort(
2735 _("unresolved conflicts, can't continue"),
2735 _("unresolved conflicts, can't continue"),
2736 hint=_('use hg resolve and hg graft --continue'))
2736 hint=_('use hg resolve and hg graft --continue'))
2737 else:
2737 else:
2738 cont = False
2738 cont = False
2739
2739
2740 # commit
2740 # commit
2741 source = ctx.extra().get('source')
2741 source = ctx.extra().get('source')
2742 if not source:
2742 if not source:
2743 source = ctx.hex()
2743 source = ctx.hex()
2744 extra = {'source': source}
2744 extra = {'source': source}
2745 user = ctx.user()
2745 user = ctx.user()
2746 if opts.get('user'):
2746 if opts.get('user'):
2747 user = opts['user']
2747 user = opts['user']
2748 date = ctx.date()
2748 date = ctx.date()
2749 if opts.get('date'):
2749 if opts.get('date'):
2750 date = opts['date']
2750 date = opts['date']
2751 node = repo.commit(text=ctx.description(), user=user,
2751 node = repo.commit(text=ctx.description(), user=user,
2752 date=date, extra=extra, editor=editor)
2752 date=date, extra=extra, editor=editor)
2753 if node is None:
2753 if node is None:
2754 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2754 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2755 finally:
2755 finally:
2756 wlock.release()
2756 wlock.release()
2757
2757
2758 # remove state when we complete successfully
2758 # remove state when we complete successfully
2759 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2759 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2760 util.unlinkpath(repo.join('graftstate'))
2760 util.unlinkpath(repo.join('graftstate'))
2761
2761
2762 return 0
2762 return 0
2763
2763
2764 @command('grep',
2764 @command('grep',
2765 [('0', 'print0', None, _('end fields with NUL')),
2765 [('0', 'print0', None, _('end fields with NUL')),
2766 ('', 'all', None, _('print all revisions that match')),
2766 ('', 'all', None, _('print all revisions that match')),
2767 ('a', 'text', None, _('treat all files as text')),
2767 ('a', 'text', None, _('treat all files as text')),
2768 ('f', 'follow', None,
2768 ('f', 'follow', None,
2769 _('follow changeset history,'
2769 _('follow changeset history,'
2770 ' or file history across copies and renames')),
2770 ' or file history across copies and renames')),
2771 ('i', 'ignore-case', None, _('ignore case when matching')),
2771 ('i', 'ignore-case', None, _('ignore case when matching')),
2772 ('l', 'files-with-matches', None,
2772 ('l', 'files-with-matches', None,
2773 _('print only filenames and revisions that match')),
2773 _('print only filenames and revisions that match')),
2774 ('n', 'line-number', None, _('print matching line numbers')),
2774 ('n', 'line-number', None, _('print matching line numbers')),
2775 ('r', 'rev', [],
2775 ('r', 'rev', [],
2776 _('only search files changed within revision range'), _('REV')),
2776 _('only search files changed within revision range'), _('REV')),
2777 ('u', 'user', None, _('list the author (long with -v)')),
2777 ('u', 'user', None, _('list the author (long with -v)')),
2778 ('d', 'date', None, _('list the date (short with -q)')),
2778 ('d', 'date', None, _('list the date (short with -q)')),
2779 ] + walkopts,
2779 ] + walkopts,
2780 _('[OPTION]... PATTERN [FILE]...'))
2780 _('[OPTION]... PATTERN [FILE]...'))
2781 def grep(ui, repo, pattern, *pats, **opts):
2781 def grep(ui, repo, pattern, *pats, **opts):
2782 """search for a pattern in specified files and revisions
2782 """search for a pattern in specified files and revisions
2783
2783
2784 Search revisions of files for a regular expression.
2784 Search revisions of files for a regular expression.
2785
2785
2786 This command behaves differently than Unix grep. It only accepts
2786 This command behaves differently than Unix grep. It only accepts
2787 Python/Perl regexps. It searches repository history, not the
2787 Python/Perl regexps. It searches repository history, not the
2788 working directory. It always prints the revision number in which a
2788 working directory. It always prints the revision number in which a
2789 match appears.
2789 match appears.
2790
2790
2791 By default, grep only prints output for the first revision of a
2791 By default, grep only prints output for the first revision of a
2792 file in which it finds a match. To get it to print every revision
2792 file in which it finds a match. To get it to print every revision
2793 that contains a change in match status ("-" for a match that
2793 that contains a change in match status ("-" for a match that
2794 becomes a non-match, or "+" for a non-match that becomes a match),
2794 becomes a non-match, or "+" for a non-match that becomes a match),
2795 use the --all flag.
2795 use the --all flag.
2796
2796
2797 Returns 0 if a match is found, 1 otherwise.
2797 Returns 0 if a match is found, 1 otherwise.
2798 """
2798 """
2799 reflags = re.M
2799 reflags = re.M
2800 if opts.get('ignore_case'):
2800 if opts.get('ignore_case'):
2801 reflags |= re.I
2801 reflags |= re.I
2802 try:
2802 try:
2803 regexp = re.compile(pattern, reflags)
2803 regexp = re.compile(pattern, reflags)
2804 except re.error, inst:
2804 except re.error, inst:
2805 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2805 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2806 return 1
2806 return 1
2807 sep, eol = ':', '\n'
2807 sep, eol = ':', '\n'
2808 if opts.get('print0'):
2808 if opts.get('print0'):
2809 sep = eol = '\0'
2809 sep = eol = '\0'
2810
2810
2811 getfile = util.lrucachefunc(repo.file)
2811 getfile = util.lrucachefunc(repo.file)
2812
2812
2813 def matchlines(body):
2813 def matchlines(body):
2814 begin = 0
2814 begin = 0
2815 linenum = 0
2815 linenum = 0
2816 while True:
2816 while True:
2817 match = regexp.search(body, begin)
2817 match = regexp.search(body, begin)
2818 if not match:
2818 if not match:
2819 break
2819 break
2820 mstart, mend = match.span()
2820 mstart, mend = match.span()
2821 linenum += body.count('\n', begin, mstart) + 1
2821 linenum += body.count('\n', begin, mstart) + 1
2822 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2822 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2823 begin = body.find('\n', mend) + 1 or len(body) + 1
2823 begin = body.find('\n', mend) + 1 or len(body) + 1
2824 lend = begin - 1
2824 lend = begin - 1
2825 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2825 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2826
2826
2827 class linestate(object):
2827 class linestate(object):
2828 def __init__(self, line, linenum, colstart, colend):
2828 def __init__(self, line, linenum, colstart, colend):
2829 self.line = line
2829 self.line = line
2830 self.linenum = linenum
2830 self.linenum = linenum
2831 self.colstart = colstart
2831 self.colstart = colstart
2832 self.colend = colend
2832 self.colend = colend
2833
2833
2834 def __hash__(self):
2834 def __hash__(self):
2835 return hash((self.linenum, self.line))
2835 return hash((self.linenum, self.line))
2836
2836
2837 def __eq__(self, other):
2837 def __eq__(self, other):
2838 return self.line == other.line
2838 return self.line == other.line
2839
2839
2840 matches = {}
2840 matches = {}
2841 copies = {}
2841 copies = {}
2842 def grepbody(fn, rev, body):
2842 def grepbody(fn, rev, body):
2843 matches[rev].setdefault(fn, [])
2843 matches[rev].setdefault(fn, [])
2844 m = matches[rev][fn]
2844 m = matches[rev][fn]
2845 for lnum, cstart, cend, line in matchlines(body):
2845 for lnum, cstart, cend, line in matchlines(body):
2846 s = linestate(line, lnum, cstart, cend)
2846 s = linestate(line, lnum, cstart, cend)
2847 m.append(s)
2847 m.append(s)
2848
2848
2849 def difflinestates(a, b):
2849 def difflinestates(a, b):
2850 sm = difflib.SequenceMatcher(None, a, b)
2850 sm = difflib.SequenceMatcher(None, a, b)
2851 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2851 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2852 if tag == 'insert':
2852 if tag == 'insert':
2853 for i in xrange(blo, bhi):
2853 for i in xrange(blo, bhi):
2854 yield ('+', b[i])
2854 yield ('+', b[i])
2855 elif tag == 'delete':
2855 elif tag == 'delete':
2856 for i in xrange(alo, ahi):
2856 for i in xrange(alo, ahi):
2857 yield ('-', a[i])
2857 yield ('-', a[i])
2858 elif tag == 'replace':
2858 elif tag == 'replace':
2859 for i in xrange(alo, ahi):
2859 for i in xrange(alo, ahi):
2860 yield ('-', a[i])
2860 yield ('-', a[i])
2861 for i in xrange(blo, bhi):
2861 for i in xrange(blo, bhi):
2862 yield ('+', b[i])
2862 yield ('+', b[i])
2863
2863
2864 def display(fn, ctx, pstates, states):
2864 def display(fn, ctx, pstates, states):
2865 rev = ctx.rev()
2865 rev = ctx.rev()
2866 datefunc = ui.quiet and util.shortdate or util.datestr
2866 datefunc = ui.quiet and util.shortdate or util.datestr
2867 found = False
2867 found = False
2868 filerevmatches = {}
2868 filerevmatches = {}
2869 def binary():
2869 def binary():
2870 flog = getfile(fn)
2870 flog = getfile(fn)
2871 return util.binary(flog.read(ctx.filenode(fn)))
2871 return util.binary(flog.read(ctx.filenode(fn)))
2872
2872
2873 if opts.get('all'):
2873 if opts.get('all'):
2874 iter = difflinestates(pstates, states)
2874 iter = difflinestates(pstates, states)
2875 else:
2875 else:
2876 iter = [('', l) for l in states]
2876 iter = [('', l) for l in states]
2877 for change, l in iter:
2877 for change, l in iter:
2878 cols = [fn, str(rev)]
2878 cols = [fn, str(rev)]
2879 before, match, after = None, None, None
2879 before, match, after = None, None, None
2880 if opts.get('line_number'):
2880 if opts.get('line_number'):
2881 cols.append(str(l.linenum))
2881 cols.append(str(l.linenum))
2882 if opts.get('all'):
2882 if opts.get('all'):
2883 cols.append(change)
2883 cols.append(change)
2884 if opts.get('user'):
2884 if opts.get('user'):
2885 cols.append(ui.shortuser(ctx.user()))
2885 cols.append(ui.shortuser(ctx.user()))
2886 if opts.get('date'):
2886 if opts.get('date'):
2887 cols.append(datefunc(ctx.date()))
2887 cols.append(datefunc(ctx.date()))
2888 if opts.get('files_with_matches'):
2888 if opts.get('files_with_matches'):
2889 c = (fn, rev)
2889 c = (fn, rev)
2890 if c in filerevmatches:
2890 if c in filerevmatches:
2891 continue
2891 continue
2892 filerevmatches[c] = 1
2892 filerevmatches[c] = 1
2893 else:
2893 else:
2894 before = l.line[:l.colstart]
2894 before = l.line[:l.colstart]
2895 match = l.line[l.colstart:l.colend]
2895 match = l.line[l.colstart:l.colend]
2896 after = l.line[l.colend:]
2896 after = l.line[l.colend:]
2897 ui.write(sep.join(cols))
2897 ui.write(sep.join(cols))
2898 if before is not None:
2898 if before is not None:
2899 if not opts.get('text') and binary():
2899 if not opts.get('text') and binary():
2900 ui.write(sep + " Binary file matches")
2900 ui.write(sep + " Binary file matches")
2901 else:
2901 else:
2902 ui.write(sep + before)
2902 ui.write(sep + before)
2903 ui.write(match, label='grep.match')
2903 ui.write(match, label='grep.match')
2904 ui.write(after)
2904 ui.write(after)
2905 ui.write(eol)
2905 ui.write(eol)
2906 found = True
2906 found = True
2907 return found
2907 return found
2908
2908
2909 skip = {}
2909 skip = {}
2910 revfiles = {}
2910 revfiles = {}
2911 matchfn = scmutil.match(repo[None], pats, opts)
2911 matchfn = scmutil.match(repo[None], pats, opts)
2912 found = False
2912 found = False
2913 follow = opts.get('follow')
2913 follow = opts.get('follow')
2914
2914
2915 def prep(ctx, fns):
2915 def prep(ctx, fns):
2916 rev = ctx.rev()
2916 rev = ctx.rev()
2917 pctx = ctx.p1()
2917 pctx = ctx.p1()
2918 parent = pctx.rev()
2918 parent = pctx.rev()
2919 matches.setdefault(rev, {})
2919 matches.setdefault(rev, {})
2920 matches.setdefault(parent, {})
2920 matches.setdefault(parent, {})
2921 files = revfiles.setdefault(rev, [])
2921 files = revfiles.setdefault(rev, [])
2922 for fn in fns:
2922 for fn in fns:
2923 flog = getfile(fn)
2923 flog = getfile(fn)
2924 try:
2924 try:
2925 fnode = ctx.filenode(fn)
2925 fnode = ctx.filenode(fn)
2926 except error.LookupError:
2926 except error.LookupError:
2927 continue
2927 continue
2928
2928
2929 copied = flog.renamed(fnode)
2929 copied = flog.renamed(fnode)
2930 copy = follow and copied and copied[0]
2930 copy = follow and copied and copied[0]
2931 if copy:
2931 if copy:
2932 copies.setdefault(rev, {})[fn] = copy
2932 copies.setdefault(rev, {})[fn] = copy
2933 if fn in skip:
2933 if fn in skip:
2934 if copy:
2934 if copy:
2935 skip[copy] = True
2935 skip[copy] = True
2936 continue
2936 continue
2937 files.append(fn)
2937 files.append(fn)
2938
2938
2939 if fn not in matches[rev]:
2939 if fn not in matches[rev]:
2940 grepbody(fn, rev, flog.read(fnode))
2940 grepbody(fn, rev, flog.read(fnode))
2941
2941
2942 pfn = copy or fn
2942 pfn = copy or fn
2943 if pfn not in matches[parent]:
2943 if pfn not in matches[parent]:
2944 try:
2944 try:
2945 fnode = pctx.filenode(pfn)
2945 fnode = pctx.filenode(pfn)
2946 grepbody(pfn, parent, flog.read(fnode))
2946 grepbody(pfn, parent, flog.read(fnode))
2947 except error.LookupError:
2947 except error.LookupError:
2948 pass
2948 pass
2949
2949
2950 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2950 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2951 rev = ctx.rev()
2951 rev = ctx.rev()
2952 parent = ctx.p1().rev()
2952 parent = ctx.p1().rev()
2953 for fn in sorted(revfiles.get(rev, [])):
2953 for fn in sorted(revfiles.get(rev, [])):
2954 states = matches[rev][fn]
2954 states = matches[rev][fn]
2955 copy = copies.get(rev, {}).get(fn)
2955 copy = copies.get(rev, {}).get(fn)
2956 if fn in skip:
2956 if fn in skip:
2957 if copy:
2957 if copy:
2958 skip[copy] = True
2958 skip[copy] = True
2959 continue
2959 continue
2960 pstates = matches.get(parent, {}).get(copy or fn, [])
2960 pstates = matches.get(parent, {}).get(copy or fn, [])
2961 if pstates or states:
2961 if pstates or states:
2962 r = display(fn, ctx, pstates, states)
2962 r = display(fn, ctx, pstates, states)
2963 found = found or r
2963 found = found or r
2964 if r and not opts.get('all'):
2964 if r and not opts.get('all'):
2965 skip[fn] = True
2965 skip[fn] = True
2966 if copy:
2966 if copy:
2967 skip[copy] = True
2967 skip[copy] = True
2968 del matches[rev]
2968 del matches[rev]
2969 del revfiles[rev]
2969 del revfiles[rev]
2970
2970
2971 return not found
2971 return not found
2972
2972
2973 @command('heads',
2973 @command('heads',
2974 [('r', 'rev', '',
2974 [('r', 'rev', '',
2975 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2975 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2976 ('t', 'topo', False, _('show topological heads only')),
2976 ('t', 'topo', False, _('show topological heads only')),
2977 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2977 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2978 ('c', 'closed', False, _('show normal and closed branch heads')),
2978 ('c', 'closed', False, _('show normal and closed branch heads')),
2979 ] + templateopts,
2979 ] + templateopts,
2980 _('[-ac] [-r STARTREV] [REV]...'))
2980 _('[-ac] [-r STARTREV] [REV]...'))
2981 def heads(ui, repo, *branchrevs, **opts):
2981 def heads(ui, repo, *branchrevs, **opts):
2982 """show current repository heads or show branch heads
2982 """show current repository heads or show branch heads
2983
2983
2984 With no arguments, show all repository branch heads.
2984 With no arguments, show all repository branch heads.
2985
2985
2986 Repository "heads" are changesets with no child changesets. They are
2986 Repository "heads" are changesets with no child changesets. They are
2987 where development generally takes place and are the usual targets
2987 where development generally takes place and are the usual targets
2988 for update and merge operations. Branch heads are changesets that have
2988 for update and merge operations. Branch heads are changesets that have
2989 no child changeset on the same branch.
2989 no child changeset on the same branch.
2990
2990
2991 If one or more REVs are given, only branch heads on the branches
2991 If one or more REVs are given, only branch heads on the branches
2992 associated with the specified changesets are shown. This means
2992 associated with the specified changesets are shown. This means
2993 that you can use :hg:`heads foo` to see the heads on a branch
2993 that you can use :hg:`heads foo` to see the heads on a branch
2994 named ``foo``.
2994 named ``foo``.
2995
2995
2996 If -c/--closed is specified, also show branch heads marked closed
2996 If -c/--closed is specified, also show branch heads marked closed
2997 (see :hg:`commit --close-branch`).
2997 (see :hg:`commit --close-branch`).
2998
2998
2999 If STARTREV is specified, only those heads that are descendants of
2999 If STARTREV is specified, only those heads that are descendants of
3000 STARTREV will be displayed.
3000 STARTREV will be displayed.
3001
3001
3002 If -t/--topo is specified, named branch mechanics will be ignored and only
3002 If -t/--topo is specified, named branch mechanics will be ignored and only
3003 changesets without children will be shown.
3003 changesets without children will be shown.
3004
3004
3005 Returns 0 if matching heads are found, 1 if not.
3005 Returns 0 if matching heads are found, 1 if not.
3006 """
3006 """
3007
3007
3008 start = None
3008 start = None
3009 if 'rev' in opts:
3009 if 'rev' in opts:
3010 start = scmutil.revsingle(repo, opts['rev'], None).node()
3010 start = scmutil.revsingle(repo, opts['rev'], None).node()
3011
3011
3012 if opts.get('topo'):
3012 if opts.get('topo'):
3013 heads = [repo[h] for h in repo.heads(start)]
3013 heads = [repo[h] for h in repo.heads(start)]
3014 else:
3014 else:
3015 heads = []
3015 heads = []
3016 for branch in repo.branchmap():
3016 for branch in repo.branchmap():
3017 heads += repo.branchheads(branch, start, opts.get('closed'))
3017 heads += repo.branchheads(branch, start, opts.get('closed'))
3018 heads = [repo[h] for h in heads]
3018 heads = [repo[h] for h in heads]
3019
3019
3020 if branchrevs:
3020 if branchrevs:
3021 branches = set(repo[br].branch() for br in branchrevs)
3021 branches = set(repo[br].branch() for br in branchrevs)
3022 heads = [h for h in heads if h.branch() in branches]
3022 heads = [h for h in heads if h.branch() in branches]
3023
3023
3024 if opts.get('active') and branchrevs:
3024 if opts.get('active') and branchrevs:
3025 dagheads = repo.heads(start)
3025 dagheads = repo.heads(start)
3026 heads = [h for h in heads if h.node() in dagheads]
3026 heads = [h for h in heads if h.node() in dagheads]
3027
3027
3028 if branchrevs:
3028 if branchrevs:
3029 haveheads = set(h.branch() for h in heads)
3029 haveheads = set(h.branch() for h in heads)
3030 if branches - haveheads:
3030 if branches - haveheads:
3031 headless = ', '.join(b for b in branches - haveheads)
3031 headless = ', '.join(b for b in branches - haveheads)
3032 msg = _('no open branch heads found on branches %s')
3032 msg = _('no open branch heads found on branches %s')
3033 if opts.get('rev'):
3033 if opts.get('rev'):
3034 msg += _(' (started at %s)') % opts['rev']
3034 msg += _(' (started at %s)') % opts['rev']
3035 ui.warn((msg + '\n') % headless)
3035 ui.warn((msg + '\n') % headless)
3036
3036
3037 if not heads:
3037 if not heads:
3038 return 1
3038 return 1
3039
3039
3040 heads = sorted(heads, key=lambda x: -x.rev())
3040 heads = sorted(heads, key=lambda x: -x.rev())
3041 displayer = cmdutil.show_changeset(ui, repo, opts)
3041 displayer = cmdutil.show_changeset(ui, repo, opts)
3042 for ctx in heads:
3042 for ctx in heads:
3043 displayer.show(ctx)
3043 displayer.show(ctx)
3044 displayer.close()
3044 displayer.close()
3045
3045
3046 @command('help',
3046 @command('help',
3047 [('e', 'extension', None, _('show only help for extensions')),
3047 [('e', 'extension', None, _('show only help for extensions')),
3048 ('c', 'command', None, _('show only help for commands'))],
3048 ('c', 'command', None, _('show only help for commands'))],
3049 _('[-ec] [TOPIC]'))
3049 _('[-ec] [TOPIC]'))
3050 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3050 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3051 """show help for a given topic or a help overview
3051 """show help for a given topic or a help overview
3052
3052
3053 With no arguments, print a list of commands with short help messages.
3053 With no arguments, print a list of commands with short help messages.
3054
3054
3055 Given a topic, extension, or command name, print help for that
3055 Given a topic, extension, or command name, print help for that
3056 topic.
3056 topic.
3057
3057
3058 Returns 0 if successful.
3058 Returns 0 if successful.
3059 """
3059 """
3060
3060
3061 textwidth = min(ui.termwidth(), 80) - 2
3061 textwidth = min(ui.termwidth(), 80) - 2
3062
3062
3063 def optrst(options):
3063 def optrst(options):
3064 data = []
3064 data = []
3065 multioccur = False
3065 multioccur = False
3066 for option in options:
3066 for option in options:
3067 if len(option) == 5:
3067 if len(option) == 5:
3068 shortopt, longopt, default, desc, optlabel = option
3068 shortopt, longopt, default, desc, optlabel = option
3069 else:
3069 else:
3070 shortopt, longopt, default, desc = option
3070 shortopt, longopt, default, desc = option
3071 optlabel = _("VALUE") # default label
3071 optlabel = _("VALUE") # default label
3072
3072
3073 if _("DEPRECATED") in desc and not ui.verbose:
3073 if _("DEPRECATED") in desc and not ui.verbose:
3074 continue
3074 continue
3075
3075
3076 so = ''
3076 so = ''
3077 if shortopt:
3077 if shortopt:
3078 so = '-' + shortopt
3078 so = '-' + shortopt
3079 lo = '--' + longopt
3079 lo = '--' + longopt
3080 if default:
3080 if default:
3081 desc += _(" (default: %s)") % default
3081 desc += _(" (default: %s)") % default
3082
3082
3083 if isinstance(default, list):
3083 if isinstance(default, list):
3084 lo += " %s [+]" % optlabel
3084 lo += " %s [+]" % optlabel
3085 multioccur = True
3085 multioccur = True
3086 elif (default is not None) and not isinstance(default, bool):
3086 elif (default is not None) and not isinstance(default, bool):
3087 lo += " %s" % optlabel
3087 lo += " %s" % optlabel
3088
3088
3089 data.append((so, lo, desc))
3089 data.append((so, lo, desc))
3090
3090
3091 rst = minirst.maketable(data, 1)
3091 rst = minirst.maketable(data, 1)
3092
3092
3093 if multioccur:
3093 if multioccur:
3094 rst += _("\n[+] marked option can be specified multiple times\n")
3094 rst += _("\n[+] marked option can be specified multiple times\n")
3095
3095
3096 return rst
3096 return rst
3097
3097
3098 # list all option lists
3098 # list all option lists
3099 def opttext(optlist, width):
3099 def opttext(optlist, width):
3100 rst = ''
3100 rst = ''
3101 if not optlist:
3101 if not optlist:
3102 return ''
3102 return ''
3103
3103
3104 for title, options in optlist:
3104 for title, options in optlist:
3105 rst += '\n%s\n' % title
3105 rst += '\n%s\n' % title
3106 if options:
3106 if options:
3107 rst += "\n"
3107 rst += "\n"
3108 rst += optrst(options)
3108 rst += optrst(options)
3109 rst += '\n'
3109 rst += '\n'
3110
3110
3111 return '\n' + minirst.format(rst, width)
3111 return '\n' + minirst.format(rst, width)
3112
3112
3113 def addglobalopts(optlist, aliases):
3113 def addglobalopts(optlist, aliases):
3114 if ui.quiet:
3114 if ui.quiet:
3115 return []
3115 return []
3116
3116
3117 if ui.verbose:
3117 if ui.verbose:
3118 optlist.append((_("global options:"), globalopts))
3118 optlist.append((_("global options:"), globalopts))
3119 if name == 'shortlist':
3119 if name == 'shortlist':
3120 optlist.append((_('use "hg help" for the full list '
3120 optlist.append((_('use "hg help" for the full list '
3121 'of commands'), ()))
3121 'of commands'), ()))
3122 else:
3122 else:
3123 if name == 'shortlist':
3123 if name == 'shortlist':
3124 msg = _('use "hg help" for the full list of commands '
3124 msg = _('use "hg help" for the full list of commands '
3125 'or "hg -v" for details')
3125 'or "hg -v" for details')
3126 elif name and not full:
3126 elif name and not full:
3127 msg = _('use "hg help %s" to show the full help text') % name
3127 msg = _('use "hg help %s" to show the full help text') % name
3128 elif aliases:
3128 elif aliases:
3129 msg = _('use "hg -v help%s" to show builtin aliases and '
3129 msg = _('use "hg -v help%s" to show builtin aliases and '
3130 'global options') % (name and " " + name or "")
3130 'global options') % (name and " " + name or "")
3131 else:
3131 else:
3132 msg = _('use "hg -v help %s" to show more info') % name
3132 msg = _('use "hg -v help %s" to show more info') % name
3133 optlist.append((msg, ()))
3133 optlist.append((msg, ()))
3134
3134
3135 def helpcmd(name):
3135 def helpcmd(name):
3136 try:
3136 try:
3137 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3137 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3138 except error.AmbiguousCommand, inst:
3138 except error.AmbiguousCommand, inst:
3139 # py3k fix: except vars can't be used outside the scope of the
3139 # py3k fix: except vars can't be used outside the scope of the
3140 # except block, nor can be used inside a lambda. python issue4617
3140 # except block, nor can be used inside a lambda. python issue4617
3141 prefix = inst.args[0]
3141 prefix = inst.args[0]
3142 select = lambda c: c.lstrip('^').startswith(prefix)
3142 select = lambda c: c.lstrip('^').startswith(prefix)
3143 helplist(select)
3143 helplist(select)
3144 return
3144 return
3145
3145
3146 # check if it's an invalid alias and display its error if it is
3146 # check if it's an invalid alias and display its error if it is
3147 if getattr(entry[0], 'badalias', False):
3147 if getattr(entry[0], 'badalias', False):
3148 if not unknowncmd:
3148 if not unknowncmd:
3149 entry[0](ui)
3149 entry[0](ui)
3150 return
3150 return
3151
3151
3152 rst = ""
3152 rst = ""
3153
3153
3154 # synopsis
3154 # synopsis
3155 if len(entry) > 2:
3155 if len(entry) > 2:
3156 if entry[2].startswith('hg'):
3156 if entry[2].startswith('hg'):
3157 rst += "%s\n" % entry[2]
3157 rst += "%s\n" % entry[2]
3158 else:
3158 else:
3159 rst += 'hg %s %s\n' % (aliases[0], entry[2])
3159 rst += 'hg %s %s\n' % (aliases[0], entry[2])
3160 else:
3160 else:
3161 rst += 'hg %s\n' % aliases[0]
3161 rst += 'hg %s\n' % aliases[0]
3162
3162
3163 # aliases
3163 # aliases
3164 if full and not ui.quiet and len(aliases) > 1:
3164 if full and not ui.quiet and len(aliases) > 1:
3165 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
3165 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
3166
3166
3167 # description
3167 # description
3168 doc = gettext(entry[0].__doc__)
3168 doc = gettext(entry[0].__doc__)
3169 if not doc:
3169 if not doc:
3170 doc = _("(no help text available)")
3170 doc = _("(no help text available)")
3171 if util.safehasattr(entry[0], 'definition'): # aliased command
3171 if util.safehasattr(entry[0], 'definition'): # aliased command
3172 if entry[0].definition.startswith('!'): # shell alias
3172 if entry[0].definition.startswith('!'): # shell alias
3173 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3173 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3174 else:
3174 else:
3175 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3175 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3176 if ui.quiet or not full:
3176 if ui.quiet or not full:
3177 doc = doc.splitlines()[0]
3177 doc = doc.splitlines()[0]
3178 rst += "\n" + doc + "\n"
3178 rst += "\n" + doc + "\n"
3179
3179
3180 # check if this command shadows a non-trivial (multi-line)
3180 # check if this command shadows a non-trivial (multi-line)
3181 # extension help text
3181 # extension help text
3182 try:
3182 try:
3183 mod = extensions.find(name)
3183 mod = extensions.find(name)
3184 doc = gettext(mod.__doc__) or ''
3184 doc = gettext(mod.__doc__) or ''
3185 if '\n' in doc.strip():
3185 if '\n' in doc.strip():
3186 msg = _('use "hg help -e %s" to show help for '
3186 msg = _('use "hg help -e %s" to show help for '
3187 'the %s extension') % (name, name)
3187 'the %s extension') % (name, name)
3188 rst += '\n%s\n' % msg
3188 rst += '\n%s\n' % msg
3189 except KeyError:
3189 except KeyError:
3190 pass
3190 pass
3191
3191
3192 # options
3192 # options
3193 if not ui.quiet and entry[1]:
3193 if not ui.quiet and entry[1]:
3194 rst += '\n'
3194 rst += '\n'
3195 rst += _("options:")
3195 rst += _("options:")
3196 rst += '\n\n'
3196 rst += '\n\n'
3197 rst += optrst(entry[1])
3197 rst += optrst(entry[1])
3198
3198
3199 if ui.verbose:
3199 if ui.verbose:
3200 rst += '\n'
3200 rst += '\n'
3201 rst += _("global options:")
3201 rst += _("global options:")
3202 rst += '\n\n'
3202 rst += '\n\n'
3203 rst += optrst(globalopts)
3203 rst += optrst(globalopts)
3204
3204
3205 keep = ui.verbose and ['verbose'] or []
3205 keep = ui.verbose and ['verbose'] or []
3206 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
3206 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
3207 ui.write(formatted)
3207 ui.write(formatted)
3208
3208
3209 if not ui.verbose:
3209 if not ui.verbose:
3210 if not full:
3210 if not full:
3211 ui.write(_('\nuse "hg help %s" to show the full help text\n')
3211 ui.write(_('\nuse "hg help %s" to show the full help text\n')
3212 % name)
3212 % name)
3213 elif not ui.quiet:
3213 elif not ui.quiet:
3214 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
3214 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
3215
3215
3216
3216
3217 def helplist(select=None):
3217 def helplist(select=None):
3218 # list of commands
3218 # list of commands
3219 if name == "shortlist":
3219 if name == "shortlist":
3220 header = _('basic commands:\n\n')
3220 header = _('basic commands:\n\n')
3221 else:
3221 else:
3222 header = _('list of commands:\n\n')
3222 header = _('list of commands:\n\n')
3223
3223
3224 h = {}
3224 h = {}
3225 cmds = {}
3225 cmds = {}
3226 for c, e in table.iteritems():
3226 for c, e in table.iteritems():
3227 f = c.split("|", 1)[0]
3227 f = c.split("|", 1)[0]
3228 if select and not select(f):
3228 if select and not select(f):
3229 continue
3229 continue
3230 if (not select and name != 'shortlist' and
3230 if (not select and name != 'shortlist' and
3231 e[0].__module__ != __name__):
3231 e[0].__module__ != __name__):
3232 continue
3232 continue
3233 if name == "shortlist" and not f.startswith("^"):
3233 if name == "shortlist" and not f.startswith("^"):
3234 continue
3234 continue
3235 f = f.lstrip("^")
3235 f = f.lstrip("^")
3236 if not ui.debugflag and f.startswith("debug"):
3236 if not ui.debugflag and f.startswith("debug"):
3237 continue
3237 continue
3238 doc = e[0].__doc__
3238 doc = e[0].__doc__
3239 if doc and 'DEPRECATED' in doc and not ui.verbose:
3239 if doc and 'DEPRECATED' in doc and not ui.verbose:
3240 continue
3240 continue
3241 doc = gettext(doc)
3241 doc = gettext(doc)
3242 if not doc:
3242 if not doc:
3243 doc = _("(no help text available)")
3243 doc = _("(no help text available)")
3244 h[f] = doc.splitlines()[0].rstrip()
3244 h[f] = doc.splitlines()[0].rstrip()
3245 cmds[f] = c.lstrip("^")
3245 cmds[f] = c.lstrip("^")
3246
3246
3247 if not h:
3247 if not h:
3248 ui.status(_('no commands defined\n'))
3248 ui.status(_('no commands defined\n'))
3249 return
3249 return
3250
3250
3251 ui.status(header)
3251 ui.status(header)
3252 fns = sorted(h)
3252 fns = sorted(h)
3253 m = max(map(len, fns))
3253 m = max(map(len, fns))
3254 for f in fns:
3254 for f in fns:
3255 if ui.verbose:
3255 if ui.verbose:
3256 commands = cmds[f].replace("|",", ")
3256 commands = cmds[f].replace("|",", ")
3257 ui.write(" %s:\n %s\n"%(commands, h[f]))
3257 ui.write(" %s:\n %s\n"%(commands, h[f]))
3258 else:
3258 else:
3259 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3259 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3260 initindent=' %-*s ' % (m, f),
3260 initindent=' %-*s ' % (m, f),
3261 hangindent=' ' * (m + 4))))
3261 hangindent=' ' * (m + 4))))
3262
3262
3263 if not name:
3263 if not name:
3264 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3264 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3265 if text:
3265 if text:
3266 ui.write("\n%s" % minirst.format(text, textwidth))
3266 ui.write("\n%s" % minirst.format(text, textwidth))
3267
3267
3268 ui.write(_("\nadditional help topics:\n\n"))
3268 ui.write(_("\nadditional help topics:\n\n"))
3269 topics = []
3269 topics = []
3270 for names, header, doc in help.helptable:
3270 for names, header, doc in help.helptable:
3271 topics.append((sorted(names, key=len, reverse=True)[0], header))
3271 topics.append((sorted(names, key=len, reverse=True)[0], header))
3272 topics_len = max([len(s[0]) for s in topics])
3272 topics_len = max([len(s[0]) for s in topics])
3273 for t, desc in topics:
3273 for t, desc in topics:
3274 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3274 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3275
3275
3276 optlist = []
3276 optlist = []
3277 addglobalopts(optlist, True)
3277 addglobalopts(optlist, True)
3278 ui.write(opttext(optlist, textwidth))
3278 ui.write(opttext(optlist, textwidth))
3279
3279
3280 def helptopic(name):
3280 def helptopic(name):
3281 for names, header, doc in help.helptable:
3281 for names, header, doc in help.helptable:
3282 if name in names:
3282 if name in names:
3283 break
3283 break
3284 else:
3284 else:
3285 raise error.UnknownCommand(name)
3285 raise error.UnknownCommand(name)
3286
3286
3287 # description
3287 # description
3288 if not doc:
3288 if not doc:
3289 doc = _("(no help text available)")
3289 doc = _("(no help text available)")
3290 if util.safehasattr(doc, '__call__'):
3290 if util.safehasattr(doc, '__call__'):
3291 doc = doc()
3291 doc = doc()
3292
3292
3293 ui.write("%s\n\n" % header)
3293 ui.write("%s\n\n" % header)
3294 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3294 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3295 try:
3295 try:
3296 cmdutil.findcmd(name, table)
3296 cmdutil.findcmd(name, table)
3297 ui.write(_('\nuse "hg help -c %s" to see help for '
3297 ui.write(_('\nuse "hg help -c %s" to see help for '
3298 'the %s command\n') % (name, name))
3298 'the %s command\n') % (name, name))
3299 except error.UnknownCommand:
3299 except error.UnknownCommand:
3300 pass
3300 pass
3301
3301
3302 def helpext(name):
3302 def helpext(name):
3303 try:
3303 try:
3304 mod = extensions.find(name)
3304 mod = extensions.find(name)
3305 doc = gettext(mod.__doc__) or _('no help text available')
3305 doc = gettext(mod.__doc__) or _('no help text available')
3306 except KeyError:
3306 except KeyError:
3307 mod = None
3307 mod = None
3308 doc = extensions.disabledext(name)
3308 doc = extensions.disabledext(name)
3309 if not doc:
3309 if not doc:
3310 raise error.UnknownCommand(name)
3310 raise error.UnknownCommand(name)
3311
3311
3312 if '\n' not in doc:
3312 if '\n' not in doc:
3313 head, tail = doc, ""
3313 head, tail = doc, ""
3314 else:
3314 else:
3315 head, tail = doc.split('\n', 1)
3315 head, tail = doc.split('\n', 1)
3316 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3316 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3317 if tail:
3317 if tail:
3318 ui.write(minirst.format(tail, textwidth))
3318 ui.write(minirst.format(tail, textwidth))
3319 ui.status('\n')
3319 ui.status('\n')
3320
3320
3321 if mod:
3321 if mod:
3322 try:
3322 try:
3323 ct = mod.cmdtable
3323 ct = mod.cmdtable
3324 except AttributeError:
3324 except AttributeError:
3325 ct = {}
3325 ct = {}
3326 modcmds = set([c.split('|', 1)[0] for c in ct])
3326 modcmds = set([c.split('|', 1)[0] for c in ct])
3327 helplist(modcmds.__contains__)
3327 helplist(modcmds.__contains__)
3328 else:
3328 else:
3329 ui.write(_('use "hg help extensions" for information on enabling '
3329 ui.write(_('use "hg help extensions" for information on enabling '
3330 'extensions\n'))
3330 'extensions\n'))
3331
3331
3332 def helpextcmd(name):
3332 def helpextcmd(name):
3333 cmd, ext, mod = extensions.disabledcmd(ui, name,
3333 cmd, ext, mod = extensions.disabledcmd(ui, name,
3334 ui.configbool('ui', 'strict'))
3334 ui.configbool('ui', 'strict'))
3335 doc = gettext(mod.__doc__).splitlines()[0]
3335 doc = gettext(mod.__doc__).splitlines()[0]
3336
3336
3337 msg = help.listexts(_("'%s' is provided by the following "
3337 msg = help.listexts(_("'%s' is provided by the following "
3338 "extension:") % cmd, {ext: doc}, indent=4)
3338 "extension:") % cmd, {ext: doc}, indent=4)
3339 ui.write(minirst.format(msg, textwidth))
3339 ui.write(minirst.format(msg, textwidth))
3340 ui.write('\n')
3340 ui.write('\n')
3341 ui.write(_('use "hg help extensions" for information on enabling '
3341 ui.write(_('use "hg help extensions" for information on enabling '
3342 'extensions\n'))
3342 'extensions\n'))
3343
3343
3344 if name and name != 'shortlist':
3344 if name and name != 'shortlist':
3345 i = None
3345 i = None
3346 if unknowncmd:
3346 if unknowncmd:
3347 queries = (helpextcmd,)
3347 queries = (helpextcmd,)
3348 elif opts.get('extension'):
3348 elif opts.get('extension'):
3349 queries = (helpext,)
3349 queries = (helpext,)
3350 elif opts.get('command'):
3350 elif opts.get('command'):
3351 queries = (helpcmd,)
3351 queries = (helpcmd,)
3352 else:
3352 else:
3353 queries = (helptopic, helpcmd, helpext, helpextcmd)
3353 queries = (helptopic, helpcmd, helpext, helpextcmd)
3354 for f in queries:
3354 for f in queries:
3355 try:
3355 try:
3356 f(name)
3356 f(name)
3357 i = None
3357 i = None
3358 break
3358 break
3359 except error.UnknownCommand, inst:
3359 except error.UnknownCommand, inst:
3360 i = inst
3360 i = inst
3361 if i:
3361 if i:
3362 raise i
3362 raise i
3363 else:
3363 else:
3364 # program name
3364 # program name
3365 ui.status(_("Mercurial Distributed SCM\n"))
3365 ui.status(_("Mercurial Distributed SCM\n"))
3366 ui.status('\n')
3366 ui.status('\n')
3367 helplist()
3367 helplist()
3368
3368
3369
3369
3370 @command('identify|id',
3370 @command('identify|id',
3371 [('r', 'rev', '',
3371 [('r', 'rev', '',
3372 _('identify the specified revision'), _('REV')),
3372 _('identify the specified revision'), _('REV')),
3373 ('n', 'num', None, _('show local revision number')),
3373 ('n', 'num', None, _('show local revision number')),
3374 ('i', 'id', None, _('show global revision id')),
3374 ('i', 'id', None, _('show global revision id')),
3375 ('b', 'branch', None, _('show branch')),
3375 ('b', 'branch', None, _('show branch')),
3376 ('t', 'tags', None, _('show tags')),
3376 ('t', 'tags', None, _('show tags')),
3377 ('B', 'bookmarks', None, _('show bookmarks')),
3377 ('B', 'bookmarks', None, _('show bookmarks')),
3378 ] + remoteopts,
3378 ] + remoteopts,
3379 _('[-nibtB] [-r REV] [SOURCE]'))
3379 _('[-nibtB] [-r REV] [SOURCE]'))
3380 def identify(ui, repo, source=None, rev=None,
3380 def identify(ui, repo, source=None, rev=None,
3381 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3381 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3382 """identify the working copy or specified revision
3382 """identify the working copy or specified revision
3383
3383
3384 Print a summary identifying the repository state at REV using one or
3384 Print a summary identifying the repository state at REV using one or
3385 two parent hash identifiers, followed by a "+" if the working
3385 two parent hash identifiers, followed by a "+" if the working
3386 directory has uncommitted changes, the branch name (if not default),
3386 directory has uncommitted changes, the branch name (if not default),
3387 a list of tags, and a list of bookmarks.
3387 a list of tags, and a list of bookmarks.
3388
3388
3389 When REV is not given, print a summary of the current state of the
3389 When REV is not given, print a summary of the current state of the
3390 repository.
3390 repository.
3391
3391
3392 Specifying a path to a repository root or Mercurial bundle will
3392 Specifying a path to a repository root or Mercurial bundle will
3393 cause lookup to operate on that repository/bundle.
3393 cause lookup to operate on that repository/bundle.
3394
3394
3395 .. container:: verbose
3395 .. container:: verbose
3396
3396
3397 Examples:
3397 Examples:
3398
3398
3399 - generate a build identifier for the working directory::
3399 - generate a build identifier for the working directory::
3400
3400
3401 hg id --id > build-id.dat
3401 hg id --id > build-id.dat
3402
3402
3403 - find the revision corresponding to a tag::
3403 - find the revision corresponding to a tag::
3404
3404
3405 hg id -n -r 1.3
3405 hg id -n -r 1.3
3406
3406
3407 - check the most recent revision of a remote repository::
3407 - check the most recent revision of a remote repository::
3408
3408
3409 hg id -r tip http://selenic.com/hg/
3409 hg id -r tip http://selenic.com/hg/
3410
3410
3411 Returns 0 if successful.
3411 Returns 0 if successful.
3412 """
3412 """
3413
3413
3414 if not repo and not source:
3414 if not repo and not source:
3415 raise util.Abort(_("there is no Mercurial repository here "
3415 raise util.Abort(_("there is no Mercurial repository here "
3416 "(.hg not found)"))
3416 "(.hg not found)"))
3417
3417
3418 hexfunc = ui.debugflag and hex or short
3418 hexfunc = ui.debugflag and hex or short
3419 default = not (num or id or branch or tags or bookmarks)
3419 default = not (num or id or branch or tags or bookmarks)
3420 output = []
3420 output = []
3421 revs = []
3421 revs = []
3422
3422
3423 if source:
3423 if source:
3424 source, branches = hg.parseurl(ui.expandpath(source))
3424 source, branches = hg.parseurl(ui.expandpath(source))
3425 repo = hg.peer(ui, opts, source)
3425 repo = hg.peer(ui, opts, source)
3426 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3426 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3427
3427
3428 if not repo.local():
3428 if not repo.local():
3429 if num or branch or tags:
3429 if num or branch or tags:
3430 raise util.Abort(
3430 raise util.Abort(
3431 _("can't query remote revision number, branch, or tags"))
3431 _("can't query remote revision number, branch, or tags"))
3432 if not rev and revs:
3432 if not rev and revs:
3433 rev = revs[0]
3433 rev = revs[0]
3434 if not rev:
3434 if not rev:
3435 rev = "tip"
3435 rev = "tip"
3436
3436
3437 remoterev = repo.lookup(rev)
3437 remoterev = repo.lookup(rev)
3438 if default or id:
3438 if default or id:
3439 output = [hexfunc(remoterev)]
3439 output = [hexfunc(remoterev)]
3440
3440
3441 def getbms():
3441 def getbms():
3442 bms = []
3442 bms = []
3443
3443
3444 if 'bookmarks' in repo.listkeys('namespaces'):
3444 if 'bookmarks' in repo.listkeys('namespaces'):
3445 hexremoterev = hex(remoterev)
3445 hexremoterev = hex(remoterev)
3446 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3446 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3447 if bmr == hexremoterev]
3447 if bmr == hexremoterev]
3448
3448
3449 return bms
3449 return bms
3450
3450
3451 if bookmarks:
3451 if bookmarks:
3452 output.extend(getbms())
3452 output.extend(getbms())
3453 elif default and not ui.quiet:
3453 elif default and not ui.quiet:
3454 # multiple bookmarks for a single parent separated by '/'
3454 # multiple bookmarks for a single parent separated by '/'
3455 bm = '/'.join(getbms())
3455 bm = '/'.join(getbms())
3456 if bm:
3456 if bm:
3457 output.append(bm)
3457 output.append(bm)
3458 else:
3458 else:
3459 if not rev:
3459 if not rev:
3460 ctx = repo[None]
3460 ctx = repo[None]
3461 parents = ctx.parents()
3461 parents = ctx.parents()
3462 changed = ""
3462 changed = ""
3463 if default or id or num:
3463 if default or id or num:
3464 changed = util.any(repo.status()) and "+" or ""
3464 changed = util.any(repo.status()) and "+" or ""
3465 if default or id:
3465 if default or id:
3466 output = ["%s%s" %
3466 output = ["%s%s" %
3467 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3467 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3468 if num:
3468 if num:
3469 output.append("%s%s" %
3469 output.append("%s%s" %
3470 ('+'.join([str(p.rev()) for p in parents]), changed))
3470 ('+'.join([str(p.rev()) for p in parents]), changed))
3471 else:
3471 else:
3472 ctx = scmutil.revsingle(repo, rev)
3472 ctx = scmutil.revsingle(repo, rev)
3473 if default or id:
3473 if default or id:
3474 output = [hexfunc(ctx.node())]
3474 output = [hexfunc(ctx.node())]
3475 if num:
3475 if num:
3476 output.append(str(ctx.rev()))
3476 output.append(str(ctx.rev()))
3477
3477
3478 if default and not ui.quiet:
3478 if default and not ui.quiet:
3479 b = ctx.branch()
3479 b = ctx.branch()
3480 if b != 'default':
3480 if b != 'default':
3481 output.append("(%s)" % b)
3481 output.append("(%s)" % b)
3482
3482
3483 # multiple tags for a single parent separated by '/'
3483 # multiple tags for a single parent separated by '/'
3484 t = '/'.join(ctx.tags())
3484 t = '/'.join(ctx.tags())
3485 if t:
3485 if t:
3486 output.append(t)
3486 output.append(t)
3487
3487
3488 # multiple bookmarks for a single parent separated by '/'
3488 # multiple bookmarks for a single parent separated by '/'
3489 bm = '/'.join(ctx.bookmarks())
3489 bm = '/'.join(ctx.bookmarks())
3490 if bm:
3490 if bm:
3491 output.append(bm)
3491 output.append(bm)
3492 else:
3492 else:
3493 if branch:
3493 if branch:
3494 output.append(ctx.branch())
3494 output.append(ctx.branch())
3495
3495
3496 if tags:
3496 if tags:
3497 output.extend(ctx.tags())
3497 output.extend(ctx.tags())
3498
3498
3499 if bookmarks:
3499 if bookmarks:
3500 output.extend(ctx.bookmarks())
3500 output.extend(ctx.bookmarks())
3501
3501
3502 ui.write("%s\n" % ' '.join(output))
3502 ui.write("%s\n" % ' '.join(output))
3503
3503
3504 @command('import|patch',
3504 @command('import|patch',
3505 [('p', 'strip', 1,
3505 [('p', 'strip', 1,
3506 _('directory strip option for patch. This has the same '
3506 _('directory strip option for patch. This has the same '
3507 'meaning as the corresponding patch option'), _('NUM')),
3507 'meaning as the corresponding patch option'), _('NUM')),
3508 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3508 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3509 ('e', 'edit', False, _('invoke editor on commit messages')),
3509 ('e', 'edit', False, _('invoke editor on commit messages')),
3510 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3510 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3511 ('', 'no-commit', None,
3511 ('', 'no-commit', None,
3512 _("don't commit, just update the working directory")),
3512 _("don't commit, just update the working directory")),
3513 ('', 'bypass', None,
3513 ('', 'bypass', None,
3514 _("apply patch without touching the working directory")),
3514 _("apply patch without touching the working directory")),
3515 ('', 'exact', None,
3515 ('', 'exact', None,
3516 _('apply patch to the nodes from which it was generated')),
3516 _('apply patch to the nodes from which it was generated')),
3517 ('', 'import-branch', None,
3517 ('', 'import-branch', None,
3518 _('use any branch information in patch (implied by --exact)'))] +
3518 _('use any branch information in patch (implied by --exact)'))] +
3519 commitopts + commitopts2 + similarityopts,
3519 commitopts + commitopts2 + similarityopts,
3520 _('[OPTION]... PATCH...'))
3520 _('[OPTION]... PATCH...'))
3521 def import_(ui, repo, patch1=None, *patches, **opts):
3521 def import_(ui, repo, patch1=None, *patches, **opts):
3522 """import an ordered set of patches
3522 """import an ordered set of patches
3523
3523
3524 Import a list of patches and commit them individually (unless
3524 Import a list of patches and commit them individually (unless
3525 --no-commit is specified).
3525 --no-commit is specified).
3526
3526
3527 If there are outstanding changes in the working directory, import
3527 If there are outstanding changes in the working directory, import
3528 will abort unless given the -f/--force flag.
3528 will abort unless given the -f/--force flag.
3529
3529
3530 You can import a patch straight from a mail message. Even patches
3530 You can import a patch straight from a mail message. Even patches
3531 as attachments work (to use the body part, it must have type
3531 as attachments work (to use the body part, it must have type
3532 text/plain or text/x-patch). From and Subject headers of email
3532 text/plain or text/x-patch). From and Subject headers of email
3533 message are used as default committer and commit message. All
3533 message are used as default committer and commit message. All
3534 text/plain body parts before first diff are added to commit
3534 text/plain body parts before first diff are added to commit
3535 message.
3535 message.
3536
3536
3537 If the imported patch was generated by :hg:`export`, user and
3537 If the imported patch was generated by :hg:`export`, user and
3538 description from patch override values from message headers and
3538 description from patch override values from message headers and
3539 body. Values given on command line with -m/--message and -u/--user
3539 body. Values given on command line with -m/--message and -u/--user
3540 override these.
3540 override these.
3541
3541
3542 If --exact is specified, import will set the working directory to
3542 If --exact is specified, import will set the working directory to
3543 the parent of each patch before applying it, and will abort if the
3543 the parent of each patch before applying it, and will abort if the
3544 resulting changeset has a different ID than the one recorded in
3544 resulting changeset has a different ID than the one recorded in
3545 the patch. This may happen due to character set problems or other
3545 the patch. This may happen due to character set problems or other
3546 deficiencies in the text patch format.
3546 deficiencies in the text patch format.
3547
3547
3548 Use --bypass to apply and commit patches directly to the
3548 Use --bypass to apply and commit patches directly to the
3549 repository, not touching the working directory. Without --exact,
3549 repository, not touching the working directory. Without --exact,
3550 patches will be applied on top of the working directory parent
3550 patches will be applied on top of the working directory parent
3551 revision.
3551 revision.
3552
3552
3553 With -s/--similarity, hg will attempt to discover renames and
3553 With -s/--similarity, hg will attempt to discover renames and
3554 copies in the patch in the same way as :hg:`addremove`.
3554 copies in the patch in the same way as :hg:`addremove`.
3555
3555
3556 To read a patch from standard input, use "-" as the patch name. If
3556 To read a patch from standard input, use "-" as the patch name. If
3557 a URL is specified, the patch will be downloaded from it.
3557 a URL is specified, the patch will be downloaded from it.
3558 See :hg:`help dates` for a list of formats valid for -d/--date.
3558 See :hg:`help dates` for a list of formats valid for -d/--date.
3559
3559
3560 .. container:: verbose
3560 .. container:: verbose
3561
3561
3562 Examples:
3562 Examples:
3563
3563
3564 - import a traditional patch from a website and detect renames::
3564 - import a traditional patch from a website and detect renames::
3565
3565
3566 hg import -s 80 http://example.com/bugfix.patch
3566 hg import -s 80 http://example.com/bugfix.patch
3567
3567
3568 - import a changeset from an hgweb server::
3568 - import a changeset from an hgweb server::
3569
3569
3570 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3570 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3571
3571
3572 - import all the patches in an Unix-style mbox::
3572 - import all the patches in an Unix-style mbox::
3573
3573
3574 hg import incoming-patches.mbox
3574 hg import incoming-patches.mbox
3575
3575
3576 - attempt to exactly restore an exported changeset (not always
3576 - attempt to exactly restore an exported changeset (not always
3577 possible)::
3577 possible)::
3578
3578
3579 hg import --exact proposed-fix.patch
3579 hg import --exact proposed-fix.patch
3580
3580
3581 Returns 0 on success.
3581 Returns 0 on success.
3582 """
3582 """
3583
3583
3584 if not patch1:
3584 if not patch1:
3585 raise util.Abort(_('need at least one patch to import'))
3585 raise util.Abort(_('need at least one patch to import'))
3586
3586
3587 patches = (patch1,) + patches
3587 patches = (patch1,) + patches
3588
3588
3589 date = opts.get('date')
3589 date = opts.get('date')
3590 if date:
3590 if date:
3591 opts['date'] = util.parsedate(date)
3591 opts['date'] = util.parsedate(date)
3592
3592
3593 editor = cmdutil.commiteditor
3593 editor = cmdutil.commiteditor
3594 if opts.get('edit'):
3594 if opts.get('edit'):
3595 editor = cmdutil.commitforceeditor
3595 editor = cmdutil.commitforceeditor
3596
3596
3597 update = not opts.get('bypass')
3597 update = not opts.get('bypass')
3598 if not update and opts.get('no_commit'):
3598 if not update and opts.get('no_commit'):
3599 raise util.Abort(_('cannot use --no-commit with --bypass'))
3599 raise util.Abort(_('cannot use --no-commit with --bypass'))
3600 try:
3600 try:
3601 sim = float(opts.get('similarity') or 0)
3601 sim = float(opts.get('similarity') or 0)
3602 except ValueError:
3602 except ValueError:
3603 raise util.Abort(_('similarity must be a number'))
3603 raise util.Abort(_('similarity must be a number'))
3604 if sim < 0 or sim > 100:
3604 if sim < 0 or sim > 100:
3605 raise util.Abort(_('similarity must be between 0 and 100'))
3605 raise util.Abort(_('similarity must be between 0 and 100'))
3606 if sim and not update:
3606 if sim and not update:
3607 raise util.Abort(_('cannot use --similarity with --bypass'))
3607 raise util.Abort(_('cannot use --similarity with --bypass'))
3608
3608
3609 if (opts.get('exact') or not opts.get('force')) and update:
3609 if (opts.get('exact') or not opts.get('force')) and update:
3610 cmdutil.bailifchanged(repo)
3610 cmdutil.bailifchanged(repo)
3611
3611
3612 base = opts["base"]
3612 base = opts["base"]
3613 strip = opts["strip"]
3613 strip = opts["strip"]
3614 wlock = lock = tr = None
3614 wlock = lock = tr = None
3615 msgs = []
3615 msgs = []
3616
3616
3617 def checkexact(repo, n, nodeid):
3617 def checkexact(repo, n, nodeid):
3618 if opts.get('exact') and hex(n) != nodeid:
3618 if opts.get('exact') and hex(n) != nodeid:
3619 repo.rollback()
3619 repo.rollback()
3620 raise util.Abort(_('patch is damaged or loses information'))
3620 raise util.Abort(_('patch is damaged or loses information'))
3621
3621
3622 def tryone(ui, hunk, parents):
3622 def tryone(ui, hunk, parents):
3623 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3623 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3624 patch.extract(ui, hunk)
3624 patch.extract(ui, hunk)
3625
3625
3626 if not tmpname:
3626 if not tmpname:
3627 return (None, None)
3627 return (None, None)
3628 msg = _('applied to working directory')
3628 msg = _('applied to working directory')
3629
3629
3630 try:
3630 try:
3631 cmdline_message = cmdutil.logmessage(ui, opts)
3631 cmdline_message = cmdutil.logmessage(ui, opts)
3632 if cmdline_message:
3632 if cmdline_message:
3633 # pickup the cmdline msg
3633 # pickup the cmdline msg
3634 message = cmdline_message
3634 message = cmdline_message
3635 elif message:
3635 elif message:
3636 # pickup the patch msg
3636 # pickup the patch msg
3637 message = message.strip()
3637 message = message.strip()
3638 else:
3638 else:
3639 # launch the editor
3639 # launch the editor
3640 message = None
3640 message = None
3641 ui.debug('message:\n%s\n' % message)
3641 ui.debug('message:\n%s\n' % message)
3642
3642
3643 if len(parents) == 1:
3643 if len(parents) == 1:
3644 parents.append(repo[nullid])
3644 parents.append(repo[nullid])
3645 if opts.get('exact'):
3645 if opts.get('exact'):
3646 if not nodeid or not p1:
3646 if not nodeid or not p1:
3647 raise util.Abort(_('not a Mercurial patch'))
3647 raise util.Abort(_('not a Mercurial patch'))
3648 p1 = repo[p1]
3648 p1 = repo[p1]
3649 p2 = repo[p2 or nullid]
3649 p2 = repo[p2 or nullid]
3650 elif p2:
3650 elif p2:
3651 try:
3651 try:
3652 p1 = repo[p1]
3652 p1 = repo[p1]
3653 p2 = repo[p2]
3653 p2 = repo[p2]
3654 # Without any options, consider p2 only if the
3654 # Without any options, consider p2 only if the
3655 # patch is being applied on top of the recorded
3655 # patch is being applied on top of the recorded
3656 # first parent.
3656 # first parent.
3657 if p1 != parents[0]:
3657 if p1 != parents[0]:
3658 p1 = parents[0]
3658 p1 = parents[0]
3659 p2 = repo[nullid]
3659 p2 = repo[nullid]
3660 except error.RepoError:
3660 except error.RepoError:
3661 p1, p2 = parents
3661 p1, p2 = parents
3662 else:
3662 else:
3663 p1, p2 = parents
3663 p1, p2 = parents
3664
3664
3665 n = None
3665 n = None
3666 if update:
3666 if update:
3667 if p1 != parents[0]:
3667 if p1 != parents[0]:
3668 hg.clean(repo, p1.node())
3668 hg.clean(repo, p1.node())
3669 if p2 != parents[1]:
3669 if p2 != parents[1]:
3670 repo.setparents(p1.node(), p2.node())
3670 repo.setparents(p1.node(), p2.node())
3671
3671
3672 if opts.get('exact') or opts.get('import_branch'):
3672 if opts.get('exact') or opts.get('import_branch'):
3673 repo.dirstate.setbranch(branch or 'default')
3673 repo.dirstate.setbranch(branch or 'default')
3674
3674
3675 files = set()
3675 files = set()
3676 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3676 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3677 eolmode=None, similarity=sim / 100.0)
3677 eolmode=None, similarity=sim / 100.0)
3678 files = list(files)
3678 files = list(files)
3679 if opts.get('no_commit'):
3679 if opts.get('no_commit'):
3680 if message:
3680 if message:
3681 msgs.append(message)
3681 msgs.append(message)
3682 else:
3682 else:
3683 if opts.get('exact') or p2:
3683 if opts.get('exact') or p2:
3684 # If you got here, you either use --force and know what
3684 # If you got here, you either use --force and know what
3685 # you are doing or used --exact or a merge patch while
3685 # you are doing or used --exact or a merge patch while
3686 # being updated to its first parent.
3686 # being updated to its first parent.
3687 m = None
3687 m = None
3688 else:
3688 else:
3689 m = scmutil.matchfiles(repo, files or [])
3689 m = scmutil.matchfiles(repo, files or [])
3690 n = repo.commit(message, opts.get('user') or user,
3690 n = repo.commit(message, opts.get('user') or user,
3691 opts.get('date') or date, match=m,
3691 opts.get('date') or date, match=m,
3692 editor=editor)
3692 editor=editor)
3693 checkexact(repo, n, nodeid)
3693 checkexact(repo, n, nodeid)
3694 else:
3694 else:
3695 if opts.get('exact') or opts.get('import_branch'):
3695 if opts.get('exact') or opts.get('import_branch'):
3696 branch = branch or 'default'
3696 branch = branch or 'default'
3697 else:
3697 else:
3698 branch = p1.branch()
3698 branch = p1.branch()
3699 store = patch.filestore()
3699 store = patch.filestore()
3700 try:
3700 try:
3701 files = set()
3701 files = set()
3702 try:
3702 try:
3703 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3703 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3704 files, eolmode=None)
3704 files, eolmode=None)
3705 except patch.PatchError, e:
3705 except patch.PatchError, e:
3706 raise util.Abort(str(e))
3706 raise util.Abort(str(e))
3707 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3707 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3708 message,
3708 message,
3709 opts.get('user') or user,
3709 opts.get('user') or user,
3710 opts.get('date') or date,
3710 opts.get('date') or date,
3711 branch, files, store,
3711 branch, files, store,
3712 editor=cmdutil.commiteditor)
3712 editor=cmdutil.commiteditor)
3713 repo.savecommitmessage(memctx.description())
3713 repo.savecommitmessage(memctx.description())
3714 n = memctx.commit()
3714 n = memctx.commit()
3715 checkexact(repo, n, nodeid)
3715 checkexact(repo, n, nodeid)
3716 finally:
3716 finally:
3717 store.close()
3717 store.close()
3718 if n:
3718 if n:
3719 # i18n: refers to a short changeset id
3719 # i18n: refers to a short changeset id
3720 msg = _('created %s') % short(n)
3720 msg = _('created %s') % short(n)
3721 return (msg, n)
3721 return (msg, n)
3722 finally:
3722 finally:
3723 os.unlink(tmpname)
3723 os.unlink(tmpname)
3724
3724
3725 try:
3725 try:
3726 try:
3726 try:
3727 wlock = repo.wlock()
3727 wlock = repo.wlock()
3728 if not opts.get('no_commit'):
3728 if not opts.get('no_commit'):
3729 lock = repo.lock()
3729 lock = repo.lock()
3730 tr = repo.transaction('import')
3730 tr = repo.transaction('import')
3731 parents = repo.parents()
3731 parents = repo.parents()
3732 for patchurl in patches:
3732 for patchurl in patches:
3733 if patchurl == '-':
3733 if patchurl == '-':
3734 ui.status(_('applying patch from stdin\n'))
3734 ui.status(_('applying patch from stdin\n'))
3735 patchfile = ui.fin
3735 patchfile = ui.fin
3736 patchurl = 'stdin' # for error message
3736 patchurl = 'stdin' # for error message
3737 else:
3737 else:
3738 patchurl = os.path.join(base, patchurl)
3738 patchurl = os.path.join(base, patchurl)
3739 ui.status(_('applying %s\n') % patchurl)
3739 ui.status(_('applying %s\n') % patchurl)
3740 patchfile = url.open(ui, patchurl)
3740 patchfile = url.open(ui, patchurl)
3741
3741
3742 haspatch = False
3742 haspatch = False
3743 for hunk in patch.split(patchfile):
3743 for hunk in patch.split(patchfile):
3744 (msg, node) = tryone(ui, hunk, parents)
3744 (msg, node) = tryone(ui, hunk, parents)
3745 if msg:
3745 if msg:
3746 haspatch = True
3746 haspatch = True
3747 ui.note(msg + '\n')
3747 ui.note(msg + '\n')
3748 if update or opts.get('exact'):
3748 if update or opts.get('exact'):
3749 parents = repo.parents()
3749 parents = repo.parents()
3750 else:
3750 else:
3751 parents = [repo[node]]
3751 parents = [repo[node]]
3752
3752
3753 if not haspatch:
3753 if not haspatch:
3754 raise util.Abort(_('%s: no diffs found') % patchurl)
3754 raise util.Abort(_('%s: no diffs found') % patchurl)
3755
3755
3756 if tr:
3756 if tr:
3757 tr.close()
3757 tr.close()
3758 if msgs:
3758 if msgs:
3759 repo.savecommitmessage('\n* * *\n'.join(msgs))
3759 repo.savecommitmessage('\n* * *\n'.join(msgs))
3760 except:
3760 except:
3761 # wlock.release() indirectly calls dirstate.write(): since
3761 # wlock.release() indirectly calls dirstate.write(): since
3762 # we're crashing, we do not want to change the working dir
3762 # we're crashing, we do not want to change the working dir
3763 # parent after all, so make sure it writes nothing
3763 # parent after all, so make sure it writes nothing
3764 repo.dirstate.invalidate()
3764 repo.dirstate.invalidate()
3765 raise
3765 raise
3766 finally:
3766 finally:
3767 if tr:
3767 if tr:
3768 tr.release()
3768 tr.release()
3769 release(lock, wlock)
3769 release(lock, wlock)
3770
3770
3771 @command('incoming|in',
3771 @command('incoming|in',
3772 [('f', 'force', None,
3772 [('f', 'force', None,
3773 _('run even if remote repository is unrelated')),
3773 _('run even if remote repository is unrelated')),
3774 ('n', 'newest-first', None, _('show newest record first')),
3774 ('n', 'newest-first', None, _('show newest record first')),
3775 ('', 'bundle', '',
3775 ('', 'bundle', '',
3776 _('file to store the bundles into'), _('FILE')),
3776 _('file to store the bundles into'), _('FILE')),
3777 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3777 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3778 ('B', 'bookmarks', False, _("compare bookmarks")),
3778 ('B', 'bookmarks', False, _("compare bookmarks")),
3779 ('b', 'branch', [],
3779 ('b', 'branch', [],
3780 _('a specific branch you would like to pull'), _('BRANCH')),
3780 _('a specific branch you would like to pull'), _('BRANCH')),
3781 ] + logopts + remoteopts + subrepoopts,
3781 ] + logopts + remoteopts + subrepoopts,
3782 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3782 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3783 def incoming(ui, repo, source="default", **opts):
3783 def incoming(ui, repo, source="default", **opts):
3784 """show new changesets found in source
3784 """show new changesets found in source
3785
3785
3786 Show new changesets found in the specified path/URL or the default
3786 Show new changesets found in the specified path/URL or the default
3787 pull location. These are the changesets that would have been pulled
3787 pull location. These are the changesets that would have been pulled
3788 if a pull at the time you issued this command.
3788 if a pull at the time you issued this command.
3789
3789
3790 For remote repository, using --bundle avoids downloading the
3790 For remote repository, using --bundle avoids downloading the
3791 changesets twice if the incoming is followed by a pull.
3791 changesets twice if the incoming is followed by a pull.
3792
3792
3793 See pull for valid source format details.
3793 See pull for valid source format details.
3794
3794
3795 Returns 0 if there are incoming changes, 1 otherwise.
3795 Returns 0 if there are incoming changes, 1 otherwise.
3796 """
3796 """
3797 if opts.get('bundle') and opts.get('subrepos'):
3797 if opts.get('bundle') and opts.get('subrepos'):
3798 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3798 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3799
3799
3800 if opts.get('bookmarks'):
3800 if opts.get('bookmarks'):
3801 source, branches = hg.parseurl(ui.expandpath(source),
3801 source, branches = hg.parseurl(ui.expandpath(source),
3802 opts.get('branch'))
3802 opts.get('branch'))
3803 other = hg.peer(repo, opts, source)
3803 other = hg.peer(repo, opts, source)
3804 if 'bookmarks' not in other.listkeys('namespaces'):
3804 if 'bookmarks' not in other.listkeys('namespaces'):
3805 ui.warn(_("remote doesn't support bookmarks\n"))
3805 ui.warn(_("remote doesn't support bookmarks\n"))
3806 return 0
3806 return 0
3807 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3807 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3808 return bookmarks.diff(ui, repo, other)
3808 return bookmarks.diff(ui, repo, other)
3809
3809
3810 repo._subtoppath = ui.expandpath(source)
3810 repo._subtoppath = ui.expandpath(source)
3811 try:
3811 try:
3812 return hg.incoming(ui, repo, source, opts)
3812 return hg.incoming(ui, repo, source, opts)
3813 finally:
3813 finally:
3814 del repo._subtoppath
3814 del repo._subtoppath
3815
3815
3816
3816
3817 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3817 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3818 def init(ui, dest=".", **opts):
3818 def init(ui, dest=".", **opts):
3819 """create a new repository in the given directory
3819 """create a new repository in the given directory
3820
3820
3821 Initialize a new repository in the given directory. If the given
3821 Initialize a new repository in the given directory. If the given
3822 directory does not exist, it will be created.
3822 directory does not exist, it will be created.
3823
3823
3824 If no directory is given, the current directory is used.
3824 If no directory is given, the current directory is used.
3825
3825
3826 It is possible to specify an ``ssh://`` URL as the destination.
3826 It is possible to specify an ``ssh://`` URL as the destination.
3827 See :hg:`help urls` for more information.
3827 See :hg:`help urls` for more information.
3828
3828
3829 Returns 0 on success.
3829 Returns 0 on success.
3830 """
3830 """
3831 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3831 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3832
3832
3833 @command('locate',
3833 @command('locate',
3834 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3834 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3835 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3835 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3836 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3836 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3837 ] + walkopts,
3837 ] + walkopts,
3838 _('[OPTION]... [PATTERN]...'))
3838 _('[OPTION]... [PATTERN]...'))
3839 def locate(ui, repo, *pats, **opts):
3839 def locate(ui, repo, *pats, **opts):
3840 """locate files matching specific patterns
3840 """locate files matching specific patterns
3841
3841
3842 Print files under Mercurial control in the working directory whose
3842 Print files under Mercurial control in the working directory whose
3843 names match the given patterns.
3843 names match the given patterns.
3844
3844
3845 By default, this command searches all directories in the working
3845 By default, this command searches all directories in the working
3846 directory. To search just the current directory and its
3846 directory. To search just the current directory and its
3847 subdirectories, use "--include .".
3847 subdirectories, use "--include .".
3848
3848
3849 If no patterns are given to match, this command prints the names
3849 If no patterns are given to match, this command prints the names
3850 of all files under Mercurial control in the working directory.
3850 of all files under Mercurial control in the working directory.
3851
3851
3852 If you want to feed the output of this command into the "xargs"
3852 If you want to feed the output of this command into the "xargs"
3853 command, use the -0 option to both this command and "xargs". This
3853 command, use the -0 option to both this command and "xargs". This
3854 will avoid the problem of "xargs" treating single filenames that
3854 will avoid the problem of "xargs" treating single filenames that
3855 contain whitespace as multiple filenames.
3855 contain whitespace as multiple filenames.
3856
3856
3857 Returns 0 if a match is found, 1 otherwise.
3857 Returns 0 if a match is found, 1 otherwise.
3858 """
3858 """
3859 end = opts.get('print0') and '\0' or '\n'
3859 end = opts.get('print0') and '\0' or '\n'
3860 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3860 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3861
3861
3862 ret = 1
3862 ret = 1
3863 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3863 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3864 m.bad = lambda x, y: False
3864 m.bad = lambda x, y: False
3865 for abs in repo[rev].walk(m):
3865 for abs in repo[rev].walk(m):
3866 if not rev and abs not in repo.dirstate:
3866 if not rev and abs not in repo.dirstate:
3867 continue
3867 continue
3868 if opts.get('fullpath'):
3868 if opts.get('fullpath'):
3869 ui.write(repo.wjoin(abs), end)
3869 ui.write(repo.wjoin(abs), end)
3870 else:
3870 else:
3871 ui.write(((pats and m.rel(abs)) or abs), end)
3871 ui.write(((pats and m.rel(abs)) or abs), end)
3872 ret = 0
3872 ret = 0
3873
3873
3874 return ret
3874 return ret
3875
3875
3876 @command('^log|history',
3876 @command('^log|history',
3877 [('f', 'follow', None,
3877 [('f', 'follow', None,
3878 _('follow changeset history, or file history across copies and renames')),
3878 _('follow changeset history, or file history across copies and renames')),
3879 ('', 'follow-first', None,
3879 ('', 'follow-first', None,
3880 _('only follow the first parent of merge changesets (DEPRECATED)')),
3880 _('only follow the first parent of merge changesets (DEPRECATED)')),
3881 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3881 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3882 ('C', 'copies', None, _('show copied files')),
3882 ('C', 'copies', None, _('show copied files')),
3883 ('k', 'keyword', [],
3883 ('k', 'keyword', [],
3884 _('do case-insensitive search for a given text'), _('TEXT')),
3884 _('do case-insensitive search for a given text'), _('TEXT')),
3885 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3885 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3886 ('', 'removed', None, _('include revisions where files were removed')),
3886 ('', 'removed', None, _('include revisions where files were removed')),
3887 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3887 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3888 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3888 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3889 ('', 'only-branch', [],
3889 ('', 'only-branch', [],
3890 _('show only changesets within the given named branch (DEPRECATED)'),
3890 _('show only changesets within the given named branch (DEPRECATED)'),
3891 _('BRANCH')),
3891 _('BRANCH')),
3892 ('b', 'branch', [],
3892 ('b', 'branch', [],
3893 _('show changesets within the given named branch'), _('BRANCH')),
3893 _('show changesets within the given named branch'), _('BRANCH')),
3894 ('P', 'prune', [],
3894 ('P', 'prune', [],
3895 _('do not display revision or any of its ancestors'), _('REV')),
3895 _('do not display revision or any of its ancestors'), _('REV')),
3896 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
3896 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
3897 ] + logopts + walkopts,
3897 ] + logopts + walkopts,
3898 _('[OPTION]... [FILE]'))
3898 _('[OPTION]... [FILE]'))
3899 def log(ui, repo, *pats, **opts):
3899 def log(ui, repo, *pats, **opts):
3900 """show revision history of entire repository or files
3900 """show revision history of entire repository or files
3901
3901
3902 Print the revision history of the specified files or the entire
3902 Print the revision history of the specified files or the entire
3903 project.
3903 project.
3904
3904
3905 If no revision range is specified, the default is ``tip:0`` unless
3905 If no revision range is specified, the default is ``tip:0`` unless
3906 --follow is set, in which case the working directory parent is
3906 --follow is set, in which case the working directory parent is
3907 used as the starting revision.
3907 used as the starting revision.
3908
3908
3909 File history is shown without following rename or copy history of
3909 File history is shown without following rename or copy history of
3910 files. Use -f/--follow with a filename to follow history across
3910 files. Use -f/--follow with a filename to follow history across
3911 renames and copies. --follow without a filename will only show
3911 renames and copies. --follow without a filename will only show
3912 ancestors or descendants of the starting revision.
3912 ancestors or descendants of the starting revision.
3913
3913
3914 By default this command prints revision number and changeset id,
3914 By default this command prints revision number and changeset id,
3915 tags, non-trivial parents, user, date and time, and a summary for
3915 tags, non-trivial parents, user, date and time, and a summary for
3916 each commit. When the -v/--verbose switch is used, the list of
3916 each commit. When the -v/--verbose switch is used, the list of
3917 changed files and full commit message are shown.
3917 changed files and full commit message are shown.
3918
3918
3919 .. note::
3919 .. note::
3920 log -p/--patch may generate unexpected diff output for merge
3920 log -p/--patch may generate unexpected diff output for merge
3921 changesets, as it will only compare the merge changeset against
3921 changesets, as it will only compare the merge changeset against
3922 its first parent. Also, only files different from BOTH parents
3922 its first parent. Also, only files different from BOTH parents
3923 will appear in files:.
3923 will appear in files:.
3924
3924
3925 .. note::
3925 .. note::
3926 for performance reasons, log FILE may omit duplicate changes
3926 for performance reasons, log FILE may omit duplicate changes
3927 made on branches and will not show deletions. To see all
3927 made on branches and will not show deletions. To see all
3928 changes including duplicates and deletions, use the --removed
3928 changes including duplicates and deletions, use the --removed
3929 switch.
3929 switch.
3930
3930
3931 .. container:: verbose
3931 .. container:: verbose
3932
3932
3933 Some examples:
3933 Some examples:
3934
3934
3935 - changesets with full descriptions and file lists::
3935 - changesets with full descriptions and file lists::
3936
3936
3937 hg log -v
3937 hg log -v
3938
3938
3939 - changesets ancestral to the working directory::
3939 - changesets ancestral to the working directory::
3940
3940
3941 hg log -f
3941 hg log -f
3942
3942
3943 - last 10 commits on the current branch::
3943 - last 10 commits on the current branch::
3944
3944
3945 hg log -l 10 -b .
3945 hg log -l 10 -b .
3946
3946
3947 - changesets showing all modifications of a file, including removals::
3947 - changesets showing all modifications of a file, including removals::
3948
3948
3949 hg log --removed file.c
3949 hg log --removed file.c
3950
3950
3951 - all changesets that touch a directory, with diffs, excluding merges::
3951 - all changesets that touch a directory, with diffs, excluding merges::
3952
3952
3953 hg log -Mp lib/
3953 hg log -Mp lib/
3954
3954
3955 - all revision numbers that match a keyword::
3955 - all revision numbers that match a keyword::
3956
3956
3957 hg log -k bug --template "{rev}\\n"
3957 hg log -k bug --template "{rev}\\n"
3958
3958
3959 - check if a given changeset is included is a tagged release::
3959 - check if a given changeset is included is a tagged release::
3960
3960
3961 hg log -r "a21ccf and ancestor(1.9)"
3961 hg log -r "a21ccf and ancestor(1.9)"
3962
3962
3963 - find all changesets by some user in a date range::
3963 - find all changesets by some user in a date range::
3964
3964
3965 hg log -k alice -d "may 2008 to jul 2008"
3965 hg log -k alice -d "may 2008 to jul 2008"
3966
3966
3967 - summary of all changesets after the last tag::
3967 - summary of all changesets after the last tag::
3968
3968
3969 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3969 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3970
3970
3971 See :hg:`help dates` for a list of formats valid for -d/--date.
3971 See :hg:`help dates` for a list of formats valid for -d/--date.
3972
3972
3973 See :hg:`help revisions` and :hg:`help revsets` for more about
3973 See :hg:`help revisions` and :hg:`help revsets` for more about
3974 specifying revisions.
3974 specifying revisions.
3975
3975
3976 See :hg:`help templates` for more about pre-packaged styles and
3976 See :hg:`help templates` for more about pre-packaged styles and
3977 specifying custom templates.
3977 specifying custom templates.
3978
3978
3979 Returns 0 on success.
3979 Returns 0 on success.
3980 """
3980 """
3981
3981
3982 matchfn = scmutil.match(repo[None], pats, opts)
3982 matchfn = scmutil.match(repo[None], pats, opts)
3983 limit = cmdutil.loglimit(opts)
3983 limit = cmdutil.loglimit(opts)
3984 count = 0
3984 count = 0
3985
3985
3986 getrenamed, endrev = None, None
3986 getrenamed, endrev = None, None
3987 if opts.get('copies'):
3987 if opts.get('copies'):
3988 if opts.get('rev'):
3988 if opts.get('rev'):
3989 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3989 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3990 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3990 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3991
3991
3992 df = False
3992 df = False
3993 if opts["date"]:
3993 if opts["date"]:
3994 df = util.matchdate(opts["date"])
3994 df = util.matchdate(opts["date"])
3995
3995
3996 branches = opts.get('branch', []) + opts.get('only_branch', [])
3996 branches = opts.get('branch', []) + opts.get('only_branch', [])
3997 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3997 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3998
3998
3999 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3999 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4000 def prep(ctx, fns):
4000 def prep(ctx, fns):
4001 rev = ctx.rev()
4001 rev = ctx.rev()
4002 parents = [p for p in repo.changelog.parentrevs(rev)
4002 parents = [p for p in repo.changelog.parentrevs(rev)
4003 if p != nullrev]
4003 if p != nullrev]
4004 if opts.get('no_merges') and len(parents) == 2:
4004 if opts.get('no_merges') and len(parents) == 2:
4005 return
4005 return
4006 if opts.get('only_merges') and len(parents) != 2:
4006 if opts.get('only_merges') and len(parents) != 2:
4007 return
4007 return
4008 if opts.get('branch') and ctx.branch() not in opts['branch']:
4008 if opts.get('branch') and ctx.branch() not in opts['branch']:
4009 return
4009 return
4010 if not opts.get('hidden') and ctx.hidden():
4010 if not opts.get('hidden') and ctx.hidden():
4011 return
4011 return
4012 if df and not df(ctx.date()[0]):
4012 if df and not df(ctx.date()[0]):
4013 return
4013 return
4014
4014
4015 lower = encoding.lower
4015 lower = encoding.lower
4016 if opts.get('user'):
4016 if opts.get('user'):
4017 luser = lower(ctx.user())
4017 luser = lower(ctx.user())
4018 for k in [lower(x) for x in opts['user']]:
4018 for k in [lower(x) for x in opts['user']]:
4019 if (k in luser):
4019 if (k in luser):
4020 break
4020 break
4021 else:
4021 else:
4022 return
4022 return
4023 if opts.get('keyword'):
4023 if opts.get('keyword'):
4024 luser = lower(ctx.user())
4024 luser = lower(ctx.user())
4025 ldesc = lower(ctx.description())
4025 ldesc = lower(ctx.description())
4026 lfiles = lower(" ".join(ctx.files()))
4026 lfiles = lower(" ".join(ctx.files()))
4027 for k in [lower(x) for x in opts['keyword']]:
4027 for k in [lower(x) for x in opts['keyword']]:
4028 if (k in luser or k in ldesc or k in lfiles):
4028 if (k in luser or k in ldesc or k in lfiles):
4029 break
4029 break
4030 else:
4030 else:
4031 return
4031 return
4032
4032
4033 copies = None
4033 copies = None
4034 if getrenamed is not None and rev:
4034 if getrenamed is not None and rev:
4035 copies = []
4035 copies = []
4036 for fn in ctx.files():
4036 for fn in ctx.files():
4037 rename = getrenamed(fn, rev)
4037 rename = getrenamed(fn, rev)
4038 if rename:
4038 if rename:
4039 copies.append((fn, rename[0]))
4039 copies.append((fn, rename[0]))
4040
4040
4041 revmatchfn = None
4041 revmatchfn = None
4042 if opts.get('patch') or opts.get('stat'):
4042 if opts.get('patch') or opts.get('stat'):
4043 if opts.get('follow') or opts.get('follow_first'):
4043 if opts.get('follow') or opts.get('follow_first'):
4044 # note: this might be wrong when following through merges
4044 # note: this might be wrong when following through merges
4045 revmatchfn = scmutil.match(repo[None], fns, default='path')
4045 revmatchfn = scmutil.match(repo[None], fns, default='path')
4046 else:
4046 else:
4047 revmatchfn = matchfn
4047 revmatchfn = matchfn
4048
4048
4049 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4049 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4050
4050
4051 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4051 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4052 if count == limit:
4052 if count == limit:
4053 break
4053 break
4054 if displayer.flush(ctx.rev()):
4054 if displayer.flush(ctx.rev()):
4055 count += 1
4055 count += 1
4056 displayer.close()
4056 displayer.close()
4057
4057
4058 @command('manifest',
4058 @command('manifest',
4059 [('r', 'rev', '', _('revision to display'), _('REV')),
4059 [('r', 'rev', '', _('revision to display'), _('REV')),
4060 ('', 'all', False, _("list files from all revisions"))],
4060 ('', 'all', False, _("list files from all revisions"))],
4061 _('[-r REV]'))
4061 _('[-r REV]'))
4062 def manifest(ui, repo, node=None, rev=None, **opts):
4062 def manifest(ui, repo, node=None, rev=None, **opts):
4063 """output the current or given revision of the project manifest
4063 """output the current or given revision of the project manifest
4064
4064
4065 Print a list of version controlled files for the given revision.
4065 Print a list of version controlled files for the given revision.
4066 If no revision is given, the first parent of the working directory
4066 If no revision is given, the first parent of the working directory
4067 is used, or the null revision if no revision is checked out.
4067 is used, or the null revision if no revision is checked out.
4068
4068
4069 With -v, print file permissions, symlink and executable bits.
4069 With -v, print file permissions, symlink and executable bits.
4070 With --debug, print file revision hashes.
4070 With --debug, print file revision hashes.
4071
4071
4072 If option --all is specified, the list of all files from all revisions
4072 If option --all is specified, the list of all files from all revisions
4073 is printed. This includes deleted and renamed files.
4073 is printed. This includes deleted and renamed files.
4074
4074
4075 Returns 0 on success.
4075 Returns 0 on success.
4076 """
4076 """
4077 if opts.get('all'):
4077 if opts.get('all'):
4078 if rev or node:
4078 if rev or node:
4079 raise util.Abort(_("can't specify a revision with --all"))
4079 raise util.Abort(_("can't specify a revision with --all"))
4080
4080
4081 res = []
4081 res = []
4082 prefix = "data/"
4082 prefix = "data/"
4083 suffix = ".i"
4083 suffix = ".i"
4084 plen = len(prefix)
4084 plen = len(prefix)
4085 slen = len(suffix)
4085 slen = len(suffix)
4086 lock = repo.lock()
4086 lock = repo.lock()
4087 try:
4087 try:
4088 for fn, b, size in repo.store.datafiles():
4088 for fn, b, size in repo.store.datafiles():
4089 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4089 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4090 res.append(fn[plen:-slen])
4090 res.append(fn[plen:-slen])
4091 finally:
4091 finally:
4092 lock.release()
4092 lock.release()
4093 for f in sorted(res):
4093 for f in sorted(res):
4094 ui.write("%s\n" % f)
4094 ui.write("%s\n" % f)
4095 return
4095 return
4096
4096
4097 if rev and node:
4097 if rev and node:
4098 raise util.Abort(_("please specify just one revision"))
4098 raise util.Abort(_("please specify just one revision"))
4099
4099
4100 if not node:
4100 if not node:
4101 node = rev
4101 node = rev
4102
4102
4103 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
4103 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
4104 ctx = scmutil.revsingle(repo, node)
4104 ctx = scmutil.revsingle(repo, node)
4105 for f in ctx:
4105 for f in ctx:
4106 if ui.debugflag:
4106 if ui.debugflag:
4107 ui.write("%40s " % hex(ctx.manifest()[f]))
4107 ui.write("%40s " % hex(ctx.manifest()[f]))
4108 if ui.verbose:
4108 if ui.verbose:
4109 ui.write(decor[ctx.flags(f)])
4109 ui.write(decor[ctx.flags(f)])
4110 ui.write("%s\n" % f)
4110 ui.write("%s\n" % f)
4111
4111
4112 @command('^merge',
4112 @command('^merge',
4113 [('f', 'force', None, _('force a merge with outstanding changes')),
4113 [('f', 'force', None, _('force a merge with outstanding changes')),
4114 ('r', 'rev', '', _('revision to merge'), _('REV')),
4114 ('r', 'rev', '', _('revision to merge'), _('REV')),
4115 ('P', 'preview', None,
4115 ('P', 'preview', None,
4116 _('review revisions to merge (no merge is performed)'))
4116 _('review revisions to merge (no merge is performed)'))
4117 ] + mergetoolopts,
4117 ] + mergetoolopts,
4118 _('[-P] [-f] [[-r] REV]'))
4118 _('[-P] [-f] [[-r] REV]'))
4119 def merge(ui, repo, node=None, **opts):
4119 def merge(ui, repo, node=None, **opts):
4120 """merge working directory with another revision
4120 """merge working directory with another revision
4121
4121
4122 The current working directory is updated with all changes made in
4122 The current working directory is updated with all changes made in
4123 the requested revision since the last common predecessor revision.
4123 the requested revision since the last common predecessor revision.
4124
4124
4125 Files that changed between either parent are marked as changed for
4125 Files that changed between either parent are marked as changed for
4126 the next commit and a commit must be performed before any further
4126 the next commit and a commit must be performed before any further
4127 updates to the repository are allowed. The next commit will have
4127 updates to the repository are allowed. The next commit will have
4128 two parents.
4128 two parents.
4129
4129
4130 ``--tool`` can be used to specify the merge tool used for file
4130 ``--tool`` can be used to specify the merge tool used for file
4131 merges. It overrides the HGMERGE environment variable and your
4131 merges. It overrides the HGMERGE environment variable and your
4132 configuration files. See :hg:`help merge-tools` for options.
4132 configuration files. See :hg:`help merge-tools` for options.
4133
4133
4134 If no revision is specified, the working directory's parent is a
4134 If no revision is specified, the working directory's parent is a
4135 head revision, and the current branch contains exactly one other
4135 head revision, and the current branch contains exactly one other
4136 head, the other head is merged with by default. Otherwise, an
4136 head, the other head is merged with by default. Otherwise, an
4137 explicit revision with which to merge with must be provided.
4137 explicit revision with which to merge with must be provided.
4138
4138
4139 :hg:`resolve` must be used to resolve unresolved files.
4139 :hg:`resolve` must be used to resolve unresolved files.
4140
4140
4141 To undo an uncommitted merge, use :hg:`update --clean .` which
4141 To undo an uncommitted merge, use :hg:`update --clean .` which
4142 will check out a clean copy of the original merge parent, losing
4142 will check out a clean copy of the original merge parent, losing
4143 all changes.
4143 all changes.
4144
4144
4145 Returns 0 on success, 1 if there are unresolved files.
4145 Returns 0 on success, 1 if there are unresolved files.
4146 """
4146 """
4147
4147
4148 if opts.get('rev') and node:
4148 if opts.get('rev') and node:
4149 raise util.Abort(_("please specify just one revision"))
4149 raise util.Abort(_("please specify just one revision"))
4150 if not node:
4150 if not node:
4151 node = opts.get('rev')
4151 node = opts.get('rev')
4152
4152
4153 if not node:
4153 if not node:
4154 branch = repo[None].branch()
4154 branch = repo[None].branch()
4155 bheads = repo.branchheads(branch)
4155 bheads = repo.branchheads(branch)
4156 if len(bheads) > 2:
4156 if len(bheads) > 2:
4157 raise util.Abort(_("branch '%s' has %d heads - "
4157 raise util.Abort(_("branch '%s' has %d heads - "
4158 "please merge with an explicit rev")
4158 "please merge with an explicit rev")
4159 % (branch, len(bheads)),
4159 % (branch, len(bheads)),
4160 hint=_("run 'hg heads .' to see heads"))
4160 hint=_("run 'hg heads .' to see heads"))
4161
4161
4162 parent = repo.dirstate.p1()
4162 parent = repo.dirstate.p1()
4163 if len(bheads) == 1:
4163 if len(bheads) == 1:
4164 if len(repo.heads()) > 1:
4164 if len(repo.heads()) > 1:
4165 raise util.Abort(_("branch '%s' has one head - "
4165 raise util.Abort(_("branch '%s' has one head - "
4166 "please merge with an explicit rev")
4166 "please merge with an explicit rev")
4167 % branch,
4167 % branch,
4168 hint=_("run 'hg heads' to see all heads"))
4168 hint=_("run 'hg heads' to see all heads"))
4169 msg, hint = _('nothing to merge'), None
4169 msg, hint = _('nothing to merge'), None
4170 if parent != repo.lookup(branch):
4170 if parent != repo.lookup(branch):
4171 hint = _("use 'hg update' instead")
4171 hint = _("use 'hg update' instead")
4172 raise util.Abort(msg, hint=hint)
4172 raise util.Abort(msg, hint=hint)
4173
4173
4174 if parent not in bheads:
4174 if parent not in bheads:
4175 raise util.Abort(_('working directory not at a head revision'),
4175 raise util.Abort(_('working directory not at a head revision'),
4176 hint=_("use 'hg update' or merge with an "
4176 hint=_("use 'hg update' or merge with an "
4177 "explicit revision"))
4177 "explicit revision"))
4178 node = parent == bheads[0] and bheads[-1] or bheads[0]
4178 node = parent == bheads[0] and bheads[-1] or bheads[0]
4179 else:
4179 else:
4180 node = scmutil.revsingle(repo, node).node()
4180 node = scmutil.revsingle(repo, node).node()
4181
4181
4182 if opts.get('preview'):
4182 if opts.get('preview'):
4183 # find nodes that are ancestors of p2 but not of p1
4183 # find nodes that are ancestors of p2 but not of p1
4184 p1 = repo.lookup('.')
4184 p1 = repo.lookup('.')
4185 p2 = repo.lookup(node)
4185 p2 = repo.lookup(node)
4186 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4186 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4187
4187
4188 displayer = cmdutil.show_changeset(ui, repo, opts)
4188 displayer = cmdutil.show_changeset(ui, repo, opts)
4189 for node in nodes:
4189 for node in nodes:
4190 displayer.show(repo[node])
4190 displayer.show(repo[node])
4191 displayer.close()
4191 displayer.close()
4192 return 0
4192 return 0
4193
4193
4194 try:
4194 try:
4195 # ui.forcemerge is an internal variable, do not document
4195 # ui.forcemerge is an internal variable, do not document
4196 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4196 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4197 return hg.merge(repo, node, force=opts.get('force'))
4197 return hg.merge(repo, node, force=opts.get('force'))
4198 finally:
4198 finally:
4199 ui.setconfig('ui', 'forcemerge', '')
4199 ui.setconfig('ui', 'forcemerge', '')
4200
4200
4201 @command('outgoing|out',
4201 @command('outgoing|out',
4202 [('f', 'force', None, _('run even when the destination is unrelated')),
4202 [('f', 'force', None, _('run even when the destination is unrelated')),
4203 ('r', 'rev', [],
4203 ('r', 'rev', [],
4204 _('a changeset intended to be included in the destination'), _('REV')),
4204 _('a changeset intended to be included in the destination'), _('REV')),
4205 ('n', 'newest-first', None, _('show newest record first')),
4205 ('n', 'newest-first', None, _('show newest record first')),
4206 ('B', 'bookmarks', False, _('compare bookmarks')),
4206 ('B', 'bookmarks', False, _('compare bookmarks')),
4207 ('b', 'branch', [], _('a specific branch you would like to push'),
4207 ('b', 'branch', [], _('a specific branch you would like to push'),
4208 _('BRANCH')),
4208 _('BRANCH')),
4209 ] + logopts + remoteopts + subrepoopts,
4209 ] + logopts + remoteopts + subrepoopts,
4210 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4210 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4211 def outgoing(ui, repo, dest=None, **opts):
4211 def outgoing(ui, repo, dest=None, **opts):
4212 """show changesets not found in the destination
4212 """show changesets not found in the destination
4213
4213
4214 Show changesets not found in the specified destination repository
4214 Show changesets not found in the specified destination repository
4215 or the default push location. These are the changesets that would
4215 or the default push location. These are the changesets that would
4216 be pushed if a push was requested.
4216 be pushed if a push was requested.
4217
4217
4218 See pull for details of valid destination formats.
4218 See pull for details of valid destination formats.
4219
4219
4220 Returns 0 if there are outgoing changes, 1 otherwise.
4220 Returns 0 if there are outgoing changes, 1 otherwise.
4221 """
4221 """
4222
4222
4223 if opts.get('bookmarks'):
4223 if opts.get('bookmarks'):
4224 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4224 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4225 dest, branches = hg.parseurl(dest, opts.get('branch'))
4225 dest, branches = hg.parseurl(dest, opts.get('branch'))
4226 other = hg.peer(repo, opts, dest)
4226 other = hg.peer(repo, opts, dest)
4227 if 'bookmarks' not in other.listkeys('namespaces'):
4227 if 'bookmarks' not in other.listkeys('namespaces'):
4228 ui.warn(_("remote doesn't support bookmarks\n"))
4228 ui.warn(_("remote doesn't support bookmarks\n"))
4229 return 0
4229 return 0
4230 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4230 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4231 return bookmarks.diff(ui, other, repo)
4231 return bookmarks.diff(ui, other, repo)
4232
4232
4233 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4233 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4234 try:
4234 try:
4235 return hg.outgoing(ui, repo, dest, opts)
4235 return hg.outgoing(ui, repo, dest, opts)
4236 finally:
4236 finally:
4237 del repo._subtoppath
4237 del repo._subtoppath
4238
4238
4239 @command('parents',
4239 @command('parents',
4240 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4240 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4241 ] + templateopts,
4241 ] + templateopts,
4242 _('[-r REV] [FILE]'))
4242 _('[-r REV] [FILE]'))
4243 def parents(ui, repo, file_=None, **opts):
4243 def parents(ui, repo, file_=None, **opts):
4244 """show the parents of the working directory or revision
4244 """show the parents of the working directory or revision
4245
4245
4246 Print the working directory's parent revisions. If a revision is
4246 Print the working directory's parent revisions. If a revision is
4247 given via -r/--rev, the parent of that revision will be printed.
4247 given via -r/--rev, the parent of that revision will be printed.
4248 If a file argument is given, the revision in which the file was
4248 If a file argument is given, the revision in which the file was
4249 last changed (before the working directory revision or the
4249 last changed (before the working directory revision or the
4250 argument to --rev if given) is printed.
4250 argument to --rev if given) is printed.
4251
4251
4252 Returns 0 on success.
4252 Returns 0 on success.
4253 """
4253 """
4254
4254
4255 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4255 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4256
4256
4257 if file_:
4257 if file_:
4258 m = scmutil.match(ctx, (file_,), opts)
4258 m = scmutil.match(ctx, (file_,), opts)
4259 if m.anypats() or len(m.files()) != 1:
4259 if m.anypats() or len(m.files()) != 1:
4260 raise util.Abort(_('can only specify an explicit filename'))
4260 raise util.Abort(_('can only specify an explicit filename'))
4261 file_ = m.files()[0]
4261 file_ = m.files()[0]
4262 filenodes = []
4262 filenodes = []
4263 for cp in ctx.parents():
4263 for cp in ctx.parents():
4264 if not cp:
4264 if not cp:
4265 continue
4265 continue
4266 try:
4266 try:
4267 filenodes.append(cp.filenode(file_))
4267 filenodes.append(cp.filenode(file_))
4268 except error.LookupError:
4268 except error.LookupError:
4269 pass
4269 pass
4270 if not filenodes:
4270 if not filenodes:
4271 raise util.Abort(_("'%s' not found in manifest!") % file_)
4271 raise util.Abort(_("'%s' not found in manifest!") % file_)
4272 fl = repo.file(file_)
4272 fl = repo.file(file_)
4273 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4273 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4274 else:
4274 else:
4275 p = [cp.node() for cp in ctx.parents()]
4275 p = [cp.node() for cp in ctx.parents()]
4276
4276
4277 displayer = cmdutil.show_changeset(ui, repo, opts)
4277 displayer = cmdutil.show_changeset(ui, repo, opts)
4278 for n in p:
4278 for n in p:
4279 if n != nullid:
4279 if n != nullid:
4280 displayer.show(repo[n])
4280 displayer.show(repo[n])
4281 displayer.close()
4281 displayer.close()
4282
4282
4283 @command('paths', [], _('[NAME]'))
4283 @command('paths', [], _('[NAME]'))
4284 def paths(ui, repo, search=None):
4284 def paths(ui, repo, search=None):
4285 """show aliases for remote repositories
4285 """show aliases for remote repositories
4286
4286
4287 Show definition of symbolic path name NAME. If no name is given,
4287 Show definition of symbolic path name NAME. If no name is given,
4288 show definition of all available names.
4288 show definition of all available names.
4289
4289
4290 Option -q/--quiet suppresses all output when searching for NAME
4290 Option -q/--quiet suppresses all output when searching for NAME
4291 and shows only the path names when listing all definitions.
4291 and shows only the path names when listing all definitions.
4292
4292
4293 Path names are defined in the [paths] section of your
4293 Path names are defined in the [paths] section of your
4294 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4294 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4295 repository, ``.hg/hgrc`` is used, too.
4295 repository, ``.hg/hgrc`` is used, too.
4296
4296
4297 The path names ``default`` and ``default-push`` have a special
4297 The path names ``default`` and ``default-push`` have a special
4298 meaning. When performing a push or pull operation, they are used
4298 meaning. When performing a push or pull operation, they are used
4299 as fallbacks if no location is specified on the command-line.
4299 as fallbacks if no location is specified on the command-line.
4300 When ``default-push`` is set, it will be used for push and
4300 When ``default-push`` is set, it will be used for push and
4301 ``default`` will be used for pull; otherwise ``default`` is used
4301 ``default`` will be used for pull; otherwise ``default`` is used
4302 as the fallback for both. When cloning a repository, the clone
4302 as the fallback for both. When cloning a repository, the clone
4303 source is written as ``default`` in ``.hg/hgrc``. Note that
4303 source is written as ``default`` in ``.hg/hgrc``. Note that
4304 ``default`` and ``default-push`` apply to all inbound (e.g.
4304 ``default`` and ``default-push`` apply to all inbound (e.g.
4305 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4305 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4306 :hg:`bundle`) operations.
4306 :hg:`bundle`) operations.
4307
4307
4308 See :hg:`help urls` for more information.
4308 See :hg:`help urls` for more information.
4309
4309
4310 Returns 0 on success.
4310 Returns 0 on success.
4311 """
4311 """
4312 if search:
4312 if search:
4313 for name, path in ui.configitems("paths"):
4313 for name, path in ui.configitems("paths"):
4314 if name == search:
4314 if name == search:
4315 ui.status("%s\n" % util.hidepassword(path))
4315 ui.status("%s\n" % util.hidepassword(path))
4316 return
4316 return
4317 if not ui.quiet:
4317 if not ui.quiet:
4318 ui.warn(_("not found!\n"))
4318 ui.warn(_("not found!\n"))
4319 return 1
4319 return 1
4320 else:
4320 else:
4321 for name, path in ui.configitems("paths"):
4321 for name, path in ui.configitems("paths"):
4322 if ui.quiet:
4322 if ui.quiet:
4323 ui.write("%s\n" % name)
4323 ui.write("%s\n" % name)
4324 else:
4324 else:
4325 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4325 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4326
4326
4327 @command('^phase',
4327 @command('^phase',
4328 [('p', 'public', False, _('set changeset phase to public')),
4328 [('p', 'public', False, _('set changeset phase to public')),
4329 ('d', 'draft', False, _('set changeset phase to draft')),
4329 ('d', 'draft', False, _('set changeset phase to draft')),
4330 ('s', 'secret', False, _('set changeset phase to secret')),
4330 ('s', 'secret', False, _('set changeset phase to secret')),
4331 ('f', 'force', False, _('allow to move boundary backward')),
4331 ('f', 'force', False, _('allow to move boundary backward')),
4332 ('r', 'rev', [], _('target revision'), _('REV')),
4332 ('r', 'rev', [], _('target revision'), _('REV')),
4333 ],
4333 ],
4334 _('[-p|-d|-s] [-f] [-r] REV...'))
4334 _('[-p|-d|-s] [-f] [-r] REV...'))
4335 def phase(ui, repo, *revs, **opts):
4335 def phase(ui, repo, *revs, **opts):
4336 """set or show the current phase name
4336 """set or show the current phase name
4337
4337
4338 With no argument, show the phase name of specified revisions.
4338 With no argument, show the phase name of specified revisions.
4339
4339
4340 With one of -p/--public, -d/--draft or -s/--secret, change the
4340 With one of -p/--public, -d/--draft or -s/--secret, change the
4341 phase value of the specified revisions.
4341 phase value of the specified revisions.
4342
4342
4343 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4343 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4344 lower phase to an higher phase. Phases are ordered as follows::
4344 lower phase to an higher phase. Phases are ordered as follows::
4345
4345
4346 public < draft < secret
4346 public < draft < secret
4347
4347
4348 Return 0 on success, 1 if no phases were changed or some could not
4348 Return 0 on success, 1 if no phases were changed or some could not
4349 be changed.
4349 be changed.
4350 """
4350 """
4351 # search for a unique phase argument
4351 # search for a unique phase argument
4352 targetphase = None
4352 targetphase = None
4353 for idx, name in enumerate(phases.phasenames):
4353 for idx, name in enumerate(phases.phasenames):
4354 if opts[name]:
4354 if opts[name]:
4355 if targetphase is not None:
4355 if targetphase is not None:
4356 raise util.Abort(_('only one phase can be specified'))
4356 raise util.Abort(_('only one phase can be specified'))
4357 targetphase = idx
4357 targetphase = idx
4358
4358
4359 # look for specified revision
4359 # look for specified revision
4360 revs = list(revs)
4360 revs = list(revs)
4361 revs.extend(opts['rev'])
4361 revs.extend(opts['rev'])
4362 if not revs:
4362 if not revs:
4363 raise util.Abort(_('no revisions specified'))
4363 raise util.Abort(_('no revisions specified'))
4364
4364
4365 revs = scmutil.revrange(repo, revs)
4365 revs = scmutil.revrange(repo, revs)
4366
4366
4367 lock = None
4367 lock = None
4368 ret = 0
4368 ret = 0
4369 if targetphase is None:
4369 if targetphase is None:
4370 # display
4370 # display
4371 for r in revs:
4371 for r in revs:
4372 ctx = repo[r]
4372 ctx = repo[r]
4373 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4373 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4374 else:
4374 else:
4375 lock = repo.lock()
4375 lock = repo.lock()
4376 try:
4376 try:
4377 # set phase
4377 # set phase
4378 nodes = [ctx.node() for ctx in repo.set('%ld', revs)]
4378 nodes = [ctx.node() for ctx in repo.set('%ld', revs)]
4379 if not nodes:
4379 if not nodes:
4380 raise util.Abort(_('empty revision set'))
4380 raise util.Abort(_('empty revision set'))
4381 olddata = repo._phaserev[:]
4381 olddata = repo._phasecache.getphaserevs(repo)[:]
4382 phases.advanceboundary(repo, targetphase, nodes)
4382 phases.advanceboundary(repo, targetphase, nodes)
4383 if opts['force']:
4383 if opts['force']:
4384 phases.retractboundary(repo, targetphase, nodes)
4384 phases.retractboundary(repo, targetphase, nodes)
4385 finally:
4385 finally:
4386 lock.release()
4386 lock.release()
4387 if olddata is not None:
4387 if olddata is not None:
4388 changes = 0
4388 changes = 0
4389 newdata = repo._phaserev
4389 newdata = repo._phasecache.getphaserevs(repo)
4390 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4390 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4391 rejected = [n for n in nodes
4391 rejected = [n for n in nodes
4392 if newdata[repo[n].rev()] < targetphase]
4392 if newdata[repo[n].rev()] < targetphase]
4393 if rejected:
4393 if rejected:
4394 ui.warn(_('cannot move %i changesets to a more permissive '
4394 ui.warn(_('cannot move %i changesets to a more permissive '
4395 'phase, use --force\n') % len(rejected))
4395 'phase, use --force\n') % len(rejected))
4396 ret = 1
4396 ret = 1
4397 if changes:
4397 if changes:
4398 msg = _('phase changed for %i changesets\n') % changes
4398 msg = _('phase changed for %i changesets\n') % changes
4399 if ret:
4399 if ret:
4400 ui.status(msg)
4400 ui.status(msg)
4401 else:
4401 else:
4402 ui.note(msg)
4402 ui.note(msg)
4403 else:
4403 else:
4404 ui.warn(_('no phases changed\n'))
4404 ui.warn(_('no phases changed\n'))
4405 ret = 1
4405 ret = 1
4406 return ret
4406 return ret
4407
4407
4408 def postincoming(ui, repo, modheads, optupdate, checkout):
4408 def postincoming(ui, repo, modheads, optupdate, checkout):
4409 if modheads == 0:
4409 if modheads == 0:
4410 return
4410 return
4411 if optupdate:
4411 if optupdate:
4412 movemarkfrom = repo['.'].node()
4412 movemarkfrom = repo['.'].node()
4413 try:
4413 try:
4414 ret = hg.update(repo, checkout)
4414 ret = hg.update(repo, checkout)
4415 except util.Abort, inst:
4415 except util.Abort, inst:
4416 ui.warn(_("not updating: %s\n") % str(inst))
4416 ui.warn(_("not updating: %s\n") % str(inst))
4417 return 0
4417 return 0
4418 if not ret and not checkout:
4418 if not ret and not checkout:
4419 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4419 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4420 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4420 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4421 return ret
4421 return ret
4422 if modheads > 1:
4422 if modheads > 1:
4423 currentbranchheads = len(repo.branchheads())
4423 currentbranchheads = len(repo.branchheads())
4424 if currentbranchheads == modheads:
4424 if currentbranchheads == modheads:
4425 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4425 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4426 elif currentbranchheads > 1:
4426 elif currentbranchheads > 1:
4427 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4427 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4428 else:
4428 else:
4429 ui.status(_("(run 'hg heads' to see heads)\n"))
4429 ui.status(_("(run 'hg heads' to see heads)\n"))
4430 else:
4430 else:
4431 ui.status(_("(run 'hg update' to get a working copy)\n"))
4431 ui.status(_("(run 'hg update' to get a working copy)\n"))
4432
4432
4433 @command('^pull',
4433 @command('^pull',
4434 [('u', 'update', None,
4434 [('u', 'update', None,
4435 _('update to new branch head if changesets were pulled')),
4435 _('update to new branch head if changesets were pulled')),
4436 ('f', 'force', None, _('run even when remote repository is unrelated')),
4436 ('f', 'force', None, _('run even when remote repository is unrelated')),
4437 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4437 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4438 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4438 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4439 ('b', 'branch', [], _('a specific branch you would like to pull'),
4439 ('b', 'branch', [], _('a specific branch you would like to pull'),
4440 _('BRANCH')),
4440 _('BRANCH')),
4441 ] + remoteopts,
4441 ] + remoteopts,
4442 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4442 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4443 def pull(ui, repo, source="default", **opts):
4443 def pull(ui, repo, source="default", **opts):
4444 """pull changes from the specified source
4444 """pull changes from the specified source
4445
4445
4446 Pull changes from a remote repository to a local one.
4446 Pull changes from a remote repository to a local one.
4447
4447
4448 This finds all changes from the repository at the specified path
4448 This finds all changes from the repository at the specified path
4449 or URL and adds them to a local repository (the current one unless
4449 or URL and adds them to a local repository (the current one unless
4450 -R is specified). By default, this does not update the copy of the
4450 -R is specified). By default, this does not update the copy of the
4451 project in the working directory.
4451 project in the working directory.
4452
4452
4453 Use :hg:`incoming` if you want to see what would have been added
4453 Use :hg:`incoming` if you want to see what would have been added
4454 by a pull at the time you issued this command. If you then decide
4454 by a pull at the time you issued this command. If you then decide
4455 to add those changes to the repository, you should use :hg:`pull
4455 to add those changes to the repository, you should use :hg:`pull
4456 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4456 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4457
4457
4458 If SOURCE is omitted, the 'default' path will be used.
4458 If SOURCE is omitted, the 'default' path will be used.
4459 See :hg:`help urls` for more information.
4459 See :hg:`help urls` for more information.
4460
4460
4461 Returns 0 on success, 1 if an update had unresolved files.
4461 Returns 0 on success, 1 if an update had unresolved files.
4462 """
4462 """
4463 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4463 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4464 other = hg.peer(repo, opts, source)
4464 other = hg.peer(repo, opts, source)
4465 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4465 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4466 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4466 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4467
4467
4468 if opts.get('bookmark'):
4468 if opts.get('bookmark'):
4469 if not revs:
4469 if not revs:
4470 revs = []
4470 revs = []
4471 rb = other.listkeys('bookmarks')
4471 rb = other.listkeys('bookmarks')
4472 for b in opts['bookmark']:
4472 for b in opts['bookmark']:
4473 if b not in rb:
4473 if b not in rb:
4474 raise util.Abort(_('remote bookmark %s not found!') % b)
4474 raise util.Abort(_('remote bookmark %s not found!') % b)
4475 revs.append(rb[b])
4475 revs.append(rb[b])
4476
4476
4477 if revs:
4477 if revs:
4478 try:
4478 try:
4479 revs = [other.lookup(rev) for rev in revs]
4479 revs = [other.lookup(rev) for rev in revs]
4480 except error.CapabilityError:
4480 except error.CapabilityError:
4481 err = _("other repository doesn't support revision lookup, "
4481 err = _("other repository doesn't support revision lookup, "
4482 "so a rev cannot be specified.")
4482 "so a rev cannot be specified.")
4483 raise util.Abort(err)
4483 raise util.Abort(err)
4484
4484
4485 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4485 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4486 bookmarks.updatefromremote(ui, repo, other, source)
4486 bookmarks.updatefromremote(ui, repo, other, source)
4487 if checkout:
4487 if checkout:
4488 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4488 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4489 repo._subtoppath = source
4489 repo._subtoppath = source
4490 try:
4490 try:
4491 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4491 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4492
4492
4493 finally:
4493 finally:
4494 del repo._subtoppath
4494 del repo._subtoppath
4495
4495
4496 # update specified bookmarks
4496 # update specified bookmarks
4497 if opts.get('bookmark'):
4497 if opts.get('bookmark'):
4498 for b in opts['bookmark']:
4498 for b in opts['bookmark']:
4499 # explicit pull overrides local bookmark if any
4499 # explicit pull overrides local bookmark if any
4500 ui.status(_("importing bookmark %s\n") % b)
4500 ui.status(_("importing bookmark %s\n") % b)
4501 repo._bookmarks[b] = repo[rb[b]].node()
4501 repo._bookmarks[b] = repo[rb[b]].node()
4502 bookmarks.write(repo)
4502 bookmarks.write(repo)
4503
4503
4504 return ret
4504 return ret
4505
4505
4506 @command('^push',
4506 @command('^push',
4507 [('f', 'force', None, _('force push')),
4507 [('f', 'force', None, _('force push')),
4508 ('r', 'rev', [],
4508 ('r', 'rev', [],
4509 _('a changeset intended to be included in the destination'),
4509 _('a changeset intended to be included in the destination'),
4510 _('REV')),
4510 _('REV')),
4511 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4511 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4512 ('b', 'branch', [],
4512 ('b', 'branch', [],
4513 _('a specific branch you would like to push'), _('BRANCH')),
4513 _('a specific branch you would like to push'), _('BRANCH')),
4514 ('', 'new-branch', False, _('allow pushing a new branch')),
4514 ('', 'new-branch', False, _('allow pushing a new branch')),
4515 ] + remoteopts,
4515 ] + remoteopts,
4516 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4516 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4517 def push(ui, repo, dest=None, **opts):
4517 def push(ui, repo, dest=None, **opts):
4518 """push changes to the specified destination
4518 """push changes to the specified destination
4519
4519
4520 Push changesets from the local repository to the specified
4520 Push changesets from the local repository to the specified
4521 destination.
4521 destination.
4522
4522
4523 This operation is symmetrical to pull: it is identical to a pull
4523 This operation is symmetrical to pull: it is identical to a pull
4524 in the destination repository from the current one.
4524 in the destination repository from the current one.
4525
4525
4526 By default, push will not allow creation of new heads at the
4526 By default, push will not allow creation of new heads at the
4527 destination, since multiple heads would make it unclear which head
4527 destination, since multiple heads would make it unclear which head
4528 to use. In this situation, it is recommended to pull and merge
4528 to use. In this situation, it is recommended to pull and merge
4529 before pushing.
4529 before pushing.
4530
4530
4531 Use --new-branch if you want to allow push to create a new named
4531 Use --new-branch if you want to allow push to create a new named
4532 branch that is not present at the destination. This allows you to
4532 branch that is not present at the destination. This allows you to
4533 only create a new branch without forcing other changes.
4533 only create a new branch without forcing other changes.
4534
4534
4535 Use -f/--force to override the default behavior and push all
4535 Use -f/--force to override the default behavior and push all
4536 changesets on all branches.
4536 changesets on all branches.
4537
4537
4538 If -r/--rev is used, the specified revision and all its ancestors
4538 If -r/--rev is used, the specified revision and all its ancestors
4539 will be pushed to the remote repository.
4539 will be pushed to the remote repository.
4540
4540
4541 Please see :hg:`help urls` for important details about ``ssh://``
4541 Please see :hg:`help urls` for important details about ``ssh://``
4542 URLs. If DESTINATION is omitted, a default path will be used.
4542 URLs. If DESTINATION is omitted, a default path will be used.
4543
4543
4544 Returns 0 if push was successful, 1 if nothing to push.
4544 Returns 0 if push was successful, 1 if nothing to push.
4545 """
4545 """
4546
4546
4547 if opts.get('bookmark'):
4547 if opts.get('bookmark'):
4548 for b in opts['bookmark']:
4548 for b in opts['bookmark']:
4549 # translate -B options to -r so changesets get pushed
4549 # translate -B options to -r so changesets get pushed
4550 if b in repo._bookmarks:
4550 if b in repo._bookmarks:
4551 opts.setdefault('rev', []).append(b)
4551 opts.setdefault('rev', []).append(b)
4552 else:
4552 else:
4553 # if we try to push a deleted bookmark, translate it to null
4553 # if we try to push a deleted bookmark, translate it to null
4554 # this lets simultaneous -r, -b options continue working
4554 # this lets simultaneous -r, -b options continue working
4555 opts.setdefault('rev', []).append("null")
4555 opts.setdefault('rev', []).append("null")
4556
4556
4557 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4557 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4558 dest, branches = hg.parseurl(dest, opts.get('branch'))
4558 dest, branches = hg.parseurl(dest, opts.get('branch'))
4559 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4559 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4560 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4560 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4561 other = hg.peer(repo, opts, dest)
4561 other = hg.peer(repo, opts, dest)
4562 if revs:
4562 if revs:
4563 revs = [repo.lookup(rev) for rev in revs]
4563 revs = [repo.lookup(rev) for rev in revs]
4564
4564
4565 repo._subtoppath = dest
4565 repo._subtoppath = dest
4566 try:
4566 try:
4567 # push subrepos depth-first for coherent ordering
4567 # push subrepos depth-first for coherent ordering
4568 c = repo['']
4568 c = repo['']
4569 subs = c.substate # only repos that are committed
4569 subs = c.substate # only repos that are committed
4570 for s in sorted(subs):
4570 for s in sorted(subs):
4571 if c.sub(s).push(opts) == 0:
4571 if c.sub(s).push(opts) == 0:
4572 return False
4572 return False
4573 finally:
4573 finally:
4574 del repo._subtoppath
4574 del repo._subtoppath
4575 result = repo.push(other, opts.get('force'), revs=revs,
4575 result = repo.push(other, opts.get('force'), revs=revs,
4576 newbranch=opts.get('new_branch'))
4576 newbranch=opts.get('new_branch'))
4577
4577
4578 result = not result
4578 result = not result
4579
4579
4580 if opts.get('bookmark'):
4580 if opts.get('bookmark'):
4581 rb = other.listkeys('bookmarks')
4581 rb = other.listkeys('bookmarks')
4582 for b in opts['bookmark']:
4582 for b in opts['bookmark']:
4583 # explicit push overrides remote bookmark if any
4583 # explicit push overrides remote bookmark if any
4584 if b in repo._bookmarks:
4584 if b in repo._bookmarks:
4585 ui.status(_("exporting bookmark %s\n") % b)
4585 ui.status(_("exporting bookmark %s\n") % b)
4586 new = repo[b].hex()
4586 new = repo[b].hex()
4587 elif b in rb:
4587 elif b in rb:
4588 ui.status(_("deleting remote bookmark %s\n") % b)
4588 ui.status(_("deleting remote bookmark %s\n") % b)
4589 new = '' # delete
4589 new = '' # delete
4590 else:
4590 else:
4591 ui.warn(_('bookmark %s does not exist on the local '
4591 ui.warn(_('bookmark %s does not exist on the local '
4592 'or remote repository!\n') % b)
4592 'or remote repository!\n') % b)
4593 return 2
4593 return 2
4594 old = rb.get(b, '')
4594 old = rb.get(b, '')
4595 r = other.pushkey('bookmarks', b, old, new)
4595 r = other.pushkey('bookmarks', b, old, new)
4596 if not r:
4596 if not r:
4597 ui.warn(_('updating bookmark %s failed!\n') % b)
4597 ui.warn(_('updating bookmark %s failed!\n') % b)
4598 if not result:
4598 if not result:
4599 result = 2
4599 result = 2
4600
4600
4601 return result
4601 return result
4602
4602
4603 @command('recover', [])
4603 @command('recover', [])
4604 def recover(ui, repo):
4604 def recover(ui, repo):
4605 """roll back an interrupted transaction
4605 """roll back an interrupted transaction
4606
4606
4607 Recover from an interrupted commit or pull.
4607 Recover from an interrupted commit or pull.
4608
4608
4609 This command tries to fix the repository status after an
4609 This command tries to fix the repository status after an
4610 interrupted operation. It should only be necessary when Mercurial
4610 interrupted operation. It should only be necessary when Mercurial
4611 suggests it.
4611 suggests it.
4612
4612
4613 Returns 0 if successful, 1 if nothing to recover or verify fails.
4613 Returns 0 if successful, 1 if nothing to recover or verify fails.
4614 """
4614 """
4615 if repo.recover():
4615 if repo.recover():
4616 return hg.verify(repo)
4616 return hg.verify(repo)
4617 return 1
4617 return 1
4618
4618
4619 @command('^remove|rm',
4619 @command('^remove|rm',
4620 [('A', 'after', None, _('record delete for missing files')),
4620 [('A', 'after', None, _('record delete for missing files')),
4621 ('f', 'force', None,
4621 ('f', 'force', None,
4622 _('remove (and delete) file even if added or modified')),
4622 _('remove (and delete) file even if added or modified')),
4623 ] + walkopts,
4623 ] + walkopts,
4624 _('[OPTION]... FILE...'))
4624 _('[OPTION]... FILE...'))
4625 def remove(ui, repo, *pats, **opts):
4625 def remove(ui, repo, *pats, **opts):
4626 """remove the specified files on the next commit
4626 """remove the specified files on the next commit
4627
4627
4628 Schedule the indicated files for removal from the current branch.
4628 Schedule the indicated files for removal from the current branch.
4629
4629
4630 This command schedules the files to be removed at the next commit.
4630 This command schedules the files to be removed at the next commit.
4631 To undo a remove before that, see :hg:`revert`. To undo added
4631 To undo a remove before that, see :hg:`revert`. To undo added
4632 files, see :hg:`forget`.
4632 files, see :hg:`forget`.
4633
4633
4634 .. container:: verbose
4634 .. container:: verbose
4635
4635
4636 -A/--after can be used to remove only files that have already
4636 -A/--after can be used to remove only files that have already
4637 been deleted, -f/--force can be used to force deletion, and -Af
4637 been deleted, -f/--force can be used to force deletion, and -Af
4638 can be used to remove files from the next revision without
4638 can be used to remove files from the next revision without
4639 deleting them from the working directory.
4639 deleting them from the working directory.
4640
4640
4641 The following table details the behavior of remove for different
4641 The following table details the behavior of remove for different
4642 file states (columns) and option combinations (rows). The file
4642 file states (columns) and option combinations (rows). The file
4643 states are Added [A], Clean [C], Modified [M] and Missing [!]
4643 states are Added [A], Clean [C], Modified [M] and Missing [!]
4644 (as reported by :hg:`status`). The actions are Warn, Remove
4644 (as reported by :hg:`status`). The actions are Warn, Remove
4645 (from branch) and Delete (from disk):
4645 (from branch) and Delete (from disk):
4646
4646
4647 ======= == == == ==
4647 ======= == == == ==
4648 A C M !
4648 A C M !
4649 ======= == == == ==
4649 ======= == == == ==
4650 none W RD W R
4650 none W RD W R
4651 -f R RD RD R
4651 -f R RD RD R
4652 -A W W W R
4652 -A W W W R
4653 -Af R R R R
4653 -Af R R R R
4654 ======= == == == ==
4654 ======= == == == ==
4655
4655
4656 Note that remove never deletes files in Added [A] state from the
4656 Note that remove never deletes files in Added [A] state from the
4657 working directory, not even if option --force is specified.
4657 working directory, not even if option --force is specified.
4658
4658
4659 Returns 0 on success, 1 if any warnings encountered.
4659 Returns 0 on success, 1 if any warnings encountered.
4660 """
4660 """
4661
4661
4662 ret = 0
4662 ret = 0
4663 after, force = opts.get('after'), opts.get('force')
4663 after, force = opts.get('after'), opts.get('force')
4664 if not pats and not after:
4664 if not pats and not after:
4665 raise util.Abort(_('no files specified'))
4665 raise util.Abort(_('no files specified'))
4666
4666
4667 m = scmutil.match(repo[None], pats, opts)
4667 m = scmutil.match(repo[None], pats, opts)
4668 s = repo.status(match=m, clean=True)
4668 s = repo.status(match=m, clean=True)
4669 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4669 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4670
4670
4671 for f in m.files():
4671 for f in m.files():
4672 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4672 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4673 if os.path.exists(m.rel(f)):
4673 if os.path.exists(m.rel(f)):
4674 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4674 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4675 ret = 1
4675 ret = 1
4676
4676
4677 if force:
4677 if force:
4678 list = modified + deleted + clean + added
4678 list = modified + deleted + clean + added
4679 elif after:
4679 elif after:
4680 list = deleted
4680 list = deleted
4681 for f in modified + added + clean:
4681 for f in modified + added + clean:
4682 ui.warn(_('not removing %s: file still exists (use -f'
4682 ui.warn(_('not removing %s: file still exists (use -f'
4683 ' to force removal)\n') % m.rel(f))
4683 ' to force removal)\n') % m.rel(f))
4684 ret = 1
4684 ret = 1
4685 else:
4685 else:
4686 list = deleted + clean
4686 list = deleted + clean
4687 for f in modified:
4687 for f in modified:
4688 ui.warn(_('not removing %s: file is modified (use -f'
4688 ui.warn(_('not removing %s: file is modified (use -f'
4689 ' to force removal)\n') % m.rel(f))
4689 ' to force removal)\n') % m.rel(f))
4690 ret = 1
4690 ret = 1
4691 for f in added:
4691 for f in added:
4692 ui.warn(_('not removing %s: file has been marked for add'
4692 ui.warn(_('not removing %s: file has been marked for add'
4693 ' (use forget to undo)\n') % m.rel(f))
4693 ' (use forget to undo)\n') % m.rel(f))
4694 ret = 1
4694 ret = 1
4695
4695
4696 for f in sorted(list):
4696 for f in sorted(list):
4697 if ui.verbose or not m.exact(f):
4697 if ui.verbose or not m.exact(f):
4698 ui.status(_('removing %s\n') % m.rel(f))
4698 ui.status(_('removing %s\n') % m.rel(f))
4699
4699
4700 wlock = repo.wlock()
4700 wlock = repo.wlock()
4701 try:
4701 try:
4702 if not after:
4702 if not after:
4703 for f in list:
4703 for f in list:
4704 if f in added:
4704 if f in added:
4705 continue # we never unlink added files on remove
4705 continue # we never unlink added files on remove
4706 try:
4706 try:
4707 util.unlinkpath(repo.wjoin(f))
4707 util.unlinkpath(repo.wjoin(f))
4708 except OSError, inst:
4708 except OSError, inst:
4709 if inst.errno != errno.ENOENT:
4709 if inst.errno != errno.ENOENT:
4710 raise
4710 raise
4711 repo[None].forget(list)
4711 repo[None].forget(list)
4712 finally:
4712 finally:
4713 wlock.release()
4713 wlock.release()
4714
4714
4715 return ret
4715 return ret
4716
4716
4717 @command('rename|move|mv',
4717 @command('rename|move|mv',
4718 [('A', 'after', None, _('record a rename that has already occurred')),
4718 [('A', 'after', None, _('record a rename that has already occurred')),
4719 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4719 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4720 ] + walkopts + dryrunopts,
4720 ] + walkopts + dryrunopts,
4721 _('[OPTION]... SOURCE... DEST'))
4721 _('[OPTION]... SOURCE... DEST'))
4722 def rename(ui, repo, *pats, **opts):
4722 def rename(ui, repo, *pats, **opts):
4723 """rename files; equivalent of copy + remove
4723 """rename files; equivalent of copy + remove
4724
4724
4725 Mark dest as copies of sources; mark sources for deletion. If dest
4725 Mark dest as copies of sources; mark sources for deletion. If dest
4726 is a directory, copies are put in that directory. If dest is a
4726 is a directory, copies are put in that directory. If dest is a
4727 file, there can only be one source.
4727 file, there can only be one source.
4728
4728
4729 By default, this command copies the contents of files as they
4729 By default, this command copies the contents of files as they
4730 exist in the working directory. If invoked with -A/--after, the
4730 exist in the working directory. If invoked with -A/--after, the
4731 operation is recorded, but no copying is performed.
4731 operation is recorded, but no copying is performed.
4732
4732
4733 This command takes effect at the next commit. To undo a rename
4733 This command takes effect at the next commit. To undo a rename
4734 before that, see :hg:`revert`.
4734 before that, see :hg:`revert`.
4735
4735
4736 Returns 0 on success, 1 if errors are encountered.
4736 Returns 0 on success, 1 if errors are encountered.
4737 """
4737 """
4738 wlock = repo.wlock(False)
4738 wlock = repo.wlock(False)
4739 try:
4739 try:
4740 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4740 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4741 finally:
4741 finally:
4742 wlock.release()
4742 wlock.release()
4743
4743
4744 @command('resolve',
4744 @command('resolve',
4745 [('a', 'all', None, _('select all unresolved files')),
4745 [('a', 'all', None, _('select all unresolved files')),
4746 ('l', 'list', None, _('list state of files needing merge')),
4746 ('l', 'list', None, _('list state of files needing merge')),
4747 ('m', 'mark', None, _('mark files as resolved')),
4747 ('m', 'mark', None, _('mark files as resolved')),
4748 ('u', 'unmark', None, _('mark files as unresolved')),
4748 ('u', 'unmark', None, _('mark files as unresolved')),
4749 ('n', 'no-status', None, _('hide status prefix'))]
4749 ('n', 'no-status', None, _('hide status prefix'))]
4750 + mergetoolopts + walkopts,
4750 + mergetoolopts + walkopts,
4751 _('[OPTION]... [FILE]...'))
4751 _('[OPTION]... [FILE]...'))
4752 def resolve(ui, repo, *pats, **opts):
4752 def resolve(ui, repo, *pats, **opts):
4753 """redo merges or set/view the merge status of files
4753 """redo merges or set/view the merge status of files
4754
4754
4755 Merges with unresolved conflicts are often the result of
4755 Merges with unresolved conflicts are often the result of
4756 non-interactive merging using the ``internal:merge`` configuration
4756 non-interactive merging using the ``internal:merge`` configuration
4757 setting, or a command-line merge tool like ``diff3``. The resolve
4757 setting, or a command-line merge tool like ``diff3``. The resolve
4758 command is used to manage the files involved in a merge, after
4758 command is used to manage the files involved in a merge, after
4759 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4759 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4760 working directory must have two parents). See :hg:`help
4760 working directory must have two parents). See :hg:`help
4761 merge-tools` for information on configuring merge tools.
4761 merge-tools` for information on configuring merge tools.
4762
4762
4763 The resolve command can be used in the following ways:
4763 The resolve command can be used in the following ways:
4764
4764
4765 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4765 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4766 files, discarding any previous merge attempts. Re-merging is not
4766 files, discarding any previous merge attempts. Re-merging is not
4767 performed for files already marked as resolved. Use ``--all/-a``
4767 performed for files already marked as resolved. Use ``--all/-a``
4768 to select all unresolved files. ``--tool`` can be used to specify
4768 to select all unresolved files. ``--tool`` can be used to specify
4769 the merge tool used for the given files. It overrides the HGMERGE
4769 the merge tool used for the given files. It overrides the HGMERGE
4770 environment variable and your configuration files. Previous file
4770 environment variable and your configuration files. Previous file
4771 contents are saved with a ``.orig`` suffix.
4771 contents are saved with a ``.orig`` suffix.
4772
4772
4773 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4773 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4774 (e.g. after having manually fixed-up the files). The default is
4774 (e.g. after having manually fixed-up the files). The default is
4775 to mark all unresolved files.
4775 to mark all unresolved files.
4776
4776
4777 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4777 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4778 default is to mark all resolved files.
4778 default is to mark all resolved files.
4779
4779
4780 - :hg:`resolve -l`: list files which had or still have conflicts.
4780 - :hg:`resolve -l`: list files which had or still have conflicts.
4781 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4781 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4782
4782
4783 Note that Mercurial will not let you commit files with unresolved
4783 Note that Mercurial will not let you commit files with unresolved
4784 merge conflicts. You must use :hg:`resolve -m ...` before you can
4784 merge conflicts. You must use :hg:`resolve -m ...` before you can
4785 commit after a conflicting merge.
4785 commit after a conflicting merge.
4786
4786
4787 Returns 0 on success, 1 if any files fail a resolve attempt.
4787 Returns 0 on success, 1 if any files fail a resolve attempt.
4788 """
4788 """
4789
4789
4790 all, mark, unmark, show, nostatus = \
4790 all, mark, unmark, show, nostatus = \
4791 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4791 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4792
4792
4793 if (show and (mark or unmark)) or (mark and unmark):
4793 if (show and (mark or unmark)) or (mark and unmark):
4794 raise util.Abort(_("too many options specified"))
4794 raise util.Abort(_("too many options specified"))
4795 if pats and all:
4795 if pats and all:
4796 raise util.Abort(_("can't specify --all and patterns"))
4796 raise util.Abort(_("can't specify --all and patterns"))
4797 if not (all or pats or show or mark or unmark):
4797 if not (all or pats or show or mark or unmark):
4798 raise util.Abort(_('no files or directories specified; '
4798 raise util.Abort(_('no files or directories specified; '
4799 'use --all to remerge all files'))
4799 'use --all to remerge all files'))
4800
4800
4801 ms = mergemod.mergestate(repo)
4801 ms = mergemod.mergestate(repo)
4802 m = scmutil.match(repo[None], pats, opts)
4802 m = scmutil.match(repo[None], pats, opts)
4803 ret = 0
4803 ret = 0
4804
4804
4805 for f in ms:
4805 for f in ms:
4806 if m(f):
4806 if m(f):
4807 if show:
4807 if show:
4808 if nostatus:
4808 if nostatus:
4809 ui.write("%s\n" % f)
4809 ui.write("%s\n" % f)
4810 else:
4810 else:
4811 ui.write("%s %s\n" % (ms[f].upper(), f),
4811 ui.write("%s %s\n" % (ms[f].upper(), f),
4812 label='resolve.' +
4812 label='resolve.' +
4813 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4813 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4814 elif mark:
4814 elif mark:
4815 ms.mark(f, "r")
4815 ms.mark(f, "r")
4816 elif unmark:
4816 elif unmark:
4817 ms.mark(f, "u")
4817 ms.mark(f, "u")
4818 else:
4818 else:
4819 wctx = repo[None]
4819 wctx = repo[None]
4820 mctx = wctx.parents()[-1]
4820 mctx = wctx.parents()[-1]
4821
4821
4822 # backup pre-resolve (merge uses .orig for its own purposes)
4822 # backup pre-resolve (merge uses .orig for its own purposes)
4823 a = repo.wjoin(f)
4823 a = repo.wjoin(f)
4824 util.copyfile(a, a + ".resolve")
4824 util.copyfile(a, a + ".resolve")
4825
4825
4826 try:
4826 try:
4827 # resolve file
4827 # resolve file
4828 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4828 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4829 if ms.resolve(f, wctx, mctx):
4829 if ms.resolve(f, wctx, mctx):
4830 ret = 1
4830 ret = 1
4831 finally:
4831 finally:
4832 ui.setconfig('ui', 'forcemerge', '')
4832 ui.setconfig('ui', 'forcemerge', '')
4833
4833
4834 # replace filemerge's .orig file with our resolve file
4834 # replace filemerge's .orig file with our resolve file
4835 util.rename(a + ".resolve", a + ".orig")
4835 util.rename(a + ".resolve", a + ".orig")
4836
4836
4837 ms.commit()
4837 ms.commit()
4838 return ret
4838 return ret
4839
4839
4840 @command('revert',
4840 @command('revert',
4841 [('a', 'all', None, _('revert all changes when no arguments given')),
4841 [('a', 'all', None, _('revert all changes when no arguments given')),
4842 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4842 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4843 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4843 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4844 ('C', 'no-backup', None, _('do not save backup copies of files')),
4844 ('C', 'no-backup', None, _('do not save backup copies of files')),
4845 ] + walkopts + dryrunopts,
4845 ] + walkopts + dryrunopts,
4846 _('[OPTION]... [-r REV] [NAME]...'))
4846 _('[OPTION]... [-r REV] [NAME]...'))
4847 def revert(ui, repo, *pats, **opts):
4847 def revert(ui, repo, *pats, **opts):
4848 """restore files to their checkout state
4848 """restore files to their checkout state
4849
4849
4850 .. note::
4850 .. note::
4851 To check out earlier revisions, you should use :hg:`update REV`.
4851 To check out earlier revisions, you should use :hg:`update REV`.
4852 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4852 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4853
4853
4854 With no revision specified, revert the specified files or directories
4854 With no revision specified, revert the specified files or directories
4855 to the contents they had in the parent of the working directory.
4855 to the contents they had in the parent of the working directory.
4856 This restores the contents of files to an unmodified
4856 This restores the contents of files to an unmodified
4857 state and unschedules adds, removes, copies, and renames. If the
4857 state and unschedules adds, removes, copies, and renames. If the
4858 working directory has two parents, you must explicitly specify a
4858 working directory has two parents, you must explicitly specify a
4859 revision.
4859 revision.
4860
4860
4861 Using the -r/--rev or -d/--date options, revert the given files or
4861 Using the -r/--rev or -d/--date options, revert the given files or
4862 directories to their states as of a specific revision. Because
4862 directories to their states as of a specific revision. Because
4863 revert does not change the working directory parents, this will
4863 revert does not change the working directory parents, this will
4864 cause these files to appear modified. This can be helpful to "back
4864 cause these files to appear modified. This can be helpful to "back
4865 out" some or all of an earlier change. See :hg:`backout` for a
4865 out" some or all of an earlier change. See :hg:`backout` for a
4866 related method.
4866 related method.
4867
4867
4868 Modified files are saved with a .orig suffix before reverting.
4868 Modified files are saved with a .orig suffix before reverting.
4869 To disable these backups, use --no-backup.
4869 To disable these backups, use --no-backup.
4870
4870
4871 See :hg:`help dates` for a list of formats valid for -d/--date.
4871 See :hg:`help dates` for a list of formats valid for -d/--date.
4872
4872
4873 Returns 0 on success.
4873 Returns 0 on success.
4874 """
4874 """
4875
4875
4876 if opts.get("date"):
4876 if opts.get("date"):
4877 if opts.get("rev"):
4877 if opts.get("rev"):
4878 raise util.Abort(_("you can't specify a revision and a date"))
4878 raise util.Abort(_("you can't specify a revision and a date"))
4879 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4879 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4880
4880
4881 parent, p2 = repo.dirstate.parents()
4881 parent, p2 = repo.dirstate.parents()
4882 if not opts.get('rev') and p2 != nullid:
4882 if not opts.get('rev') and p2 != nullid:
4883 # revert after merge is a trap for new users (issue2915)
4883 # revert after merge is a trap for new users (issue2915)
4884 raise util.Abort(_('uncommitted merge with no revision specified'),
4884 raise util.Abort(_('uncommitted merge with no revision specified'),
4885 hint=_('use "hg update" or see "hg help revert"'))
4885 hint=_('use "hg update" or see "hg help revert"'))
4886
4886
4887 ctx = scmutil.revsingle(repo, opts.get('rev'))
4887 ctx = scmutil.revsingle(repo, opts.get('rev'))
4888
4888
4889 if not pats and not opts.get('all'):
4889 if not pats and not opts.get('all'):
4890 msg = _("no files or directories specified")
4890 msg = _("no files or directories specified")
4891 if p2 != nullid:
4891 if p2 != nullid:
4892 hint = _("uncommitted merge, use --all to discard all changes,"
4892 hint = _("uncommitted merge, use --all to discard all changes,"
4893 " or 'hg update -C .' to abort the merge")
4893 " or 'hg update -C .' to abort the merge")
4894 raise util.Abort(msg, hint=hint)
4894 raise util.Abort(msg, hint=hint)
4895 dirty = util.any(repo.status())
4895 dirty = util.any(repo.status())
4896 node = ctx.node()
4896 node = ctx.node()
4897 if node != parent:
4897 if node != parent:
4898 if dirty:
4898 if dirty:
4899 hint = _("uncommitted changes, use --all to discard all"
4899 hint = _("uncommitted changes, use --all to discard all"
4900 " changes, or 'hg update %s' to update") % ctx.rev()
4900 " changes, or 'hg update %s' to update") % ctx.rev()
4901 else:
4901 else:
4902 hint = _("use --all to revert all files,"
4902 hint = _("use --all to revert all files,"
4903 " or 'hg update %s' to update") % ctx.rev()
4903 " or 'hg update %s' to update") % ctx.rev()
4904 elif dirty:
4904 elif dirty:
4905 hint = _("uncommitted changes, use --all to discard all changes")
4905 hint = _("uncommitted changes, use --all to discard all changes")
4906 else:
4906 else:
4907 hint = _("use --all to revert all files")
4907 hint = _("use --all to revert all files")
4908 raise util.Abort(msg, hint=hint)
4908 raise util.Abort(msg, hint=hint)
4909
4909
4910 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4910 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4911
4911
4912 @command('rollback', dryrunopts +
4912 @command('rollback', dryrunopts +
4913 [('f', 'force', False, _('ignore safety measures'))])
4913 [('f', 'force', False, _('ignore safety measures'))])
4914 def rollback(ui, repo, **opts):
4914 def rollback(ui, repo, **opts):
4915 """roll back the last transaction (dangerous)
4915 """roll back the last transaction (dangerous)
4916
4916
4917 This command should be used with care. There is only one level of
4917 This command should be used with care. There is only one level of
4918 rollback, and there is no way to undo a rollback. It will also
4918 rollback, and there is no way to undo a rollback. It will also
4919 restore the dirstate at the time of the last transaction, losing
4919 restore the dirstate at the time of the last transaction, losing
4920 any dirstate changes since that time. This command does not alter
4920 any dirstate changes since that time. This command does not alter
4921 the working directory.
4921 the working directory.
4922
4922
4923 Transactions are used to encapsulate the effects of all commands
4923 Transactions are used to encapsulate the effects of all commands
4924 that create new changesets or propagate existing changesets into a
4924 that create new changesets or propagate existing changesets into a
4925 repository. For example, the following commands are transactional,
4925 repository. For example, the following commands are transactional,
4926 and their effects can be rolled back:
4926 and their effects can be rolled back:
4927
4927
4928 - commit
4928 - commit
4929 - import
4929 - import
4930 - pull
4930 - pull
4931 - push (with this repository as the destination)
4931 - push (with this repository as the destination)
4932 - unbundle
4932 - unbundle
4933
4933
4934 To avoid permanent data loss, rollback will refuse to rollback a
4934 To avoid permanent data loss, rollback will refuse to rollback a
4935 commit transaction if it isn't checked out. Use --force to
4935 commit transaction if it isn't checked out. Use --force to
4936 override this protection.
4936 override this protection.
4937
4937
4938 This command is not intended for use on public repositories. Once
4938 This command is not intended for use on public repositories. Once
4939 changes are visible for pull by other users, rolling a transaction
4939 changes are visible for pull by other users, rolling a transaction
4940 back locally is ineffective (someone else may already have pulled
4940 back locally is ineffective (someone else may already have pulled
4941 the changes). Furthermore, a race is possible with readers of the
4941 the changes). Furthermore, a race is possible with readers of the
4942 repository; for example an in-progress pull from the repository
4942 repository; for example an in-progress pull from the repository
4943 may fail if a rollback is performed.
4943 may fail if a rollback is performed.
4944
4944
4945 Returns 0 on success, 1 if no rollback data is available.
4945 Returns 0 on success, 1 if no rollback data is available.
4946 """
4946 """
4947 return repo.rollback(dryrun=opts.get('dry_run'),
4947 return repo.rollback(dryrun=opts.get('dry_run'),
4948 force=opts.get('force'))
4948 force=opts.get('force'))
4949
4949
4950 @command('root', [])
4950 @command('root', [])
4951 def root(ui, repo):
4951 def root(ui, repo):
4952 """print the root (top) of the current working directory
4952 """print the root (top) of the current working directory
4953
4953
4954 Print the root directory of the current repository.
4954 Print the root directory of the current repository.
4955
4955
4956 Returns 0 on success.
4956 Returns 0 on success.
4957 """
4957 """
4958 ui.write(repo.root + "\n")
4958 ui.write(repo.root + "\n")
4959
4959
4960 @command('^serve',
4960 @command('^serve',
4961 [('A', 'accesslog', '', _('name of access log file to write to'),
4961 [('A', 'accesslog', '', _('name of access log file to write to'),
4962 _('FILE')),
4962 _('FILE')),
4963 ('d', 'daemon', None, _('run server in background')),
4963 ('d', 'daemon', None, _('run server in background')),
4964 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4964 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4965 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4965 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4966 # use string type, then we can check if something was passed
4966 # use string type, then we can check if something was passed
4967 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4967 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4968 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4968 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4969 _('ADDR')),
4969 _('ADDR')),
4970 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4970 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4971 _('PREFIX')),
4971 _('PREFIX')),
4972 ('n', 'name', '',
4972 ('n', 'name', '',
4973 _('name to show in web pages (default: working directory)'), _('NAME')),
4973 _('name to show in web pages (default: working directory)'), _('NAME')),
4974 ('', 'web-conf', '',
4974 ('', 'web-conf', '',
4975 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4975 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4976 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4976 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4977 _('FILE')),
4977 _('FILE')),
4978 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4978 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4979 ('', 'stdio', None, _('for remote clients')),
4979 ('', 'stdio', None, _('for remote clients')),
4980 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4980 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4981 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4981 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4982 ('', 'style', '', _('template style to use'), _('STYLE')),
4982 ('', 'style', '', _('template style to use'), _('STYLE')),
4983 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4983 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4984 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4984 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4985 _('[OPTION]...'))
4985 _('[OPTION]...'))
4986 def serve(ui, repo, **opts):
4986 def serve(ui, repo, **opts):
4987 """start stand-alone webserver
4987 """start stand-alone webserver
4988
4988
4989 Start a local HTTP repository browser and pull server. You can use
4989 Start a local HTTP repository browser and pull server. You can use
4990 this for ad-hoc sharing and browsing of repositories. It is
4990 this for ad-hoc sharing and browsing of repositories. It is
4991 recommended to use a real web server to serve a repository for
4991 recommended to use a real web server to serve a repository for
4992 longer periods of time.
4992 longer periods of time.
4993
4993
4994 Please note that the server does not implement access control.
4994 Please note that the server does not implement access control.
4995 This means that, by default, anybody can read from the server and
4995 This means that, by default, anybody can read from the server and
4996 nobody can write to it by default. Set the ``web.allow_push``
4996 nobody can write to it by default. Set the ``web.allow_push``
4997 option to ``*`` to allow everybody to push to the server. You
4997 option to ``*`` to allow everybody to push to the server. You
4998 should use a real web server if you need to authenticate users.
4998 should use a real web server if you need to authenticate users.
4999
4999
5000 By default, the server logs accesses to stdout and errors to
5000 By default, the server logs accesses to stdout and errors to
5001 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5001 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5002 files.
5002 files.
5003
5003
5004 To have the server choose a free port number to listen on, specify
5004 To have the server choose a free port number to listen on, specify
5005 a port number of 0; in this case, the server will print the port
5005 a port number of 0; in this case, the server will print the port
5006 number it uses.
5006 number it uses.
5007
5007
5008 Returns 0 on success.
5008 Returns 0 on success.
5009 """
5009 """
5010
5010
5011 if opts["stdio"] and opts["cmdserver"]:
5011 if opts["stdio"] and opts["cmdserver"]:
5012 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5012 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5013
5013
5014 def checkrepo():
5014 def checkrepo():
5015 if repo is None:
5015 if repo is None:
5016 raise error.RepoError(_("There is no Mercurial repository here"
5016 raise error.RepoError(_("There is no Mercurial repository here"
5017 " (.hg not found)"))
5017 " (.hg not found)"))
5018
5018
5019 if opts["stdio"]:
5019 if opts["stdio"]:
5020 checkrepo()
5020 checkrepo()
5021 s = sshserver.sshserver(ui, repo)
5021 s = sshserver.sshserver(ui, repo)
5022 s.serve_forever()
5022 s.serve_forever()
5023
5023
5024 if opts["cmdserver"]:
5024 if opts["cmdserver"]:
5025 checkrepo()
5025 checkrepo()
5026 s = commandserver.server(ui, repo, opts["cmdserver"])
5026 s = commandserver.server(ui, repo, opts["cmdserver"])
5027 return s.serve()
5027 return s.serve()
5028
5028
5029 # this way we can check if something was given in the command-line
5029 # this way we can check if something was given in the command-line
5030 if opts.get('port'):
5030 if opts.get('port'):
5031 opts['port'] = util.getport(opts.get('port'))
5031 opts['port'] = util.getport(opts.get('port'))
5032
5032
5033 baseui = repo and repo.baseui or ui
5033 baseui = repo and repo.baseui or ui
5034 optlist = ("name templates style address port prefix ipv6"
5034 optlist = ("name templates style address port prefix ipv6"
5035 " accesslog errorlog certificate encoding")
5035 " accesslog errorlog certificate encoding")
5036 for o in optlist.split():
5036 for o in optlist.split():
5037 val = opts.get(o, '')
5037 val = opts.get(o, '')
5038 if val in (None, ''): # should check against default options instead
5038 if val in (None, ''): # should check against default options instead
5039 continue
5039 continue
5040 baseui.setconfig("web", o, val)
5040 baseui.setconfig("web", o, val)
5041 if repo and repo.ui != baseui:
5041 if repo and repo.ui != baseui:
5042 repo.ui.setconfig("web", o, val)
5042 repo.ui.setconfig("web", o, val)
5043
5043
5044 o = opts.get('web_conf') or opts.get('webdir_conf')
5044 o = opts.get('web_conf') or opts.get('webdir_conf')
5045 if not o:
5045 if not o:
5046 if not repo:
5046 if not repo:
5047 raise error.RepoError(_("There is no Mercurial repository"
5047 raise error.RepoError(_("There is no Mercurial repository"
5048 " here (.hg not found)"))
5048 " here (.hg not found)"))
5049 o = repo.root
5049 o = repo.root
5050
5050
5051 app = hgweb.hgweb(o, baseui=ui)
5051 app = hgweb.hgweb(o, baseui=ui)
5052
5052
5053 class service(object):
5053 class service(object):
5054 def init(self):
5054 def init(self):
5055 util.setsignalhandler()
5055 util.setsignalhandler()
5056 self.httpd = hgweb.server.create_server(ui, app)
5056 self.httpd = hgweb.server.create_server(ui, app)
5057
5057
5058 if opts['port'] and not ui.verbose:
5058 if opts['port'] and not ui.verbose:
5059 return
5059 return
5060
5060
5061 if self.httpd.prefix:
5061 if self.httpd.prefix:
5062 prefix = self.httpd.prefix.strip('/') + '/'
5062 prefix = self.httpd.prefix.strip('/') + '/'
5063 else:
5063 else:
5064 prefix = ''
5064 prefix = ''
5065
5065
5066 port = ':%d' % self.httpd.port
5066 port = ':%d' % self.httpd.port
5067 if port == ':80':
5067 if port == ':80':
5068 port = ''
5068 port = ''
5069
5069
5070 bindaddr = self.httpd.addr
5070 bindaddr = self.httpd.addr
5071 if bindaddr == '0.0.0.0':
5071 if bindaddr == '0.0.0.0':
5072 bindaddr = '*'
5072 bindaddr = '*'
5073 elif ':' in bindaddr: # IPv6
5073 elif ':' in bindaddr: # IPv6
5074 bindaddr = '[%s]' % bindaddr
5074 bindaddr = '[%s]' % bindaddr
5075
5075
5076 fqaddr = self.httpd.fqaddr
5076 fqaddr = self.httpd.fqaddr
5077 if ':' in fqaddr:
5077 if ':' in fqaddr:
5078 fqaddr = '[%s]' % fqaddr
5078 fqaddr = '[%s]' % fqaddr
5079 if opts['port']:
5079 if opts['port']:
5080 write = ui.status
5080 write = ui.status
5081 else:
5081 else:
5082 write = ui.write
5082 write = ui.write
5083 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5083 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5084 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5084 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5085
5085
5086 def run(self):
5086 def run(self):
5087 self.httpd.serve_forever()
5087 self.httpd.serve_forever()
5088
5088
5089 service = service()
5089 service = service()
5090
5090
5091 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5091 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5092
5092
5093 @command('showconfig|debugconfig',
5093 @command('showconfig|debugconfig',
5094 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5094 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5095 _('[-u] [NAME]...'))
5095 _('[-u] [NAME]...'))
5096 def showconfig(ui, repo, *values, **opts):
5096 def showconfig(ui, repo, *values, **opts):
5097 """show combined config settings from all hgrc files
5097 """show combined config settings from all hgrc files
5098
5098
5099 With no arguments, print names and values of all config items.
5099 With no arguments, print names and values of all config items.
5100
5100
5101 With one argument of the form section.name, print just the value
5101 With one argument of the form section.name, print just the value
5102 of that config item.
5102 of that config item.
5103
5103
5104 With multiple arguments, print names and values of all config
5104 With multiple arguments, print names and values of all config
5105 items with matching section names.
5105 items with matching section names.
5106
5106
5107 With --debug, the source (filename and line number) is printed
5107 With --debug, the source (filename and line number) is printed
5108 for each config item.
5108 for each config item.
5109
5109
5110 Returns 0 on success.
5110 Returns 0 on success.
5111 """
5111 """
5112
5112
5113 for f in scmutil.rcpath():
5113 for f in scmutil.rcpath():
5114 ui.debug('read config from: %s\n' % f)
5114 ui.debug('read config from: %s\n' % f)
5115 untrusted = bool(opts.get('untrusted'))
5115 untrusted = bool(opts.get('untrusted'))
5116 if values:
5116 if values:
5117 sections = [v for v in values if '.' not in v]
5117 sections = [v for v in values if '.' not in v]
5118 items = [v for v in values if '.' in v]
5118 items = [v for v in values if '.' in v]
5119 if len(items) > 1 or items and sections:
5119 if len(items) > 1 or items and sections:
5120 raise util.Abort(_('only one config item permitted'))
5120 raise util.Abort(_('only one config item permitted'))
5121 for section, name, value in ui.walkconfig(untrusted=untrusted):
5121 for section, name, value in ui.walkconfig(untrusted=untrusted):
5122 value = str(value).replace('\n', '\\n')
5122 value = str(value).replace('\n', '\\n')
5123 sectname = section + '.' + name
5123 sectname = section + '.' + name
5124 if values:
5124 if values:
5125 for v in values:
5125 for v in values:
5126 if v == section:
5126 if v == section:
5127 ui.debug('%s: ' %
5127 ui.debug('%s: ' %
5128 ui.configsource(section, name, untrusted))
5128 ui.configsource(section, name, untrusted))
5129 ui.write('%s=%s\n' % (sectname, value))
5129 ui.write('%s=%s\n' % (sectname, value))
5130 elif v == sectname:
5130 elif v == sectname:
5131 ui.debug('%s: ' %
5131 ui.debug('%s: ' %
5132 ui.configsource(section, name, untrusted))
5132 ui.configsource(section, name, untrusted))
5133 ui.write(value, '\n')
5133 ui.write(value, '\n')
5134 else:
5134 else:
5135 ui.debug('%s: ' %
5135 ui.debug('%s: ' %
5136 ui.configsource(section, name, untrusted))
5136 ui.configsource(section, name, untrusted))
5137 ui.write('%s=%s\n' % (sectname, value))
5137 ui.write('%s=%s\n' % (sectname, value))
5138
5138
5139 @command('^status|st',
5139 @command('^status|st',
5140 [('A', 'all', None, _('show status of all files')),
5140 [('A', 'all', None, _('show status of all files')),
5141 ('m', 'modified', None, _('show only modified files')),
5141 ('m', 'modified', None, _('show only modified files')),
5142 ('a', 'added', None, _('show only added files')),
5142 ('a', 'added', None, _('show only added files')),
5143 ('r', 'removed', None, _('show only removed files')),
5143 ('r', 'removed', None, _('show only removed files')),
5144 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5144 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5145 ('c', 'clean', None, _('show only files without changes')),
5145 ('c', 'clean', None, _('show only files without changes')),
5146 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5146 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5147 ('i', 'ignored', None, _('show only ignored files')),
5147 ('i', 'ignored', None, _('show only ignored files')),
5148 ('n', 'no-status', None, _('hide status prefix')),
5148 ('n', 'no-status', None, _('hide status prefix')),
5149 ('C', 'copies', None, _('show source of copied files')),
5149 ('C', 'copies', None, _('show source of copied files')),
5150 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5150 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5151 ('', 'rev', [], _('show difference from revision'), _('REV')),
5151 ('', 'rev', [], _('show difference from revision'), _('REV')),
5152 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5152 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5153 ] + walkopts + subrepoopts,
5153 ] + walkopts + subrepoopts,
5154 _('[OPTION]... [FILE]...'))
5154 _('[OPTION]... [FILE]...'))
5155 def status(ui, repo, *pats, **opts):
5155 def status(ui, repo, *pats, **opts):
5156 """show changed files in the working directory
5156 """show changed files in the working directory
5157
5157
5158 Show status of files in the repository. If names are given, only
5158 Show status of files in the repository. If names are given, only
5159 files that match are shown. Files that are clean or ignored or
5159 files that match are shown. Files that are clean or ignored or
5160 the source of a copy/move operation, are not listed unless
5160 the source of a copy/move operation, are not listed unless
5161 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5161 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5162 Unless options described with "show only ..." are given, the
5162 Unless options described with "show only ..." are given, the
5163 options -mardu are used.
5163 options -mardu are used.
5164
5164
5165 Option -q/--quiet hides untracked (unknown and ignored) files
5165 Option -q/--quiet hides untracked (unknown and ignored) files
5166 unless explicitly requested with -u/--unknown or -i/--ignored.
5166 unless explicitly requested with -u/--unknown or -i/--ignored.
5167
5167
5168 .. note::
5168 .. note::
5169 status may appear to disagree with diff if permissions have
5169 status may appear to disagree with diff if permissions have
5170 changed or a merge has occurred. The standard diff format does
5170 changed or a merge has occurred. The standard diff format does
5171 not report permission changes and diff only reports changes
5171 not report permission changes and diff only reports changes
5172 relative to one merge parent.
5172 relative to one merge parent.
5173
5173
5174 If one revision is given, it is used as the base revision.
5174 If one revision is given, it is used as the base revision.
5175 If two revisions are given, the differences between them are
5175 If two revisions are given, the differences between them are
5176 shown. The --change option can also be used as a shortcut to list
5176 shown. The --change option can also be used as a shortcut to list
5177 the changed files of a revision from its first parent.
5177 the changed files of a revision from its first parent.
5178
5178
5179 The codes used to show the status of files are::
5179 The codes used to show the status of files are::
5180
5180
5181 M = modified
5181 M = modified
5182 A = added
5182 A = added
5183 R = removed
5183 R = removed
5184 C = clean
5184 C = clean
5185 ! = missing (deleted by non-hg command, but still tracked)
5185 ! = missing (deleted by non-hg command, but still tracked)
5186 ? = not tracked
5186 ? = not tracked
5187 I = ignored
5187 I = ignored
5188 = origin of the previous file listed as A (added)
5188 = origin of the previous file listed as A (added)
5189
5189
5190 .. container:: verbose
5190 .. container:: verbose
5191
5191
5192 Examples:
5192 Examples:
5193
5193
5194 - show changes in the working directory relative to a
5194 - show changes in the working directory relative to a
5195 changeset::
5195 changeset::
5196
5196
5197 hg status --rev 9353
5197 hg status --rev 9353
5198
5198
5199 - show all changes including copies in an existing changeset::
5199 - show all changes including copies in an existing changeset::
5200
5200
5201 hg status --copies --change 9353
5201 hg status --copies --change 9353
5202
5202
5203 - get a NUL separated list of added files, suitable for xargs::
5203 - get a NUL separated list of added files, suitable for xargs::
5204
5204
5205 hg status -an0
5205 hg status -an0
5206
5206
5207 Returns 0 on success.
5207 Returns 0 on success.
5208 """
5208 """
5209
5209
5210 revs = opts.get('rev')
5210 revs = opts.get('rev')
5211 change = opts.get('change')
5211 change = opts.get('change')
5212
5212
5213 if revs and change:
5213 if revs and change:
5214 msg = _('cannot specify --rev and --change at the same time')
5214 msg = _('cannot specify --rev and --change at the same time')
5215 raise util.Abort(msg)
5215 raise util.Abort(msg)
5216 elif change:
5216 elif change:
5217 node2 = scmutil.revsingle(repo, change, None).node()
5217 node2 = scmutil.revsingle(repo, change, None).node()
5218 node1 = repo[node2].p1().node()
5218 node1 = repo[node2].p1().node()
5219 else:
5219 else:
5220 node1, node2 = scmutil.revpair(repo, revs)
5220 node1, node2 = scmutil.revpair(repo, revs)
5221
5221
5222 cwd = (pats and repo.getcwd()) or ''
5222 cwd = (pats and repo.getcwd()) or ''
5223 end = opts.get('print0') and '\0' or '\n'
5223 end = opts.get('print0') and '\0' or '\n'
5224 copy = {}
5224 copy = {}
5225 states = 'modified added removed deleted unknown ignored clean'.split()
5225 states = 'modified added removed deleted unknown ignored clean'.split()
5226 show = [k for k in states if opts.get(k)]
5226 show = [k for k in states if opts.get(k)]
5227 if opts.get('all'):
5227 if opts.get('all'):
5228 show += ui.quiet and (states[:4] + ['clean']) or states
5228 show += ui.quiet and (states[:4] + ['clean']) or states
5229 if not show:
5229 if not show:
5230 show = ui.quiet and states[:4] or states[:5]
5230 show = ui.quiet and states[:4] or states[:5]
5231
5231
5232 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5232 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5233 'ignored' in show, 'clean' in show, 'unknown' in show,
5233 'ignored' in show, 'clean' in show, 'unknown' in show,
5234 opts.get('subrepos'))
5234 opts.get('subrepos'))
5235 changestates = zip(states, 'MAR!?IC', stat)
5235 changestates = zip(states, 'MAR!?IC', stat)
5236
5236
5237 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5237 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5238 copy = copies.pathcopies(repo[node1], repo[node2])
5238 copy = copies.pathcopies(repo[node1], repo[node2])
5239
5239
5240 fm = ui.formatter('status', opts)
5240 fm = ui.formatter('status', opts)
5241 format = '%s %s' + end
5241 format = '%s %s' + end
5242 if opts.get('no_status'):
5242 if opts.get('no_status'):
5243 format = '%.0s%s' + end
5243 format = '%.0s%s' + end
5244
5244
5245 for state, char, files in changestates:
5245 for state, char, files in changestates:
5246 if state in show:
5246 if state in show:
5247 label = 'status.' + state
5247 label = 'status.' + state
5248 for f in files:
5248 for f in files:
5249 fm.startitem()
5249 fm.startitem()
5250 fm.write("status path", format, char,
5250 fm.write("status path", format, char,
5251 repo.pathto(f, cwd), label=label)
5251 repo.pathto(f, cwd), label=label)
5252 if f in copy:
5252 if f in copy:
5253 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5253 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5254 label='status.copied')
5254 label='status.copied')
5255 fm.end()
5255 fm.end()
5256
5256
5257 @command('^summary|sum',
5257 @command('^summary|sum',
5258 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5258 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5259 def summary(ui, repo, **opts):
5259 def summary(ui, repo, **opts):
5260 """summarize working directory state
5260 """summarize working directory state
5261
5261
5262 This generates a brief summary of the working directory state,
5262 This generates a brief summary of the working directory state,
5263 including parents, branch, commit status, and available updates.
5263 including parents, branch, commit status, and available updates.
5264
5264
5265 With the --remote option, this will check the default paths for
5265 With the --remote option, this will check the default paths for
5266 incoming and outgoing changes. This can be time-consuming.
5266 incoming and outgoing changes. This can be time-consuming.
5267
5267
5268 Returns 0 on success.
5268 Returns 0 on success.
5269 """
5269 """
5270
5270
5271 ctx = repo[None]
5271 ctx = repo[None]
5272 parents = ctx.parents()
5272 parents = ctx.parents()
5273 pnode = parents[0].node()
5273 pnode = parents[0].node()
5274 marks = []
5274 marks = []
5275
5275
5276 for p in parents:
5276 for p in parents:
5277 # label with log.changeset (instead of log.parent) since this
5277 # label with log.changeset (instead of log.parent) since this
5278 # shows a working directory parent *changeset*:
5278 # shows a working directory parent *changeset*:
5279 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5279 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5280 label='log.changeset')
5280 label='log.changeset')
5281 ui.write(' '.join(p.tags()), label='log.tag')
5281 ui.write(' '.join(p.tags()), label='log.tag')
5282 if p.bookmarks():
5282 if p.bookmarks():
5283 marks.extend(p.bookmarks())
5283 marks.extend(p.bookmarks())
5284 if p.rev() == -1:
5284 if p.rev() == -1:
5285 if not len(repo):
5285 if not len(repo):
5286 ui.write(_(' (empty repository)'))
5286 ui.write(_(' (empty repository)'))
5287 else:
5287 else:
5288 ui.write(_(' (no revision checked out)'))
5288 ui.write(_(' (no revision checked out)'))
5289 ui.write('\n')
5289 ui.write('\n')
5290 if p.description():
5290 if p.description():
5291 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5291 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5292 label='log.summary')
5292 label='log.summary')
5293
5293
5294 branch = ctx.branch()
5294 branch = ctx.branch()
5295 bheads = repo.branchheads(branch)
5295 bheads = repo.branchheads(branch)
5296 m = _('branch: %s\n') % branch
5296 m = _('branch: %s\n') % branch
5297 if branch != 'default':
5297 if branch != 'default':
5298 ui.write(m, label='log.branch')
5298 ui.write(m, label='log.branch')
5299 else:
5299 else:
5300 ui.status(m, label='log.branch')
5300 ui.status(m, label='log.branch')
5301
5301
5302 if marks:
5302 if marks:
5303 current = repo._bookmarkcurrent
5303 current = repo._bookmarkcurrent
5304 ui.write(_('bookmarks:'), label='log.bookmark')
5304 ui.write(_('bookmarks:'), label='log.bookmark')
5305 if current is not None:
5305 if current is not None:
5306 try:
5306 try:
5307 marks.remove(current)
5307 marks.remove(current)
5308 ui.write(' *' + current, label='bookmarks.current')
5308 ui.write(' *' + current, label='bookmarks.current')
5309 except ValueError:
5309 except ValueError:
5310 # current bookmark not in parent ctx marks
5310 # current bookmark not in parent ctx marks
5311 pass
5311 pass
5312 for m in marks:
5312 for m in marks:
5313 ui.write(' ' + m, label='log.bookmark')
5313 ui.write(' ' + m, label='log.bookmark')
5314 ui.write('\n', label='log.bookmark')
5314 ui.write('\n', label='log.bookmark')
5315
5315
5316 st = list(repo.status(unknown=True))[:6]
5316 st = list(repo.status(unknown=True))[:6]
5317
5317
5318 c = repo.dirstate.copies()
5318 c = repo.dirstate.copies()
5319 copied, renamed = [], []
5319 copied, renamed = [], []
5320 for d, s in c.iteritems():
5320 for d, s in c.iteritems():
5321 if s in st[2]:
5321 if s in st[2]:
5322 st[2].remove(s)
5322 st[2].remove(s)
5323 renamed.append(d)
5323 renamed.append(d)
5324 else:
5324 else:
5325 copied.append(d)
5325 copied.append(d)
5326 if d in st[1]:
5326 if d in st[1]:
5327 st[1].remove(d)
5327 st[1].remove(d)
5328 st.insert(3, renamed)
5328 st.insert(3, renamed)
5329 st.insert(4, copied)
5329 st.insert(4, copied)
5330
5330
5331 ms = mergemod.mergestate(repo)
5331 ms = mergemod.mergestate(repo)
5332 st.append([f for f in ms if ms[f] == 'u'])
5332 st.append([f for f in ms if ms[f] == 'u'])
5333
5333
5334 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5334 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5335 st.append(subs)
5335 st.append(subs)
5336
5336
5337 labels = [ui.label(_('%d modified'), 'status.modified'),
5337 labels = [ui.label(_('%d modified'), 'status.modified'),
5338 ui.label(_('%d added'), 'status.added'),
5338 ui.label(_('%d added'), 'status.added'),
5339 ui.label(_('%d removed'), 'status.removed'),
5339 ui.label(_('%d removed'), 'status.removed'),
5340 ui.label(_('%d renamed'), 'status.copied'),
5340 ui.label(_('%d renamed'), 'status.copied'),
5341 ui.label(_('%d copied'), 'status.copied'),
5341 ui.label(_('%d copied'), 'status.copied'),
5342 ui.label(_('%d deleted'), 'status.deleted'),
5342 ui.label(_('%d deleted'), 'status.deleted'),
5343 ui.label(_('%d unknown'), 'status.unknown'),
5343 ui.label(_('%d unknown'), 'status.unknown'),
5344 ui.label(_('%d ignored'), 'status.ignored'),
5344 ui.label(_('%d ignored'), 'status.ignored'),
5345 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5345 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5346 ui.label(_('%d subrepos'), 'status.modified')]
5346 ui.label(_('%d subrepos'), 'status.modified')]
5347 t = []
5347 t = []
5348 for s, l in zip(st, labels):
5348 for s, l in zip(st, labels):
5349 if s:
5349 if s:
5350 t.append(l % len(s))
5350 t.append(l % len(s))
5351
5351
5352 t = ', '.join(t)
5352 t = ', '.join(t)
5353 cleanworkdir = False
5353 cleanworkdir = False
5354
5354
5355 if len(parents) > 1:
5355 if len(parents) > 1:
5356 t += _(' (merge)')
5356 t += _(' (merge)')
5357 elif branch != parents[0].branch():
5357 elif branch != parents[0].branch():
5358 t += _(' (new branch)')
5358 t += _(' (new branch)')
5359 elif (parents[0].extra().get('close') and
5359 elif (parents[0].extra().get('close') and
5360 pnode in repo.branchheads(branch, closed=True)):
5360 pnode in repo.branchheads(branch, closed=True)):
5361 t += _(' (head closed)')
5361 t += _(' (head closed)')
5362 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5362 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5363 t += _(' (clean)')
5363 t += _(' (clean)')
5364 cleanworkdir = True
5364 cleanworkdir = True
5365 elif pnode not in bheads:
5365 elif pnode not in bheads:
5366 t += _(' (new branch head)')
5366 t += _(' (new branch head)')
5367
5367
5368 if cleanworkdir:
5368 if cleanworkdir:
5369 ui.status(_('commit: %s\n') % t.strip())
5369 ui.status(_('commit: %s\n') % t.strip())
5370 else:
5370 else:
5371 ui.write(_('commit: %s\n') % t.strip())
5371 ui.write(_('commit: %s\n') % t.strip())
5372
5372
5373 # all ancestors of branch heads - all ancestors of parent = new csets
5373 # all ancestors of branch heads - all ancestors of parent = new csets
5374 new = [0] * len(repo)
5374 new = [0] * len(repo)
5375 cl = repo.changelog
5375 cl = repo.changelog
5376 for a in [cl.rev(n) for n in bheads]:
5376 for a in [cl.rev(n) for n in bheads]:
5377 new[a] = 1
5377 new[a] = 1
5378 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5378 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5379 new[a] = 1
5379 new[a] = 1
5380 for a in [p.rev() for p in parents]:
5380 for a in [p.rev() for p in parents]:
5381 if a >= 0:
5381 if a >= 0:
5382 new[a] = 0
5382 new[a] = 0
5383 for a in cl.ancestors(*[p.rev() for p in parents]):
5383 for a in cl.ancestors(*[p.rev() for p in parents]):
5384 new[a] = 0
5384 new[a] = 0
5385 new = sum(new)
5385 new = sum(new)
5386
5386
5387 if new == 0:
5387 if new == 0:
5388 ui.status(_('update: (current)\n'))
5388 ui.status(_('update: (current)\n'))
5389 elif pnode not in bheads:
5389 elif pnode not in bheads:
5390 ui.write(_('update: %d new changesets (update)\n') % new)
5390 ui.write(_('update: %d new changesets (update)\n') % new)
5391 else:
5391 else:
5392 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5392 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5393 (new, len(bheads)))
5393 (new, len(bheads)))
5394
5394
5395 if opts.get('remote'):
5395 if opts.get('remote'):
5396 t = []
5396 t = []
5397 source, branches = hg.parseurl(ui.expandpath('default'))
5397 source, branches = hg.parseurl(ui.expandpath('default'))
5398 other = hg.peer(repo, {}, source)
5398 other = hg.peer(repo, {}, source)
5399 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5399 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5400 ui.debug('comparing with %s\n' % util.hidepassword(source))
5400 ui.debug('comparing with %s\n' % util.hidepassword(source))
5401 repo.ui.pushbuffer()
5401 repo.ui.pushbuffer()
5402 commoninc = discovery.findcommonincoming(repo, other)
5402 commoninc = discovery.findcommonincoming(repo, other)
5403 _common, incoming, _rheads = commoninc
5403 _common, incoming, _rheads = commoninc
5404 repo.ui.popbuffer()
5404 repo.ui.popbuffer()
5405 if incoming:
5405 if incoming:
5406 t.append(_('1 or more incoming'))
5406 t.append(_('1 or more incoming'))
5407
5407
5408 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5408 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5409 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5409 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5410 if source != dest:
5410 if source != dest:
5411 other = hg.peer(repo, {}, dest)
5411 other = hg.peer(repo, {}, dest)
5412 commoninc = None
5412 commoninc = None
5413 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5413 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5414 repo.ui.pushbuffer()
5414 repo.ui.pushbuffer()
5415 outgoing = discovery.findcommonoutgoing(repo, other,
5415 outgoing = discovery.findcommonoutgoing(repo, other,
5416 commoninc=commoninc)
5416 commoninc=commoninc)
5417 repo.ui.popbuffer()
5417 repo.ui.popbuffer()
5418 o = outgoing.missing
5418 o = outgoing.missing
5419 if o:
5419 if o:
5420 t.append(_('%d outgoing') % len(o))
5420 t.append(_('%d outgoing') % len(o))
5421 if 'bookmarks' in other.listkeys('namespaces'):
5421 if 'bookmarks' in other.listkeys('namespaces'):
5422 lmarks = repo.listkeys('bookmarks')
5422 lmarks = repo.listkeys('bookmarks')
5423 rmarks = other.listkeys('bookmarks')
5423 rmarks = other.listkeys('bookmarks')
5424 diff = set(rmarks) - set(lmarks)
5424 diff = set(rmarks) - set(lmarks)
5425 if len(diff) > 0:
5425 if len(diff) > 0:
5426 t.append(_('%d incoming bookmarks') % len(diff))
5426 t.append(_('%d incoming bookmarks') % len(diff))
5427 diff = set(lmarks) - set(rmarks)
5427 diff = set(lmarks) - set(rmarks)
5428 if len(diff) > 0:
5428 if len(diff) > 0:
5429 t.append(_('%d outgoing bookmarks') % len(diff))
5429 t.append(_('%d outgoing bookmarks') % len(diff))
5430
5430
5431 if t:
5431 if t:
5432 ui.write(_('remote: %s\n') % (', '.join(t)))
5432 ui.write(_('remote: %s\n') % (', '.join(t)))
5433 else:
5433 else:
5434 ui.status(_('remote: (synced)\n'))
5434 ui.status(_('remote: (synced)\n'))
5435
5435
5436 @command('tag',
5436 @command('tag',
5437 [('f', 'force', None, _('force tag')),
5437 [('f', 'force', None, _('force tag')),
5438 ('l', 'local', None, _('make the tag local')),
5438 ('l', 'local', None, _('make the tag local')),
5439 ('r', 'rev', '', _('revision to tag'), _('REV')),
5439 ('r', 'rev', '', _('revision to tag'), _('REV')),
5440 ('', 'remove', None, _('remove a tag')),
5440 ('', 'remove', None, _('remove a tag')),
5441 # -l/--local is already there, commitopts cannot be used
5441 # -l/--local is already there, commitopts cannot be used
5442 ('e', 'edit', None, _('edit commit message')),
5442 ('e', 'edit', None, _('edit commit message')),
5443 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5443 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5444 ] + commitopts2,
5444 ] + commitopts2,
5445 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5445 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5446 def tag(ui, repo, name1, *names, **opts):
5446 def tag(ui, repo, name1, *names, **opts):
5447 """add one or more tags for the current or given revision
5447 """add one or more tags for the current or given revision
5448
5448
5449 Name a particular revision using <name>.
5449 Name a particular revision using <name>.
5450
5450
5451 Tags are used to name particular revisions of the repository and are
5451 Tags are used to name particular revisions of the repository and are
5452 very useful to compare different revisions, to go back to significant
5452 very useful to compare different revisions, to go back to significant
5453 earlier versions or to mark branch points as releases, etc. Changing
5453 earlier versions or to mark branch points as releases, etc. Changing
5454 an existing tag is normally disallowed; use -f/--force to override.
5454 an existing tag is normally disallowed; use -f/--force to override.
5455
5455
5456 If no revision is given, the parent of the working directory is
5456 If no revision is given, the parent of the working directory is
5457 used, or tip if no revision is checked out.
5457 used, or tip if no revision is checked out.
5458
5458
5459 To facilitate version control, distribution, and merging of tags,
5459 To facilitate version control, distribution, and merging of tags,
5460 they are stored as a file named ".hgtags" which is managed similarly
5460 they are stored as a file named ".hgtags" which is managed similarly
5461 to other project files and can be hand-edited if necessary. This
5461 to other project files and can be hand-edited if necessary. This
5462 also means that tagging creates a new commit. The file
5462 also means that tagging creates a new commit. The file
5463 ".hg/localtags" is used for local tags (not shared among
5463 ".hg/localtags" is used for local tags (not shared among
5464 repositories).
5464 repositories).
5465
5465
5466 Tag commits are usually made at the head of a branch. If the parent
5466 Tag commits are usually made at the head of a branch. If the parent
5467 of the working directory is not a branch head, :hg:`tag` aborts; use
5467 of the working directory is not a branch head, :hg:`tag` aborts; use
5468 -f/--force to force the tag commit to be based on a non-head
5468 -f/--force to force the tag commit to be based on a non-head
5469 changeset.
5469 changeset.
5470
5470
5471 See :hg:`help dates` for a list of formats valid for -d/--date.
5471 See :hg:`help dates` for a list of formats valid for -d/--date.
5472
5472
5473 Since tag names have priority over branch names during revision
5473 Since tag names have priority over branch names during revision
5474 lookup, using an existing branch name as a tag name is discouraged.
5474 lookup, using an existing branch name as a tag name is discouraged.
5475
5475
5476 Returns 0 on success.
5476 Returns 0 on success.
5477 """
5477 """
5478 wlock = lock = None
5478 wlock = lock = None
5479 try:
5479 try:
5480 wlock = repo.wlock()
5480 wlock = repo.wlock()
5481 lock = repo.lock()
5481 lock = repo.lock()
5482 rev_ = "."
5482 rev_ = "."
5483 names = [t.strip() for t in (name1,) + names]
5483 names = [t.strip() for t in (name1,) + names]
5484 if len(names) != len(set(names)):
5484 if len(names) != len(set(names)):
5485 raise util.Abort(_('tag names must be unique'))
5485 raise util.Abort(_('tag names must be unique'))
5486 for n in names:
5486 for n in names:
5487 if n in ['tip', '.', 'null']:
5487 if n in ['tip', '.', 'null']:
5488 raise util.Abort(_("the name '%s' is reserved") % n)
5488 raise util.Abort(_("the name '%s' is reserved") % n)
5489 if not n:
5489 if not n:
5490 raise util.Abort(_('tag names cannot consist entirely of '
5490 raise util.Abort(_('tag names cannot consist entirely of '
5491 'whitespace'))
5491 'whitespace'))
5492 if opts.get('rev') and opts.get('remove'):
5492 if opts.get('rev') and opts.get('remove'):
5493 raise util.Abort(_("--rev and --remove are incompatible"))
5493 raise util.Abort(_("--rev and --remove are incompatible"))
5494 if opts.get('rev'):
5494 if opts.get('rev'):
5495 rev_ = opts['rev']
5495 rev_ = opts['rev']
5496 message = opts.get('message')
5496 message = opts.get('message')
5497 if opts.get('remove'):
5497 if opts.get('remove'):
5498 expectedtype = opts.get('local') and 'local' or 'global'
5498 expectedtype = opts.get('local') and 'local' or 'global'
5499 for n in names:
5499 for n in names:
5500 if not repo.tagtype(n):
5500 if not repo.tagtype(n):
5501 raise util.Abort(_("tag '%s' does not exist") % n)
5501 raise util.Abort(_("tag '%s' does not exist") % n)
5502 if repo.tagtype(n) != expectedtype:
5502 if repo.tagtype(n) != expectedtype:
5503 if expectedtype == 'global':
5503 if expectedtype == 'global':
5504 raise util.Abort(_("tag '%s' is not a global tag") % n)
5504 raise util.Abort(_("tag '%s' is not a global tag") % n)
5505 else:
5505 else:
5506 raise util.Abort(_("tag '%s' is not a local tag") % n)
5506 raise util.Abort(_("tag '%s' is not a local tag") % n)
5507 rev_ = nullid
5507 rev_ = nullid
5508 if not message:
5508 if not message:
5509 # we don't translate commit messages
5509 # we don't translate commit messages
5510 message = 'Removed tag %s' % ', '.join(names)
5510 message = 'Removed tag %s' % ', '.join(names)
5511 elif not opts.get('force'):
5511 elif not opts.get('force'):
5512 for n in names:
5512 for n in names:
5513 if n in repo.tags():
5513 if n in repo.tags():
5514 raise util.Abort(_("tag '%s' already exists "
5514 raise util.Abort(_("tag '%s' already exists "
5515 "(use -f to force)") % n)
5515 "(use -f to force)") % n)
5516 if not opts.get('local'):
5516 if not opts.get('local'):
5517 p1, p2 = repo.dirstate.parents()
5517 p1, p2 = repo.dirstate.parents()
5518 if p2 != nullid:
5518 if p2 != nullid:
5519 raise util.Abort(_('uncommitted merge'))
5519 raise util.Abort(_('uncommitted merge'))
5520 bheads = repo.branchheads()
5520 bheads = repo.branchheads()
5521 if not opts.get('force') and bheads and p1 not in bheads:
5521 if not opts.get('force') and bheads and p1 not in bheads:
5522 raise util.Abort(_('not at a branch head (use -f to force)'))
5522 raise util.Abort(_('not at a branch head (use -f to force)'))
5523 r = scmutil.revsingle(repo, rev_).node()
5523 r = scmutil.revsingle(repo, rev_).node()
5524
5524
5525 if not message:
5525 if not message:
5526 # we don't translate commit messages
5526 # we don't translate commit messages
5527 message = ('Added tag %s for changeset %s' %
5527 message = ('Added tag %s for changeset %s' %
5528 (', '.join(names), short(r)))
5528 (', '.join(names), short(r)))
5529
5529
5530 date = opts.get('date')
5530 date = opts.get('date')
5531 if date:
5531 if date:
5532 date = util.parsedate(date)
5532 date = util.parsedate(date)
5533
5533
5534 if opts.get('edit'):
5534 if opts.get('edit'):
5535 message = ui.edit(message, ui.username())
5535 message = ui.edit(message, ui.username())
5536
5536
5537 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5537 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5538 finally:
5538 finally:
5539 release(lock, wlock)
5539 release(lock, wlock)
5540
5540
5541 @command('tags', [], '')
5541 @command('tags', [], '')
5542 def tags(ui, repo):
5542 def tags(ui, repo):
5543 """list repository tags
5543 """list repository tags
5544
5544
5545 This lists both regular and local tags. When the -v/--verbose
5545 This lists both regular and local tags. When the -v/--verbose
5546 switch is used, a third column "local" is printed for local tags.
5546 switch is used, a third column "local" is printed for local tags.
5547
5547
5548 Returns 0 on success.
5548 Returns 0 on success.
5549 """
5549 """
5550
5550
5551 hexfunc = ui.debugflag and hex or short
5551 hexfunc = ui.debugflag and hex or short
5552 tagtype = ""
5552 tagtype = ""
5553
5553
5554 for t, n in reversed(repo.tagslist()):
5554 for t, n in reversed(repo.tagslist()):
5555 if ui.quiet:
5555 if ui.quiet:
5556 ui.write("%s\n" % t, label='tags.normal')
5556 ui.write("%s\n" % t, label='tags.normal')
5557 continue
5557 continue
5558
5558
5559 hn = hexfunc(n)
5559 hn = hexfunc(n)
5560 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5560 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5561 rev = ui.label(r, 'log.changeset')
5561 rev = ui.label(r, 'log.changeset')
5562 spaces = " " * (30 - encoding.colwidth(t))
5562 spaces = " " * (30 - encoding.colwidth(t))
5563
5563
5564 tag = ui.label(t, 'tags.normal')
5564 tag = ui.label(t, 'tags.normal')
5565 if ui.verbose:
5565 if ui.verbose:
5566 if repo.tagtype(t) == 'local':
5566 if repo.tagtype(t) == 'local':
5567 tagtype = " local"
5567 tagtype = " local"
5568 tag = ui.label(t, 'tags.local')
5568 tag = ui.label(t, 'tags.local')
5569 else:
5569 else:
5570 tagtype = ""
5570 tagtype = ""
5571 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5571 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5572
5572
5573 @command('tip',
5573 @command('tip',
5574 [('p', 'patch', None, _('show patch')),
5574 [('p', 'patch', None, _('show patch')),
5575 ('g', 'git', None, _('use git extended diff format')),
5575 ('g', 'git', None, _('use git extended diff format')),
5576 ] + templateopts,
5576 ] + templateopts,
5577 _('[-p] [-g]'))
5577 _('[-p] [-g]'))
5578 def tip(ui, repo, **opts):
5578 def tip(ui, repo, **opts):
5579 """show the tip revision
5579 """show the tip revision
5580
5580
5581 The tip revision (usually just called the tip) is the changeset
5581 The tip revision (usually just called the tip) is the changeset
5582 most recently added to the repository (and therefore the most
5582 most recently added to the repository (and therefore the most
5583 recently changed head).
5583 recently changed head).
5584
5584
5585 If you have just made a commit, that commit will be the tip. If
5585 If you have just made a commit, that commit will be the tip. If
5586 you have just pulled changes from another repository, the tip of
5586 you have just pulled changes from another repository, the tip of
5587 that repository becomes the current tip. The "tip" tag is special
5587 that repository becomes the current tip. The "tip" tag is special
5588 and cannot be renamed or assigned to a different changeset.
5588 and cannot be renamed or assigned to a different changeset.
5589
5589
5590 Returns 0 on success.
5590 Returns 0 on success.
5591 """
5591 """
5592 displayer = cmdutil.show_changeset(ui, repo, opts)
5592 displayer = cmdutil.show_changeset(ui, repo, opts)
5593 displayer.show(repo[len(repo) - 1])
5593 displayer.show(repo[len(repo) - 1])
5594 displayer.close()
5594 displayer.close()
5595
5595
5596 @command('unbundle',
5596 @command('unbundle',
5597 [('u', 'update', None,
5597 [('u', 'update', None,
5598 _('update to new branch head if changesets were unbundled'))],
5598 _('update to new branch head if changesets were unbundled'))],
5599 _('[-u] FILE...'))
5599 _('[-u] FILE...'))
5600 def unbundle(ui, repo, fname1, *fnames, **opts):
5600 def unbundle(ui, repo, fname1, *fnames, **opts):
5601 """apply one or more changegroup files
5601 """apply one or more changegroup files
5602
5602
5603 Apply one or more compressed changegroup files generated by the
5603 Apply one or more compressed changegroup files generated by the
5604 bundle command.
5604 bundle command.
5605
5605
5606 Returns 0 on success, 1 if an update has unresolved files.
5606 Returns 0 on success, 1 if an update has unresolved files.
5607 """
5607 """
5608 fnames = (fname1,) + fnames
5608 fnames = (fname1,) + fnames
5609
5609
5610 lock = repo.lock()
5610 lock = repo.lock()
5611 wc = repo['.']
5611 wc = repo['.']
5612 try:
5612 try:
5613 for fname in fnames:
5613 for fname in fnames:
5614 f = url.open(ui, fname)
5614 f = url.open(ui, fname)
5615 gen = changegroup.readbundle(f, fname)
5615 gen = changegroup.readbundle(f, fname)
5616 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5616 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5617 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5617 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5618 finally:
5618 finally:
5619 lock.release()
5619 lock.release()
5620 return postincoming(ui, repo, modheads, opts.get('update'), None)
5620 return postincoming(ui, repo, modheads, opts.get('update'), None)
5621
5621
5622 @command('^update|up|checkout|co',
5622 @command('^update|up|checkout|co',
5623 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5623 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5624 ('c', 'check', None,
5624 ('c', 'check', None,
5625 _('update across branches if no uncommitted changes')),
5625 _('update across branches if no uncommitted changes')),
5626 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5626 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5627 ('r', 'rev', '', _('revision'), _('REV'))],
5627 ('r', 'rev', '', _('revision'), _('REV'))],
5628 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5628 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5629 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5629 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5630 """update working directory (or switch revisions)
5630 """update working directory (or switch revisions)
5631
5631
5632 Update the repository's working directory to the specified
5632 Update the repository's working directory to the specified
5633 changeset. If no changeset is specified, update to the tip of the
5633 changeset. If no changeset is specified, update to the tip of the
5634 current named branch and move the current bookmark (see :hg:`help
5634 current named branch and move the current bookmark (see :hg:`help
5635 bookmarks`).
5635 bookmarks`).
5636
5636
5637 If the changeset is not a descendant of the working directory's
5637 If the changeset is not a descendant of the working directory's
5638 parent, the update is aborted. With the -c/--check option, the
5638 parent, the update is aborted. With the -c/--check option, the
5639 working directory is checked for uncommitted changes; if none are
5639 working directory is checked for uncommitted changes; if none are
5640 found, the working directory is updated to the specified
5640 found, the working directory is updated to the specified
5641 changeset.
5641 changeset.
5642
5642
5643 Update sets the working directory's parent revison to the specified
5643 Update sets the working directory's parent revison to the specified
5644 changeset (see :hg:`help parents`).
5644 changeset (see :hg:`help parents`).
5645
5645
5646 The following rules apply when the working directory contains
5646 The following rules apply when the working directory contains
5647 uncommitted changes:
5647 uncommitted changes:
5648
5648
5649 1. If neither -c/--check nor -C/--clean is specified, and if
5649 1. If neither -c/--check nor -C/--clean is specified, and if
5650 the requested changeset is an ancestor or descendant of
5650 the requested changeset is an ancestor or descendant of
5651 the working directory's parent, the uncommitted changes
5651 the working directory's parent, the uncommitted changes
5652 are merged into the requested changeset and the merged
5652 are merged into the requested changeset and the merged
5653 result is left uncommitted. If the requested changeset is
5653 result is left uncommitted. If the requested changeset is
5654 not an ancestor or descendant (that is, it is on another
5654 not an ancestor or descendant (that is, it is on another
5655 branch), the update is aborted and the uncommitted changes
5655 branch), the update is aborted and the uncommitted changes
5656 are preserved.
5656 are preserved.
5657
5657
5658 2. With the -c/--check option, the update is aborted and the
5658 2. With the -c/--check option, the update is aborted and the
5659 uncommitted changes are preserved.
5659 uncommitted changes are preserved.
5660
5660
5661 3. With the -C/--clean option, uncommitted changes are discarded and
5661 3. With the -C/--clean option, uncommitted changes are discarded and
5662 the working directory is updated to the requested changeset.
5662 the working directory is updated to the requested changeset.
5663
5663
5664 Use null as the changeset to remove the working directory (like
5664 Use null as the changeset to remove the working directory (like
5665 :hg:`clone -U`).
5665 :hg:`clone -U`).
5666
5666
5667 If you want to revert just one file to an older revision, use
5667 If you want to revert just one file to an older revision, use
5668 :hg:`revert [-r REV] NAME`.
5668 :hg:`revert [-r REV] NAME`.
5669
5669
5670 See :hg:`help dates` for a list of formats valid for -d/--date.
5670 See :hg:`help dates` for a list of formats valid for -d/--date.
5671
5671
5672 Returns 0 on success, 1 if there are unresolved files.
5672 Returns 0 on success, 1 if there are unresolved files.
5673 """
5673 """
5674 if rev and node:
5674 if rev and node:
5675 raise util.Abort(_("please specify just one revision"))
5675 raise util.Abort(_("please specify just one revision"))
5676
5676
5677 if rev is None or rev == '':
5677 if rev is None or rev == '':
5678 rev = node
5678 rev = node
5679
5679
5680 # with no argument, we also move the current bookmark, if any
5680 # with no argument, we also move the current bookmark, if any
5681 movemarkfrom = None
5681 movemarkfrom = None
5682 if rev is None or node == '':
5682 if rev is None or node == '':
5683 movemarkfrom = repo['.'].node()
5683 movemarkfrom = repo['.'].node()
5684
5684
5685 # if we defined a bookmark, we have to remember the original bookmark name
5685 # if we defined a bookmark, we have to remember the original bookmark name
5686 brev = rev
5686 brev = rev
5687 rev = scmutil.revsingle(repo, rev, rev).rev()
5687 rev = scmutil.revsingle(repo, rev, rev).rev()
5688
5688
5689 if check and clean:
5689 if check and clean:
5690 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5690 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5691
5691
5692 if date:
5692 if date:
5693 if rev is not None:
5693 if rev is not None:
5694 raise util.Abort(_("you can't specify a revision and a date"))
5694 raise util.Abort(_("you can't specify a revision and a date"))
5695 rev = cmdutil.finddate(ui, repo, date)
5695 rev = cmdutil.finddate(ui, repo, date)
5696
5696
5697 if check:
5697 if check:
5698 c = repo[None]
5698 c = repo[None]
5699 if c.dirty(merge=False, branch=False):
5699 if c.dirty(merge=False, branch=False):
5700 raise util.Abort(_("uncommitted local changes"))
5700 raise util.Abort(_("uncommitted local changes"))
5701 if rev is None:
5701 if rev is None:
5702 rev = repo[repo[None].branch()].rev()
5702 rev = repo[repo[None].branch()].rev()
5703 mergemod._checkunknown(repo, repo[None], repo[rev])
5703 mergemod._checkunknown(repo, repo[None], repo[rev])
5704
5704
5705 if clean:
5705 if clean:
5706 ret = hg.clean(repo, rev)
5706 ret = hg.clean(repo, rev)
5707 else:
5707 else:
5708 ret = hg.update(repo, rev)
5708 ret = hg.update(repo, rev)
5709
5709
5710 if not ret and movemarkfrom:
5710 if not ret and movemarkfrom:
5711 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5711 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5712 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5712 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5713 elif brev in repo._bookmarks:
5713 elif brev in repo._bookmarks:
5714 bookmarks.setcurrent(repo, brev)
5714 bookmarks.setcurrent(repo, brev)
5715 elif brev:
5715 elif brev:
5716 bookmarks.unsetcurrent(repo)
5716 bookmarks.unsetcurrent(repo)
5717
5717
5718 return ret
5718 return ret
5719
5719
5720 @command('verify', [])
5720 @command('verify', [])
5721 def verify(ui, repo):
5721 def verify(ui, repo):
5722 """verify the integrity of the repository
5722 """verify the integrity of the repository
5723
5723
5724 Verify the integrity of the current repository.
5724 Verify the integrity of the current repository.
5725
5725
5726 This will perform an extensive check of the repository's
5726 This will perform an extensive check of the repository's
5727 integrity, validating the hashes and checksums of each entry in
5727 integrity, validating the hashes and checksums of each entry in
5728 the changelog, manifest, and tracked files, as well as the
5728 the changelog, manifest, and tracked files, as well as the
5729 integrity of their crosslinks and indices.
5729 integrity of their crosslinks and indices.
5730
5730
5731 Returns 0 on success, 1 if errors are encountered.
5731 Returns 0 on success, 1 if errors are encountered.
5732 """
5732 """
5733 return hg.verify(repo)
5733 return hg.verify(repo)
5734
5734
5735 @command('version', [])
5735 @command('version', [])
5736 def version_(ui):
5736 def version_(ui):
5737 """output version and copyright information"""
5737 """output version and copyright information"""
5738 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5738 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5739 % util.version())
5739 % util.version())
5740 ui.status(_(
5740 ui.status(_(
5741 "(see http://mercurial.selenic.com for more information)\n"
5741 "(see http://mercurial.selenic.com for more information)\n"
5742 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5742 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5743 "This is free software; see the source for copying conditions. "
5743 "This is free software; see the source for copying conditions. "
5744 "There is NO\nwarranty; "
5744 "There is NO\nwarranty; "
5745 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5745 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5746 ))
5746 ))
5747
5747
5748 norepo = ("clone init version help debugcommands debugcomplete"
5748 norepo = ("clone init version help debugcommands debugcomplete"
5749 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5749 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5750 " debugknown debuggetbundle debugbundle")
5750 " debugknown debuggetbundle debugbundle")
5751 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5751 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5752 " debugdata debugindex debugindexdot debugrevlog")
5752 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1275 +1,1270 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import nullid, nullrev, short, hex, bin
8 from node import nullid, nullrev, short, hex, bin
9 from i18n import _
9 from i18n import _
10 import ancestor, mdiff, error, util, scmutil, subrepo, patch, encoding, phases
10 import ancestor, mdiff, error, util, scmutil, subrepo, patch, encoding, phases
11 import copies
11 import copies
12 import match as matchmod
12 import match as matchmod
13 import os, errno, stat
13 import os, errno, stat
14
14
15 propertycache = util.propertycache
15 propertycache = util.propertycache
16
16
17 class changectx(object):
17 class changectx(object):
18 """A changecontext object makes access to data related to a particular
18 """A changecontext object makes access to data related to a particular
19 changeset convenient."""
19 changeset convenient."""
20 def __init__(self, repo, changeid=''):
20 def __init__(self, repo, changeid=''):
21 """changeid is a revision number, node, or tag"""
21 """changeid is a revision number, node, or tag"""
22 if changeid == '':
22 if changeid == '':
23 changeid = '.'
23 changeid = '.'
24 self._repo = repo
24 self._repo = repo
25
25
26 if isinstance(changeid, int):
26 if isinstance(changeid, int):
27 self._rev = changeid
27 self._rev = changeid
28 self._node = repo.changelog.node(changeid)
28 self._node = repo.changelog.node(changeid)
29 return
29 return
30 if changeid == '.':
30 if changeid == '.':
31 self._node = repo.dirstate.p1()
31 self._node = repo.dirstate.p1()
32 self._rev = repo.changelog.rev(self._node)
32 self._rev = repo.changelog.rev(self._node)
33 return
33 return
34 if changeid == 'null':
34 if changeid == 'null':
35 self._node = nullid
35 self._node = nullid
36 self._rev = nullrev
36 self._rev = nullrev
37 return
37 return
38 if changeid == 'tip':
38 if changeid == 'tip':
39 self._rev = len(repo.changelog) - 1
39 self._rev = len(repo.changelog) - 1
40 self._node = repo.changelog.node(self._rev)
40 self._node = repo.changelog.node(self._rev)
41 return
41 return
42 if len(changeid) == 20:
42 if len(changeid) == 20:
43 try:
43 try:
44 self._node = changeid
44 self._node = changeid
45 self._rev = repo.changelog.rev(changeid)
45 self._rev = repo.changelog.rev(changeid)
46 return
46 return
47 except LookupError:
47 except LookupError:
48 pass
48 pass
49
49
50 try:
50 try:
51 r = int(changeid)
51 r = int(changeid)
52 if str(r) != changeid:
52 if str(r) != changeid:
53 raise ValueError
53 raise ValueError
54 l = len(repo.changelog)
54 l = len(repo.changelog)
55 if r < 0:
55 if r < 0:
56 r += l
56 r += l
57 if r < 0 or r >= l:
57 if r < 0 or r >= l:
58 raise ValueError
58 raise ValueError
59 self._rev = r
59 self._rev = r
60 self._node = repo.changelog.node(r)
60 self._node = repo.changelog.node(r)
61 return
61 return
62 except (ValueError, OverflowError):
62 except (ValueError, OverflowError):
63 pass
63 pass
64
64
65 if len(changeid) == 40:
65 if len(changeid) == 40:
66 try:
66 try:
67 self._node = bin(changeid)
67 self._node = bin(changeid)
68 self._rev = repo.changelog.rev(self._node)
68 self._rev = repo.changelog.rev(self._node)
69 return
69 return
70 except (TypeError, LookupError):
70 except (TypeError, LookupError):
71 pass
71 pass
72
72
73 if changeid in repo._bookmarks:
73 if changeid in repo._bookmarks:
74 self._node = repo._bookmarks[changeid]
74 self._node = repo._bookmarks[changeid]
75 self._rev = repo.changelog.rev(self._node)
75 self._rev = repo.changelog.rev(self._node)
76 return
76 return
77 if changeid in repo._tagscache.tags:
77 if changeid in repo._tagscache.tags:
78 self._node = repo._tagscache.tags[changeid]
78 self._node = repo._tagscache.tags[changeid]
79 self._rev = repo.changelog.rev(self._node)
79 self._rev = repo.changelog.rev(self._node)
80 return
80 return
81 if changeid in repo.branchtags():
81 if changeid in repo.branchtags():
82 self._node = repo.branchtags()[changeid]
82 self._node = repo.branchtags()[changeid]
83 self._rev = repo.changelog.rev(self._node)
83 self._rev = repo.changelog.rev(self._node)
84 return
84 return
85
85
86 self._node = repo.changelog._partialmatch(changeid)
86 self._node = repo.changelog._partialmatch(changeid)
87 if self._node is not None:
87 if self._node is not None:
88 self._rev = repo.changelog.rev(self._node)
88 self._rev = repo.changelog.rev(self._node)
89 return
89 return
90
90
91 # lookup failed
91 # lookup failed
92 # check if it might have come from damaged dirstate
92 # check if it might have come from damaged dirstate
93 if changeid in repo.dirstate.parents():
93 if changeid in repo.dirstate.parents():
94 raise error.Abort(_("working directory has unknown parent '%s'!")
94 raise error.Abort(_("working directory has unknown parent '%s'!")
95 % short(changeid))
95 % short(changeid))
96 try:
96 try:
97 if len(changeid) == 20:
97 if len(changeid) == 20:
98 changeid = hex(changeid)
98 changeid = hex(changeid)
99 except TypeError:
99 except TypeError:
100 pass
100 pass
101 raise error.RepoLookupError(
101 raise error.RepoLookupError(
102 _("unknown revision '%s'") % changeid)
102 _("unknown revision '%s'") % changeid)
103
103
104 def __str__(self):
104 def __str__(self):
105 return short(self.node())
105 return short(self.node())
106
106
107 def __int__(self):
107 def __int__(self):
108 return self.rev()
108 return self.rev()
109
109
110 def __repr__(self):
110 def __repr__(self):
111 return "<changectx %s>" % str(self)
111 return "<changectx %s>" % str(self)
112
112
113 def __hash__(self):
113 def __hash__(self):
114 try:
114 try:
115 return hash(self._rev)
115 return hash(self._rev)
116 except AttributeError:
116 except AttributeError:
117 return id(self)
117 return id(self)
118
118
119 def __eq__(self, other):
119 def __eq__(self, other):
120 try:
120 try:
121 return self._rev == other._rev
121 return self._rev == other._rev
122 except AttributeError:
122 except AttributeError:
123 return False
123 return False
124
124
125 def __ne__(self, other):
125 def __ne__(self, other):
126 return not (self == other)
126 return not (self == other)
127
127
128 def __nonzero__(self):
128 def __nonzero__(self):
129 return self._rev != nullrev
129 return self._rev != nullrev
130
130
131 @propertycache
131 @propertycache
132 def _changeset(self):
132 def _changeset(self):
133 return self._repo.changelog.read(self.rev())
133 return self._repo.changelog.read(self.rev())
134
134
135 @propertycache
135 @propertycache
136 def _manifest(self):
136 def _manifest(self):
137 return self._repo.manifest.read(self._changeset[0])
137 return self._repo.manifest.read(self._changeset[0])
138
138
139 @propertycache
139 @propertycache
140 def _manifestdelta(self):
140 def _manifestdelta(self):
141 return self._repo.manifest.readdelta(self._changeset[0])
141 return self._repo.manifest.readdelta(self._changeset[0])
142
142
143 @propertycache
143 @propertycache
144 def _parents(self):
144 def _parents(self):
145 p = self._repo.changelog.parentrevs(self._rev)
145 p = self._repo.changelog.parentrevs(self._rev)
146 if p[1] == nullrev:
146 if p[1] == nullrev:
147 p = p[:-1]
147 p = p[:-1]
148 return [changectx(self._repo, x) for x in p]
148 return [changectx(self._repo, x) for x in p]
149
149
150 @propertycache
150 @propertycache
151 def substate(self):
151 def substate(self):
152 return subrepo.state(self, self._repo.ui)
152 return subrepo.state(self, self._repo.ui)
153
153
154 def __contains__(self, key):
154 def __contains__(self, key):
155 return key in self._manifest
155 return key in self._manifest
156
156
157 def __getitem__(self, key):
157 def __getitem__(self, key):
158 return self.filectx(key)
158 return self.filectx(key)
159
159
160 def __iter__(self):
160 def __iter__(self):
161 for f in sorted(self._manifest):
161 for f in sorted(self._manifest):
162 yield f
162 yield f
163
163
164 def changeset(self):
164 def changeset(self):
165 return self._changeset
165 return self._changeset
166 def manifest(self):
166 def manifest(self):
167 return self._manifest
167 return self._manifest
168 def manifestnode(self):
168 def manifestnode(self):
169 return self._changeset[0]
169 return self._changeset[0]
170
170
171 def rev(self):
171 def rev(self):
172 return self._rev
172 return self._rev
173 def node(self):
173 def node(self):
174 return self._node
174 return self._node
175 def hex(self):
175 def hex(self):
176 return hex(self._node)
176 return hex(self._node)
177 def user(self):
177 def user(self):
178 return self._changeset[1]
178 return self._changeset[1]
179 def date(self):
179 def date(self):
180 return self._changeset[2]
180 return self._changeset[2]
181 def files(self):
181 def files(self):
182 return self._changeset[3]
182 return self._changeset[3]
183 def description(self):
183 def description(self):
184 return self._changeset[4]
184 return self._changeset[4]
185 def branch(self):
185 def branch(self):
186 return encoding.tolocal(self._changeset[5].get("branch"))
186 return encoding.tolocal(self._changeset[5].get("branch"))
187 def extra(self):
187 def extra(self):
188 return self._changeset[5]
188 return self._changeset[5]
189 def tags(self):
189 def tags(self):
190 return self._repo.nodetags(self._node)
190 return self._repo.nodetags(self._node)
191 def bookmarks(self):
191 def bookmarks(self):
192 return self._repo.nodebookmarks(self._node)
192 return self._repo.nodebookmarks(self._node)
193 def phase(self):
193 def phase(self):
194 if self._rev == -1:
194 return self._repo._phasecache.phase(self._repo, self._rev)
195 return phases.public
196 if self._rev >= len(self._repo._phaserev):
197 # outdated cache
198 del self._repo._phaserev
199 return self._repo._phaserev[self._rev]
200 def phasestr(self):
195 def phasestr(self):
201 return phases.phasenames[self.phase()]
196 return phases.phasenames[self.phase()]
202 def mutable(self):
197 def mutable(self):
203 return self.phase() > phases.public
198 return self.phase() > phases.public
204 def hidden(self):
199 def hidden(self):
205 return self._rev in self._repo.changelog.hiddenrevs
200 return self._rev in self._repo.changelog.hiddenrevs
206
201
207 def parents(self):
202 def parents(self):
208 """return contexts for each parent changeset"""
203 """return contexts for each parent changeset"""
209 return self._parents
204 return self._parents
210
205
211 def p1(self):
206 def p1(self):
212 return self._parents[0]
207 return self._parents[0]
213
208
214 def p2(self):
209 def p2(self):
215 if len(self._parents) == 2:
210 if len(self._parents) == 2:
216 return self._parents[1]
211 return self._parents[1]
217 return changectx(self._repo, -1)
212 return changectx(self._repo, -1)
218
213
219 def children(self):
214 def children(self):
220 """return contexts for each child changeset"""
215 """return contexts for each child changeset"""
221 c = self._repo.changelog.children(self._node)
216 c = self._repo.changelog.children(self._node)
222 return [changectx(self._repo, x) for x in c]
217 return [changectx(self._repo, x) for x in c]
223
218
224 def ancestors(self):
219 def ancestors(self):
225 for a in self._repo.changelog.ancestors(self._rev):
220 for a in self._repo.changelog.ancestors(self._rev):
226 yield changectx(self._repo, a)
221 yield changectx(self._repo, a)
227
222
228 def descendants(self):
223 def descendants(self):
229 for d in self._repo.changelog.descendants(self._rev):
224 for d in self._repo.changelog.descendants(self._rev):
230 yield changectx(self._repo, d)
225 yield changectx(self._repo, d)
231
226
232 def _fileinfo(self, path):
227 def _fileinfo(self, path):
233 if '_manifest' in self.__dict__:
228 if '_manifest' in self.__dict__:
234 try:
229 try:
235 return self._manifest[path], self._manifest.flags(path)
230 return self._manifest[path], self._manifest.flags(path)
236 except KeyError:
231 except KeyError:
237 raise error.LookupError(self._node, path,
232 raise error.LookupError(self._node, path,
238 _('not found in manifest'))
233 _('not found in manifest'))
239 if '_manifestdelta' in self.__dict__ or path in self.files():
234 if '_manifestdelta' in self.__dict__ or path in self.files():
240 if path in self._manifestdelta:
235 if path in self._manifestdelta:
241 return self._manifestdelta[path], self._manifestdelta.flags(path)
236 return self._manifestdelta[path], self._manifestdelta.flags(path)
242 node, flag = self._repo.manifest.find(self._changeset[0], path)
237 node, flag = self._repo.manifest.find(self._changeset[0], path)
243 if not node:
238 if not node:
244 raise error.LookupError(self._node, path,
239 raise error.LookupError(self._node, path,
245 _('not found in manifest'))
240 _('not found in manifest'))
246
241
247 return node, flag
242 return node, flag
248
243
249 def filenode(self, path):
244 def filenode(self, path):
250 return self._fileinfo(path)[0]
245 return self._fileinfo(path)[0]
251
246
252 def flags(self, path):
247 def flags(self, path):
253 try:
248 try:
254 return self._fileinfo(path)[1]
249 return self._fileinfo(path)[1]
255 except error.LookupError:
250 except error.LookupError:
256 return ''
251 return ''
257
252
258 def filectx(self, path, fileid=None, filelog=None):
253 def filectx(self, path, fileid=None, filelog=None):
259 """get a file context from this changeset"""
254 """get a file context from this changeset"""
260 if fileid is None:
255 if fileid is None:
261 fileid = self.filenode(path)
256 fileid = self.filenode(path)
262 return filectx(self._repo, path, fileid=fileid,
257 return filectx(self._repo, path, fileid=fileid,
263 changectx=self, filelog=filelog)
258 changectx=self, filelog=filelog)
264
259
265 def ancestor(self, c2):
260 def ancestor(self, c2):
266 """
261 """
267 return the ancestor context of self and c2
262 return the ancestor context of self and c2
268 """
263 """
269 # deal with workingctxs
264 # deal with workingctxs
270 n2 = c2._node
265 n2 = c2._node
271 if n2 is None:
266 if n2 is None:
272 n2 = c2._parents[0]._node
267 n2 = c2._parents[0]._node
273 n = self._repo.changelog.ancestor(self._node, n2)
268 n = self._repo.changelog.ancestor(self._node, n2)
274 return changectx(self._repo, n)
269 return changectx(self._repo, n)
275
270
276 def walk(self, match):
271 def walk(self, match):
277 fset = set(match.files())
272 fset = set(match.files())
278 # for dirstate.walk, files=['.'] means "walk the whole tree".
273 # for dirstate.walk, files=['.'] means "walk the whole tree".
279 # follow that here, too
274 # follow that here, too
280 fset.discard('.')
275 fset.discard('.')
281 for fn in self:
276 for fn in self:
282 if fn in fset:
277 if fn in fset:
283 # specified pattern is the exact name
278 # specified pattern is the exact name
284 fset.remove(fn)
279 fset.remove(fn)
285 if match(fn):
280 if match(fn):
286 yield fn
281 yield fn
287 for fn in sorted(fset):
282 for fn in sorted(fset):
288 if fn in self._dirs:
283 if fn in self._dirs:
289 # specified pattern is a directory
284 # specified pattern is a directory
290 continue
285 continue
291 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
286 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
292 yield fn
287 yield fn
293
288
294 def sub(self, path):
289 def sub(self, path):
295 return subrepo.subrepo(self, path)
290 return subrepo.subrepo(self, path)
296
291
297 def match(self, pats=[], include=None, exclude=None, default='glob'):
292 def match(self, pats=[], include=None, exclude=None, default='glob'):
298 r = self._repo
293 r = self._repo
299 return matchmod.match(r.root, r.getcwd(), pats,
294 return matchmod.match(r.root, r.getcwd(), pats,
300 include, exclude, default,
295 include, exclude, default,
301 auditor=r.auditor, ctx=self)
296 auditor=r.auditor, ctx=self)
302
297
303 def diff(self, ctx2=None, match=None, **opts):
298 def diff(self, ctx2=None, match=None, **opts):
304 """Returns a diff generator for the given contexts and matcher"""
299 """Returns a diff generator for the given contexts and matcher"""
305 if ctx2 is None:
300 if ctx2 is None:
306 ctx2 = self.p1()
301 ctx2 = self.p1()
307 if ctx2 is not None and not isinstance(ctx2, changectx):
302 if ctx2 is not None and not isinstance(ctx2, changectx):
308 ctx2 = self._repo[ctx2]
303 ctx2 = self._repo[ctx2]
309 diffopts = patch.diffopts(self._repo.ui, opts)
304 diffopts = patch.diffopts(self._repo.ui, opts)
310 return patch.diff(self._repo, ctx2.node(), self.node(),
305 return patch.diff(self._repo, ctx2.node(), self.node(),
311 match=match, opts=diffopts)
306 match=match, opts=diffopts)
312
307
313 @propertycache
308 @propertycache
314 def _dirs(self):
309 def _dirs(self):
315 dirs = set()
310 dirs = set()
316 for f in self._manifest:
311 for f in self._manifest:
317 pos = f.rfind('/')
312 pos = f.rfind('/')
318 while pos != -1:
313 while pos != -1:
319 f = f[:pos]
314 f = f[:pos]
320 if f in dirs:
315 if f in dirs:
321 break # dirs already contains this and above
316 break # dirs already contains this and above
322 dirs.add(f)
317 dirs.add(f)
323 pos = f.rfind('/')
318 pos = f.rfind('/')
324 return dirs
319 return dirs
325
320
326 def dirs(self):
321 def dirs(self):
327 return self._dirs
322 return self._dirs
328
323
329 class filectx(object):
324 class filectx(object):
330 """A filecontext object makes access to data related to a particular
325 """A filecontext object makes access to data related to a particular
331 filerevision convenient."""
326 filerevision convenient."""
332 def __init__(self, repo, path, changeid=None, fileid=None,
327 def __init__(self, repo, path, changeid=None, fileid=None,
333 filelog=None, changectx=None):
328 filelog=None, changectx=None):
334 """changeid can be a changeset revision, node, or tag.
329 """changeid can be a changeset revision, node, or tag.
335 fileid can be a file revision or node."""
330 fileid can be a file revision or node."""
336 self._repo = repo
331 self._repo = repo
337 self._path = path
332 self._path = path
338
333
339 assert (changeid is not None
334 assert (changeid is not None
340 or fileid is not None
335 or fileid is not None
341 or changectx is not None), \
336 or changectx is not None), \
342 ("bad args: changeid=%r, fileid=%r, changectx=%r"
337 ("bad args: changeid=%r, fileid=%r, changectx=%r"
343 % (changeid, fileid, changectx))
338 % (changeid, fileid, changectx))
344
339
345 if filelog:
340 if filelog:
346 self._filelog = filelog
341 self._filelog = filelog
347
342
348 if changeid is not None:
343 if changeid is not None:
349 self._changeid = changeid
344 self._changeid = changeid
350 if changectx is not None:
345 if changectx is not None:
351 self._changectx = changectx
346 self._changectx = changectx
352 if fileid is not None:
347 if fileid is not None:
353 self._fileid = fileid
348 self._fileid = fileid
354
349
355 @propertycache
350 @propertycache
356 def _changectx(self):
351 def _changectx(self):
357 return changectx(self._repo, self._changeid)
352 return changectx(self._repo, self._changeid)
358
353
359 @propertycache
354 @propertycache
360 def _filelog(self):
355 def _filelog(self):
361 return self._repo.file(self._path)
356 return self._repo.file(self._path)
362
357
363 @propertycache
358 @propertycache
364 def _changeid(self):
359 def _changeid(self):
365 if '_changectx' in self.__dict__:
360 if '_changectx' in self.__dict__:
366 return self._changectx.rev()
361 return self._changectx.rev()
367 else:
362 else:
368 return self._filelog.linkrev(self._filerev)
363 return self._filelog.linkrev(self._filerev)
369
364
370 @propertycache
365 @propertycache
371 def _filenode(self):
366 def _filenode(self):
372 if '_fileid' in self.__dict__:
367 if '_fileid' in self.__dict__:
373 return self._filelog.lookup(self._fileid)
368 return self._filelog.lookup(self._fileid)
374 else:
369 else:
375 return self._changectx.filenode(self._path)
370 return self._changectx.filenode(self._path)
376
371
377 @propertycache
372 @propertycache
378 def _filerev(self):
373 def _filerev(self):
379 return self._filelog.rev(self._filenode)
374 return self._filelog.rev(self._filenode)
380
375
381 @propertycache
376 @propertycache
382 def _repopath(self):
377 def _repopath(self):
383 return self._path
378 return self._path
384
379
385 def __nonzero__(self):
380 def __nonzero__(self):
386 try:
381 try:
387 self._filenode
382 self._filenode
388 return True
383 return True
389 except error.LookupError:
384 except error.LookupError:
390 # file is missing
385 # file is missing
391 return False
386 return False
392
387
393 def __str__(self):
388 def __str__(self):
394 return "%s@%s" % (self.path(), short(self.node()))
389 return "%s@%s" % (self.path(), short(self.node()))
395
390
396 def __repr__(self):
391 def __repr__(self):
397 return "<filectx %s>" % str(self)
392 return "<filectx %s>" % str(self)
398
393
399 def __hash__(self):
394 def __hash__(self):
400 try:
395 try:
401 return hash((self._path, self._filenode))
396 return hash((self._path, self._filenode))
402 except AttributeError:
397 except AttributeError:
403 return id(self)
398 return id(self)
404
399
405 def __eq__(self, other):
400 def __eq__(self, other):
406 try:
401 try:
407 return (self._path == other._path
402 return (self._path == other._path
408 and self._filenode == other._filenode)
403 and self._filenode == other._filenode)
409 except AttributeError:
404 except AttributeError:
410 return False
405 return False
411
406
412 def __ne__(self, other):
407 def __ne__(self, other):
413 return not (self == other)
408 return not (self == other)
414
409
415 def filectx(self, fileid):
410 def filectx(self, fileid):
416 '''opens an arbitrary revision of the file without
411 '''opens an arbitrary revision of the file without
417 opening a new filelog'''
412 opening a new filelog'''
418 return filectx(self._repo, self._path, fileid=fileid,
413 return filectx(self._repo, self._path, fileid=fileid,
419 filelog=self._filelog)
414 filelog=self._filelog)
420
415
421 def filerev(self):
416 def filerev(self):
422 return self._filerev
417 return self._filerev
423 def filenode(self):
418 def filenode(self):
424 return self._filenode
419 return self._filenode
425 def flags(self):
420 def flags(self):
426 return self._changectx.flags(self._path)
421 return self._changectx.flags(self._path)
427 def filelog(self):
422 def filelog(self):
428 return self._filelog
423 return self._filelog
429
424
430 def rev(self):
425 def rev(self):
431 if '_changectx' in self.__dict__:
426 if '_changectx' in self.__dict__:
432 return self._changectx.rev()
427 return self._changectx.rev()
433 if '_changeid' in self.__dict__:
428 if '_changeid' in self.__dict__:
434 return self._changectx.rev()
429 return self._changectx.rev()
435 return self._filelog.linkrev(self._filerev)
430 return self._filelog.linkrev(self._filerev)
436
431
437 def linkrev(self):
432 def linkrev(self):
438 return self._filelog.linkrev(self._filerev)
433 return self._filelog.linkrev(self._filerev)
439 def node(self):
434 def node(self):
440 return self._changectx.node()
435 return self._changectx.node()
441 def hex(self):
436 def hex(self):
442 return hex(self.node())
437 return hex(self.node())
443 def user(self):
438 def user(self):
444 return self._changectx.user()
439 return self._changectx.user()
445 def date(self):
440 def date(self):
446 return self._changectx.date()
441 return self._changectx.date()
447 def files(self):
442 def files(self):
448 return self._changectx.files()
443 return self._changectx.files()
449 def description(self):
444 def description(self):
450 return self._changectx.description()
445 return self._changectx.description()
451 def branch(self):
446 def branch(self):
452 return self._changectx.branch()
447 return self._changectx.branch()
453 def extra(self):
448 def extra(self):
454 return self._changectx.extra()
449 return self._changectx.extra()
455 def manifest(self):
450 def manifest(self):
456 return self._changectx.manifest()
451 return self._changectx.manifest()
457 def changectx(self):
452 def changectx(self):
458 return self._changectx
453 return self._changectx
459
454
460 def data(self):
455 def data(self):
461 return self._filelog.read(self._filenode)
456 return self._filelog.read(self._filenode)
462 def path(self):
457 def path(self):
463 return self._path
458 return self._path
464 def size(self):
459 def size(self):
465 return self._filelog.size(self._filerev)
460 return self._filelog.size(self._filerev)
466
461
467 def isbinary(self):
462 def isbinary(self):
468 try:
463 try:
469 return util.binary(self.data())
464 return util.binary(self.data())
470 except IOError:
465 except IOError:
471 return False
466 return False
472
467
473 def cmp(self, fctx):
468 def cmp(self, fctx):
474 """compare with other file context
469 """compare with other file context
475
470
476 returns True if different than fctx.
471 returns True if different than fctx.
477 """
472 """
478 if (fctx._filerev is None
473 if (fctx._filerev is None
479 and (self._repo._encodefilterpats
474 and (self._repo._encodefilterpats
480 # if file data starts with '\1\n', empty metadata block is
475 # if file data starts with '\1\n', empty metadata block is
481 # prepended, which adds 4 bytes to filelog.size().
476 # prepended, which adds 4 bytes to filelog.size().
482 or self.size() - 4 == fctx.size())
477 or self.size() - 4 == fctx.size())
483 or self.size() == fctx.size()):
478 or self.size() == fctx.size()):
484 return self._filelog.cmp(self._filenode, fctx.data())
479 return self._filelog.cmp(self._filenode, fctx.data())
485
480
486 return True
481 return True
487
482
488 def renamed(self):
483 def renamed(self):
489 """check if file was actually renamed in this changeset revision
484 """check if file was actually renamed in this changeset revision
490
485
491 If rename logged in file revision, we report copy for changeset only
486 If rename logged in file revision, we report copy for changeset only
492 if file revisions linkrev points back to the changeset in question
487 if file revisions linkrev points back to the changeset in question
493 or both changeset parents contain different file revisions.
488 or both changeset parents contain different file revisions.
494 """
489 """
495
490
496 renamed = self._filelog.renamed(self._filenode)
491 renamed = self._filelog.renamed(self._filenode)
497 if not renamed:
492 if not renamed:
498 return renamed
493 return renamed
499
494
500 if self.rev() == self.linkrev():
495 if self.rev() == self.linkrev():
501 return renamed
496 return renamed
502
497
503 name = self.path()
498 name = self.path()
504 fnode = self._filenode
499 fnode = self._filenode
505 for p in self._changectx.parents():
500 for p in self._changectx.parents():
506 try:
501 try:
507 if fnode == p.filenode(name):
502 if fnode == p.filenode(name):
508 return None
503 return None
509 except error.LookupError:
504 except error.LookupError:
510 pass
505 pass
511 return renamed
506 return renamed
512
507
513 def parents(self):
508 def parents(self):
514 p = self._path
509 p = self._path
515 fl = self._filelog
510 fl = self._filelog
516 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
511 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
517
512
518 r = self._filelog.renamed(self._filenode)
513 r = self._filelog.renamed(self._filenode)
519 if r:
514 if r:
520 pl[0] = (r[0], r[1], None)
515 pl[0] = (r[0], r[1], None)
521
516
522 return [filectx(self._repo, p, fileid=n, filelog=l)
517 return [filectx(self._repo, p, fileid=n, filelog=l)
523 for p, n, l in pl if n != nullid]
518 for p, n, l in pl if n != nullid]
524
519
525 def p1(self):
520 def p1(self):
526 return self.parents()[0]
521 return self.parents()[0]
527
522
528 def p2(self):
523 def p2(self):
529 p = self.parents()
524 p = self.parents()
530 if len(p) == 2:
525 if len(p) == 2:
531 return p[1]
526 return p[1]
532 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
527 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
533
528
534 def children(self):
529 def children(self):
535 # hard for renames
530 # hard for renames
536 c = self._filelog.children(self._filenode)
531 c = self._filelog.children(self._filenode)
537 return [filectx(self._repo, self._path, fileid=x,
532 return [filectx(self._repo, self._path, fileid=x,
538 filelog=self._filelog) for x in c]
533 filelog=self._filelog) for x in c]
539
534
540 def annotate(self, follow=False, linenumber=None, diffopts=None):
535 def annotate(self, follow=False, linenumber=None, diffopts=None):
541 '''returns a list of tuples of (ctx, line) for each line
536 '''returns a list of tuples of (ctx, line) for each line
542 in the file, where ctx is the filectx of the node where
537 in the file, where ctx is the filectx of the node where
543 that line was last changed.
538 that line was last changed.
544 This returns tuples of ((ctx, linenumber), line) for each line,
539 This returns tuples of ((ctx, linenumber), line) for each line,
545 if "linenumber" parameter is NOT "None".
540 if "linenumber" parameter is NOT "None".
546 In such tuples, linenumber means one at the first appearance
541 In such tuples, linenumber means one at the first appearance
547 in the managed file.
542 in the managed file.
548 To reduce annotation cost,
543 To reduce annotation cost,
549 this returns fixed value(False is used) as linenumber,
544 this returns fixed value(False is used) as linenumber,
550 if "linenumber" parameter is "False".'''
545 if "linenumber" parameter is "False".'''
551
546
552 def decorate_compat(text, rev):
547 def decorate_compat(text, rev):
553 return ([rev] * len(text.splitlines()), text)
548 return ([rev] * len(text.splitlines()), text)
554
549
555 def without_linenumber(text, rev):
550 def without_linenumber(text, rev):
556 return ([(rev, False)] * len(text.splitlines()), text)
551 return ([(rev, False)] * len(text.splitlines()), text)
557
552
558 def with_linenumber(text, rev):
553 def with_linenumber(text, rev):
559 size = len(text.splitlines())
554 size = len(text.splitlines())
560 return ([(rev, i) for i in xrange(1, size + 1)], text)
555 return ([(rev, i) for i in xrange(1, size + 1)], text)
561
556
562 decorate = (((linenumber is None) and decorate_compat) or
557 decorate = (((linenumber is None) and decorate_compat) or
563 (linenumber and with_linenumber) or
558 (linenumber and with_linenumber) or
564 without_linenumber)
559 without_linenumber)
565
560
566 def pair(parent, child):
561 def pair(parent, child):
567 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
562 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
568 refine=True)
563 refine=True)
569 for (a1, a2, b1, b2), t in blocks:
564 for (a1, a2, b1, b2), t in blocks:
570 # Changed blocks ('!') or blocks made only of blank lines ('~')
565 # Changed blocks ('!') or blocks made only of blank lines ('~')
571 # belong to the child.
566 # belong to the child.
572 if t == '=':
567 if t == '=':
573 child[0][b1:b2] = parent[0][a1:a2]
568 child[0][b1:b2] = parent[0][a1:a2]
574 return child
569 return child
575
570
576 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
571 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
577 def getctx(path, fileid):
572 def getctx(path, fileid):
578 log = path == self._path and self._filelog or getlog(path)
573 log = path == self._path and self._filelog or getlog(path)
579 return filectx(self._repo, path, fileid=fileid, filelog=log)
574 return filectx(self._repo, path, fileid=fileid, filelog=log)
580 getctx = util.lrucachefunc(getctx)
575 getctx = util.lrucachefunc(getctx)
581
576
582 def parents(f):
577 def parents(f):
583 # we want to reuse filectx objects as much as possible
578 # we want to reuse filectx objects as much as possible
584 p = f._path
579 p = f._path
585 if f._filerev is None: # working dir
580 if f._filerev is None: # working dir
586 pl = [(n.path(), n.filerev()) for n in f.parents()]
581 pl = [(n.path(), n.filerev()) for n in f.parents()]
587 else:
582 else:
588 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
583 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
589
584
590 if follow:
585 if follow:
591 r = f.renamed()
586 r = f.renamed()
592 if r:
587 if r:
593 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
588 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
594
589
595 return [getctx(p, n) for p, n in pl if n != nullrev]
590 return [getctx(p, n) for p, n in pl if n != nullrev]
596
591
597 # use linkrev to find the first changeset where self appeared
592 # use linkrev to find the first changeset where self appeared
598 if self.rev() != self.linkrev():
593 if self.rev() != self.linkrev():
599 base = self.filectx(self.filerev())
594 base = self.filectx(self.filerev())
600 else:
595 else:
601 base = self
596 base = self
602
597
603 # This algorithm would prefer to be recursive, but Python is a
598 # This algorithm would prefer to be recursive, but Python is a
604 # bit recursion-hostile. Instead we do an iterative
599 # bit recursion-hostile. Instead we do an iterative
605 # depth-first search.
600 # depth-first search.
606
601
607 visit = [base]
602 visit = [base]
608 hist = {}
603 hist = {}
609 pcache = {}
604 pcache = {}
610 needed = {base: 1}
605 needed = {base: 1}
611 while visit:
606 while visit:
612 f = visit[-1]
607 f = visit[-1]
613 if f not in pcache:
608 if f not in pcache:
614 pcache[f] = parents(f)
609 pcache[f] = parents(f)
615
610
616 ready = True
611 ready = True
617 pl = pcache[f]
612 pl = pcache[f]
618 for p in pl:
613 for p in pl:
619 if p not in hist:
614 if p not in hist:
620 ready = False
615 ready = False
621 visit.append(p)
616 visit.append(p)
622 needed[p] = needed.get(p, 0) + 1
617 needed[p] = needed.get(p, 0) + 1
623 if ready:
618 if ready:
624 visit.pop()
619 visit.pop()
625 curr = decorate(f.data(), f)
620 curr = decorate(f.data(), f)
626 for p in pl:
621 for p in pl:
627 curr = pair(hist[p], curr)
622 curr = pair(hist[p], curr)
628 if needed[p] == 1:
623 if needed[p] == 1:
629 del hist[p]
624 del hist[p]
630 else:
625 else:
631 needed[p] -= 1
626 needed[p] -= 1
632
627
633 hist[f] = curr
628 hist[f] = curr
634 pcache[f] = []
629 pcache[f] = []
635
630
636 return zip(hist[base][0], hist[base][1].splitlines(True))
631 return zip(hist[base][0], hist[base][1].splitlines(True))
637
632
638 def ancestor(self, fc2, actx):
633 def ancestor(self, fc2, actx):
639 """
634 """
640 find the common ancestor file context, if any, of self, and fc2
635 find the common ancestor file context, if any, of self, and fc2
641
636
642 actx must be the changectx of the common ancestor
637 actx must be the changectx of the common ancestor
643 of self's and fc2's respective changesets.
638 of self's and fc2's respective changesets.
644 """
639 """
645
640
646 # the easy case: no (relevant) renames
641 # the easy case: no (relevant) renames
647 if fc2.path() == self.path() and self.path() in actx:
642 if fc2.path() == self.path() and self.path() in actx:
648 return actx[self.path()]
643 return actx[self.path()]
649
644
650 # the next easiest cases: unambiguous predecessor (name trumps
645 # the next easiest cases: unambiguous predecessor (name trumps
651 # history)
646 # history)
652 if self.path() in actx and fc2.path() not in actx:
647 if self.path() in actx and fc2.path() not in actx:
653 return actx[self.path()]
648 return actx[self.path()]
654 if fc2.path() in actx and self.path() not in actx:
649 if fc2.path() in actx and self.path() not in actx:
655 return actx[fc2.path()]
650 return actx[fc2.path()]
656
651
657 # prime the ancestor cache for the working directory
652 # prime the ancestor cache for the working directory
658 acache = {}
653 acache = {}
659 for c in (self, fc2):
654 for c in (self, fc2):
660 if c._filerev is None:
655 if c._filerev is None:
661 pl = [(n.path(), n.filenode()) for n in c.parents()]
656 pl = [(n.path(), n.filenode()) for n in c.parents()]
662 acache[(c._path, None)] = pl
657 acache[(c._path, None)] = pl
663
658
664 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
659 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
665 def parents(vertex):
660 def parents(vertex):
666 if vertex in acache:
661 if vertex in acache:
667 return acache[vertex]
662 return acache[vertex]
668 f, n = vertex
663 f, n = vertex
669 if f not in flcache:
664 if f not in flcache:
670 flcache[f] = self._repo.file(f)
665 flcache[f] = self._repo.file(f)
671 fl = flcache[f]
666 fl = flcache[f]
672 pl = [(f, p) for p in fl.parents(n) if p != nullid]
667 pl = [(f, p) for p in fl.parents(n) if p != nullid]
673 re = fl.renamed(n)
668 re = fl.renamed(n)
674 if re:
669 if re:
675 pl.append(re)
670 pl.append(re)
676 acache[vertex] = pl
671 acache[vertex] = pl
677 return pl
672 return pl
678
673
679 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
674 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
680 v = ancestor.ancestor(a, b, parents)
675 v = ancestor.ancestor(a, b, parents)
681 if v:
676 if v:
682 f, n = v
677 f, n = v
683 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
678 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
684
679
685 return None
680 return None
686
681
687 def ancestors(self, followfirst=False):
682 def ancestors(self, followfirst=False):
688 visit = {}
683 visit = {}
689 c = self
684 c = self
690 cut = followfirst and 1 or None
685 cut = followfirst and 1 or None
691 while True:
686 while True:
692 for parent in c.parents()[:cut]:
687 for parent in c.parents()[:cut]:
693 visit[(parent.rev(), parent.node())] = parent
688 visit[(parent.rev(), parent.node())] = parent
694 if not visit:
689 if not visit:
695 break
690 break
696 c = visit.pop(max(visit))
691 c = visit.pop(max(visit))
697 yield c
692 yield c
698
693
699 def copies(self, c2):
694 def copies(self, c2):
700 if not util.safehasattr(self, "_copycache"):
695 if not util.safehasattr(self, "_copycache"):
701 self._copycache = {}
696 self._copycache = {}
702 sc2 = str(c2)
697 sc2 = str(c2)
703 if sc2 not in self._copycache:
698 if sc2 not in self._copycache:
704 self._copycache[sc2] = copies.pathcopies(c2)
699 self._copycache[sc2] = copies.pathcopies(c2)
705 return self._copycache[sc2]
700 return self._copycache[sc2]
706
701
707 class workingctx(changectx):
702 class workingctx(changectx):
708 """A workingctx object makes access to data related to
703 """A workingctx object makes access to data related to
709 the current working directory convenient.
704 the current working directory convenient.
710 date - any valid date string or (unixtime, offset), or None.
705 date - any valid date string or (unixtime, offset), or None.
711 user - username string, or None.
706 user - username string, or None.
712 extra - a dictionary of extra values, or None.
707 extra - a dictionary of extra values, or None.
713 changes - a list of file lists as returned by localrepo.status()
708 changes - a list of file lists as returned by localrepo.status()
714 or None to use the repository status.
709 or None to use the repository status.
715 """
710 """
716 def __init__(self, repo, text="", user=None, date=None, extra=None,
711 def __init__(self, repo, text="", user=None, date=None, extra=None,
717 changes=None):
712 changes=None):
718 self._repo = repo
713 self._repo = repo
719 self._rev = None
714 self._rev = None
720 self._node = None
715 self._node = None
721 self._text = text
716 self._text = text
722 if date:
717 if date:
723 self._date = util.parsedate(date)
718 self._date = util.parsedate(date)
724 if user:
719 if user:
725 self._user = user
720 self._user = user
726 if changes:
721 if changes:
727 self._status = list(changes[:4])
722 self._status = list(changes[:4])
728 self._unknown = changes[4]
723 self._unknown = changes[4]
729 self._ignored = changes[5]
724 self._ignored = changes[5]
730 self._clean = changes[6]
725 self._clean = changes[6]
731 else:
726 else:
732 self._unknown = None
727 self._unknown = None
733 self._ignored = None
728 self._ignored = None
734 self._clean = None
729 self._clean = None
735
730
736 self._extra = {}
731 self._extra = {}
737 if extra:
732 if extra:
738 self._extra = extra.copy()
733 self._extra = extra.copy()
739 if 'branch' not in self._extra:
734 if 'branch' not in self._extra:
740 try:
735 try:
741 branch = encoding.fromlocal(self._repo.dirstate.branch())
736 branch = encoding.fromlocal(self._repo.dirstate.branch())
742 except UnicodeDecodeError:
737 except UnicodeDecodeError:
743 raise util.Abort(_('branch name not in UTF-8!'))
738 raise util.Abort(_('branch name not in UTF-8!'))
744 self._extra['branch'] = branch
739 self._extra['branch'] = branch
745 if self._extra['branch'] == '':
740 if self._extra['branch'] == '':
746 self._extra['branch'] = 'default'
741 self._extra['branch'] = 'default'
747
742
748 def __str__(self):
743 def __str__(self):
749 return str(self._parents[0]) + "+"
744 return str(self._parents[0]) + "+"
750
745
751 def __repr__(self):
746 def __repr__(self):
752 return "<workingctx %s>" % str(self)
747 return "<workingctx %s>" % str(self)
753
748
754 def __nonzero__(self):
749 def __nonzero__(self):
755 return True
750 return True
756
751
757 def __contains__(self, key):
752 def __contains__(self, key):
758 return self._repo.dirstate[key] not in "?r"
753 return self._repo.dirstate[key] not in "?r"
759
754
760 def _buildflagfunc(self):
755 def _buildflagfunc(self):
761 # Create a fallback function for getting file flags when the
756 # Create a fallback function for getting file flags when the
762 # filesystem doesn't support them
757 # filesystem doesn't support them
763
758
764 copiesget = self._repo.dirstate.copies().get
759 copiesget = self._repo.dirstate.copies().get
765
760
766 if len(self._parents) < 2:
761 if len(self._parents) < 2:
767 # when we have one parent, it's easy: copy from parent
762 # when we have one parent, it's easy: copy from parent
768 man = self._parents[0].manifest()
763 man = self._parents[0].manifest()
769 def func(f):
764 def func(f):
770 f = copiesget(f, f)
765 f = copiesget(f, f)
771 return man.flags(f)
766 return man.flags(f)
772 else:
767 else:
773 # merges are tricky: we try to reconstruct the unstored
768 # merges are tricky: we try to reconstruct the unstored
774 # result from the merge (issue1802)
769 # result from the merge (issue1802)
775 p1, p2 = self._parents
770 p1, p2 = self._parents
776 pa = p1.ancestor(p2)
771 pa = p1.ancestor(p2)
777 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
772 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
778
773
779 def func(f):
774 def func(f):
780 f = copiesget(f, f) # may be wrong for merges with copies
775 f = copiesget(f, f) # may be wrong for merges with copies
781 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
776 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
782 if fl1 == fl2:
777 if fl1 == fl2:
783 return fl1
778 return fl1
784 if fl1 == fla:
779 if fl1 == fla:
785 return fl2
780 return fl2
786 if fl2 == fla:
781 if fl2 == fla:
787 return fl1
782 return fl1
788 return '' # punt for conflicts
783 return '' # punt for conflicts
789
784
790 return func
785 return func
791
786
792 @propertycache
787 @propertycache
793 def _flagfunc(self):
788 def _flagfunc(self):
794 return self._repo.dirstate.flagfunc(self._buildflagfunc)
789 return self._repo.dirstate.flagfunc(self._buildflagfunc)
795
790
796 @propertycache
791 @propertycache
797 def _manifest(self):
792 def _manifest(self):
798 """generate a manifest corresponding to the working directory"""
793 """generate a manifest corresponding to the working directory"""
799
794
800 man = self._parents[0].manifest().copy()
795 man = self._parents[0].manifest().copy()
801 if len(self._parents) > 1:
796 if len(self._parents) > 1:
802 man2 = self.p2().manifest()
797 man2 = self.p2().manifest()
803 def getman(f):
798 def getman(f):
804 if f in man:
799 if f in man:
805 return man
800 return man
806 return man2
801 return man2
807 else:
802 else:
808 getman = lambda f: man
803 getman = lambda f: man
809
804
810 copied = self._repo.dirstate.copies()
805 copied = self._repo.dirstate.copies()
811 ff = self._flagfunc
806 ff = self._flagfunc
812 modified, added, removed, deleted = self._status
807 modified, added, removed, deleted = self._status
813 for i, l in (("a", added), ("m", modified)):
808 for i, l in (("a", added), ("m", modified)):
814 for f in l:
809 for f in l:
815 orig = copied.get(f, f)
810 orig = copied.get(f, f)
816 man[f] = getman(orig).get(orig, nullid) + i
811 man[f] = getman(orig).get(orig, nullid) + i
817 try:
812 try:
818 man.set(f, ff(f))
813 man.set(f, ff(f))
819 except OSError:
814 except OSError:
820 pass
815 pass
821
816
822 for f in deleted + removed:
817 for f in deleted + removed:
823 if f in man:
818 if f in man:
824 del man[f]
819 del man[f]
825
820
826 return man
821 return man
827
822
828 def __iter__(self):
823 def __iter__(self):
829 d = self._repo.dirstate
824 d = self._repo.dirstate
830 for f in d:
825 for f in d:
831 if d[f] != 'r':
826 if d[f] != 'r':
832 yield f
827 yield f
833
828
834 @propertycache
829 @propertycache
835 def _status(self):
830 def _status(self):
836 return self._repo.status()[:4]
831 return self._repo.status()[:4]
837
832
838 @propertycache
833 @propertycache
839 def _user(self):
834 def _user(self):
840 return self._repo.ui.username()
835 return self._repo.ui.username()
841
836
842 @propertycache
837 @propertycache
843 def _date(self):
838 def _date(self):
844 return util.makedate()
839 return util.makedate()
845
840
846 @propertycache
841 @propertycache
847 def _parents(self):
842 def _parents(self):
848 p = self._repo.dirstate.parents()
843 p = self._repo.dirstate.parents()
849 if p[1] == nullid:
844 if p[1] == nullid:
850 p = p[:-1]
845 p = p[:-1]
851 self._parents = [changectx(self._repo, x) for x in p]
846 self._parents = [changectx(self._repo, x) for x in p]
852 return self._parents
847 return self._parents
853
848
854 def status(self, ignored=False, clean=False, unknown=False):
849 def status(self, ignored=False, clean=False, unknown=False):
855 """Explicit status query
850 """Explicit status query
856 Unless this method is used to query the working copy status, the
851 Unless this method is used to query the working copy status, the
857 _status property will implicitly read the status using its default
852 _status property will implicitly read the status using its default
858 arguments."""
853 arguments."""
859 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
854 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
860 self._unknown = self._ignored = self._clean = None
855 self._unknown = self._ignored = self._clean = None
861 if unknown:
856 if unknown:
862 self._unknown = stat[4]
857 self._unknown = stat[4]
863 if ignored:
858 if ignored:
864 self._ignored = stat[5]
859 self._ignored = stat[5]
865 if clean:
860 if clean:
866 self._clean = stat[6]
861 self._clean = stat[6]
867 self._status = stat[:4]
862 self._status = stat[:4]
868 return stat
863 return stat
869
864
870 def manifest(self):
865 def manifest(self):
871 return self._manifest
866 return self._manifest
872 def user(self):
867 def user(self):
873 return self._user or self._repo.ui.username()
868 return self._user or self._repo.ui.username()
874 def date(self):
869 def date(self):
875 return self._date
870 return self._date
876 def description(self):
871 def description(self):
877 return self._text
872 return self._text
878 def files(self):
873 def files(self):
879 return sorted(self._status[0] + self._status[1] + self._status[2])
874 return sorted(self._status[0] + self._status[1] + self._status[2])
880
875
881 def modified(self):
876 def modified(self):
882 return self._status[0]
877 return self._status[0]
883 def added(self):
878 def added(self):
884 return self._status[1]
879 return self._status[1]
885 def removed(self):
880 def removed(self):
886 return self._status[2]
881 return self._status[2]
887 def deleted(self):
882 def deleted(self):
888 return self._status[3]
883 return self._status[3]
889 def unknown(self):
884 def unknown(self):
890 assert self._unknown is not None # must call status first
885 assert self._unknown is not None # must call status first
891 return self._unknown
886 return self._unknown
892 def ignored(self):
887 def ignored(self):
893 assert self._ignored is not None # must call status first
888 assert self._ignored is not None # must call status first
894 return self._ignored
889 return self._ignored
895 def clean(self):
890 def clean(self):
896 assert self._clean is not None # must call status first
891 assert self._clean is not None # must call status first
897 return self._clean
892 return self._clean
898 def branch(self):
893 def branch(self):
899 return encoding.tolocal(self._extra['branch'])
894 return encoding.tolocal(self._extra['branch'])
900 def extra(self):
895 def extra(self):
901 return self._extra
896 return self._extra
902
897
903 def tags(self):
898 def tags(self):
904 t = []
899 t = []
905 for p in self.parents():
900 for p in self.parents():
906 t.extend(p.tags())
901 t.extend(p.tags())
907 return t
902 return t
908
903
909 def bookmarks(self):
904 def bookmarks(self):
910 b = []
905 b = []
911 for p in self.parents():
906 for p in self.parents():
912 b.extend(p.bookmarks())
907 b.extend(p.bookmarks())
913 return b
908 return b
914
909
915 def phase(self):
910 def phase(self):
916 phase = phases.draft # default phase to draft
911 phase = phases.draft # default phase to draft
917 for p in self.parents():
912 for p in self.parents():
918 phase = max(phase, p.phase())
913 phase = max(phase, p.phase())
919 return phase
914 return phase
920
915
921 def hidden(self):
916 def hidden(self):
922 return False
917 return False
923
918
924 def children(self):
919 def children(self):
925 return []
920 return []
926
921
927 def flags(self, path):
922 def flags(self, path):
928 if '_manifest' in self.__dict__:
923 if '_manifest' in self.__dict__:
929 try:
924 try:
930 return self._manifest.flags(path)
925 return self._manifest.flags(path)
931 except KeyError:
926 except KeyError:
932 return ''
927 return ''
933
928
934 try:
929 try:
935 return self._flagfunc(path)
930 return self._flagfunc(path)
936 except OSError:
931 except OSError:
937 return ''
932 return ''
938
933
939 def filectx(self, path, filelog=None):
934 def filectx(self, path, filelog=None):
940 """get a file context from the working directory"""
935 """get a file context from the working directory"""
941 return workingfilectx(self._repo, path, workingctx=self,
936 return workingfilectx(self._repo, path, workingctx=self,
942 filelog=filelog)
937 filelog=filelog)
943
938
944 def ancestor(self, c2):
939 def ancestor(self, c2):
945 """return the ancestor context of self and c2"""
940 """return the ancestor context of self and c2"""
946 return self._parents[0].ancestor(c2) # punt on two parents for now
941 return self._parents[0].ancestor(c2) # punt on two parents for now
947
942
948 def walk(self, match):
943 def walk(self, match):
949 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
944 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
950 True, False))
945 True, False))
951
946
952 def dirty(self, missing=False, merge=True, branch=True):
947 def dirty(self, missing=False, merge=True, branch=True):
953 "check whether a working directory is modified"
948 "check whether a working directory is modified"
954 # check subrepos first
949 # check subrepos first
955 for s in self.substate:
950 for s in self.substate:
956 if self.sub(s).dirty():
951 if self.sub(s).dirty():
957 return True
952 return True
958 # check current working dir
953 # check current working dir
959 return ((merge and self.p2()) or
954 return ((merge and self.p2()) or
960 (branch and self.branch() != self.p1().branch()) or
955 (branch and self.branch() != self.p1().branch()) or
961 self.modified() or self.added() or self.removed() or
956 self.modified() or self.added() or self.removed() or
962 (missing and self.deleted()))
957 (missing and self.deleted()))
963
958
964 def add(self, list, prefix=""):
959 def add(self, list, prefix=""):
965 join = lambda f: os.path.join(prefix, f)
960 join = lambda f: os.path.join(prefix, f)
966 wlock = self._repo.wlock()
961 wlock = self._repo.wlock()
967 ui, ds = self._repo.ui, self._repo.dirstate
962 ui, ds = self._repo.ui, self._repo.dirstate
968 try:
963 try:
969 rejected = []
964 rejected = []
970 for f in list:
965 for f in list:
971 scmutil.checkportable(ui, join(f))
966 scmutil.checkportable(ui, join(f))
972 p = self._repo.wjoin(f)
967 p = self._repo.wjoin(f)
973 try:
968 try:
974 st = os.lstat(p)
969 st = os.lstat(p)
975 except OSError:
970 except OSError:
976 ui.warn(_("%s does not exist!\n") % join(f))
971 ui.warn(_("%s does not exist!\n") % join(f))
977 rejected.append(f)
972 rejected.append(f)
978 continue
973 continue
979 if st.st_size > 10000000:
974 if st.st_size > 10000000:
980 ui.warn(_("%s: up to %d MB of RAM may be required "
975 ui.warn(_("%s: up to %d MB of RAM may be required "
981 "to manage this file\n"
976 "to manage this file\n"
982 "(use 'hg revert %s' to cancel the "
977 "(use 'hg revert %s' to cancel the "
983 "pending addition)\n")
978 "pending addition)\n")
984 % (f, 3 * st.st_size // 1000000, join(f)))
979 % (f, 3 * st.st_size // 1000000, join(f)))
985 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
980 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
986 ui.warn(_("%s not added: only files and symlinks "
981 ui.warn(_("%s not added: only files and symlinks "
987 "supported currently\n") % join(f))
982 "supported currently\n") % join(f))
988 rejected.append(p)
983 rejected.append(p)
989 elif ds[f] in 'amn':
984 elif ds[f] in 'amn':
990 ui.warn(_("%s already tracked!\n") % join(f))
985 ui.warn(_("%s already tracked!\n") % join(f))
991 elif ds[f] == 'r':
986 elif ds[f] == 'r':
992 ds.normallookup(f)
987 ds.normallookup(f)
993 else:
988 else:
994 ds.add(f)
989 ds.add(f)
995 return rejected
990 return rejected
996 finally:
991 finally:
997 wlock.release()
992 wlock.release()
998
993
999 def forget(self, files, prefix=""):
994 def forget(self, files, prefix=""):
1000 join = lambda f: os.path.join(prefix, f)
995 join = lambda f: os.path.join(prefix, f)
1001 wlock = self._repo.wlock()
996 wlock = self._repo.wlock()
1002 try:
997 try:
1003 rejected = []
998 rejected = []
1004 for f in files:
999 for f in files:
1005 if f not in self._repo.dirstate:
1000 if f not in self._repo.dirstate:
1006 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1001 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1007 rejected.append(f)
1002 rejected.append(f)
1008 elif self._repo.dirstate[f] != 'a':
1003 elif self._repo.dirstate[f] != 'a':
1009 self._repo.dirstate.remove(f)
1004 self._repo.dirstate.remove(f)
1010 else:
1005 else:
1011 self._repo.dirstate.drop(f)
1006 self._repo.dirstate.drop(f)
1012 return rejected
1007 return rejected
1013 finally:
1008 finally:
1014 wlock.release()
1009 wlock.release()
1015
1010
1016 def ancestors(self):
1011 def ancestors(self):
1017 for a in self._repo.changelog.ancestors(
1012 for a in self._repo.changelog.ancestors(
1018 *[p.rev() for p in self._parents]):
1013 *[p.rev() for p in self._parents]):
1019 yield changectx(self._repo, a)
1014 yield changectx(self._repo, a)
1020
1015
1021 def undelete(self, list):
1016 def undelete(self, list):
1022 pctxs = self.parents()
1017 pctxs = self.parents()
1023 wlock = self._repo.wlock()
1018 wlock = self._repo.wlock()
1024 try:
1019 try:
1025 for f in list:
1020 for f in list:
1026 if self._repo.dirstate[f] != 'r':
1021 if self._repo.dirstate[f] != 'r':
1027 self._repo.ui.warn(_("%s not removed!\n") % f)
1022 self._repo.ui.warn(_("%s not removed!\n") % f)
1028 else:
1023 else:
1029 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1024 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1030 t = fctx.data()
1025 t = fctx.data()
1031 self._repo.wwrite(f, t, fctx.flags())
1026 self._repo.wwrite(f, t, fctx.flags())
1032 self._repo.dirstate.normal(f)
1027 self._repo.dirstate.normal(f)
1033 finally:
1028 finally:
1034 wlock.release()
1029 wlock.release()
1035
1030
1036 def copy(self, source, dest):
1031 def copy(self, source, dest):
1037 p = self._repo.wjoin(dest)
1032 p = self._repo.wjoin(dest)
1038 if not os.path.lexists(p):
1033 if not os.path.lexists(p):
1039 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1034 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1040 elif not (os.path.isfile(p) or os.path.islink(p)):
1035 elif not (os.path.isfile(p) or os.path.islink(p)):
1041 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1036 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1042 "symbolic link\n") % dest)
1037 "symbolic link\n") % dest)
1043 else:
1038 else:
1044 wlock = self._repo.wlock()
1039 wlock = self._repo.wlock()
1045 try:
1040 try:
1046 if self._repo.dirstate[dest] in '?r':
1041 if self._repo.dirstate[dest] in '?r':
1047 self._repo.dirstate.add(dest)
1042 self._repo.dirstate.add(dest)
1048 self._repo.dirstate.copy(source, dest)
1043 self._repo.dirstate.copy(source, dest)
1049 finally:
1044 finally:
1050 wlock.release()
1045 wlock.release()
1051
1046
1052 def dirs(self):
1047 def dirs(self):
1053 return self._repo.dirstate.dirs()
1048 return self._repo.dirstate.dirs()
1054
1049
1055 class workingfilectx(filectx):
1050 class workingfilectx(filectx):
1056 """A workingfilectx object makes access to data related to a particular
1051 """A workingfilectx object makes access to data related to a particular
1057 file in the working directory convenient."""
1052 file in the working directory convenient."""
1058 def __init__(self, repo, path, filelog=None, workingctx=None):
1053 def __init__(self, repo, path, filelog=None, workingctx=None):
1059 """changeid can be a changeset revision, node, or tag.
1054 """changeid can be a changeset revision, node, or tag.
1060 fileid can be a file revision or node."""
1055 fileid can be a file revision or node."""
1061 self._repo = repo
1056 self._repo = repo
1062 self._path = path
1057 self._path = path
1063 self._changeid = None
1058 self._changeid = None
1064 self._filerev = self._filenode = None
1059 self._filerev = self._filenode = None
1065
1060
1066 if filelog:
1061 if filelog:
1067 self._filelog = filelog
1062 self._filelog = filelog
1068 if workingctx:
1063 if workingctx:
1069 self._changectx = workingctx
1064 self._changectx = workingctx
1070
1065
1071 @propertycache
1066 @propertycache
1072 def _changectx(self):
1067 def _changectx(self):
1073 return workingctx(self._repo)
1068 return workingctx(self._repo)
1074
1069
1075 def __nonzero__(self):
1070 def __nonzero__(self):
1076 return True
1071 return True
1077
1072
1078 def __str__(self):
1073 def __str__(self):
1079 return "%s@%s" % (self.path(), self._changectx)
1074 return "%s@%s" % (self.path(), self._changectx)
1080
1075
1081 def __repr__(self):
1076 def __repr__(self):
1082 return "<workingfilectx %s>" % str(self)
1077 return "<workingfilectx %s>" % str(self)
1083
1078
1084 def data(self):
1079 def data(self):
1085 return self._repo.wread(self._path)
1080 return self._repo.wread(self._path)
1086 def renamed(self):
1081 def renamed(self):
1087 rp = self._repo.dirstate.copied(self._path)
1082 rp = self._repo.dirstate.copied(self._path)
1088 if not rp:
1083 if not rp:
1089 return None
1084 return None
1090 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1085 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1091
1086
1092 def parents(self):
1087 def parents(self):
1093 '''return parent filectxs, following copies if necessary'''
1088 '''return parent filectxs, following copies if necessary'''
1094 def filenode(ctx, path):
1089 def filenode(ctx, path):
1095 return ctx._manifest.get(path, nullid)
1090 return ctx._manifest.get(path, nullid)
1096
1091
1097 path = self._path
1092 path = self._path
1098 fl = self._filelog
1093 fl = self._filelog
1099 pcl = self._changectx._parents
1094 pcl = self._changectx._parents
1100 renamed = self.renamed()
1095 renamed = self.renamed()
1101
1096
1102 if renamed:
1097 if renamed:
1103 pl = [renamed + (None,)]
1098 pl = [renamed + (None,)]
1104 else:
1099 else:
1105 pl = [(path, filenode(pcl[0], path), fl)]
1100 pl = [(path, filenode(pcl[0], path), fl)]
1106
1101
1107 for pc in pcl[1:]:
1102 for pc in pcl[1:]:
1108 pl.append((path, filenode(pc, path), fl))
1103 pl.append((path, filenode(pc, path), fl))
1109
1104
1110 return [filectx(self._repo, p, fileid=n, filelog=l)
1105 return [filectx(self._repo, p, fileid=n, filelog=l)
1111 for p, n, l in pl if n != nullid]
1106 for p, n, l in pl if n != nullid]
1112
1107
1113 def children(self):
1108 def children(self):
1114 return []
1109 return []
1115
1110
1116 def size(self):
1111 def size(self):
1117 return os.lstat(self._repo.wjoin(self._path)).st_size
1112 return os.lstat(self._repo.wjoin(self._path)).st_size
1118 def date(self):
1113 def date(self):
1119 t, tz = self._changectx.date()
1114 t, tz = self._changectx.date()
1120 try:
1115 try:
1121 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
1116 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
1122 except OSError, err:
1117 except OSError, err:
1123 if err.errno != errno.ENOENT:
1118 if err.errno != errno.ENOENT:
1124 raise
1119 raise
1125 return (t, tz)
1120 return (t, tz)
1126
1121
1127 def cmp(self, fctx):
1122 def cmp(self, fctx):
1128 """compare with other file context
1123 """compare with other file context
1129
1124
1130 returns True if different than fctx.
1125 returns True if different than fctx.
1131 """
1126 """
1132 # fctx should be a filectx (not a wfctx)
1127 # fctx should be a filectx (not a wfctx)
1133 # invert comparison to reuse the same code path
1128 # invert comparison to reuse the same code path
1134 return fctx.cmp(self)
1129 return fctx.cmp(self)
1135
1130
1136 class memctx(object):
1131 class memctx(object):
1137 """Use memctx to perform in-memory commits via localrepo.commitctx().
1132 """Use memctx to perform in-memory commits via localrepo.commitctx().
1138
1133
1139 Revision information is supplied at initialization time while
1134 Revision information is supplied at initialization time while
1140 related files data and is made available through a callback
1135 related files data and is made available through a callback
1141 mechanism. 'repo' is the current localrepo, 'parents' is a
1136 mechanism. 'repo' is the current localrepo, 'parents' is a
1142 sequence of two parent revisions identifiers (pass None for every
1137 sequence of two parent revisions identifiers (pass None for every
1143 missing parent), 'text' is the commit message and 'files' lists
1138 missing parent), 'text' is the commit message and 'files' lists
1144 names of files touched by the revision (normalized and relative to
1139 names of files touched by the revision (normalized and relative to
1145 repository root).
1140 repository root).
1146
1141
1147 filectxfn(repo, memctx, path) is a callable receiving the
1142 filectxfn(repo, memctx, path) is a callable receiving the
1148 repository, the current memctx object and the normalized path of
1143 repository, the current memctx object and the normalized path of
1149 requested file, relative to repository root. It is fired by the
1144 requested file, relative to repository root. It is fired by the
1150 commit function for every file in 'files', but calls order is
1145 commit function for every file in 'files', but calls order is
1151 undefined. If the file is available in the revision being
1146 undefined. If the file is available in the revision being
1152 committed (updated or added), filectxfn returns a memfilectx
1147 committed (updated or added), filectxfn returns a memfilectx
1153 object. If the file was removed, filectxfn raises an
1148 object. If the file was removed, filectxfn raises an
1154 IOError. Moved files are represented by marking the source file
1149 IOError. Moved files are represented by marking the source file
1155 removed and the new file added with copy information (see
1150 removed and the new file added with copy information (see
1156 memfilectx).
1151 memfilectx).
1157
1152
1158 user receives the committer name and defaults to current
1153 user receives the committer name and defaults to current
1159 repository username, date is the commit date in any format
1154 repository username, date is the commit date in any format
1160 supported by util.parsedate() and defaults to current date, extra
1155 supported by util.parsedate() and defaults to current date, extra
1161 is a dictionary of metadata or is left empty.
1156 is a dictionary of metadata or is left empty.
1162 """
1157 """
1163 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1158 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1164 date=None, extra=None):
1159 date=None, extra=None):
1165 self._repo = repo
1160 self._repo = repo
1166 self._rev = None
1161 self._rev = None
1167 self._node = None
1162 self._node = None
1168 self._text = text
1163 self._text = text
1169 self._date = date and util.parsedate(date) or util.makedate()
1164 self._date = date and util.parsedate(date) or util.makedate()
1170 self._user = user
1165 self._user = user
1171 parents = [(p or nullid) for p in parents]
1166 parents = [(p or nullid) for p in parents]
1172 p1, p2 = parents
1167 p1, p2 = parents
1173 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1168 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1174 files = sorted(set(files))
1169 files = sorted(set(files))
1175 self._status = [files, [], [], [], []]
1170 self._status = [files, [], [], [], []]
1176 self._filectxfn = filectxfn
1171 self._filectxfn = filectxfn
1177
1172
1178 self._extra = extra and extra.copy() or {}
1173 self._extra = extra and extra.copy() or {}
1179 if self._extra.get('branch', '') == '':
1174 if self._extra.get('branch', '') == '':
1180 self._extra['branch'] = 'default'
1175 self._extra['branch'] = 'default'
1181
1176
1182 def __str__(self):
1177 def __str__(self):
1183 return str(self._parents[0]) + "+"
1178 return str(self._parents[0]) + "+"
1184
1179
1185 def __int__(self):
1180 def __int__(self):
1186 return self._rev
1181 return self._rev
1187
1182
1188 def __nonzero__(self):
1183 def __nonzero__(self):
1189 return True
1184 return True
1190
1185
1191 def __getitem__(self, key):
1186 def __getitem__(self, key):
1192 return self.filectx(key)
1187 return self.filectx(key)
1193
1188
1194 def p1(self):
1189 def p1(self):
1195 return self._parents[0]
1190 return self._parents[0]
1196 def p2(self):
1191 def p2(self):
1197 return self._parents[1]
1192 return self._parents[1]
1198
1193
1199 def user(self):
1194 def user(self):
1200 return self._user or self._repo.ui.username()
1195 return self._user or self._repo.ui.username()
1201 def date(self):
1196 def date(self):
1202 return self._date
1197 return self._date
1203 def description(self):
1198 def description(self):
1204 return self._text
1199 return self._text
1205 def files(self):
1200 def files(self):
1206 return self.modified()
1201 return self.modified()
1207 def modified(self):
1202 def modified(self):
1208 return self._status[0]
1203 return self._status[0]
1209 def added(self):
1204 def added(self):
1210 return self._status[1]
1205 return self._status[1]
1211 def removed(self):
1206 def removed(self):
1212 return self._status[2]
1207 return self._status[2]
1213 def deleted(self):
1208 def deleted(self):
1214 return self._status[3]
1209 return self._status[3]
1215 def unknown(self):
1210 def unknown(self):
1216 return self._status[4]
1211 return self._status[4]
1217 def ignored(self):
1212 def ignored(self):
1218 return self._status[5]
1213 return self._status[5]
1219 def clean(self):
1214 def clean(self):
1220 return self._status[6]
1215 return self._status[6]
1221 def branch(self):
1216 def branch(self):
1222 return encoding.tolocal(self._extra['branch'])
1217 return encoding.tolocal(self._extra['branch'])
1223 def extra(self):
1218 def extra(self):
1224 return self._extra
1219 return self._extra
1225 def flags(self, f):
1220 def flags(self, f):
1226 return self[f].flags()
1221 return self[f].flags()
1227
1222
1228 def parents(self):
1223 def parents(self):
1229 """return contexts for each parent changeset"""
1224 """return contexts for each parent changeset"""
1230 return self._parents
1225 return self._parents
1231
1226
1232 def filectx(self, path, filelog=None):
1227 def filectx(self, path, filelog=None):
1233 """get a file context from the working directory"""
1228 """get a file context from the working directory"""
1234 return self._filectxfn(self._repo, self, path)
1229 return self._filectxfn(self._repo, self, path)
1235
1230
1236 def commit(self):
1231 def commit(self):
1237 """commit context to the repo"""
1232 """commit context to the repo"""
1238 return self._repo.commitctx(self)
1233 return self._repo.commitctx(self)
1239
1234
1240 class memfilectx(object):
1235 class memfilectx(object):
1241 """memfilectx represents an in-memory file to commit.
1236 """memfilectx represents an in-memory file to commit.
1242
1237
1243 See memctx for more details.
1238 See memctx for more details.
1244 """
1239 """
1245 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1240 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1246 """
1241 """
1247 path is the normalized file path relative to repository root.
1242 path is the normalized file path relative to repository root.
1248 data is the file content as a string.
1243 data is the file content as a string.
1249 islink is True if the file is a symbolic link.
1244 islink is True if the file is a symbolic link.
1250 isexec is True if the file is executable.
1245 isexec is True if the file is executable.
1251 copied is the source file path if current file was copied in the
1246 copied is the source file path if current file was copied in the
1252 revision being committed, or None."""
1247 revision being committed, or None."""
1253 self._path = path
1248 self._path = path
1254 self._data = data
1249 self._data = data
1255 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1250 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1256 self._copied = None
1251 self._copied = None
1257 if copied:
1252 if copied:
1258 self._copied = (copied, nullid)
1253 self._copied = (copied, nullid)
1259
1254
1260 def __nonzero__(self):
1255 def __nonzero__(self):
1261 return True
1256 return True
1262 def __str__(self):
1257 def __str__(self):
1263 return "%s@%s" % (self.path(), self._changectx)
1258 return "%s@%s" % (self.path(), self._changectx)
1264 def path(self):
1259 def path(self):
1265 return self._path
1260 return self._path
1266 def data(self):
1261 def data(self):
1267 return self._data
1262 return self._data
1268 def flags(self):
1263 def flags(self):
1269 return self._flags
1264 return self._flags
1270 def isexec(self):
1265 def isexec(self):
1271 return 'x' in self._flags
1266 return 'x' in self._flags
1272 def islink(self):
1267 def islink(self):
1273 return 'l' in self._flags
1268 return 'l' in self._flags
1274 def renamed(self):
1269 def renamed(self):
1275 return self._copied
1270 return self._copied
@@ -1,241 +1,241 b''
1 # discovery.py - protocol changeset discovery functions
1 # discovery.py - protocol changeset discovery functions
2 #
2 #
3 # Copyright 2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import nullid, short
8 from node import nullid, short
9 from i18n import _
9 from i18n import _
10 import util, setdiscovery, treediscovery, phases
10 import util, setdiscovery, treediscovery, phases
11
11
12 def findcommonincoming(repo, remote, heads=None, force=False):
12 def findcommonincoming(repo, remote, heads=None, force=False):
13 """Return a tuple (common, anyincoming, heads) used to identify the common
13 """Return a tuple (common, anyincoming, heads) used to identify the common
14 subset of nodes between repo and remote.
14 subset of nodes between repo and remote.
15
15
16 "common" is a list of (at least) the heads of the common subset.
16 "common" is a list of (at least) the heads of the common subset.
17 "anyincoming" is testable as a boolean indicating if any nodes are missing
17 "anyincoming" is testable as a boolean indicating if any nodes are missing
18 locally. If remote does not support getbundle, this actually is a list of
18 locally. If remote does not support getbundle, this actually is a list of
19 roots of the nodes that would be incoming, to be supplied to
19 roots of the nodes that would be incoming, to be supplied to
20 changegroupsubset. No code except for pull should be relying on this fact
20 changegroupsubset. No code except for pull should be relying on this fact
21 any longer.
21 any longer.
22 "heads" is either the supplied heads, or else the remote's heads.
22 "heads" is either the supplied heads, or else the remote's heads.
23
23
24 If you pass heads and they are all known locally, the reponse lists justs
24 If you pass heads and they are all known locally, the reponse lists justs
25 these heads in "common" and in "heads".
25 these heads in "common" and in "heads".
26
26
27 Please use findcommonoutgoing to compute the set of outgoing nodes to give
27 Please use findcommonoutgoing to compute the set of outgoing nodes to give
28 extensions a good hook into outgoing.
28 extensions a good hook into outgoing.
29 """
29 """
30
30
31 if not remote.capable('getbundle'):
31 if not remote.capable('getbundle'):
32 return treediscovery.findcommonincoming(repo, remote, heads, force)
32 return treediscovery.findcommonincoming(repo, remote, heads, force)
33
33
34 if heads:
34 if heads:
35 allknown = True
35 allknown = True
36 nm = repo.changelog.nodemap
36 nm = repo.changelog.nodemap
37 for h in heads:
37 for h in heads:
38 if nm.get(h) is None:
38 if nm.get(h) is None:
39 allknown = False
39 allknown = False
40 break
40 break
41 if allknown:
41 if allknown:
42 return (heads, False, heads)
42 return (heads, False, heads)
43
43
44 res = setdiscovery.findcommonheads(repo.ui, repo, remote,
44 res = setdiscovery.findcommonheads(repo.ui, repo, remote,
45 abortwhenunrelated=not force)
45 abortwhenunrelated=not force)
46 common, anyinc, srvheads = res
46 common, anyinc, srvheads = res
47 return (list(common), anyinc, heads or list(srvheads))
47 return (list(common), anyinc, heads or list(srvheads))
48
48
49 class outgoing(object):
49 class outgoing(object):
50 '''Represents the set of nodes present in a local repo but not in a
50 '''Represents the set of nodes present in a local repo but not in a
51 (possibly) remote one.
51 (possibly) remote one.
52
52
53 Members:
53 Members:
54
54
55 missing is a list of all nodes present in local but not in remote.
55 missing is a list of all nodes present in local but not in remote.
56 common is a list of all nodes shared between the two repos.
56 common is a list of all nodes shared between the two repos.
57 excluded is the list of missing changeset that shouldn't be sent remotely.
57 excluded is the list of missing changeset that shouldn't be sent remotely.
58 missingheads is the list of heads of missing.
58 missingheads is the list of heads of missing.
59 commonheads is the list of heads of common.
59 commonheads is the list of heads of common.
60
60
61 The sets are computed on demand from the heads, unless provided upfront
61 The sets are computed on demand from the heads, unless provided upfront
62 by discovery.'''
62 by discovery.'''
63
63
64 def __init__(self, revlog, commonheads, missingheads):
64 def __init__(self, revlog, commonheads, missingheads):
65 self.commonheads = commonheads
65 self.commonheads = commonheads
66 self.missingheads = missingheads
66 self.missingheads = missingheads
67 self._revlog = revlog
67 self._revlog = revlog
68 self._common = None
68 self._common = None
69 self._missing = None
69 self._missing = None
70 self.excluded = []
70 self.excluded = []
71
71
72 def _computecommonmissing(self):
72 def _computecommonmissing(self):
73 sets = self._revlog.findcommonmissing(self.commonheads,
73 sets = self._revlog.findcommonmissing(self.commonheads,
74 self.missingheads)
74 self.missingheads)
75 self._common, self._missing = sets
75 self._common, self._missing = sets
76
76
77 @util.propertycache
77 @util.propertycache
78 def common(self):
78 def common(self):
79 if self._common is None:
79 if self._common is None:
80 self._computecommonmissing()
80 self._computecommonmissing()
81 return self._common
81 return self._common
82
82
83 @util.propertycache
83 @util.propertycache
84 def missing(self):
84 def missing(self):
85 if self._missing is None:
85 if self._missing is None:
86 self._computecommonmissing()
86 self._computecommonmissing()
87 return self._missing
87 return self._missing
88
88
89 def findcommonoutgoing(repo, other, onlyheads=None, force=False, commoninc=None):
89 def findcommonoutgoing(repo, other, onlyheads=None, force=False, commoninc=None):
90 '''Return an outgoing instance to identify the nodes present in repo but
90 '''Return an outgoing instance to identify the nodes present in repo but
91 not in other.
91 not in other.
92
92
93 If onlyheads is given, only nodes ancestral to nodes in onlyheads (inclusive)
93 If onlyheads is given, only nodes ancestral to nodes in onlyheads (inclusive)
94 are included. If you already know the local repo's heads, passing them in
94 are included. If you already know the local repo's heads, passing them in
95 onlyheads is faster than letting them be recomputed here.
95 onlyheads is faster than letting them be recomputed here.
96
96
97 If commoninc is given, it must the the result of a prior call to
97 If commoninc is given, it must the the result of a prior call to
98 findcommonincoming(repo, other, force) to avoid recomputing it here.'''
98 findcommonincoming(repo, other, force) to avoid recomputing it here.'''
99 # declare an empty outgoing object to be filled later
99 # declare an empty outgoing object to be filled later
100 og = outgoing(repo.changelog, None, None)
100 og = outgoing(repo.changelog, None, None)
101
101
102 # get common set if not provided
102 # get common set if not provided
103 if commoninc is None:
103 if commoninc is None:
104 commoninc = findcommonincoming(repo, other, force=force)
104 commoninc = findcommonincoming(repo, other, force=force)
105 og.commonheads, _any, _hds = commoninc
105 og.commonheads, _any, _hds = commoninc
106
106
107 # compute outgoing
107 # compute outgoing
108 if not repo._phaseroots[phases.secret]:
108 if not repo._phasecache.phaseroots[phases.secret]:
109 og.missingheads = onlyheads or repo.heads()
109 og.missingheads = onlyheads or repo.heads()
110 elif onlyheads is None:
110 elif onlyheads is None:
111 # use visible heads as it should be cached
111 # use visible heads as it should be cached
112 og.missingheads = phases.visibleheads(repo)
112 og.missingheads = phases.visibleheads(repo)
113 og.excluded = [ctx.node() for ctx in repo.set('secret()')]
113 og.excluded = [ctx.node() for ctx in repo.set('secret()')]
114 else:
114 else:
115 # compute common, missing and exclude secret stuff
115 # compute common, missing and exclude secret stuff
116 sets = repo.changelog.findcommonmissing(og.commonheads, onlyheads)
116 sets = repo.changelog.findcommonmissing(og.commonheads, onlyheads)
117 og._common, allmissing = sets
117 og._common, allmissing = sets
118 og._missing = missing = []
118 og._missing = missing = []
119 og.excluded = excluded = []
119 og.excluded = excluded = []
120 for node in allmissing:
120 for node in allmissing:
121 if repo[node].phase() >= phases.secret:
121 if repo[node].phase() >= phases.secret:
122 excluded.append(node)
122 excluded.append(node)
123 else:
123 else:
124 missing.append(node)
124 missing.append(node)
125 if excluded:
125 if excluded:
126 # update missing heads
126 # update missing heads
127 missingheads = phases.newheads(repo, onlyheads, excluded)
127 missingheads = phases.newheads(repo, onlyheads, excluded)
128 else:
128 else:
129 missingheads = onlyheads
129 missingheads = onlyheads
130 og.missingheads = missingheads
130 og.missingheads = missingheads
131
131
132 return og
132 return og
133
133
134 def checkheads(repo, remote, outgoing, remoteheads, newbranch=False, inc=False):
134 def checkheads(repo, remote, outgoing, remoteheads, newbranch=False, inc=False):
135 """Check that a push won't add any outgoing head
135 """Check that a push won't add any outgoing head
136
136
137 raise Abort error and display ui message as needed.
137 raise Abort error and display ui message as needed.
138 """
138 """
139 if remoteheads == [nullid]:
139 if remoteheads == [nullid]:
140 # remote is empty, nothing to check.
140 # remote is empty, nothing to check.
141 return
141 return
142
142
143 cl = repo.changelog
143 cl = repo.changelog
144 if remote.capable('branchmap'):
144 if remote.capable('branchmap'):
145 # Check for each named branch if we're creating new remote heads.
145 # Check for each named branch if we're creating new remote heads.
146 # To be a remote head after push, node must be either:
146 # To be a remote head after push, node must be either:
147 # - unknown locally
147 # - unknown locally
148 # - a local outgoing head descended from update
148 # - a local outgoing head descended from update
149 # - a remote head that's known locally and not
149 # - a remote head that's known locally and not
150 # ancestral to an outgoing head
150 # ancestral to an outgoing head
151
151
152 # 1. Create set of branches involved in the push.
152 # 1. Create set of branches involved in the push.
153 branches = set(repo[n].branch() for n in outgoing.missing)
153 branches = set(repo[n].branch() for n in outgoing.missing)
154
154
155 # 2. Check for new branches on the remote.
155 # 2. Check for new branches on the remote.
156 if remote.local():
156 if remote.local():
157 remotemap = phases.visiblebranchmap(remote)
157 remotemap = phases.visiblebranchmap(remote)
158 else:
158 else:
159 remotemap = remote.branchmap()
159 remotemap = remote.branchmap()
160 newbranches = branches - set(remotemap)
160 newbranches = branches - set(remotemap)
161 if newbranches and not newbranch: # new branch requires --new-branch
161 if newbranches and not newbranch: # new branch requires --new-branch
162 branchnames = ', '.join(sorted(newbranches))
162 branchnames = ', '.join(sorted(newbranches))
163 raise util.Abort(_("push creates new remote branches: %s!")
163 raise util.Abort(_("push creates new remote branches: %s!")
164 % branchnames,
164 % branchnames,
165 hint=_("use 'hg push --new-branch' to create"
165 hint=_("use 'hg push --new-branch' to create"
166 " new remote branches"))
166 " new remote branches"))
167 branches.difference_update(newbranches)
167 branches.difference_update(newbranches)
168
168
169 # 3. Construct the initial oldmap and newmap dicts.
169 # 3. Construct the initial oldmap and newmap dicts.
170 # They contain information about the remote heads before and
170 # They contain information about the remote heads before and
171 # after the push, respectively.
171 # after the push, respectively.
172 # Heads not found locally are not included in either dict,
172 # Heads not found locally are not included in either dict,
173 # since they won't be affected by the push.
173 # since they won't be affected by the push.
174 # unsynced contains all branches with incoming changesets.
174 # unsynced contains all branches with incoming changesets.
175 oldmap = {}
175 oldmap = {}
176 newmap = {}
176 newmap = {}
177 unsynced = set()
177 unsynced = set()
178 for branch in branches:
178 for branch in branches:
179 remotebrheads = remotemap[branch]
179 remotebrheads = remotemap[branch]
180 prunedbrheads = [h for h in remotebrheads if h in cl.nodemap]
180 prunedbrheads = [h for h in remotebrheads if h in cl.nodemap]
181 oldmap[branch] = prunedbrheads
181 oldmap[branch] = prunedbrheads
182 newmap[branch] = list(prunedbrheads)
182 newmap[branch] = list(prunedbrheads)
183 if len(remotebrheads) > len(prunedbrheads):
183 if len(remotebrheads) > len(prunedbrheads):
184 unsynced.add(branch)
184 unsynced.add(branch)
185
185
186 # 4. Update newmap with outgoing changes.
186 # 4. Update newmap with outgoing changes.
187 # This will possibly add new heads and remove existing ones.
187 # This will possibly add new heads and remove existing ones.
188 ctxgen = (repo[n] for n in outgoing.missing)
188 ctxgen = (repo[n] for n in outgoing.missing)
189 repo._updatebranchcache(newmap, ctxgen)
189 repo._updatebranchcache(newmap, ctxgen)
190
190
191 else:
191 else:
192 # 1-4b. old servers: Check for new topological heads.
192 # 1-4b. old servers: Check for new topological heads.
193 # Construct {old,new}map with branch = None (topological branch).
193 # Construct {old,new}map with branch = None (topological branch).
194 # (code based on _updatebranchcache)
194 # (code based on _updatebranchcache)
195 oldheads = set(h for h in remoteheads if h in cl.nodemap)
195 oldheads = set(h for h in remoteheads if h in cl.nodemap)
196 newheads = oldheads.union(outgoing.missing)
196 newheads = oldheads.union(outgoing.missing)
197 if len(newheads) > 1:
197 if len(newheads) > 1:
198 for latest in reversed(outgoing.missing):
198 for latest in reversed(outgoing.missing):
199 if latest not in newheads:
199 if latest not in newheads:
200 continue
200 continue
201 minhrev = min(cl.rev(h) for h in newheads)
201 minhrev = min(cl.rev(h) for h in newheads)
202 reachable = cl.reachable(latest, cl.node(minhrev))
202 reachable = cl.reachable(latest, cl.node(minhrev))
203 reachable.remove(latest)
203 reachable.remove(latest)
204 newheads.difference_update(reachable)
204 newheads.difference_update(reachable)
205 branches = set([None])
205 branches = set([None])
206 newmap = {None: newheads}
206 newmap = {None: newheads}
207 oldmap = {None: oldheads}
207 oldmap = {None: oldheads}
208 unsynced = inc and branches or set()
208 unsynced = inc and branches or set()
209
209
210 # 5. Check for new heads.
210 # 5. Check for new heads.
211 # If there are more heads after the push than before, a suitable
211 # If there are more heads after the push than before, a suitable
212 # error message, depending on unsynced status, is displayed.
212 # error message, depending on unsynced status, is displayed.
213 error = None
213 error = None
214 for branch in branches:
214 for branch in branches:
215 newhs = set(newmap[branch])
215 newhs = set(newmap[branch])
216 oldhs = set(oldmap[branch])
216 oldhs = set(oldmap[branch])
217 if len(newhs) > len(oldhs):
217 if len(newhs) > len(oldhs):
218 dhs = list(newhs - oldhs)
218 dhs = list(newhs - oldhs)
219 if error is None:
219 if error is None:
220 if branch not in ('default', None):
220 if branch not in ('default', None):
221 error = _("push creates new remote head %s "
221 error = _("push creates new remote head %s "
222 "on branch '%s'!") % (short(dhs[0]), branch)
222 "on branch '%s'!") % (short(dhs[0]), branch)
223 else:
223 else:
224 error = _("push creates new remote head %s!"
224 error = _("push creates new remote head %s!"
225 ) % short(dhs[0])
225 ) % short(dhs[0])
226 if branch in unsynced:
226 if branch in unsynced:
227 hint = _("you should pull and merge or "
227 hint = _("you should pull and merge or "
228 "use push -f to force")
228 "use push -f to force")
229 else:
229 else:
230 hint = _("did you forget to merge? "
230 hint = _("did you forget to merge? "
231 "use push -f to force")
231 "use push -f to force")
232 if branch is not None:
232 if branch is not None:
233 repo.ui.note(_("new remote heads on branch '%s'\n") % branch)
233 repo.ui.note(_("new remote heads on branch '%s'\n") % branch)
234 for h in dhs:
234 for h in dhs:
235 repo.ui.note(_("new remote head %s\n") % short(h))
235 repo.ui.note(_("new remote head %s\n") % short(h))
236 if error:
236 if error:
237 raise util.Abort(error, hint=hint)
237 raise util.Abort(error, hint=hint)
238
238
239 # 6. Check for unsynced changes on involved branches.
239 # 6. Check for unsynced changes on involved branches.
240 if unsynced:
240 if unsynced:
241 repo.ui.warn(_("note: unsynced remote changes!\n"))
241 repo.ui.warn(_("note: unsynced remote changes!\n"))
@@ -1,2351 +1,2335 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup, subrepo, discovery, pushkey
10 import repo, changegroup, subrepo, discovery, pushkey
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import scmutil, util, extensions, hook, error, revset
13 import scmutil, util, extensions, hook, error, revset
14 import match as matchmod
14 import match as matchmod
15 import merge as mergemod
15 import merge as mergemod
16 import tags as tagsmod
16 import tags as tagsmod
17 from lock import release
17 from lock import release
18 import weakref, errno, os, time, inspect
18 import weakref, errno, os, time, inspect
19 propertycache = util.propertycache
19 propertycache = util.propertycache
20 filecache = scmutil.filecache
20 filecache = scmutil.filecache
21
21
22 class storecache(filecache):
22 class storecache(filecache):
23 """filecache for files in the store"""
23 """filecache for files in the store"""
24 def join(self, obj, fname):
24 def join(self, obj, fname):
25 return obj.sjoin(fname)
25 return obj.sjoin(fname)
26
26
27 class localrepository(repo.repository):
27 class localrepository(repo.repository):
28 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
28 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
29 'known', 'getbundle'))
29 'known', 'getbundle'))
30 supportedformats = set(('revlogv1', 'generaldelta'))
30 supportedformats = set(('revlogv1', 'generaldelta'))
31 supported = supportedformats | set(('store', 'fncache', 'shared',
31 supported = supportedformats | set(('store', 'fncache', 'shared',
32 'dotencode'))
32 'dotencode'))
33
33
34 def __init__(self, baseui, path=None, create=False):
34 def __init__(self, baseui, path=None, create=False):
35 repo.repository.__init__(self)
35 repo.repository.__init__(self)
36 self.root = os.path.realpath(util.expandpath(path))
36 self.root = os.path.realpath(util.expandpath(path))
37 self.path = os.path.join(self.root, ".hg")
37 self.path = os.path.join(self.root, ".hg")
38 self.origroot = path
38 self.origroot = path
39 self.auditor = scmutil.pathauditor(self.root, self._checknested)
39 self.auditor = scmutil.pathauditor(self.root, self._checknested)
40 self.opener = scmutil.opener(self.path)
40 self.opener = scmutil.opener(self.path)
41 self.wopener = scmutil.opener(self.root)
41 self.wopener = scmutil.opener(self.root)
42 self.baseui = baseui
42 self.baseui = baseui
43 self.ui = baseui.copy()
43 self.ui = baseui.copy()
44 self._dirtyphases = False
45 # A list of callback to shape the phase if no data were found.
44 # A list of callback to shape the phase if no data were found.
46 # Callback are in the form: func(repo, roots) --> processed root.
45 # Callback are in the form: func(repo, roots) --> processed root.
47 # This list it to be filled by extension during repo setup
46 # This list it to be filled by extension during repo setup
48 self._phasedefaults = []
47 self._phasedefaults = []
49
48
50 try:
49 try:
51 self.ui.readconfig(self.join("hgrc"), self.root)
50 self.ui.readconfig(self.join("hgrc"), self.root)
52 extensions.loadall(self.ui)
51 extensions.loadall(self.ui)
53 except IOError:
52 except IOError:
54 pass
53 pass
55
54
56 if not os.path.isdir(self.path):
55 if not os.path.isdir(self.path):
57 if create:
56 if create:
58 if not os.path.exists(path):
57 if not os.path.exists(path):
59 util.makedirs(path)
58 util.makedirs(path)
60 util.makedir(self.path, notindexed=True)
59 util.makedir(self.path, notindexed=True)
61 requirements = ["revlogv1"]
60 requirements = ["revlogv1"]
62 if self.ui.configbool('format', 'usestore', True):
61 if self.ui.configbool('format', 'usestore', True):
63 os.mkdir(os.path.join(self.path, "store"))
62 os.mkdir(os.path.join(self.path, "store"))
64 requirements.append("store")
63 requirements.append("store")
65 if self.ui.configbool('format', 'usefncache', True):
64 if self.ui.configbool('format', 'usefncache', True):
66 requirements.append("fncache")
65 requirements.append("fncache")
67 if self.ui.configbool('format', 'dotencode', True):
66 if self.ui.configbool('format', 'dotencode', True):
68 requirements.append('dotencode')
67 requirements.append('dotencode')
69 # create an invalid changelog
68 # create an invalid changelog
70 self.opener.append(
69 self.opener.append(
71 "00changelog.i",
70 "00changelog.i",
72 '\0\0\0\2' # represents revlogv2
71 '\0\0\0\2' # represents revlogv2
73 ' dummy changelog to prevent using the old repo layout'
72 ' dummy changelog to prevent using the old repo layout'
74 )
73 )
75 if self.ui.configbool('format', 'generaldelta', False):
74 if self.ui.configbool('format', 'generaldelta', False):
76 requirements.append("generaldelta")
75 requirements.append("generaldelta")
77 requirements = set(requirements)
76 requirements = set(requirements)
78 else:
77 else:
79 raise error.RepoError(_("repository %s not found") % path)
78 raise error.RepoError(_("repository %s not found") % path)
80 elif create:
79 elif create:
81 raise error.RepoError(_("repository %s already exists") % path)
80 raise error.RepoError(_("repository %s already exists") % path)
82 else:
81 else:
83 try:
82 try:
84 requirements = scmutil.readrequires(self.opener, self.supported)
83 requirements = scmutil.readrequires(self.opener, self.supported)
85 except IOError, inst:
84 except IOError, inst:
86 if inst.errno != errno.ENOENT:
85 if inst.errno != errno.ENOENT:
87 raise
86 raise
88 requirements = set()
87 requirements = set()
89
88
90 self.sharedpath = self.path
89 self.sharedpath = self.path
91 try:
90 try:
92 s = os.path.realpath(self.opener.read("sharedpath").rstrip('\n'))
91 s = os.path.realpath(self.opener.read("sharedpath").rstrip('\n'))
93 if not os.path.exists(s):
92 if not os.path.exists(s):
94 raise error.RepoError(
93 raise error.RepoError(
95 _('.hg/sharedpath points to nonexistent directory %s') % s)
94 _('.hg/sharedpath points to nonexistent directory %s') % s)
96 self.sharedpath = s
95 self.sharedpath = s
97 except IOError, inst:
96 except IOError, inst:
98 if inst.errno != errno.ENOENT:
97 if inst.errno != errno.ENOENT:
99 raise
98 raise
100
99
101 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
100 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
102 self.spath = self.store.path
101 self.spath = self.store.path
103 self.sopener = self.store.opener
102 self.sopener = self.store.opener
104 self.sjoin = self.store.join
103 self.sjoin = self.store.join
105 self.opener.createmode = self.store.createmode
104 self.opener.createmode = self.store.createmode
106 self._applyrequirements(requirements)
105 self._applyrequirements(requirements)
107 if create:
106 if create:
108 self._writerequirements()
107 self._writerequirements()
109
108
110
109
111 self._branchcache = None
110 self._branchcache = None
112 self._branchcachetip = None
111 self._branchcachetip = None
113 self.filterpats = {}
112 self.filterpats = {}
114 self._datafilters = {}
113 self._datafilters = {}
115 self._transref = self._lockref = self._wlockref = None
114 self._transref = self._lockref = self._wlockref = None
116
115
117 # A cache for various files under .hg/ that tracks file changes,
116 # A cache for various files under .hg/ that tracks file changes,
118 # (used by the filecache decorator)
117 # (used by the filecache decorator)
119 #
118 #
120 # Maps a property name to its util.filecacheentry
119 # Maps a property name to its util.filecacheentry
121 self._filecache = {}
120 self._filecache = {}
122
121
123 def _applyrequirements(self, requirements):
122 def _applyrequirements(self, requirements):
124 self.requirements = requirements
123 self.requirements = requirements
125 openerreqs = set(('revlogv1', 'generaldelta'))
124 openerreqs = set(('revlogv1', 'generaldelta'))
126 self.sopener.options = dict((r, 1) for r in requirements
125 self.sopener.options = dict((r, 1) for r in requirements
127 if r in openerreqs)
126 if r in openerreqs)
128
127
129 def _writerequirements(self):
128 def _writerequirements(self):
130 reqfile = self.opener("requires", "w")
129 reqfile = self.opener("requires", "w")
131 for r in self.requirements:
130 for r in self.requirements:
132 reqfile.write("%s\n" % r)
131 reqfile.write("%s\n" % r)
133 reqfile.close()
132 reqfile.close()
134
133
135 def _checknested(self, path):
134 def _checknested(self, path):
136 """Determine if path is a legal nested repository."""
135 """Determine if path is a legal nested repository."""
137 if not path.startswith(self.root):
136 if not path.startswith(self.root):
138 return False
137 return False
139 subpath = path[len(self.root) + 1:]
138 subpath = path[len(self.root) + 1:]
140 normsubpath = util.pconvert(subpath)
139 normsubpath = util.pconvert(subpath)
141
140
142 # XXX: Checking against the current working copy is wrong in
141 # XXX: Checking against the current working copy is wrong in
143 # the sense that it can reject things like
142 # the sense that it can reject things like
144 #
143 #
145 # $ hg cat -r 10 sub/x.txt
144 # $ hg cat -r 10 sub/x.txt
146 #
145 #
147 # if sub/ is no longer a subrepository in the working copy
146 # if sub/ is no longer a subrepository in the working copy
148 # parent revision.
147 # parent revision.
149 #
148 #
150 # However, it can of course also allow things that would have
149 # However, it can of course also allow things that would have
151 # been rejected before, such as the above cat command if sub/
150 # been rejected before, such as the above cat command if sub/
152 # is a subrepository now, but was a normal directory before.
151 # is a subrepository now, but was a normal directory before.
153 # The old path auditor would have rejected by mistake since it
152 # The old path auditor would have rejected by mistake since it
154 # panics when it sees sub/.hg/.
153 # panics when it sees sub/.hg/.
155 #
154 #
156 # All in all, checking against the working copy seems sensible
155 # All in all, checking against the working copy seems sensible
157 # since we want to prevent access to nested repositories on
156 # since we want to prevent access to nested repositories on
158 # the filesystem *now*.
157 # the filesystem *now*.
159 ctx = self[None]
158 ctx = self[None]
160 parts = util.splitpath(subpath)
159 parts = util.splitpath(subpath)
161 while parts:
160 while parts:
162 prefix = '/'.join(parts)
161 prefix = '/'.join(parts)
163 if prefix in ctx.substate:
162 if prefix in ctx.substate:
164 if prefix == normsubpath:
163 if prefix == normsubpath:
165 return True
164 return True
166 else:
165 else:
167 sub = ctx.sub(prefix)
166 sub = ctx.sub(prefix)
168 return sub.checknested(subpath[len(prefix) + 1:])
167 return sub.checknested(subpath[len(prefix) + 1:])
169 else:
168 else:
170 parts.pop()
169 parts.pop()
171 return False
170 return False
172
171
173 @filecache('bookmarks')
172 @filecache('bookmarks')
174 def _bookmarks(self):
173 def _bookmarks(self):
175 return bookmarks.read(self)
174 return bookmarks.read(self)
176
175
177 @filecache('bookmarks.current')
176 @filecache('bookmarks.current')
178 def _bookmarkcurrent(self):
177 def _bookmarkcurrent(self):
179 return bookmarks.readcurrent(self)
178 return bookmarks.readcurrent(self)
180
179
181 def _writebookmarks(self, marks):
180 def _writebookmarks(self, marks):
182 bookmarks.write(self)
181 bookmarks.write(self)
183
182
184 @storecache('phaseroots')
183 @storecache('phaseroots')
185 def _phaseroots(self):
184 def _phasecache(self):
186 phaseroots, self._dirtyphases = phases.readroots(
185 return phases.phasecache(self, self._phasedefaults)
187 self, self._phasedefaults)
188 return phaseroots
189
190 @propertycache
191 def _phaserev(self):
192 cache = [phases.public] * len(self)
193 for phase in phases.trackedphases:
194 roots = map(self.changelog.rev, self._phaseroots[phase])
195 if roots:
196 for rev in roots:
197 cache[rev] = phase
198 for rev in self.changelog.descendants(*roots):
199 cache[rev] = phase
200 return cache
201
186
202 @storecache('00changelog.i')
187 @storecache('00changelog.i')
203 def changelog(self):
188 def changelog(self):
204 c = changelog.changelog(self.sopener)
189 c = changelog.changelog(self.sopener)
205 if 'HG_PENDING' in os.environ:
190 if 'HG_PENDING' in os.environ:
206 p = os.environ['HG_PENDING']
191 p = os.environ['HG_PENDING']
207 if p.startswith(self.root):
192 if p.startswith(self.root):
208 c.readpending('00changelog.i.a')
193 c.readpending('00changelog.i.a')
209 return c
194 return c
210
195
211 @storecache('00manifest.i')
196 @storecache('00manifest.i')
212 def manifest(self):
197 def manifest(self):
213 return manifest.manifest(self.sopener)
198 return manifest.manifest(self.sopener)
214
199
215 @filecache('dirstate')
200 @filecache('dirstate')
216 def dirstate(self):
201 def dirstate(self):
217 warned = [0]
202 warned = [0]
218 def validate(node):
203 def validate(node):
219 try:
204 try:
220 self.changelog.rev(node)
205 self.changelog.rev(node)
221 return node
206 return node
222 except error.LookupError:
207 except error.LookupError:
223 if not warned[0]:
208 if not warned[0]:
224 warned[0] = True
209 warned[0] = True
225 self.ui.warn(_("warning: ignoring unknown"
210 self.ui.warn(_("warning: ignoring unknown"
226 " working parent %s!\n") % short(node))
211 " working parent %s!\n") % short(node))
227 return nullid
212 return nullid
228
213
229 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
214 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
230
215
231 def __getitem__(self, changeid):
216 def __getitem__(self, changeid):
232 if changeid is None:
217 if changeid is None:
233 return context.workingctx(self)
218 return context.workingctx(self)
234 return context.changectx(self, changeid)
219 return context.changectx(self, changeid)
235
220
236 def __contains__(self, changeid):
221 def __contains__(self, changeid):
237 try:
222 try:
238 return bool(self.lookup(changeid))
223 return bool(self.lookup(changeid))
239 except error.RepoLookupError:
224 except error.RepoLookupError:
240 return False
225 return False
241
226
242 def __nonzero__(self):
227 def __nonzero__(self):
243 return True
228 return True
244
229
245 def __len__(self):
230 def __len__(self):
246 return len(self.changelog)
231 return len(self.changelog)
247
232
248 def __iter__(self):
233 def __iter__(self):
249 for i in xrange(len(self)):
234 for i in xrange(len(self)):
250 yield i
235 yield i
251
236
252 def revs(self, expr, *args):
237 def revs(self, expr, *args):
253 '''Return a list of revisions matching the given revset'''
238 '''Return a list of revisions matching the given revset'''
254 expr = revset.formatspec(expr, *args)
239 expr = revset.formatspec(expr, *args)
255 m = revset.match(None, expr)
240 m = revset.match(None, expr)
256 return [r for r in m(self, range(len(self)))]
241 return [r for r in m(self, range(len(self)))]
257
242
258 def set(self, expr, *args):
243 def set(self, expr, *args):
259 '''
244 '''
260 Yield a context for each matching revision, after doing arg
245 Yield a context for each matching revision, after doing arg
261 replacement via revset.formatspec
246 replacement via revset.formatspec
262 '''
247 '''
263 for r in self.revs(expr, *args):
248 for r in self.revs(expr, *args):
264 yield self[r]
249 yield self[r]
265
250
266 def url(self):
251 def url(self):
267 return 'file:' + self.root
252 return 'file:' + self.root
268
253
269 def hook(self, name, throw=False, **args):
254 def hook(self, name, throw=False, **args):
270 return hook.hook(self.ui, self, name, throw, **args)
255 return hook.hook(self.ui, self, name, throw, **args)
271
256
272 tag_disallowed = ':\r\n'
257 tag_disallowed = ':\r\n'
273
258
274 def _tag(self, names, node, message, local, user, date, extra={}):
259 def _tag(self, names, node, message, local, user, date, extra={}):
275 if isinstance(names, str):
260 if isinstance(names, str):
276 allchars = names
261 allchars = names
277 names = (names,)
262 names = (names,)
278 else:
263 else:
279 allchars = ''.join(names)
264 allchars = ''.join(names)
280 for c in self.tag_disallowed:
265 for c in self.tag_disallowed:
281 if c in allchars:
266 if c in allchars:
282 raise util.Abort(_('%r cannot be used in a tag name') % c)
267 raise util.Abort(_('%r cannot be used in a tag name') % c)
283
268
284 branches = self.branchmap()
269 branches = self.branchmap()
285 for name in names:
270 for name in names:
286 self.hook('pretag', throw=True, node=hex(node), tag=name,
271 self.hook('pretag', throw=True, node=hex(node), tag=name,
287 local=local)
272 local=local)
288 if name in branches:
273 if name in branches:
289 self.ui.warn(_("warning: tag %s conflicts with existing"
274 self.ui.warn(_("warning: tag %s conflicts with existing"
290 " branch name\n") % name)
275 " branch name\n") % name)
291
276
292 def writetags(fp, names, munge, prevtags):
277 def writetags(fp, names, munge, prevtags):
293 fp.seek(0, 2)
278 fp.seek(0, 2)
294 if prevtags and prevtags[-1] != '\n':
279 if prevtags and prevtags[-1] != '\n':
295 fp.write('\n')
280 fp.write('\n')
296 for name in names:
281 for name in names:
297 m = munge and munge(name) or name
282 m = munge and munge(name) or name
298 if self._tagscache.tagtypes and name in self._tagscache.tagtypes:
283 if self._tagscache.tagtypes and name in self._tagscache.tagtypes:
299 old = self.tags().get(name, nullid)
284 old = self.tags().get(name, nullid)
300 fp.write('%s %s\n' % (hex(old), m))
285 fp.write('%s %s\n' % (hex(old), m))
301 fp.write('%s %s\n' % (hex(node), m))
286 fp.write('%s %s\n' % (hex(node), m))
302 fp.close()
287 fp.close()
303
288
304 prevtags = ''
289 prevtags = ''
305 if local:
290 if local:
306 try:
291 try:
307 fp = self.opener('localtags', 'r+')
292 fp = self.opener('localtags', 'r+')
308 except IOError:
293 except IOError:
309 fp = self.opener('localtags', 'a')
294 fp = self.opener('localtags', 'a')
310 else:
295 else:
311 prevtags = fp.read()
296 prevtags = fp.read()
312
297
313 # local tags are stored in the current charset
298 # local tags are stored in the current charset
314 writetags(fp, names, None, prevtags)
299 writetags(fp, names, None, prevtags)
315 for name in names:
300 for name in names:
316 self.hook('tag', node=hex(node), tag=name, local=local)
301 self.hook('tag', node=hex(node), tag=name, local=local)
317 return
302 return
318
303
319 try:
304 try:
320 fp = self.wfile('.hgtags', 'rb+')
305 fp = self.wfile('.hgtags', 'rb+')
321 except IOError, e:
306 except IOError, e:
322 if e.errno != errno.ENOENT:
307 if e.errno != errno.ENOENT:
323 raise
308 raise
324 fp = self.wfile('.hgtags', 'ab')
309 fp = self.wfile('.hgtags', 'ab')
325 else:
310 else:
326 prevtags = fp.read()
311 prevtags = fp.read()
327
312
328 # committed tags are stored in UTF-8
313 # committed tags are stored in UTF-8
329 writetags(fp, names, encoding.fromlocal, prevtags)
314 writetags(fp, names, encoding.fromlocal, prevtags)
330
315
331 fp.close()
316 fp.close()
332
317
333 self.invalidatecaches()
318 self.invalidatecaches()
334
319
335 if '.hgtags' not in self.dirstate:
320 if '.hgtags' not in self.dirstate:
336 self[None].add(['.hgtags'])
321 self[None].add(['.hgtags'])
337
322
338 m = matchmod.exact(self.root, '', ['.hgtags'])
323 m = matchmod.exact(self.root, '', ['.hgtags'])
339 tagnode = self.commit(message, user, date, extra=extra, match=m)
324 tagnode = self.commit(message, user, date, extra=extra, match=m)
340
325
341 for name in names:
326 for name in names:
342 self.hook('tag', node=hex(node), tag=name, local=local)
327 self.hook('tag', node=hex(node), tag=name, local=local)
343
328
344 return tagnode
329 return tagnode
345
330
346 def tag(self, names, node, message, local, user, date):
331 def tag(self, names, node, message, local, user, date):
347 '''tag a revision with one or more symbolic names.
332 '''tag a revision with one or more symbolic names.
348
333
349 names is a list of strings or, when adding a single tag, names may be a
334 names is a list of strings or, when adding a single tag, names may be a
350 string.
335 string.
351
336
352 if local is True, the tags are stored in a per-repository file.
337 if local is True, the tags are stored in a per-repository file.
353 otherwise, they are stored in the .hgtags file, and a new
338 otherwise, they are stored in the .hgtags file, and a new
354 changeset is committed with the change.
339 changeset is committed with the change.
355
340
356 keyword arguments:
341 keyword arguments:
357
342
358 local: whether to store tags in non-version-controlled file
343 local: whether to store tags in non-version-controlled file
359 (default False)
344 (default False)
360
345
361 message: commit message to use if committing
346 message: commit message to use if committing
362
347
363 user: name of user to use if committing
348 user: name of user to use if committing
364
349
365 date: date tuple to use if committing'''
350 date: date tuple to use if committing'''
366
351
367 if not local:
352 if not local:
368 for x in self.status()[:5]:
353 for x in self.status()[:5]:
369 if '.hgtags' in x:
354 if '.hgtags' in x:
370 raise util.Abort(_('working copy of .hgtags is changed '
355 raise util.Abort(_('working copy of .hgtags is changed '
371 '(please commit .hgtags manually)'))
356 '(please commit .hgtags manually)'))
372
357
373 self.tags() # instantiate the cache
358 self.tags() # instantiate the cache
374 self._tag(names, node, message, local, user, date)
359 self._tag(names, node, message, local, user, date)
375
360
376 @propertycache
361 @propertycache
377 def _tagscache(self):
362 def _tagscache(self):
378 '''Returns a tagscache object that contains various tags related caches.'''
363 '''Returns a tagscache object that contains various tags related caches.'''
379
364
380 # This simplifies its cache management by having one decorated
365 # This simplifies its cache management by having one decorated
381 # function (this one) and the rest simply fetch things from it.
366 # function (this one) and the rest simply fetch things from it.
382 class tagscache(object):
367 class tagscache(object):
383 def __init__(self):
368 def __init__(self):
384 # These two define the set of tags for this repository. tags
369 # These two define the set of tags for this repository. tags
385 # maps tag name to node; tagtypes maps tag name to 'global' or
370 # maps tag name to node; tagtypes maps tag name to 'global' or
386 # 'local'. (Global tags are defined by .hgtags across all
371 # 'local'. (Global tags are defined by .hgtags across all
387 # heads, and local tags are defined in .hg/localtags.)
372 # heads, and local tags are defined in .hg/localtags.)
388 # They constitute the in-memory cache of tags.
373 # They constitute the in-memory cache of tags.
389 self.tags = self.tagtypes = None
374 self.tags = self.tagtypes = None
390
375
391 self.nodetagscache = self.tagslist = None
376 self.nodetagscache = self.tagslist = None
392
377
393 cache = tagscache()
378 cache = tagscache()
394 cache.tags, cache.tagtypes = self._findtags()
379 cache.tags, cache.tagtypes = self._findtags()
395
380
396 return cache
381 return cache
397
382
398 def tags(self):
383 def tags(self):
399 '''return a mapping of tag to node'''
384 '''return a mapping of tag to node'''
400 t = {}
385 t = {}
401 for k, v in self._tagscache.tags.iteritems():
386 for k, v in self._tagscache.tags.iteritems():
402 try:
387 try:
403 # ignore tags to unknown nodes
388 # ignore tags to unknown nodes
404 self.changelog.rev(v)
389 self.changelog.rev(v)
405 t[k] = v
390 t[k] = v
406 except error.LookupError:
391 except error.LookupError:
407 pass
392 pass
408 return t
393 return t
409
394
410 def _findtags(self):
395 def _findtags(self):
411 '''Do the hard work of finding tags. Return a pair of dicts
396 '''Do the hard work of finding tags. Return a pair of dicts
412 (tags, tagtypes) where tags maps tag name to node, and tagtypes
397 (tags, tagtypes) where tags maps tag name to node, and tagtypes
413 maps tag name to a string like \'global\' or \'local\'.
398 maps tag name to a string like \'global\' or \'local\'.
414 Subclasses or extensions are free to add their own tags, but
399 Subclasses or extensions are free to add their own tags, but
415 should be aware that the returned dicts will be retained for the
400 should be aware that the returned dicts will be retained for the
416 duration of the localrepo object.'''
401 duration of the localrepo object.'''
417
402
418 # XXX what tagtype should subclasses/extensions use? Currently
403 # XXX what tagtype should subclasses/extensions use? Currently
419 # mq and bookmarks add tags, but do not set the tagtype at all.
404 # mq and bookmarks add tags, but do not set the tagtype at all.
420 # Should each extension invent its own tag type? Should there
405 # Should each extension invent its own tag type? Should there
421 # be one tagtype for all such "virtual" tags? Or is the status
406 # be one tagtype for all such "virtual" tags? Or is the status
422 # quo fine?
407 # quo fine?
423
408
424 alltags = {} # map tag name to (node, hist)
409 alltags = {} # map tag name to (node, hist)
425 tagtypes = {}
410 tagtypes = {}
426
411
427 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
412 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
428 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
413 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
429
414
430 # Build the return dicts. Have to re-encode tag names because
415 # Build the return dicts. Have to re-encode tag names because
431 # the tags module always uses UTF-8 (in order not to lose info
416 # the tags module always uses UTF-8 (in order not to lose info
432 # writing to the cache), but the rest of Mercurial wants them in
417 # writing to the cache), but the rest of Mercurial wants them in
433 # local encoding.
418 # local encoding.
434 tags = {}
419 tags = {}
435 for (name, (node, hist)) in alltags.iteritems():
420 for (name, (node, hist)) in alltags.iteritems():
436 if node != nullid:
421 if node != nullid:
437 tags[encoding.tolocal(name)] = node
422 tags[encoding.tolocal(name)] = node
438 tags['tip'] = self.changelog.tip()
423 tags['tip'] = self.changelog.tip()
439 tagtypes = dict([(encoding.tolocal(name), value)
424 tagtypes = dict([(encoding.tolocal(name), value)
440 for (name, value) in tagtypes.iteritems()])
425 for (name, value) in tagtypes.iteritems()])
441 return (tags, tagtypes)
426 return (tags, tagtypes)
442
427
443 def tagtype(self, tagname):
428 def tagtype(self, tagname):
444 '''
429 '''
445 return the type of the given tag. result can be:
430 return the type of the given tag. result can be:
446
431
447 'local' : a local tag
432 'local' : a local tag
448 'global' : a global tag
433 'global' : a global tag
449 None : tag does not exist
434 None : tag does not exist
450 '''
435 '''
451
436
452 return self._tagscache.tagtypes.get(tagname)
437 return self._tagscache.tagtypes.get(tagname)
453
438
454 def tagslist(self):
439 def tagslist(self):
455 '''return a list of tags ordered by revision'''
440 '''return a list of tags ordered by revision'''
456 if not self._tagscache.tagslist:
441 if not self._tagscache.tagslist:
457 l = []
442 l = []
458 for t, n in self.tags().iteritems():
443 for t, n in self.tags().iteritems():
459 r = self.changelog.rev(n)
444 r = self.changelog.rev(n)
460 l.append((r, t, n))
445 l.append((r, t, n))
461 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
446 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
462
447
463 return self._tagscache.tagslist
448 return self._tagscache.tagslist
464
449
465 def nodetags(self, node):
450 def nodetags(self, node):
466 '''return the tags associated with a node'''
451 '''return the tags associated with a node'''
467 if not self._tagscache.nodetagscache:
452 if not self._tagscache.nodetagscache:
468 nodetagscache = {}
453 nodetagscache = {}
469 for t, n in self._tagscache.tags.iteritems():
454 for t, n in self._tagscache.tags.iteritems():
470 nodetagscache.setdefault(n, []).append(t)
455 nodetagscache.setdefault(n, []).append(t)
471 for tags in nodetagscache.itervalues():
456 for tags in nodetagscache.itervalues():
472 tags.sort()
457 tags.sort()
473 self._tagscache.nodetagscache = nodetagscache
458 self._tagscache.nodetagscache = nodetagscache
474 return self._tagscache.nodetagscache.get(node, [])
459 return self._tagscache.nodetagscache.get(node, [])
475
460
476 def nodebookmarks(self, node):
461 def nodebookmarks(self, node):
477 marks = []
462 marks = []
478 for bookmark, n in self._bookmarks.iteritems():
463 for bookmark, n in self._bookmarks.iteritems():
479 if n == node:
464 if n == node:
480 marks.append(bookmark)
465 marks.append(bookmark)
481 return sorted(marks)
466 return sorted(marks)
482
467
483 def _branchtags(self, partial, lrev):
468 def _branchtags(self, partial, lrev):
484 # TODO: rename this function?
469 # TODO: rename this function?
485 tiprev = len(self) - 1
470 tiprev = len(self) - 1
486 if lrev != tiprev:
471 if lrev != tiprev:
487 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
472 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
488 self._updatebranchcache(partial, ctxgen)
473 self._updatebranchcache(partial, ctxgen)
489 self._writebranchcache(partial, self.changelog.tip(), tiprev)
474 self._writebranchcache(partial, self.changelog.tip(), tiprev)
490
475
491 return partial
476 return partial
492
477
493 def updatebranchcache(self):
478 def updatebranchcache(self):
494 tip = self.changelog.tip()
479 tip = self.changelog.tip()
495 if self._branchcache is not None and self._branchcachetip == tip:
480 if self._branchcache is not None and self._branchcachetip == tip:
496 return
481 return
497
482
498 oldtip = self._branchcachetip
483 oldtip = self._branchcachetip
499 self._branchcachetip = tip
484 self._branchcachetip = tip
500 if oldtip is None or oldtip not in self.changelog.nodemap:
485 if oldtip is None or oldtip not in self.changelog.nodemap:
501 partial, last, lrev = self._readbranchcache()
486 partial, last, lrev = self._readbranchcache()
502 else:
487 else:
503 lrev = self.changelog.rev(oldtip)
488 lrev = self.changelog.rev(oldtip)
504 partial = self._branchcache
489 partial = self._branchcache
505
490
506 self._branchtags(partial, lrev)
491 self._branchtags(partial, lrev)
507 # this private cache holds all heads (not just the branch tips)
492 # this private cache holds all heads (not just the branch tips)
508 self._branchcache = partial
493 self._branchcache = partial
509
494
510 def branchmap(self):
495 def branchmap(self):
511 '''returns a dictionary {branch: [branchheads]}'''
496 '''returns a dictionary {branch: [branchheads]}'''
512 self.updatebranchcache()
497 self.updatebranchcache()
513 return self._branchcache
498 return self._branchcache
514
499
515 def branchtags(self):
500 def branchtags(self):
516 '''return a dict where branch names map to the tipmost head of
501 '''return a dict where branch names map to the tipmost head of
517 the branch, open heads come before closed'''
502 the branch, open heads come before closed'''
518 bt = {}
503 bt = {}
519 for bn, heads in self.branchmap().iteritems():
504 for bn, heads in self.branchmap().iteritems():
520 tip = heads[-1]
505 tip = heads[-1]
521 for h in reversed(heads):
506 for h in reversed(heads):
522 if 'close' not in self.changelog.read(h)[5]:
507 if 'close' not in self.changelog.read(h)[5]:
523 tip = h
508 tip = h
524 break
509 break
525 bt[bn] = tip
510 bt[bn] = tip
526 return bt
511 return bt
527
512
528 def _readbranchcache(self):
513 def _readbranchcache(self):
529 partial = {}
514 partial = {}
530 try:
515 try:
531 f = self.opener("cache/branchheads")
516 f = self.opener("cache/branchheads")
532 lines = f.read().split('\n')
517 lines = f.read().split('\n')
533 f.close()
518 f.close()
534 except (IOError, OSError):
519 except (IOError, OSError):
535 return {}, nullid, nullrev
520 return {}, nullid, nullrev
536
521
537 try:
522 try:
538 last, lrev = lines.pop(0).split(" ", 1)
523 last, lrev = lines.pop(0).split(" ", 1)
539 last, lrev = bin(last), int(lrev)
524 last, lrev = bin(last), int(lrev)
540 if lrev >= len(self) or self[lrev].node() != last:
525 if lrev >= len(self) or self[lrev].node() != last:
541 # invalidate the cache
526 # invalidate the cache
542 raise ValueError('invalidating branch cache (tip differs)')
527 raise ValueError('invalidating branch cache (tip differs)')
543 for l in lines:
528 for l in lines:
544 if not l:
529 if not l:
545 continue
530 continue
546 node, label = l.split(" ", 1)
531 node, label = l.split(" ", 1)
547 label = encoding.tolocal(label.strip())
532 label = encoding.tolocal(label.strip())
548 partial.setdefault(label, []).append(bin(node))
533 partial.setdefault(label, []).append(bin(node))
549 except KeyboardInterrupt:
534 except KeyboardInterrupt:
550 raise
535 raise
551 except Exception, inst:
536 except Exception, inst:
552 if self.ui.debugflag:
537 if self.ui.debugflag:
553 self.ui.warn(str(inst), '\n')
538 self.ui.warn(str(inst), '\n')
554 partial, last, lrev = {}, nullid, nullrev
539 partial, last, lrev = {}, nullid, nullrev
555 return partial, last, lrev
540 return partial, last, lrev
556
541
557 def _writebranchcache(self, branches, tip, tiprev):
542 def _writebranchcache(self, branches, tip, tiprev):
558 try:
543 try:
559 f = self.opener("cache/branchheads", "w", atomictemp=True)
544 f = self.opener("cache/branchheads", "w", atomictemp=True)
560 f.write("%s %s\n" % (hex(tip), tiprev))
545 f.write("%s %s\n" % (hex(tip), tiprev))
561 for label, nodes in branches.iteritems():
546 for label, nodes in branches.iteritems():
562 for node in nodes:
547 for node in nodes:
563 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
548 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
564 f.close()
549 f.close()
565 except (IOError, OSError):
550 except (IOError, OSError):
566 pass
551 pass
567
552
568 def _updatebranchcache(self, partial, ctxgen):
553 def _updatebranchcache(self, partial, ctxgen):
569 # collect new branch entries
554 # collect new branch entries
570 newbranches = {}
555 newbranches = {}
571 for c in ctxgen:
556 for c in ctxgen:
572 newbranches.setdefault(c.branch(), []).append(c.node())
557 newbranches.setdefault(c.branch(), []).append(c.node())
573 # if older branchheads are reachable from new ones, they aren't
558 # if older branchheads are reachable from new ones, they aren't
574 # really branchheads. Note checking parents is insufficient:
559 # really branchheads. Note checking parents is insufficient:
575 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
560 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
576 for branch, newnodes in newbranches.iteritems():
561 for branch, newnodes in newbranches.iteritems():
577 bheads = partial.setdefault(branch, [])
562 bheads = partial.setdefault(branch, [])
578 bheads.extend(newnodes)
563 bheads.extend(newnodes)
579 if len(bheads) <= 1:
564 if len(bheads) <= 1:
580 continue
565 continue
581 bheads = sorted(bheads, key=lambda x: self[x].rev())
566 bheads = sorted(bheads, key=lambda x: self[x].rev())
582 # starting from tip means fewer passes over reachable
567 # starting from tip means fewer passes over reachable
583 while newnodes:
568 while newnodes:
584 latest = newnodes.pop()
569 latest = newnodes.pop()
585 if latest not in bheads:
570 if latest not in bheads:
586 continue
571 continue
587 minbhnode = self[bheads[0]].node()
572 minbhnode = self[bheads[0]].node()
588 reachable = self.changelog.reachable(latest, minbhnode)
573 reachable = self.changelog.reachable(latest, minbhnode)
589 reachable.remove(latest)
574 reachable.remove(latest)
590 if reachable:
575 if reachable:
591 bheads = [b for b in bheads if b not in reachable]
576 bheads = [b for b in bheads if b not in reachable]
592 partial[branch] = bheads
577 partial[branch] = bheads
593
578
594 def lookup(self, key):
579 def lookup(self, key):
595 return self[key].node()
580 return self[key].node()
596
581
597 def lookupbranch(self, key, remote=None):
582 def lookupbranch(self, key, remote=None):
598 repo = remote or self
583 repo = remote or self
599 if key in repo.branchmap():
584 if key in repo.branchmap():
600 return key
585 return key
601
586
602 repo = (remote and remote.local()) and remote or self
587 repo = (remote and remote.local()) and remote or self
603 return repo[key].branch()
588 return repo[key].branch()
604
589
605 def known(self, nodes):
590 def known(self, nodes):
606 nm = self.changelog.nodemap
591 nm = self.changelog.nodemap
592 pc = self._phasecache
607 result = []
593 result = []
608 for n in nodes:
594 for n in nodes:
609 r = nm.get(n)
595 r = nm.get(n)
610 resp = not (r is None or self._phaserev[r] >= phases.secret)
596 resp = not (r is None or pc.phase(self, r) >= phases.secret)
611 result.append(resp)
597 result.append(resp)
612 return result
598 return result
613
599
614 def local(self):
600 def local(self):
615 return self
601 return self
616
602
617 def join(self, f):
603 def join(self, f):
618 return os.path.join(self.path, f)
604 return os.path.join(self.path, f)
619
605
620 def wjoin(self, f):
606 def wjoin(self, f):
621 return os.path.join(self.root, f)
607 return os.path.join(self.root, f)
622
608
623 def file(self, f):
609 def file(self, f):
624 if f[0] == '/':
610 if f[0] == '/':
625 f = f[1:]
611 f = f[1:]
626 return filelog.filelog(self.sopener, f)
612 return filelog.filelog(self.sopener, f)
627
613
628 def changectx(self, changeid):
614 def changectx(self, changeid):
629 return self[changeid]
615 return self[changeid]
630
616
631 def parents(self, changeid=None):
617 def parents(self, changeid=None):
632 '''get list of changectxs for parents of changeid'''
618 '''get list of changectxs for parents of changeid'''
633 return self[changeid].parents()
619 return self[changeid].parents()
634
620
635 def setparents(self, p1, p2=nullid):
621 def setparents(self, p1, p2=nullid):
636 copies = self.dirstate.setparents(p1, p2)
622 copies = self.dirstate.setparents(p1, p2)
637 if copies:
623 if copies:
638 # Adjust copy records, the dirstate cannot do it, it
624 # Adjust copy records, the dirstate cannot do it, it
639 # requires access to parents manifests. Preserve them
625 # requires access to parents manifests. Preserve them
640 # only for entries added to first parent.
626 # only for entries added to first parent.
641 pctx = self[p1]
627 pctx = self[p1]
642 for f in copies:
628 for f in copies:
643 if f not in pctx and copies[f] in pctx:
629 if f not in pctx and copies[f] in pctx:
644 self.dirstate.copy(copies[f], f)
630 self.dirstate.copy(copies[f], f)
645
631
646 def filectx(self, path, changeid=None, fileid=None):
632 def filectx(self, path, changeid=None, fileid=None):
647 """changeid can be a changeset revision, node, or tag.
633 """changeid can be a changeset revision, node, or tag.
648 fileid can be a file revision or node."""
634 fileid can be a file revision or node."""
649 return context.filectx(self, path, changeid, fileid)
635 return context.filectx(self, path, changeid, fileid)
650
636
651 def getcwd(self):
637 def getcwd(self):
652 return self.dirstate.getcwd()
638 return self.dirstate.getcwd()
653
639
654 def pathto(self, f, cwd=None):
640 def pathto(self, f, cwd=None):
655 return self.dirstate.pathto(f, cwd)
641 return self.dirstate.pathto(f, cwd)
656
642
657 def wfile(self, f, mode='r'):
643 def wfile(self, f, mode='r'):
658 return self.wopener(f, mode)
644 return self.wopener(f, mode)
659
645
660 def _link(self, f):
646 def _link(self, f):
661 return os.path.islink(self.wjoin(f))
647 return os.path.islink(self.wjoin(f))
662
648
663 def _loadfilter(self, filter):
649 def _loadfilter(self, filter):
664 if filter not in self.filterpats:
650 if filter not in self.filterpats:
665 l = []
651 l = []
666 for pat, cmd in self.ui.configitems(filter):
652 for pat, cmd in self.ui.configitems(filter):
667 if cmd == '!':
653 if cmd == '!':
668 continue
654 continue
669 mf = matchmod.match(self.root, '', [pat])
655 mf = matchmod.match(self.root, '', [pat])
670 fn = None
656 fn = None
671 params = cmd
657 params = cmd
672 for name, filterfn in self._datafilters.iteritems():
658 for name, filterfn in self._datafilters.iteritems():
673 if cmd.startswith(name):
659 if cmd.startswith(name):
674 fn = filterfn
660 fn = filterfn
675 params = cmd[len(name):].lstrip()
661 params = cmd[len(name):].lstrip()
676 break
662 break
677 if not fn:
663 if not fn:
678 fn = lambda s, c, **kwargs: util.filter(s, c)
664 fn = lambda s, c, **kwargs: util.filter(s, c)
679 # Wrap old filters not supporting keyword arguments
665 # Wrap old filters not supporting keyword arguments
680 if not inspect.getargspec(fn)[2]:
666 if not inspect.getargspec(fn)[2]:
681 oldfn = fn
667 oldfn = fn
682 fn = lambda s, c, **kwargs: oldfn(s, c)
668 fn = lambda s, c, **kwargs: oldfn(s, c)
683 l.append((mf, fn, params))
669 l.append((mf, fn, params))
684 self.filterpats[filter] = l
670 self.filterpats[filter] = l
685 return self.filterpats[filter]
671 return self.filterpats[filter]
686
672
687 def _filter(self, filterpats, filename, data):
673 def _filter(self, filterpats, filename, data):
688 for mf, fn, cmd in filterpats:
674 for mf, fn, cmd in filterpats:
689 if mf(filename):
675 if mf(filename):
690 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
676 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
691 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
677 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
692 break
678 break
693
679
694 return data
680 return data
695
681
696 @propertycache
682 @propertycache
697 def _encodefilterpats(self):
683 def _encodefilterpats(self):
698 return self._loadfilter('encode')
684 return self._loadfilter('encode')
699
685
700 @propertycache
686 @propertycache
701 def _decodefilterpats(self):
687 def _decodefilterpats(self):
702 return self._loadfilter('decode')
688 return self._loadfilter('decode')
703
689
704 def adddatafilter(self, name, filter):
690 def adddatafilter(self, name, filter):
705 self._datafilters[name] = filter
691 self._datafilters[name] = filter
706
692
707 def wread(self, filename):
693 def wread(self, filename):
708 if self._link(filename):
694 if self._link(filename):
709 data = os.readlink(self.wjoin(filename))
695 data = os.readlink(self.wjoin(filename))
710 else:
696 else:
711 data = self.wopener.read(filename)
697 data = self.wopener.read(filename)
712 return self._filter(self._encodefilterpats, filename, data)
698 return self._filter(self._encodefilterpats, filename, data)
713
699
714 def wwrite(self, filename, data, flags):
700 def wwrite(self, filename, data, flags):
715 data = self._filter(self._decodefilterpats, filename, data)
701 data = self._filter(self._decodefilterpats, filename, data)
716 if 'l' in flags:
702 if 'l' in flags:
717 self.wopener.symlink(data, filename)
703 self.wopener.symlink(data, filename)
718 else:
704 else:
719 self.wopener.write(filename, data)
705 self.wopener.write(filename, data)
720 if 'x' in flags:
706 if 'x' in flags:
721 util.setflags(self.wjoin(filename), False, True)
707 util.setflags(self.wjoin(filename), False, True)
722
708
723 def wwritedata(self, filename, data):
709 def wwritedata(self, filename, data):
724 return self._filter(self._decodefilterpats, filename, data)
710 return self._filter(self._decodefilterpats, filename, data)
725
711
726 def transaction(self, desc):
712 def transaction(self, desc):
727 tr = self._transref and self._transref() or None
713 tr = self._transref and self._transref() or None
728 if tr and tr.running():
714 if tr and tr.running():
729 return tr.nest()
715 return tr.nest()
730
716
731 # abort here if the journal already exists
717 # abort here if the journal already exists
732 if os.path.exists(self.sjoin("journal")):
718 if os.path.exists(self.sjoin("journal")):
733 raise error.RepoError(
719 raise error.RepoError(
734 _("abandoned transaction found - run hg recover"))
720 _("abandoned transaction found - run hg recover"))
735
721
736 self._writejournal(desc)
722 self._writejournal(desc)
737 renames = [(x, undoname(x)) for x in self._journalfiles()]
723 renames = [(x, undoname(x)) for x in self._journalfiles()]
738
724
739 tr = transaction.transaction(self.ui.warn, self.sopener,
725 tr = transaction.transaction(self.ui.warn, self.sopener,
740 self.sjoin("journal"),
726 self.sjoin("journal"),
741 aftertrans(renames),
727 aftertrans(renames),
742 self.store.createmode)
728 self.store.createmode)
743 self._transref = weakref.ref(tr)
729 self._transref = weakref.ref(tr)
744 return tr
730 return tr
745
731
746 def _journalfiles(self):
732 def _journalfiles(self):
747 return (self.sjoin('journal'), self.join('journal.dirstate'),
733 return (self.sjoin('journal'), self.join('journal.dirstate'),
748 self.join('journal.branch'), self.join('journal.desc'),
734 self.join('journal.branch'), self.join('journal.desc'),
749 self.join('journal.bookmarks'),
735 self.join('journal.bookmarks'),
750 self.sjoin('journal.phaseroots'))
736 self.sjoin('journal.phaseroots'))
751
737
752 def undofiles(self):
738 def undofiles(self):
753 return [undoname(x) for x in self._journalfiles()]
739 return [undoname(x) for x in self._journalfiles()]
754
740
755 def _writejournal(self, desc):
741 def _writejournal(self, desc):
756 self.opener.write("journal.dirstate",
742 self.opener.write("journal.dirstate",
757 self.opener.tryread("dirstate"))
743 self.opener.tryread("dirstate"))
758 self.opener.write("journal.branch",
744 self.opener.write("journal.branch",
759 encoding.fromlocal(self.dirstate.branch()))
745 encoding.fromlocal(self.dirstate.branch()))
760 self.opener.write("journal.desc",
746 self.opener.write("journal.desc",
761 "%d\n%s\n" % (len(self), desc))
747 "%d\n%s\n" % (len(self), desc))
762 self.opener.write("journal.bookmarks",
748 self.opener.write("journal.bookmarks",
763 self.opener.tryread("bookmarks"))
749 self.opener.tryread("bookmarks"))
764 self.sopener.write("journal.phaseroots",
750 self.sopener.write("journal.phaseroots",
765 self.sopener.tryread("phaseroots"))
751 self.sopener.tryread("phaseroots"))
766
752
767 def recover(self):
753 def recover(self):
768 lock = self.lock()
754 lock = self.lock()
769 try:
755 try:
770 if os.path.exists(self.sjoin("journal")):
756 if os.path.exists(self.sjoin("journal")):
771 self.ui.status(_("rolling back interrupted transaction\n"))
757 self.ui.status(_("rolling back interrupted transaction\n"))
772 transaction.rollback(self.sopener, self.sjoin("journal"),
758 transaction.rollback(self.sopener, self.sjoin("journal"),
773 self.ui.warn)
759 self.ui.warn)
774 self.invalidate()
760 self.invalidate()
775 return True
761 return True
776 else:
762 else:
777 self.ui.warn(_("no interrupted transaction available\n"))
763 self.ui.warn(_("no interrupted transaction available\n"))
778 return False
764 return False
779 finally:
765 finally:
780 lock.release()
766 lock.release()
781
767
782 def rollback(self, dryrun=False, force=False):
768 def rollback(self, dryrun=False, force=False):
783 wlock = lock = None
769 wlock = lock = None
784 try:
770 try:
785 wlock = self.wlock()
771 wlock = self.wlock()
786 lock = self.lock()
772 lock = self.lock()
787 if os.path.exists(self.sjoin("undo")):
773 if os.path.exists(self.sjoin("undo")):
788 return self._rollback(dryrun, force)
774 return self._rollback(dryrun, force)
789 else:
775 else:
790 self.ui.warn(_("no rollback information available\n"))
776 self.ui.warn(_("no rollback information available\n"))
791 return 1
777 return 1
792 finally:
778 finally:
793 release(lock, wlock)
779 release(lock, wlock)
794
780
795 def _rollback(self, dryrun, force):
781 def _rollback(self, dryrun, force):
796 ui = self.ui
782 ui = self.ui
797 try:
783 try:
798 args = self.opener.read('undo.desc').splitlines()
784 args = self.opener.read('undo.desc').splitlines()
799 (oldlen, desc, detail) = (int(args[0]), args[1], None)
785 (oldlen, desc, detail) = (int(args[0]), args[1], None)
800 if len(args) >= 3:
786 if len(args) >= 3:
801 detail = args[2]
787 detail = args[2]
802 oldtip = oldlen - 1
788 oldtip = oldlen - 1
803
789
804 if detail and ui.verbose:
790 if detail and ui.verbose:
805 msg = (_('repository tip rolled back to revision %s'
791 msg = (_('repository tip rolled back to revision %s'
806 ' (undo %s: %s)\n')
792 ' (undo %s: %s)\n')
807 % (oldtip, desc, detail))
793 % (oldtip, desc, detail))
808 else:
794 else:
809 msg = (_('repository tip rolled back to revision %s'
795 msg = (_('repository tip rolled back to revision %s'
810 ' (undo %s)\n')
796 ' (undo %s)\n')
811 % (oldtip, desc))
797 % (oldtip, desc))
812 except IOError:
798 except IOError:
813 msg = _('rolling back unknown transaction\n')
799 msg = _('rolling back unknown transaction\n')
814 desc = None
800 desc = None
815
801
816 if not force and self['.'] != self['tip'] and desc == 'commit':
802 if not force and self['.'] != self['tip'] and desc == 'commit':
817 raise util.Abort(
803 raise util.Abort(
818 _('rollback of last commit while not checked out '
804 _('rollback of last commit while not checked out '
819 'may lose data'), hint=_('use -f to force'))
805 'may lose data'), hint=_('use -f to force'))
820
806
821 ui.status(msg)
807 ui.status(msg)
822 if dryrun:
808 if dryrun:
823 return 0
809 return 0
824
810
825 parents = self.dirstate.parents()
811 parents = self.dirstate.parents()
826 transaction.rollback(self.sopener, self.sjoin('undo'), ui.warn)
812 transaction.rollback(self.sopener, self.sjoin('undo'), ui.warn)
827 if os.path.exists(self.join('undo.bookmarks')):
813 if os.path.exists(self.join('undo.bookmarks')):
828 util.rename(self.join('undo.bookmarks'),
814 util.rename(self.join('undo.bookmarks'),
829 self.join('bookmarks'))
815 self.join('bookmarks'))
830 if os.path.exists(self.sjoin('undo.phaseroots')):
816 if os.path.exists(self.sjoin('undo.phaseroots')):
831 util.rename(self.sjoin('undo.phaseroots'),
817 util.rename(self.sjoin('undo.phaseroots'),
832 self.sjoin('phaseroots'))
818 self.sjoin('phaseroots'))
833 self.invalidate()
819 self.invalidate()
834
820
835 parentgone = (parents[0] not in self.changelog.nodemap or
821 parentgone = (parents[0] not in self.changelog.nodemap or
836 parents[1] not in self.changelog.nodemap)
822 parents[1] not in self.changelog.nodemap)
837 if parentgone:
823 if parentgone:
838 util.rename(self.join('undo.dirstate'), self.join('dirstate'))
824 util.rename(self.join('undo.dirstate'), self.join('dirstate'))
839 try:
825 try:
840 branch = self.opener.read('undo.branch')
826 branch = self.opener.read('undo.branch')
841 self.dirstate.setbranch(branch)
827 self.dirstate.setbranch(branch)
842 except IOError:
828 except IOError:
843 ui.warn(_('named branch could not be reset: '
829 ui.warn(_('named branch could not be reset: '
844 'current branch is still \'%s\'\n')
830 'current branch is still \'%s\'\n')
845 % self.dirstate.branch())
831 % self.dirstate.branch())
846
832
847 self.dirstate.invalidate()
833 self.dirstate.invalidate()
848 parents = tuple([p.rev() for p in self.parents()])
834 parents = tuple([p.rev() for p in self.parents()])
849 if len(parents) > 1:
835 if len(parents) > 1:
850 ui.status(_('working directory now based on '
836 ui.status(_('working directory now based on '
851 'revisions %d and %d\n') % parents)
837 'revisions %d and %d\n') % parents)
852 else:
838 else:
853 ui.status(_('working directory now based on '
839 ui.status(_('working directory now based on '
854 'revision %d\n') % parents)
840 'revision %d\n') % parents)
855 self.destroyed()
841 self.destroyed()
856 return 0
842 return 0
857
843
858 def invalidatecaches(self):
844 def invalidatecaches(self):
859 def delcache(name):
845 def delcache(name):
860 try:
846 try:
861 delattr(self, name)
847 delattr(self, name)
862 except AttributeError:
848 except AttributeError:
863 pass
849 pass
864
850
865 delcache('_tagscache')
851 delcache('_tagscache')
866 delcache('_phaserev')
867
852
868 self._branchcache = None # in UTF-8
853 self._branchcache = None # in UTF-8
869 self._branchcachetip = None
854 self._branchcachetip = None
870
855
871 def invalidatedirstate(self):
856 def invalidatedirstate(self):
872 '''Invalidates the dirstate, causing the next call to dirstate
857 '''Invalidates the dirstate, causing the next call to dirstate
873 to check if it was modified since the last time it was read,
858 to check if it was modified since the last time it was read,
874 rereading it if it has.
859 rereading it if it has.
875
860
876 This is different to dirstate.invalidate() that it doesn't always
861 This is different to dirstate.invalidate() that it doesn't always
877 rereads the dirstate. Use dirstate.invalidate() if you want to
862 rereads the dirstate. Use dirstate.invalidate() if you want to
878 explicitly read the dirstate again (i.e. restoring it to a previous
863 explicitly read the dirstate again (i.e. restoring it to a previous
879 known good state).'''
864 known good state).'''
880 if 'dirstate' in self.__dict__:
865 if 'dirstate' in self.__dict__:
881 for k in self.dirstate._filecache:
866 for k in self.dirstate._filecache:
882 try:
867 try:
883 delattr(self.dirstate, k)
868 delattr(self.dirstate, k)
884 except AttributeError:
869 except AttributeError:
885 pass
870 pass
886 delattr(self, 'dirstate')
871 delattr(self, 'dirstate')
887
872
888 def invalidate(self):
873 def invalidate(self):
889 for k in self._filecache:
874 for k in self._filecache:
890 # dirstate is invalidated separately in invalidatedirstate()
875 # dirstate is invalidated separately in invalidatedirstate()
891 if k == 'dirstate':
876 if k == 'dirstate':
892 continue
877 continue
893
878
894 try:
879 try:
895 delattr(self, k)
880 delattr(self, k)
896 except AttributeError:
881 except AttributeError:
897 pass
882 pass
898 self.invalidatecaches()
883 self.invalidatecaches()
899
884
900 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
885 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
901 try:
886 try:
902 l = lock.lock(lockname, 0, releasefn, desc=desc)
887 l = lock.lock(lockname, 0, releasefn, desc=desc)
903 except error.LockHeld, inst:
888 except error.LockHeld, inst:
904 if not wait:
889 if not wait:
905 raise
890 raise
906 self.ui.warn(_("waiting for lock on %s held by %r\n") %
891 self.ui.warn(_("waiting for lock on %s held by %r\n") %
907 (desc, inst.locker))
892 (desc, inst.locker))
908 # default to 600 seconds timeout
893 # default to 600 seconds timeout
909 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
894 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
910 releasefn, desc=desc)
895 releasefn, desc=desc)
911 if acquirefn:
896 if acquirefn:
912 acquirefn()
897 acquirefn()
913 return l
898 return l
914
899
915 def _afterlock(self, callback):
900 def _afterlock(self, callback):
916 """add a callback to the current repository lock.
901 """add a callback to the current repository lock.
917
902
918 The callback will be executed on lock release."""
903 The callback will be executed on lock release."""
919 l = self._lockref and self._lockref()
904 l = self._lockref and self._lockref()
920 if l:
905 if l:
921 l.postrelease.append(callback)
906 l.postrelease.append(callback)
922
907
923 def lock(self, wait=True):
908 def lock(self, wait=True):
924 '''Lock the repository store (.hg/store) and return a weak reference
909 '''Lock the repository store (.hg/store) and return a weak reference
925 to the lock. Use this before modifying the store (e.g. committing or
910 to the lock. Use this before modifying the store (e.g. committing or
926 stripping). If you are opening a transaction, get a lock as well.)'''
911 stripping). If you are opening a transaction, get a lock as well.)'''
927 l = self._lockref and self._lockref()
912 l = self._lockref and self._lockref()
928 if l is not None and l.held:
913 if l is not None and l.held:
929 l.lock()
914 l.lock()
930 return l
915 return l
931
916
932 def unlock():
917 def unlock():
933 self.store.write()
918 self.store.write()
934 if self._dirtyphases:
919 if '_phasecache' in vars(self):
935 phases.writeroots(self, self._phaseroots)
920 self._phasecache.write()
936 self._dirtyphases = False
937 for k, ce in self._filecache.items():
921 for k, ce in self._filecache.items():
938 if k == 'dirstate':
922 if k == 'dirstate':
939 continue
923 continue
940 ce.refresh()
924 ce.refresh()
941
925
942 l = self._lock(self.sjoin("lock"), wait, unlock,
926 l = self._lock(self.sjoin("lock"), wait, unlock,
943 self.invalidate, _('repository %s') % self.origroot)
927 self.invalidate, _('repository %s') % self.origroot)
944 self._lockref = weakref.ref(l)
928 self._lockref = weakref.ref(l)
945 return l
929 return l
946
930
947 def wlock(self, wait=True):
931 def wlock(self, wait=True):
948 '''Lock the non-store parts of the repository (everything under
932 '''Lock the non-store parts of the repository (everything under
949 .hg except .hg/store) and return a weak reference to the lock.
933 .hg except .hg/store) and return a weak reference to the lock.
950 Use this before modifying files in .hg.'''
934 Use this before modifying files in .hg.'''
951 l = self._wlockref and self._wlockref()
935 l = self._wlockref and self._wlockref()
952 if l is not None and l.held:
936 if l is not None and l.held:
953 l.lock()
937 l.lock()
954 return l
938 return l
955
939
956 def unlock():
940 def unlock():
957 self.dirstate.write()
941 self.dirstate.write()
958 ce = self._filecache.get('dirstate')
942 ce = self._filecache.get('dirstate')
959 if ce:
943 if ce:
960 ce.refresh()
944 ce.refresh()
961
945
962 l = self._lock(self.join("wlock"), wait, unlock,
946 l = self._lock(self.join("wlock"), wait, unlock,
963 self.invalidatedirstate, _('working directory of %s') %
947 self.invalidatedirstate, _('working directory of %s') %
964 self.origroot)
948 self.origroot)
965 self._wlockref = weakref.ref(l)
949 self._wlockref = weakref.ref(l)
966 return l
950 return l
967
951
968 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
952 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
969 """
953 """
970 commit an individual file as part of a larger transaction
954 commit an individual file as part of a larger transaction
971 """
955 """
972
956
973 fname = fctx.path()
957 fname = fctx.path()
974 text = fctx.data()
958 text = fctx.data()
975 flog = self.file(fname)
959 flog = self.file(fname)
976 fparent1 = manifest1.get(fname, nullid)
960 fparent1 = manifest1.get(fname, nullid)
977 fparent2 = fparent2o = manifest2.get(fname, nullid)
961 fparent2 = fparent2o = manifest2.get(fname, nullid)
978
962
979 meta = {}
963 meta = {}
980 copy = fctx.renamed()
964 copy = fctx.renamed()
981 if copy and copy[0] != fname:
965 if copy and copy[0] != fname:
982 # Mark the new revision of this file as a copy of another
966 # Mark the new revision of this file as a copy of another
983 # file. This copy data will effectively act as a parent
967 # file. This copy data will effectively act as a parent
984 # of this new revision. If this is a merge, the first
968 # of this new revision. If this is a merge, the first
985 # parent will be the nullid (meaning "look up the copy data")
969 # parent will be the nullid (meaning "look up the copy data")
986 # and the second one will be the other parent. For example:
970 # and the second one will be the other parent. For example:
987 #
971 #
988 # 0 --- 1 --- 3 rev1 changes file foo
972 # 0 --- 1 --- 3 rev1 changes file foo
989 # \ / rev2 renames foo to bar and changes it
973 # \ / rev2 renames foo to bar and changes it
990 # \- 2 -/ rev3 should have bar with all changes and
974 # \- 2 -/ rev3 should have bar with all changes and
991 # should record that bar descends from
975 # should record that bar descends from
992 # bar in rev2 and foo in rev1
976 # bar in rev2 and foo in rev1
993 #
977 #
994 # this allows this merge to succeed:
978 # this allows this merge to succeed:
995 #
979 #
996 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
980 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
997 # \ / merging rev3 and rev4 should use bar@rev2
981 # \ / merging rev3 and rev4 should use bar@rev2
998 # \- 2 --- 4 as the merge base
982 # \- 2 --- 4 as the merge base
999 #
983 #
1000
984
1001 cfname = copy[0]
985 cfname = copy[0]
1002 crev = manifest1.get(cfname)
986 crev = manifest1.get(cfname)
1003 newfparent = fparent2
987 newfparent = fparent2
1004
988
1005 if manifest2: # branch merge
989 if manifest2: # branch merge
1006 if fparent2 == nullid or crev is None: # copied on remote side
990 if fparent2 == nullid or crev is None: # copied on remote side
1007 if cfname in manifest2:
991 if cfname in manifest2:
1008 crev = manifest2[cfname]
992 crev = manifest2[cfname]
1009 newfparent = fparent1
993 newfparent = fparent1
1010
994
1011 # find source in nearest ancestor if we've lost track
995 # find source in nearest ancestor if we've lost track
1012 if not crev:
996 if not crev:
1013 self.ui.debug(" %s: searching for copy revision for %s\n" %
997 self.ui.debug(" %s: searching for copy revision for %s\n" %
1014 (fname, cfname))
998 (fname, cfname))
1015 for ancestor in self[None].ancestors():
999 for ancestor in self[None].ancestors():
1016 if cfname in ancestor:
1000 if cfname in ancestor:
1017 crev = ancestor[cfname].filenode()
1001 crev = ancestor[cfname].filenode()
1018 break
1002 break
1019
1003
1020 if crev:
1004 if crev:
1021 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1005 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1022 meta["copy"] = cfname
1006 meta["copy"] = cfname
1023 meta["copyrev"] = hex(crev)
1007 meta["copyrev"] = hex(crev)
1024 fparent1, fparent2 = nullid, newfparent
1008 fparent1, fparent2 = nullid, newfparent
1025 else:
1009 else:
1026 self.ui.warn(_("warning: can't find ancestor for '%s' "
1010 self.ui.warn(_("warning: can't find ancestor for '%s' "
1027 "copied from '%s'!\n") % (fname, cfname))
1011 "copied from '%s'!\n") % (fname, cfname))
1028
1012
1029 elif fparent2 != nullid:
1013 elif fparent2 != nullid:
1030 # is one parent an ancestor of the other?
1014 # is one parent an ancestor of the other?
1031 fparentancestor = flog.ancestor(fparent1, fparent2)
1015 fparentancestor = flog.ancestor(fparent1, fparent2)
1032 if fparentancestor == fparent1:
1016 if fparentancestor == fparent1:
1033 fparent1, fparent2 = fparent2, nullid
1017 fparent1, fparent2 = fparent2, nullid
1034 elif fparentancestor == fparent2:
1018 elif fparentancestor == fparent2:
1035 fparent2 = nullid
1019 fparent2 = nullid
1036
1020
1037 # is the file changed?
1021 # is the file changed?
1038 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1022 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1039 changelist.append(fname)
1023 changelist.append(fname)
1040 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1024 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1041
1025
1042 # are just the flags changed during merge?
1026 # are just the flags changed during merge?
1043 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1027 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1044 changelist.append(fname)
1028 changelist.append(fname)
1045
1029
1046 return fparent1
1030 return fparent1
1047
1031
1048 def commit(self, text="", user=None, date=None, match=None, force=False,
1032 def commit(self, text="", user=None, date=None, match=None, force=False,
1049 editor=False, extra={}):
1033 editor=False, extra={}):
1050 """Add a new revision to current repository.
1034 """Add a new revision to current repository.
1051
1035
1052 Revision information is gathered from the working directory,
1036 Revision information is gathered from the working directory,
1053 match can be used to filter the committed files. If editor is
1037 match can be used to filter the committed files. If editor is
1054 supplied, it is called to get a commit message.
1038 supplied, it is called to get a commit message.
1055 """
1039 """
1056
1040
1057 def fail(f, msg):
1041 def fail(f, msg):
1058 raise util.Abort('%s: %s' % (f, msg))
1042 raise util.Abort('%s: %s' % (f, msg))
1059
1043
1060 if not match:
1044 if not match:
1061 match = matchmod.always(self.root, '')
1045 match = matchmod.always(self.root, '')
1062
1046
1063 if not force:
1047 if not force:
1064 vdirs = []
1048 vdirs = []
1065 match.dir = vdirs.append
1049 match.dir = vdirs.append
1066 match.bad = fail
1050 match.bad = fail
1067
1051
1068 wlock = self.wlock()
1052 wlock = self.wlock()
1069 try:
1053 try:
1070 wctx = self[None]
1054 wctx = self[None]
1071 merge = len(wctx.parents()) > 1
1055 merge = len(wctx.parents()) > 1
1072
1056
1073 if (not force and merge and match and
1057 if (not force and merge and match and
1074 (match.files() or match.anypats())):
1058 (match.files() or match.anypats())):
1075 raise util.Abort(_('cannot partially commit a merge '
1059 raise util.Abort(_('cannot partially commit a merge '
1076 '(do not specify files or patterns)'))
1060 '(do not specify files or patterns)'))
1077
1061
1078 changes = self.status(match=match, clean=force)
1062 changes = self.status(match=match, clean=force)
1079 if force:
1063 if force:
1080 changes[0].extend(changes[6]) # mq may commit unchanged files
1064 changes[0].extend(changes[6]) # mq may commit unchanged files
1081
1065
1082 # check subrepos
1066 # check subrepos
1083 subs = []
1067 subs = []
1084 commitsubs = set()
1068 commitsubs = set()
1085 newstate = wctx.substate.copy()
1069 newstate = wctx.substate.copy()
1086 # only manage subrepos and .hgsubstate if .hgsub is present
1070 # only manage subrepos and .hgsubstate if .hgsub is present
1087 if '.hgsub' in wctx:
1071 if '.hgsub' in wctx:
1088 # we'll decide whether to track this ourselves, thanks
1072 # we'll decide whether to track this ourselves, thanks
1089 if '.hgsubstate' in changes[0]:
1073 if '.hgsubstate' in changes[0]:
1090 changes[0].remove('.hgsubstate')
1074 changes[0].remove('.hgsubstate')
1091 if '.hgsubstate' in changes[2]:
1075 if '.hgsubstate' in changes[2]:
1092 changes[2].remove('.hgsubstate')
1076 changes[2].remove('.hgsubstate')
1093
1077
1094 # compare current state to last committed state
1078 # compare current state to last committed state
1095 # build new substate based on last committed state
1079 # build new substate based on last committed state
1096 oldstate = wctx.p1().substate
1080 oldstate = wctx.p1().substate
1097 for s in sorted(newstate.keys()):
1081 for s in sorted(newstate.keys()):
1098 if not match(s):
1082 if not match(s):
1099 # ignore working copy, use old state if present
1083 # ignore working copy, use old state if present
1100 if s in oldstate:
1084 if s in oldstate:
1101 newstate[s] = oldstate[s]
1085 newstate[s] = oldstate[s]
1102 continue
1086 continue
1103 if not force:
1087 if not force:
1104 raise util.Abort(
1088 raise util.Abort(
1105 _("commit with new subrepo %s excluded") % s)
1089 _("commit with new subrepo %s excluded") % s)
1106 if wctx.sub(s).dirty(True):
1090 if wctx.sub(s).dirty(True):
1107 if not self.ui.configbool('ui', 'commitsubrepos'):
1091 if not self.ui.configbool('ui', 'commitsubrepos'):
1108 raise util.Abort(
1092 raise util.Abort(
1109 _("uncommitted changes in subrepo %s") % s,
1093 _("uncommitted changes in subrepo %s") % s,
1110 hint=_("use --subrepos for recursive commit"))
1094 hint=_("use --subrepos for recursive commit"))
1111 subs.append(s)
1095 subs.append(s)
1112 commitsubs.add(s)
1096 commitsubs.add(s)
1113 else:
1097 else:
1114 bs = wctx.sub(s).basestate()
1098 bs = wctx.sub(s).basestate()
1115 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1099 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1116 if oldstate.get(s, (None, None, None))[1] != bs:
1100 if oldstate.get(s, (None, None, None))[1] != bs:
1117 subs.append(s)
1101 subs.append(s)
1118
1102
1119 # check for removed subrepos
1103 # check for removed subrepos
1120 for p in wctx.parents():
1104 for p in wctx.parents():
1121 r = [s for s in p.substate if s not in newstate]
1105 r = [s for s in p.substate if s not in newstate]
1122 subs += [s for s in r if match(s)]
1106 subs += [s for s in r if match(s)]
1123 if subs:
1107 if subs:
1124 if (not match('.hgsub') and
1108 if (not match('.hgsub') and
1125 '.hgsub' in (wctx.modified() + wctx.added())):
1109 '.hgsub' in (wctx.modified() + wctx.added())):
1126 raise util.Abort(
1110 raise util.Abort(
1127 _("can't commit subrepos without .hgsub"))
1111 _("can't commit subrepos without .hgsub"))
1128 changes[0].insert(0, '.hgsubstate')
1112 changes[0].insert(0, '.hgsubstate')
1129
1113
1130 elif '.hgsub' in changes[2]:
1114 elif '.hgsub' in changes[2]:
1131 # clean up .hgsubstate when .hgsub is removed
1115 # clean up .hgsubstate when .hgsub is removed
1132 if ('.hgsubstate' in wctx and
1116 if ('.hgsubstate' in wctx and
1133 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1117 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1134 changes[2].insert(0, '.hgsubstate')
1118 changes[2].insert(0, '.hgsubstate')
1135
1119
1136 # make sure all explicit patterns are matched
1120 # make sure all explicit patterns are matched
1137 if not force and match.files():
1121 if not force and match.files():
1138 matched = set(changes[0] + changes[1] + changes[2])
1122 matched = set(changes[0] + changes[1] + changes[2])
1139
1123
1140 for f in match.files():
1124 for f in match.files():
1141 if f == '.' or f in matched or f in wctx.substate:
1125 if f == '.' or f in matched or f in wctx.substate:
1142 continue
1126 continue
1143 if f in changes[3]: # missing
1127 if f in changes[3]: # missing
1144 fail(f, _('file not found!'))
1128 fail(f, _('file not found!'))
1145 if f in vdirs: # visited directory
1129 if f in vdirs: # visited directory
1146 d = f + '/'
1130 d = f + '/'
1147 for mf in matched:
1131 for mf in matched:
1148 if mf.startswith(d):
1132 if mf.startswith(d):
1149 break
1133 break
1150 else:
1134 else:
1151 fail(f, _("no match under directory!"))
1135 fail(f, _("no match under directory!"))
1152 elif f not in self.dirstate:
1136 elif f not in self.dirstate:
1153 fail(f, _("file not tracked!"))
1137 fail(f, _("file not tracked!"))
1154
1138
1155 if (not force and not extra.get("close") and not merge
1139 if (not force and not extra.get("close") and not merge
1156 and not (changes[0] or changes[1] or changes[2])
1140 and not (changes[0] or changes[1] or changes[2])
1157 and wctx.branch() == wctx.p1().branch()):
1141 and wctx.branch() == wctx.p1().branch()):
1158 return None
1142 return None
1159
1143
1160 if merge and changes[3]:
1144 if merge and changes[3]:
1161 raise util.Abort(_("cannot commit merge with missing files"))
1145 raise util.Abort(_("cannot commit merge with missing files"))
1162
1146
1163 ms = mergemod.mergestate(self)
1147 ms = mergemod.mergestate(self)
1164 for f in changes[0]:
1148 for f in changes[0]:
1165 if f in ms and ms[f] == 'u':
1149 if f in ms and ms[f] == 'u':
1166 raise util.Abort(_("unresolved merge conflicts "
1150 raise util.Abort(_("unresolved merge conflicts "
1167 "(see hg help resolve)"))
1151 "(see hg help resolve)"))
1168
1152
1169 cctx = context.workingctx(self, text, user, date, extra, changes)
1153 cctx = context.workingctx(self, text, user, date, extra, changes)
1170 if editor:
1154 if editor:
1171 cctx._text = editor(self, cctx, subs)
1155 cctx._text = editor(self, cctx, subs)
1172 edited = (text != cctx._text)
1156 edited = (text != cctx._text)
1173
1157
1174 # commit subs and write new state
1158 # commit subs and write new state
1175 if subs:
1159 if subs:
1176 for s in sorted(commitsubs):
1160 for s in sorted(commitsubs):
1177 sub = wctx.sub(s)
1161 sub = wctx.sub(s)
1178 self.ui.status(_('committing subrepository %s\n') %
1162 self.ui.status(_('committing subrepository %s\n') %
1179 subrepo.subrelpath(sub))
1163 subrepo.subrelpath(sub))
1180 sr = sub.commit(cctx._text, user, date)
1164 sr = sub.commit(cctx._text, user, date)
1181 newstate[s] = (newstate[s][0], sr)
1165 newstate[s] = (newstate[s][0], sr)
1182 subrepo.writestate(self, newstate)
1166 subrepo.writestate(self, newstate)
1183
1167
1184 # Save commit message in case this transaction gets rolled back
1168 # Save commit message in case this transaction gets rolled back
1185 # (e.g. by a pretxncommit hook). Leave the content alone on
1169 # (e.g. by a pretxncommit hook). Leave the content alone on
1186 # the assumption that the user will use the same editor again.
1170 # the assumption that the user will use the same editor again.
1187 msgfn = self.savecommitmessage(cctx._text)
1171 msgfn = self.savecommitmessage(cctx._text)
1188
1172
1189 p1, p2 = self.dirstate.parents()
1173 p1, p2 = self.dirstate.parents()
1190 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1174 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1191 try:
1175 try:
1192 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1176 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1193 ret = self.commitctx(cctx, True)
1177 ret = self.commitctx(cctx, True)
1194 except:
1178 except:
1195 if edited:
1179 if edited:
1196 self.ui.write(
1180 self.ui.write(
1197 _('note: commit message saved in %s\n') % msgfn)
1181 _('note: commit message saved in %s\n') % msgfn)
1198 raise
1182 raise
1199
1183
1200 # update bookmarks, dirstate and mergestate
1184 # update bookmarks, dirstate and mergestate
1201 bookmarks.update(self, p1, ret)
1185 bookmarks.update(self, p1, ret)
1202 for f in changes[0] + changes[1]:
1186 for f in changes[0] + changes[1]:
1203 self.dirstate.normal(f)
1187 self.dirstate.normal(f)
1204 for f in changes[2]:
1188 for f in changes[2]:
1205 self.dirstate.drop(f)
1189 self.dirstate.drop(f)
1206 self.dirstate.setparents(ret)
1190 self.dirstate.setparents(ret)
1207 ms.reset()
1191 ms.reset()
1208 finally:
1192 finally:
1209 wlock.release()
1193 wlock.release()
1210
1194
1211 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1195 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1212 return ret
1196 return ret
1213
1197
1214 def commitctx(self, ctx, error=False):
1198 def commitctx(self, ctx, error=False):
1215 """Add a new revision to current repository.
1199 """Add a new revision to current repository.
1216 Revision information is passed via the context argument.
1200 Revision information is passed via the context argument.
1217 """
1201 """
1218
1202
1219 tr = lock = None
1203 tr = lock = None
1220 removed = list(ctx.removed())
1204 removed = list(ctx.removed())
1221 p1, p2 = ctx.p1(), ctx.p2()
1205 p1, p2 = ctx.p1(), ctx.p2()
1222 user = ctx.user()
1206 user = ctx.user()
1223
1207
1224 lock = self.lock()
1208 lock = self.lock()
1225 try:
1209 try:
1226 tr = self.transaction("commit")
1210 tr = self.transaction("commit")
1227 trp = weakref.proxy(tr)
1211 trp = weakref.proxy(tr)
1228
1212
1229 if ctx.files():
1213 if ctx.files():
1230 m1 = p1.manifest().copy()
1214 m1 = p1.manifest().copy()
1231 m2 = p2.manifest()
1215 m2 = p2.manifest()
1232
1216
1233 # check in files
1217 # check in files
1234 new = {}
1218 new = {}
1235 changed = []
1219 changed = []
1236 linkrev = len(self)
1220 linkrev = len(self)
1237 for f in sorted(ctx.modified() + ctx.added()):
1221 for f in sorted(ctx.modified() + ctx.added()):
1238 self.ui.note(f + "\n")
1222 self.ui.note(f + "\n")
1239 try:
1223 try:
1240 fctx = ctx[f]
1224 fctx = ctx[f]
1241 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1225 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1242 changed)
1226 changed)
1243 m1.set(f, fctx.flags())
1227 m1.set(f, fctx.flags())
1244 except OSError, inst:
1228 except OSError, inst:
1245 self.ui.warn(_("trouble committing %s!\n") % f)
1229 self.ui.warn(_("trouble committing %s!\n") % f)
1246 raise
1230 raise
1247 except IOError, inst:
1231 except IOError, inst:
1248 errcode = getattr(inst, 'errno', errno.ENOENT)
1232 errcode = getattr(inst, 'errno', errno.ENOENT)
1249 if error or errcode and errcode != errno.ENOENT:
1233 if error or errcode and errcode != errno.ENOENT:
1250 self.ui.warn(_("trouble committing %s!\n") % f)
1234 self.ui.warn(_("trouble committing %s!\n") % f)
1251 raise
1235 raise
1252 else:
1236 else:
1253 removed.append(f)
1237 removed.append(f)
1254
1238
1255 # update manifest
1239 # update manifest
1256 m1.update(new)
1240 m1.update(new)
1257 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1241 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1258 drop = [f for f in removed if f in m1]
1242 drop = [f for f in removed if f in m1]
1259 for f in drop:
1243 for f in drop:
1260 del m1[f]
1244 del m1[f]
1261 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1245 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1262 p2.manifestnode(), (new, drop))
1246 p2.manifestnode(), (new, drop))
1263 files = changed + removed
1247 files = changed + removed
1264 else:
1248 else:
1265 mn = p1.manifestnode()
1249 mn = p1.manifestnode()
1266 files = []
1250 files = []
1267
1251
1268 # update changelog
1252 # update changelog
1269 self.changelog.delayupdate()
1253 self.changelog.delayupdate()
1270 n = self.changelog.add(mn, files, ctx.description(),
1254 n = self.changelog.add(mn, files, ctx.description(),
1271 trp, p1.node(), p2.node(),
1255 trp, p1.node(), p2.node(),
1272 user, ctx.date(), ctx.extra().copy())
1256 user, ctx.date(), ctx.extra().copy())
1273 p = lambda: self.changelog.writepending() and self.root or ""
1257 p = lambda: self.changelog.writepending() and self.root or ""
1274 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1258 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1275 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1259 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1276 parent2=xp2, pending=p)
1260 parent2=xp2, pending=p)
1277 self.changelog.finalize(trp)
1261 self.changelog.finalize(trp)
1278 # set the new commit is proper phase
1262 # set the new commit is proper phase
1279 targetphase = phases.newcommitphase(self.ui)
1263 targetphase = phases.newcommitphase(self.ui)
1280 if targetphase:
1264 if targetphase:
1281 # retract boundary do not alter parent changeset.
1265 # retract boundary do not alter parent changeset.
1282 # if a parent have higher the resulting phase will
1266 # if a parent have higher the resulting phase will
1283 # be compliant anyway
1267 # be compliant anyway
1284 #
1268 #
1285 # if minimal phase was 0 we don't need to retract anything
1269 # if minimal phase was 0 we don't need to retract anything
1286 phases.retractboundary(self, targetphase, [n])
1270 phases.retractboundary(self, targetphase, [n])
1287 tr.close()
1271 tr.close()
1288 self.updatebranchcache()
1272 self.updatebranchcache()
1289 return n
1273 return n
1290 finally:
1274 finally:
1291 if tr:
1275 if tr:
1292 tr.release()
1276 tr.release()
1293 lock.release()
1277 lock.release()
1294
1278
1295 def destroyed(self):
1279 def destroyed(self):
1296 '''Inform the repository that nodes have been destroyed.
1280 '''Inform the repository that nodes have been destroyed.
1297 Intended for use by strip and rollback, so there's a common
1281 Intended for use by strip and rollback, so there's a common
1298 place for anything that has to be done after destroying history.'''
1282 place for anything that has to be done after destroying history.'''
1299 # XXX it might be nice if we could take the list of destroyed
1283 # XXX it might be nice if we could take the list of destroyed
1300 # nodes, but I don't see an easy way for rollback() to do that
1284 # nodes, but I don't see an easy way for rollback() to do that
1301
1285
1302 # Ensure the persistent tag cache is updated. Doing it now
1286 # Ensure the persistent tag cache is updated. Doing it now
1303 # means that the tag cache only has to worry about destroyed
1287 # means that the tag cache only has to worry about destroyed
1304 # heads immediately after a strip/rollback. That in turn
1288 # heads immediately after a strip/rollback. That in turn
1305 # guarantees that "cachetip == currenttip" (comparing both rev
1289 # guarantees that "cachetip == currenttip" (comparing both rev
1306 # and node) always means no nodes have been added or destroyed.
1290 # and node) always means no nodes have been added or destroyed.
1307
1291
1308 # XXX this is suboptimal when qrefresh'ing: we strip the current
1292 # XXX this is suboptimal when qrefresh'ing: we strip the current
1309 # head, refresh the tag cache, then immediately add a new head.
1293 # head, refresh the tag cache, then immediately add a new head.
1310 # But I think doing it this way is necessary for the "instant
1294 # But I think doing it this way is necessary for the "instant
1311 # tag cache retrieval" case to work.
1295 # tag cache retrieval" case to work.
1312 self.invalidatecaches()
1296 self.invalidatecaches()
1313
1297
1314 # Discard all cache entries to force reloading everything.
1298 # Discard all cache entries to force reloading everything.
1315 self._filecache.clear()
1299 self._filecache.clear()
1316
1300
1317 def walk(self, match, node=None):
1301 def walk(self, match, node=None):
1318 '''
1302 '''
1319 walk recursively through the directory tree or a given
1303 walk recursively through the directory tree or a given
1320 changeset, finding all files matched by the match
1304 changeset, finding all files matched by the match
1321 function
1305 function
1322 '''
1306 '''
1323 return self[node].walk(match)
1307 return self[node].walk(match)
1324
1308
1325 def status(self, node1='.', node2=None, match=None,
1309 def status(self, node1='.', node2=None, match=None,
1326 ignored=False, clean=False, unknown=False,
1310 ignored=False, clean=False, unknown=False,
1327 listsubrepos=False):
1311 listsubrepos=False):
1328 """return status of files between two nodes or node and working directory
1312 """return status of files between two nodes or node and working directory
1329
1313
1330 If node1 is None, use the first dirstate parent instead.
1314 If node1 is None, use the first dirstate parent instead.
1331 If node2 is None, compare node1 with working directory.
1315 If node2 is None, compare node1 with working directory.
1332 """
1316 """
1333
1317
1334 def mfmatches(ctx):
1318 def mfmatches(ctx):
1335 mf = ctx.manifest().copy()
1319 mf = ctx.manifest().copy()
1336 if match.always():
1320 if match.always():
1337 return mf
1321 return mf
1338 for fn in mf.keys():
1322 for fn in mf.keys():
1339 if not match(fn):
1323 if not match(fn):
1340 del mf[fn]
1324 del mf[fn]
1341 return mf
1325 return mf
1342
1326
1343 if isinstance(node1, context.changectx):
1327 if isinstance(node1, context.changectx):
1344 ctx1 = node1
1328 ctx1 = node1
1345 else:
1329 else:
1346 ctx1 = self[node1]
1330 ctx1 = self[node1]
1347 if isinstance(node2, context.changectx):
1331 if isinstance(node2, context.changectx):
1348 ctx2 = node2
1332 ctx2 = node2
1349 else:
1333 else:
1350 ctx2 = self[node2]
1334 ctx2 = self[node2]
1351
1335
1352 working = ctx2.rev() is None
1336 working = ctx2.rev() is None
1353 parentworking = working and ctx1 == self['.']
1337 parentworking = working and ctx1 == self['.']
1354 match = match or matchmod.always(self.root, self.getcwd())
1338 match = match or matchmod.always(self.root, self.getcwd())
1355 listignored, listclean, listunknown = ignored, clean, unknown
1339 listignored, listclean, listunknown = ignored, clean, unknown
1356
1340
1357 # load earliest manifest first for caching reasons
1341 # load earliest manifest first for caching reasons
1358 if not working and ctx2.rev() < ctx1.rev():
1342 if not working and ctx2.rev() < ctx1.rev():
1359 ctx2.manifest()
1343 ctx2.manifest()
1360
1344
1361 if not parentworking:
1345 if not parentworking:
1362 def bad(f, msg):
1346 def bad(f, msg):
1363 # 'f' may be a directory pattern from 'match.files()',
1347 # 'f' may be a directory pattern from 'match.files()',
1364 # so 'f not in ctx1' is not enough
1348 # so 'f not in ctx1' is not enough
1365 if f not in ctx1 and f not in ctx1.dirs():
1349 if f not in ctx1 and f not in ctx1.dirs():
1366 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1350 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1367 match.bad = bad
1351 match.bad = bad
1368
1352
1369 if working: # we need to scan the working dir
1353 if working: # we need to scan the working dir
1370 subrepos = []
1354 subrepos = []
1371 if '.hgsub' in self.dirstate:
1355 if '.hgsub' in self.dirstate:
1372 subrepos = ctx2.substate.keys()
1356 subrepos = ctx2.substate.keys()
1373 s = self.dirstate.status(match, subrepos, listignored,
1357 s = self.dirstate.status(match, subrepos, listignored,
1374 listclean, listunknown)
1358 listclean, listunknown)
1375 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1359 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1376
1360
1377 # check for any possibly clean files
1361 # check for any possibly clean files
1378 if parentworking and cmp:
1362 if parentworking and cmp:
1379 fixup = []
1363 fixup = []
1380 # do a full compare of any files that might have changed
1364 # do a full compare of any files that might have changed
1381 for f in sorted(cmp):
1365 for f in sorted(cmp):
1382 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1366 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1383 or ctx1[f].cmp(ctx2[f])):
1367 or ctx1[f].cmp(ctx2[f])):
1384 modified.append(f)
1368 modified.append(f)
1385 else:
1369 else:
1386 fixup.append(f)
1370 fixup.append(f)
1387
1371
1388 # update dirstate for files that are actually clean
1372 # update dirstate for files that are actually clean
1389 if fixup:
1373 if fixup:
1390 if listclean:
1374 if listclean:
1391 clean += fixup
1375 clean += fixup
1392
1376
1393 try:
1377 try:
1394 # updating the dirstate is optional
1378 # updating the dirstate is optional
1395 # so we don't wait on the lock
1379 # so we don't wait on the lock
1396 wlock = self.wlock(False)
1380 wlock = self.wlock(False)
1397 try:
1381 try:
1398 for f in fixup:
1382 for f in fixup:
1399 self.dirstate.normal(f)
1383 self.dirstate.normal(f)
1400 finally:
1384 finally:
1401 wlock.release()
1385 wlock.release()
1402 except error.LockError:
1386 except error.LockError:
1403 pass
1387 pass
1404
1388
1405 if not parentworking:
1389 if not parentworking:
1406 mf1 = mfmatches(ctx1)
1390 mf1 = mfmatches(ctx1)
1407 if working:
1391 if working:
1408 # we are comparing working dir against non-parent
1392 # we are comparing working dir against non-parent
1409 # generate a pseudo-manifest for the working dir
1393 # generate a pseudo-manifest for the working dir
1410 mf2 = mfmatches(self['.'])
1394 mf2 = mfmatches(self['.'])
1411 for f in cmp + modified + added:
1395 for f in cmp + modified + added:
1412 mf2[f] = None
1396 mf2[f] = None
1413 mf2.set(f, ctx2.flags(f))
1397 mf2.set(f, ctx2.flags(f))
1414 for f in removed:
1398 for f in removed:
1415 if f in mf2:
1399 if f in mf2:
1416 del mf2[f]
1400 del mf2[f]
1417 else:
1401 else:
1418 # we are comparing two revisions
1402 # we are comparing two revisions
1419 deleted, unknown, ignored = [], [], []
1403 deleted, unknown, ignored = [], [], []
1420 mf2 = mfmatches(ctx2)
1404 mf2 = mfmatches(ctx2)
1421
1405
1422 modified, added, clean = [], [], []
1406 modified, added, clean = [], [], []
1423 withflags = mf1.withflags() | mf2.withflags()
1407 withflags = mf1.withflags() | mf2.withflags()
1424 for fn in mf2:
1408 for fn in mf2:
1425 if fn in mf1:
1409 if fn in mf1:
1426 if (fn not in deleted and
1410 if (fn not in deleted and
1427 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
1411 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
1428 (mf1[fn] != mf2[fn] and
1412 (mf1[fn] != mf2[fn] and
1429 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1413 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1430 modified.append(fn)
1414 modified.append(fn)
1431 elif listclean:
1415 elif listclean:
1432 clean.append(fn)
1416 clean.append(fn)
1433 del mf1[fn]
1417 del mf1[fn]
1434 elif fn not in deleted:
1418 elif fn not in deleted:
1435 added.append(fn)
1419 added.append(fn)
1436 removed = mf1.keys()
1420 removed = mf1.keys()
1437
1421
1438 if working and modified and not self.dirstate._checklink:
1422 if working and modified and not self.dirstate._checklink:
1439 # Symlink placeholders may get non-symlink-like contents
1423 # Symlink placeholders may get non-symlink-like contents
1440 # via user error or dereferencing by NFS or Samba servers,
1424 # via user error or dereferencing by NFS or Samba servers,
1441 # so we filter out any placeholders that don't look like a
1425 # so we filter out any placeholders that don't look like a
1442 # symlink
1426 # symlink
1443 sane = []
1427 sane = []
1444 for f in modified:
1428 for f in modified:
1445 if ctx2.flags(f) == 'l':
1429 if ctx2.flags(f) == 'l':
1446 d = ctx2[f].data()
1430 d = ctx2[f].data()
1447 if len(d) >= 1024 or '\n' in d or util.binary(d):
1431 if len(d) >= 1024 or '\n' in d or util.binary(d):
1448 self.ui.debug('ignoring suspect symlink placeholder'
1432 self.ui.debug('ignoring suspect symlink placeholder'
1449 ' "%s"\n' % f)
1433 ' "%s"\n' % f)
1450 continue
1434 continue
1451 sane.append(f)
1435 sane.append(f)
1452 modified = sane
1436 modified = sane
1453
1437
1454 r = modified, added, removed, deleted, unknown, ignored, clean
1438 r = modified, added, removed, deleted, unknown, ignored, clean
1455
1439
1456 if listsubrepos:
1440 if listsubrepos:
1457 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1441 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1458 if working:
1442 if working:
1459 rev2 = None
1443 rev2 = None
1460 else:
1444 else:
1461 rev2 = ctx2.substate[subpath][1]
1445 rev2 = ctx2.substate[subpath][1]
1462 try:
1446 try:
1463 submatch = matchmod.narrowmatcher(subpath, match)
1447 submatch = matchmod.narrowmatcher(subpath, match)
1464 s = sub.status(rev2, match=submatch, ignored=listignored,
1448 s = sub.status(rev2, match=submatch, ignored=listignored,
1465 clean=listclean, unknown=listunknown,
1449 clean=listclean, unknown=listunknown,
1466 listsubrepos=True)
1450 listsubrepos=True)
1467 for rfiles, sfiles in zip(r, s):
1451 for rfiles, sfiles in zip(r, s):
1468 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1452 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1469 except error.LookupError:
1453 except error.LookupError:
1470 self.ui.status(_("skipping missing subrepository: %s\n")
1454 self.ui.status(_("skipping missing subrepository: %s\n")
1471 % subpath)
1455 % subpath)
1472
1456
1473 for l in r:
1457 for l in r:
1474 l.sort()
1458 l.sort()
1475 return r
1459 return r
1476
1460
1477 def heads(self, start=None):
1461 def heads(self, start=None):
1478 heads = self.changelog.heads(start)
1462 heads = self.changelog.heads(start)
1479 # sort the output in rev descending order
1463 # sort the output in rev descending order
1480 return sorted(heads, key=self.changelog.rev, reverse=True)
1464 return sorted(heads, key=self.changelog.rev, reverse=True)
1481
1465
1482 def branchheads(self, branch=None, start=None, closed=False):
1466 def branchheads(self, branch=None, start=None, closed=False):
1483 '''return a (possibly filtered) list of heads for the given branch
1467 '''return a (possibly filtered) list of heads for the given branch
1484
1468
1485 Heads are returned in topological order, from newest to oldest.
1469 Heads are returned in topological order, from newest to oldest.
1486 If branch is None, use the dirstate branch.
1470 If branch is None, use the dirstate branch.
1487 If start is not None, return only heads reachable from start.
1471 If start is not None, return only heads reachable from start.
1488 If closed is True, return heads that are marked as closed as well.
1472 If closed is True, return heads that are marked as closed as well.
1489 '''
1473 '''
1490 if branch is None:
1474 if branch is None:
1491 branch = self[None].branch()
1475 branch = self[None].branch()
1492 branches = self.branchmap()
1476 branches = self.branchmap()
1493 if branch not in branches:
1477 if branch not in branches:
1494 return []
1478 return []
1495 # the cache returns heads ordered lowest to highest
1479 # the cache returns heads ordered lowest to highest
1496 bheads = list(reversed(branches[branch]))
1480 bheads = list(reversed(branches[branch]))
1497 if start is not None:
1481 if start is not None:
1498 # filter out the heads that cannot be reached from startrev
1482 # filter out the heads that cannot be reached from startrev
1499 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1483 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1500 bheads = [h for h in bheads if h in fbheads]
1484 bheads = [h for h in bheads if h in fbheads]
1501 if not closed:
1485 if not closed:
1502 bheads = [h for h in bheads if
1486 bheads = [h for h in bheads if
1503 ('close' not in self.changelog.read(h)[5])]
1487 ('close' not in self.changelog.read(h)[5])]
1504 return bheads
1488 return bheads
1505
1489
1506 def branches(self, nodes):
1490 def branches(self, nodes):
1507 if not nodes:
1491 if not nodes:
1508 nodes = [self.changelog.tip()]
1492 nodes = [self.changelog.tip()]
1509 b = []
1493 b = []
1510 for n in nodes:
1494 for n in nodes:
1511 t = n
1495 t = n
1512 while True:
1496 while True:
1513 p = self.changelog.parents(n)
1497 p = self.changelog.parents(n)
1514 if p[1] != nullid or p[0] == nullid:
1498 if p[1] != nullid or p[0] == nullid:
1515 b.append((t, n, p[0], p[1]))
1499 b.append((t, n, p[0], p[1]))
1516 break
1500 break
1517 n = p[0]
1501 n = p[0]
1518 return b
1502 return b
1519
1503
1520 def between(self, pairs):
1504 def between(self, pairs):
1521 r = []
1505 r = []
1522
1506
1523 for top, bottom in pairs:
1507 for top, bottom in pairs:
1524 n, l, i = top, [], 0
1508 n, l, i = top, [], 0
1525 f = 1
1509 f = 1
1526
1510
1527 while n != bottom and n != nullid:
1511 while n != bottom and n != nullid:
1528 p = self.changelog.parents(n)[0]
1512 p = self.changelog.parents(n)[0]
1529 if i == f:
1513 if i == f:
1530 l.append(n)
1514 l.append(n)
1531 f = f * 2
1515 f = f * 2
1532 n = p
1516 n = p
1533 i += 1
1517 i += 1
1534
1518
1535 r.append(l)
1519 r.append(l)
1536
1520
1537 return r
1521 return r
1538
1522
1539 def pull(self, remote, heads=None, force=False):
1523 def pull(self, remote, heads=None, force=False):
1540 lock = self.lock()
1524 lock = self.lock()
1541 try:
1525 try:
1542 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1526 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1543 force=force)
1527 force=force)
1544 common, fetch, rheads = tmp
1528 common, fetch, rheads = tmp
1545 if not fetch:
1529 if not fetch:
1546 self.ui.status(_("no changes found\n"))
1530 self.ui.status(_("no changes found\n"))
1547 added = []
1531 added = []
1548 result = 0
1532 result = 0
1549 else:
1533 else:
1550 if heads is None and list(common) == [nullid]:
1534 if heads is None and list(common) == [nullid]:
1551 self.ui.status(_("requesting all changes\n"))
1535 self.ui.status(_("requesting all changes\n"))
1552 elif heads is None and remote.capable('changegroupsubset'):
1536 elif heads is None and remote.capable('changegroupsubset'):
1553 # issue1320, avoid a race if remote changed after discovery
1537 # issue1320, avoid a race if remote changed after discovery
1554 heads = rheads
1538 heads = rheads
1555
1539
1556 if remote.capable('getbundle'):
1540 if remote.capable('getbundle'):
1557 cg = remote.getbundle('pull', common=common,
1541 cg = remote.getbundle('pull', common=common,
1558 heads=heads or rheads)
1542 heads=heads or rheads)
1559 elif heads is None:
1543 elif heads is None:
1560 cg = remote.changegroup(fetch, 'pull')
1544 cg = remote.changegroup(fetch, 'pull')
1561 elif not remote.capable('changegroupsubset'):
1545 elif not remote.capable('changegroupsubset'):
1562 raise util.Abort(_("partial pull cannot be done because "
1546 raise util.Abort(_("partial pull cannot be done because "
1563 "other repository doesn't support "
1547 "other repository doesn't support "
1564 "changegroupsubset."))
1548 "changegroupsubset."))
1565 else:
1549 else:
1566 cg = remote.changegroupsubset(fetch, heads, 'pull')
1550 cg = remote.changegroupsubset(fetch, heads, 'pull')
1567 clstart = len(self.changelog)
1551 clstart = len(self.changelog)
1568 result = self.addchangegroup(cg, 'pull', remote.url())
1552 result = self.addchangegroup(cg, 'pull', remote.url())
1569 clend = len(self.changelog)
1553 clend = len(self.changelog)
1570 added = [self.changelog.node(r) for r in xrange(clstart, clend)]
1554 added = [self.changelog.node(r) for r in xrange(clstart, clend)]
1571
1555
1572 # compute target subset
1556 # compute target subset
1573 if heads is None:
1557 if heads is None:
1574 # We pulled every thing possible
1558 # We pulled every thing possible
1575 # sync on everything common
1559 # sync on everything common
1576 subset = common + added
1560 subset = common + added
1577 else:
1561 else:
1578 # We pulled a specific subset
1562 # We pulled a specific subset
1579 # sync on this subset
1563 # sync on this subset
1580 subset = heads
1564 subset = heads
1581
1565
1582 # Get remote phases data from remote
1566 # Get remote phases data from remote
1583 remotephases = remote.listkeys('phases')
1567 remotephases = remote.listkeys('phases')
1584 publishing = bool(remotephases.get('publishing', False))
1568 publishing = bool(remotephases.get('publishing', False))
1585 if remotephases and not publishing:
1569 if remotephases and not publishing:
1586 # remote is new and unpublishing
1570 # remote is new and unpublishing
1587 pheads, _dr = phases.analyzeremotephases(self, subset,
1571 pheads, _dr = phases.analyzeremotephases(self, subset,
1588 remotephases)
1572 remotephases)
1589 phases.advanceboundary(self, phases.public, pheads)
1573 phases.advanceboundary(self, phases.public, pheads)
1590 phases.advanceboundary(self, phases.draft, subset)
1574 phases.advanceboundary(self, phases.draft, subset)
1591 else:
1575 else:
1592 # Remote is old or publishing all common changesets
1576 # Remote is old or publishing all common changesets
1593 # should be seen as public
1577 # should be seen as public
1594 phases.advanceboundary(self, phases.public, subset)
1578 phases.advanceboundary(self, phases.public, subset)
1595 finally:
1579 finally:
1596 lock.release()
1580 lock.release()
1597
1581
1598 return result
1582 return result
1599
1583
1600 def checkpush(self, force, revs):
1584 def checkpush(self, force, revs):
1601 """Extensions can override this function if additional checks have
1585 """Extensions can override this function if additional checks have
1602 to be performed before pushing, or call it if they override push
1586 to be performed before pushing, or call it if they override push
1603 command.
1587 command.
1604 """
1588 """
1605 pass
1589 pass
1606
1590
1607 def push(self, remote, force=False, revs=None, newbranch=False):
1591 def push(self, remote, force=False, revs=None, newbranch=False):
1608 '''Push outgoing changesets (limited by revs) from the current
1592 '''Push outgoing changesets (limited by revs) from the current
1609 repository to remote. Return an integer:
1593 repository to remote. Return an integer:
1610 - None means nothing to push
1594 - None means nothing to push
1611 - 0 means HTTP error
1595 - 0 means HTTP error
1612 - 1 means we pushed and remote head count is unchanged *or*
1596 - 1 means we pushed and remote head count is unchanged *or*
1613 we have outgoing changesets but refused to push
1597 we have outgoing changesets but refused to push
1614 - other values as described by addchangegroup()
1598 - other values as described by addchangegroup()
1615 '''
1599 '''
1616 # there are two ways to push to remote repo:
1600 # there are two ways to push to remote repo:
1617 #
1601 #
1618 # addchangegroup assumes local user can lock remote
1602 # addchangegroup assumes local user can lock remote
1619 # repo (local filesystem, old ssh servers).
1603 # repo (local filesystem, old ssh servers).
1620 #
1604 #
1621 # unbundle assumes local user cannot lock remote repo (new ssh
1605 # unbundle assumes local user cannot lock remote repo (new ssh
1622 # servers, http servers).
1606 # servers, http servers).
1623
1607
1624 # get local lock as we might write phase data
1608 # get local lock as we might write phase data
1625 locallock = self.lock()
1609 locallock = self.lock()
1626 try:
1610 try:
1627 self.checkpush(force, revs)
1611 self.checkpush(force, revs)
1628 lock = None
1612 lock = None
1629 unbundle = remote.capable('unbundle')
1613 unbundle = remote.capable('unbundle')
1630 if not unbundle:
1614 if not unbundle:
1631 lock = remote.lock()
1615 lock = remote.lock()
1632 try:
1616 try:
1633 # discovery
1617 # discovery
1634 fci = discovery.findcommonincoming
1618 fci = discovery.findcommonincoming
1635 commoninc = fci(self, remote, force=force)
1619 commoninc = fci(self, remote, force=force)
1636 common, inc, remoteheads = commoninc
1620 common, inc, remoteheads = commoninc
1637 fco = discovery.findcommonoutgoing
1621 fco = discovery.findcommonoutgoing
1638 outgoing = fco(self, remote, onlyheads=revs,
1622 outgoing = fco(self, remote, onlyheads=revs,
1639 commoninc=commoninc, force=force)
1623 commoninc=commoninc, force=force)
1640
1624
1641
1625
1642 if not outgoing.missing:
1626 if not outgoing.missing:
1643 # nothing to push
1627 # nothing to push
1644 scmutil.nochangesfound(self.ui, outgoing.excluded)
1628 scmutil.nochangesfound(self.ui, outgoing.excluded)
1645 ret = None
1629 ret = None
1646 else:
1630 else:
1647 # something to push
1631 # something to push
1648 if not force:
1632 if not force:
1649 discovery.checkheads(self, remote, outgoing,
1633 discovery.checkheads(self, remote, outgoing,
1650 remoteheads, newbranch,
1634 remoteheads, newbranch,
1651 bool(inc))
1635 bool(inc))
1652
1636
1653 # create a changegroup from local
1637 # create a changegroup from local
1654 if revs is None and not outgoing.excluded:
1638 if revs is None and not outgoing.excluded:
1655 # push everything,
1639 # push everything,
1656 # use the fast path, no race possible on push
1640 # use the fast path, no race possible on push
1657 cg = self._changegroup(outgoing.missing, 'push')
1641 cg = self._changegroup(outgoing.missing, 'push')
1658 else:
1642 else:
1659 cg = self.getlocalbundle('push', outgoing)
1643 cg = self.getlocalbundle('push', outgoing)
1660
1644
1661 # apply changegroup to remote
1645 # apply changegroup to remote
1662 if unbundle:
1646 if unbundle:
1663 # local repo finds heads on server, finds out what
1647 # local repo finds heads on server, finds out what
1664 # revs it must push. once revs transferred, if server
1648 # revs it must push. once revs transferred, if server
1665 # finds it has different heads (someone else won
1649 # finds it has different heads (someone else won
1666 # commit/push race), server aborts.
1650 # commit/push race), server aborts.
1667 if force:
1651 if force:
1668 remoteheads = ['force']
1652 remoteheads = ['force']
1669 # ssh: return remote's addchangegroup()
1653 # ssh: return remote's addchangegroup()
1670 # http: return remote's addchangegroup() or 0 for error
1654 # http: return remote's addchangegroup() or 0 for error
1671 ret = remote.unbundle(cg, remoteheads, 'push')
1655 ret = remote.unbundle(cg, remoteheads, 'push')
1672 else:
1656 else:
1673 # we return an integer indicating remote head count change
1657 # we return an integer indicating remote head count change
1674 ret = remote.addchangegroup(cg, 'push', self.url())
1658 ret = remote.addchangegroup(cg, 'push', self.url())
1675
1659
1676 if ret:
1660 if ret:
1677 # push succeed, synchonize target of the push
1661 # push succeed, synchonize target of the push
1678 cheads = outgoing.missingheads
1662 cheads = outgoing.missingheads
1679 elif revs is None:
1663 elif revs is None:
1680 # All out push fails. synchronize all common
1664 # All out push fails. synchronize all common
1681 cheads = outgoing.commonheads
1665 cheads = outgoing.commonheads
1682 else:
1666 else:
1683 # I want cheads = heads(::missingheads and ::commonheads)
1667 # I want cheads = heads(::missingheads and ::commonheads)
1684 # (missingheads is revs with secret changeset filtered out)
1668 # (missingheads is revs with secret changeset filtered out)
1685 #
1669 #
1686 # This can be expressed as:
1670 # This can be expressed as:
1687 # cheads = ( (missingheads and ::commonheads)
1671 # cheads = ( (missingheads and ::commonheads)
1688 # + (commonheads and ::missingheads))"
1672 # + (commonheads and ::missingheads))"
1689 # )
1673 # )
1690 #
1674 #
1691 # while trying to push we already computed the following:
1675 # while trying to push we already computed the following:
1692 # common = (::commonheads)
1676 # common = (::commonheads)
1693 # missing = ((commonheads::missingheads) - commonheads)
1677 # missing = ((commonheads::missingheads) - commonheads)
1694 #
1678 #
1695 # We can pick:
1679 # We can pick:
1696 # * missingheads part of comon (::commonheads)
1680 # * missingheads part of comon (::commonheads)
1697 common = set(outgoing.common)
1681 common = set(outgoing.common)
1698 cheads = [node for node in revs if node in common]
1682 cheads = [node for node in revs if node in common]
1699 # and
1683 # and
1700 # * commonheads parents on missing
1684 # * commonheads parents on missing
1701 revset = self.set('%ln and parents(roots(%ln))',
1685 revset = self.set('%ln and parents(roots(%ln))',
1702 outgoing.commonheads,
1686 outgoing.commonheads,
1703 outgoing.missing)
1687 outgoing.missing)
1704 cheads.extend(c.node() for c in revset)
1688 cheads.extend(c.node() for c in revset)
1705 # even when we don't push, exchanging phase data is useful
1689 # even when we don't push, exchanging phase data is useful
1706 remotephases = remote.listkeys('phases')
1690 remotephases = remote.listkeys('phases')
1707 if not remotephases: # old server or public only repo
1691 if not remotephases: # old server or public only repo
1708 phases.advanceboundary(self, phases.public, cheads)
1692 phases.advanceboundary(self, phases.public, cheads)
1709 # don't push any phase data as there is nothing to push
1693 # don't push any phase data as there is nothing to push
1710 else:
1694 else:
1711 ana = phases.analyzeremotephases(self, cheads, remotephases)
1695 ana = phases.analyzeremotephases(self, cheads, remotephases)
1712 pheads, droots = ana
1696 pheads, droots = ana
1713 ### Apply remote phase on local
1697 ### Apply remote phase on local
1714 if remotephases.get('publishing', False):
1698 if remotephases.get('publishing', False):
1715 phases.advanceboundary(self, phases.public, cheads)
1699 phases.advanceboundary(self, phases.public, cheads)
1716 else: # publish = False
1700 else: # publish = False
1717 phases.advanceboundary(self, phases.public, pheads)
1701 phases.advanceboundary(self, phases.public, pheads)
1718 phases.advanceboundary(self, phases.draft, cheads)
1702 phases.advanceboundary(self, phases.draft, cheads)
1719 ### Apply local phase on remote
1703 ### Apply local phase on remote
1720
1704
1721 # Get the list of all revs draft on remote by public here.
1705 # Get the list of all revs draft on remote by public here.
1722 # XXX Beware that revset break if droots is not strictly
1706 # XXX Beware that revset break if droots is not strictly
1723 # XXX root we may want to ensure it is but it is costly
1707 # XXX root we may want to ensure it is but it is costly
1724 outdated = self.set('heads((%ln::%ln) and public())',
1708 outdated = self.set('heads((%ln::%ln) and public())',
1725 droots, cheads)
1709 droots, cheads)
1726 for newremotehead in outdated:
1710 for newremotehead in outdated:
1727 r = remote.pushkey('phases',
1711 r = remote.pushkey('phases',
1728 newremotehead.hex(),
1712 newremotehead.hex(),
1729 str(phases.draft),
1713 str(phases.draft),
1730 str(phases.public))
1714 str(phases.public))
1731 if not r:
1715 if not r:
1732 self.ui.warn(_('updating %s to public failed!\n')
1716 self.ui.warn(_('updating %s to public failed!\n')
1733 % newremotehead)
1717 % newremotehead)
1734 finally:
1718 finally:
1735 if lock is not None:
1719 if lock is not None:
1736 lock.release()
1720 lock.release()
1737 finally:
1721 finally:
1738 locallock.release()
1722 locallock.release()
1739
1723
1740 self.ui.debug("checking for updated bookmarks\n")
1724 self.ui.debug("checking for updated bookmarks\n")
1741 rb = remote.listkeys('bookmarks')
1725 rb = remote.listkeys('bookmarks')
1742 for k in rb.keys():
1726 for k in rb.keys():
1743 if k in self._bookmarks:
1727 if k in self._bookmarks:
1744 nr, nl = rb[k], hex(self._bookmarks[k])
1728 nr, nl = rb[k], hex(self._bookmarks[k])
1745 if nr in self:
1729 if nr in self:
1746 cr = self[nr]
1730 cr = self[nr]
1747 cl = self[nl]
1731 cl = self[nl]
1748 if cl in cr.descendants():
1732 if cl in cr.descendants():
1749 r = remote.pushkey('bookmarks', k, nr, nl)
1733 r = remote.pushkey('bookmarks', k, nr, nl)
1750 if r:
1734 if r:
1751 self.ui.status(_("updating bookmark %s\n") % k)
1735 self.ui.status(_("updating bookmark %s\n") % k)
1752 else:
1736 else:
1753 self.ui.warn(_('updating bookmark %s'
1737 self.ui.warn(_('updating bookmark %s'
1754 ' failed!\n') % k)
1738 ' failed!\n') % k)
1755
1739
1756 return ret
1740 return ret
1757
1741
1758 def changegroupinfo(self, nodes, source):
1742 def changegroupinfo(self, nodes, source):
1759 if self.ui.verbose or source == 'bundle':
1743 if self.ui.verbose or source == 'bundle':
1760 self.ui.status(_("%d changesets found\n") % len(nodes))
1744 self.ui.status(_("%d changesets found\n") % len(nodes))
1761 if self.ui.debugflag:
1745 if self.ui.debugflag:
1762 self.ui.debug("list of changesets:\n")
1746 self.ui.debug("list of changesets:\n")
1763 for node in nodes:
1747 for node in nodes:
1764 self.ui.debug("%s\n" % hex(node))
1748 self.ui.debug("%s\n" % hex(node))
1765
1749
1766 def changegroupsubset(self, bases, heads, source):
1750 def changegroupsubset(self, bases, heads, source):
1767 """Compute a changegroup consisting of all the nodes that are
1751 """Compute a changegroup consisting of all the nodes that are
1768 descendants of any of the bases and ancestors of any of the heads.
1752 descendants of any of the bases and ancestors of any of the heads.
1769 Return a chunkbuffer object whose read() method will return
1753 Return a chunkbuffer object whose read() method will return
1770 successive changegroup chunks.
1754 successive changegroup chunks.
1771
1755
1772 It is fairly complex as determining which filenodes and which
1756 It is fairly complex as determining which filenodes and which
1773 manifest nodes need to be included for the changeset to be complete
1757 manifest nodes need to be included for the changeset to be complete
1774 is non-trivial.
1758 is non-trivial.
1775
1759
1776 Another wrinkle is doing the reverse, figuring out which changeset in
1760 Another wrinkle is doing the reverse, figuring out which changeset in
1777 the changegroup a particular filenode or manifestnode belongs to.
1761 the changegroup a particular filenode or manifestnode belongs to.
1778 """
1762 """
1779 cl = self.changelog
1763 cl = self.changelog
1780 if not bases:
1764 if not bases:
1781 bases = [nullid]
1765 bases = [nullid]
1782 csets, bases, heads = cl.nodesbetween(bases, heads)
1766 csets, bases, heads = cl.nodesbetween(bases, heads)
1783 # We assume that all ancestors of bases are known
1767 # We assume that all ancestors of bases are known
1784 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1768 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1785 return self._changegroupsubset(common, csets, heads, source)
1769 return self._changegroupsubset(common, csets, heads, source)
1786
1770
1787 def getlocalbundle(self, source, outgoing):
1771 def getlocalbundle(self, source, outgoing):
1788 """Like getbundle, but taking a discovery.outgoing as an argument.
1772 """Like getbundle, but taking a discovery.outgoing as an argument.
1789
1773
1790 This is only implemented for local repos and reuses potentially
1774 This is only implemented for local repos and reuses potentially
1791 precomputed sets in outgoing."""
1775 precomputed sets in outgoing."""
1792 if not outgoing.missing:
1776 if not outgoing.missing:
1793 return None
1777 return None
1794 return self._changegroupsubset(outgoing.common,
1778 return self._changegroupsubset(outgoing.common,
1795 outgoing.missing,
1779 outgoing.missing,
1796 outgoing.missingheads,
1780 outgoing.missingheads,
1797 source)
1781 source)
1798
1782
1799 def getbundle(self, source, heads=None, common=None):
1783 def getbundle(self, source, heads=None, common=None):
1800 """Like changegroupsubset, but returns the set difference between the
1784 """Like changegroupsubset, but returns the set difference between the
1801 ancestors of heads and the ancestors common.
1785 ancestors of heads and the ancestors common.
1802
1786
1803 If heads is None, use the local heads. If common is None, use [nullid].
1787 If heads is None, use the local heads. If common is None, use [nullid].
1804
1788
1805 The nodes in common might not all be known locally due to the way the
1789 The nodes in common might not all be known locally due to the way the
1806 current discovery protocol works.
1790 current discovery protocol works.
1807 """
1791 """
1808 cl = self.changelog
1792 cl = self.changelog
1809 if common:
1793 if common:
1810 nm = cl.nodemap
1794 nm = cl.nodemap
1811 common = [n for n in common if n in nm]
1795 common = [n for n in common if n in nm]
1812 else:
1796 else:
1813 common = [nullid]
1797 common = [nullid]
1814 if not heads:
1798 if not heads:
1815 heads = cl.heads()
1799 heads = cl.heads()
1816 return self.getlocalbundle(source,
1800 return self.getlocalbundle(source,
1817 discovery.outgoing(cl, common, heads))
1801 discovery.outgoing(cl, common, heads))
1818
1802
1819 def _changegroupsubset(self, commonrevs, csets, heads, source):
1803 def _changegroupsubset(self, commonrevs, csets, heads, source):
1820
1804
1821 cl = self.changelog
1805 cl = self.changelog
1822 mf = self.manifest
1806 mf = self.manifest
1823 mfs = {} # needed manifests
1807 mfs = {} # needed manifests
1824 fnodes = {} # needed file nodes
1808 fnodes = {} # needed file nodes
1825 changedfiles = set()
1809 changedfiles = set()
1826 fstate = ['', {}]
1810 fstate = ['', {}]
1827 count = [0, 0]
1811 count = [0, 0]
1828
1812
1829 # can we go through the fast path ?
1813 # can we go through the fast path ?
1830 heads.sort()
1814 heads.sort()
1831 if heads == sorted(self.heads()):
1815 if heads == sorted(self.heads()):
1832 return self._changegroup(csets, source)
1816 return self._changegroup(csets, source)
1833
1817
1834 # slow path
1818 # slow path
1835 self.hook('preoutgoing', throw=True, source=source)
1819 self.hook('preoutgoing', throw=True, source=source)
1836 self.changegroupinfo(csets, source)
1820 self.changegroupinfo(csets, source)
1837
1821
1838 # filter any nodes that claim to be part of the known set
1822 # filter any nodes that claim to be part of the known set
1839 def prune(revlog, missing):
1823 def prune(revlog, missing):
1840 rr, rl = revlog.rev, revlog.linkrev
1824 rr, rl = revlog.rev, revlog.linkrev
1841 return [n for n in missing
1825 return [n for n in missing
1842 if rl(rr(n)) not in commonrevs]
1826 if rl(rr(n)) not in commonrevs]
1843
1827
1844 progress = self.ui.progress
1828 progress = self.ui.progress
1845 _bundling = _('bundling')
1829 _bundling = _('bundling')
1846 _changesets = _('changesets')
1830 _changesets = _('changesets')
1847 _manifests = _('manifests')
1831 _manifests = _('manifests')
1848 _files = _('files')
1832 _files = _('files')
1849
1833
1850 def lookup(revlog, x):
1834 def lookup(revlog, x):
1851 if revlog == cl:
1835 if revlog == cl:
1852 c = cl.read(x)
1836 c = cl.read(x)
1853 changedfiles.update(c[3])
1837 changedfiles.update(c[3])
1854 mfs.setdefault(c[0], x)
1838 mfs.setdefault(c[0], x)
1855 count[0] += 1
1839 count[0] += 1
1856 progress(_bundling, count[0],
1840 progress(_bundling, count[0],
1857 unit=_changesets, total=count[1])
1841 unit=_changesets, total=count[1])
1858 return x
1842 return x
1859 elif revlog == mf:
1843 elif revlog == mf:
1860 clnode = mfs[x]
1844 clnode = mfs[x]
1861 mdata = mf.readfast(x)
1845 mdata = mf.readfast(x)
1862 for f, n in mdata.iteritems():
1846 for f, n in mdata.iteritems():
1863 if f in changedfiles:
1847 if f in changedfiles:
1864 fnodes[f].setdefault(n, clnode)
1848 fnodes[f].setdefault(n, clnode)
1865 count[0] += 1
1849 count[0] += 1
1866 progress(_bundling, count[0],
1850 progress(_bundling, count[0],
1867 unit=_manifests, total=count[1])
1851 unit=_manifests, total=count[1])
1868 return clnode
1852 return clnode
1869 else:
1853 else:
1870 progress(_bundling, count[0], item=fstate[0],
1854 progress(_bundling, count[0], item=fstate[0],
1871 unit=_files, total=count[1])
1855 unit=_files, total=count[1])
1872 return fstate[1][x]
1856 return fstate[1][x]
1873
1857
1874 bundler = changegroup.bundle10(lookup)
1858 bundler = changegroup.bundle10(lookup)
1875 reorder = self.ui.config('bundle', 'reorder', 'auto')
1859 reorder = self.ui.config('bundle', 'reorder', 'auto')
1876 if reorder == 'auto':
1860 if reorder == 'auto':
1877 reorder = None
1861 reorder = None
1878 else:
1862 else:
1879 reorder = util.parsebool(reorder)
1863 reorder = util.parsebool(reorder)
1880
1864
1881 def gengroup():
1865 def gengroup():
1882 # Create a changenode group generator that will call our functions
1866 # Create a changenode group generator that will call our functions
1883 # back to lookup the owning changenode and collect information.
1867 # back to lookup the owning changenode and collect information.
1884 count[:] = [0, len(csets)]
1868 count[:] = [0, len(csets)]
1885 for chunk in cl.group(csets, bundler, reorder=reorder):
1869 for chunk in cl.group(csets, bundler, reorder=reorder):
1886 yield chunk
1870 yield chunk
1887 progress(_bundling, None)
1871 progress(_bundling, None)
1888
1872
1889 # Create a generator for the manifestnodes that calls our lookup
1873 # Create a generator for the manifestnodes that calls our lookup
1890 # and data collection functions back.
1874 # and data collection functions back.
1891 for f in changedfiles:
1875 for f in changedfiles:
1892 fnodes[f] = {}
1876 fnodes[f] = {}
1893 count[:] = [0, len(mfs)]
1877 count[:] = [0, len(mfs)]
1894 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1878 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1895 yield chunk
1879 yield chunk
1896 progress(_bundling, None)
1880 progress(_bundling, None)
1897
1881
1898 mfs.clear()
1882 mfs.clear()
1899
1883
1900 # Go through all our files in order sorted by name.
1884 # Go through all our files in order sorted by name.
1901 count[:] = [0, len(changedfiles)]
1885 count[:] = [0, len(changedfiles)]
1902 for fname in sorted(changedfiles):
1886 for fname in sorted(changedfiles):
1903 filerevlog = self.file(fname)
1887 filerevlog = self.file(fname)
1904 if not len(filerevlog):
1888 if not len(filerevlog):
1905 raise util.Abort(_("empty or missing revlog for %s") % fname)
1889 raise util.Abort(_("empty or missing revlog for %s") % fname)
1906 fstate[0] = fname
1890 fstate[0] = fname
1907 fstate[1] = fnodes.pop(fname, {})
1891 fstate[1] = fnodes.pop(fname, {})
1908
1892
1909 nodelist = prune(filerevlog, fstate[1])
1893 nodelist = prune(filerevlog, fstate[1])
1910 if nodelist:
1894 if nodelist:
1911 count[0] += 1
1895 count[0] += 1
1912 yield bundler.fileheader(fname)
1896 yield bundler.fileheader(fname)
1913 for chunk in filerevlog.group(nodelist, bundler, reorder):
1897 for chunk in filerevlog.group(nodelist, bundler, reorder):
1914 yield chunk
1898 yield chunk
1915
1899
1916 # Signal that no more groups are left.
1900 # Signal that no more groups are left.
1917 yield bundler.close()
1901 yield bundler.close()
1918 progress(_bundling, None)
1902 progress(_bundling, None)
1919
1903
1920 if csets:
1904 if csets:
1921 self.hook('outgoing', node=hex(csets[0]), source=source)
1905 self.hook('outgoing', node=hex(csets[0]), source=source)
1922
1906
1923 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1907 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1924
1908
1925 def changegroup(self, basenodes, source):
1909 def changegroup(self, basenodes, source):
1926 # to avoid a race we use changegroupsubset() (issue1320)
1910 # to avoid a race we use changegroupsubset() (issue1320)
1927 return self.changegroupsubset(basenodes, self.heads(), source)
1911 return self.changegroupsubset(basenodes, self.heads(), source)
1928
1912
1929 def _changegroup(self, nodes, source):
1913 def _changegroup(self, nodes, source):
1930 """Compute the changegroup of all nodes that we have that a recipient
1914 """Compute the changegroup of all nodes that we have that a recipient
1931 doesn't. Return a chunkbuffer object whose read() method will return
1915 doesn't. Return a chunkbuffer object whose read() method will return
1932 successive changegroup chunks.
1916 successive changegroup chunks.
1933
1917
1934 This is much easier than the previous function as we can assume that
1918 This is much easier than the previous function as we can assume that
1935 the recipient has any changenode we aren't sending them.
1919 the recipient has any changenode we aren't sending them.
1936
1920
1937 nodes is the set of nodes to send"""
1921 nodes is the set of nodes to send"""
1938
1922
1939 cl = self.changelog
1923 cl = self.changelog
1940 mf = self.manifest
1924 mf = self.manifest
1941 mfs = {}
1925 mfs = {}
1942 changedfiles = set()
1926 changedfiles = set()
1943 fstate = ['']
1927 fstate = ['']
1944 count = [0, 0]
1928 count = [0, 0]
1945
1929
1946 self.hook('preoutgoing', throw=True, source=source)
1930 self.hook('preoutgoing', throw=True, source=source)
1947 self.changegroupinfo(nodes, source)
1931 self.changegroupinfo(nodes, source)
1948
1932
1949 revset = set([cl.rev(n) for n in nodes])
1933 revset = set([cl.rev(n) for n in nodes])
1950
1934
1951 def gennodelst(log):
1935 def gennodelst(log):
1952 ln, llr = log.node, log.linkrev
1936 ln, llr = log.node, log.linkrev
1953 return [ln(r) for r in log if llr(r) in revset]
1937 return [ln(r) for r in log if llr(r) in revset]
1954
1938
1955 progress = self.ui.progress
1939 progress = self.ui.progress
1956 _bundling = _('bundling')
1940 _bundling = _('bundling')
1957 _changesets = _('changesets')
1941 _changesets = _('changesets')
1958 _manifests = _('manifests')
1942 _manifests = _('manifests')
1959 _files = _('files')
1943 _files = _('files')
1960
1944
1961 def lookup(revlog, x):
1945 def lookup(revlog, x):
1962 if revlog == cl:
1946 if revlog == cl:
1963 c = cl.read(x)
1947 c = cl.read(x)
1964 changedfiles.update(c[3])
1948 changedfiles.update(c[3])
1965 mfs.setdefault(c[0], x)
1949 mfs.setdefault(c[0], x)
1966 count[0] += 1
1950 count[0] += 1
1967 progress(_bundling, count[0],
1951 progress(_bundling, count[0],
1968 unit=_changesets, total=count[1])
1952 unit=_changesets, total=count[1])
1969 return x
1953 return x
1970 elif revlog == mf:
1954 elif revlog == mf:
1971 count[0] += 1
1955 count[0] += 1
1972 progress(_bundling, count[0],
1956 progress(_bundling, count[0],
1973 unit=_manifests, total=count[1])
1957 unit=_manifests, total=count[1])
1974 return cl.node(revlog.linkrev(revlog.rev(x)))
1958 return cl.node(revlog.linkrev(revlog.rev(x)))
1975 else:
1959 else:
1976 progress(_bundling, count[0], item=fstate[0],
1960 progress(_bundling, count[0], item=fstate[0],
1977 total=count[1], unit=_files)
1961 total=count[1], unit=_files)
1978 return cl.node(revlog.linkrev(revlog.rev(x)))
1962 return cl.node(revlog.linkrev(revlog.rev(x)))
1979
1963
1980 bundler = changegroup.bundle10(lookup)
1964 bundler = changegroup.bundle10(lookup)
1981 reorder = self.ui.config('bundle', 'reorder', 'auto')
1965 reorder = self.ui.config('bundle', 'reorder', 'auto')
1982 if reorder == 'auto':
1966 if reorder == 'auto':
1983 reorder = None
1967 reorder = None
1984 else:
1968 else:
1985 reorder = util.parsebool(reorder)
1969 reorder = util.parsebool(reorder)
1986
1970
1987 def gengroup():
1971 def gengroup():
1988 '''yield a sequence of changegroup chunks (strings)'''
1972 '''yield a sequence of changegroup chunks (strings)'''
1989 # construct a list of all changed files
1973 # construct a list of all changed files
1990
1974
1991 count[:] = [0, len(nodes)]
1975 count[:] = [0, len(nodes)]
1992 for chunk in cl.group(nodes, bundler, reorder=reorder):
1976 for chunk in cl.group(nodes, bundler, reorder=reorder):
1993 yield chunk
1977 yield chunk
1994 progress(_bundling, None)
1978 progress(_bundling, None)
1995
1979
1996 count[:] = [0, len(mfs)]
1980 count[:] = [0, len(mfs)]
1997 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1981 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1998 yield chunk
1982 yield chunk
1999 progress(_bundling, None)
1983 progress(_bundling, None)
2000
1984
2001 count[:] = [0, len(changedfiles)]
1985 count[:] = [0, len(changedfiles)]
2002 for fname in sorted(changedfiles):
1986 for fname in sorted(changedfiles):
2003 filerevlog = self.file(fname)
1987 filerevlog = self.file(fname)
2004 if not len(filerevlog):
1988 if not len(filerevlog):
2005 raise util.Abort(_("empty or missing revlog for %s") % fname)
1989 raise util.Abort(_("empty or missing revlog for %s") % fname)
2006 fstate[0] = fname
1990 fstate[0] = fname
2007 nodelist = gennodelst(filerevlog)
1991 nodelist = gennodelst(filerevlog)
2008 if nodelist:
1992 if nodelist:
2009 count[0] += 1
1993 count[0] += 1
2010 yield bundler.fileheader(fname)
1994 yield bundler.fileheader(fname)
2011 for chunk in filerevlog.group(nodelist, bundler, reorder):
1995 for chunk in filerevlog.group(nodelist, bundler, reorder):
2012 yield chunk
1996 yield chunk
2013 yield bundler.close()
1997 yield bundler.close()
2014 progress(_bundling, None)
1998 progress(_bundling, None)
2015
1999
2016 if nodes:
2000 if nodes:
2017 self.hook('outgoing', node=hex(nodes[0]), source=source)
2001 self.hook('outgoing', node=hex(nodes[0]), source=source)
2018
2002
2019 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
2003 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
2020
2004
2021 def addchangegroup(self, source, srctype, url, emptyok=False):
2005 def addchangegroup(self, source, srctype, url, emptyok=False):
2022 """Add the changegroup returned by source.read() to this repo.
2006 """Add the changegroup returned by source.read() to this repo.
2023 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2007 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2024 the URL of the repo where this changegroup is coming from.
2008 the URL of the repo where this changegroup is coming from.
2025
2009
2026 Return an integer summarizing the change to this repo:
2010 Return an integer summarizing the change to this repo:
2027 - nothing changed or no source: 0
2011 - nothing changed or no source: 0
2028 - more heads than before: 1+added heads (2..n)
2012 - more heads than before: 1+added heads (2..n)
2029 - fewer heads than before: -1-removed heads (-2..-n)
2013 - fewer heads than before: -1-removed heads (-2..-n)
2030 - number of heads stays the same: 1
2014 - number of heads stays the same: 1
2031 """
2015 """
2032 def csmap(x):
2016 def csmap(x):
2033 self.ui.debug("add changeset %s\n" % short(x))
2017 self.ui.debug("add changeset %s\n" % short(x))
2034 return len(cl)
2018 return len(cl)
2035
2019
2036 def revmap(x):
2020 def revmap(x):
2037 return cl.rev(x)
2021 return cl.rev(x)
2038
2022
2039 if not source:
2023 if not source:
2040 return 0
2024 return 0
2041
2025
2042 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2026 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2043
2027
2044 changesets = files = revisions = 0
2028 changesets = files = revisions = 0
2045 efiles = set()
2029 efiles = set()
2046
2030
2047 # write changelog data to temp files so concurrent readers will not see
2031 # write changelog data to temp files so concurrent readers will not see
2048 # inconsistent view
2032 # inconsistent view
2049 cl = self.changelog
2033 cl = self.changelog
2050 cl.delayupdate()
2034 cl.delayupdate()
2051 oldheads = cl.heads()
2035 oldheads = cl.heads()
2052
2036
2053 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2037 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2054 try:
2038 try:
2055 trp = weakref.proxy(tr)
2039 trp = weakref.proxy(tr)
2056 # pull off the changeset group
2040 # pull off the changeset group
2057 self.ui.status(_("adding changesets\n"))
2041 self.ui.status(_("adding changesets\n"))
2058 clstart = len(cl)
2042 clstart = len(cl)
2059 class prog(object):
2043 class prog(object):
2060 step = _('changesets')
2044 step = _('changesets')
2061 count = 1
2045 count = 1
2062 ui = self.ui
2046 ui = self.ui
2063 total = None
2047 total = None
2064 def __call__(self):
2048 def __call__(self):
2065 self.ui.progress(self.step, self.count, unit=_('chunks'),
2049 self.ui.progress(self.step, self.count, unit=_('chunks'),
2066 total=self.total)
2050 total=self.total)
2067 self.count += 1
2051 self.count += 1
2068 pr = prog()
2052 pr = prog()
2069 source.callback = pr
2053 source.callback = pr
2070
2054
2071 source.changelogheader()
2055 source.changelogheader()
2072 srccontent = cl.addgroup(source, csmap, trp)
2056 srccontent = cl.addgroup(source, csmap, trp)
2073 if not (srccontent or emptyok):
2057 if not (srccontent or emptyok):
2074 raise util.Abort(_("received changelog group is empty"))
2058 raise util.Abort(_("received changelog group is empty"))
2075 clend = len(cl)
2059 clend = len(cl)
2076 changesets = clend - clstart
2060 changesets = clend - clstart
2077 for c in xrange(clstart, clend):
2061 for c in xrange(clstart, clend):
2078 efiles.update(self[c].files())
2062 efiles.update(self[c].files())
2079 efiles = len(efiles)
2063 efiles = len(efiles)
2080 self.ui.progress(_('changesets'), None)
2064 self.ui.progress(_('changesets'), None)
2081
2065
2082 # pull off the manifest group
2066 # pull off the manifest group
2083 self.ui.status(_("adding manifests\n"))
2067 self.ui.status(_("adding manifests\n"))
2084 pr.step = _('manifests')
2068 pr.step = _('manifests')
2085 pr.count = 1
2069 pr.count = 1
2086 pr.total = changesets # manifests <= changesets
2070 pr.total = changesets # manifests <= changesets
2087 # no need to check for empty manifest group here:
2071 # no need to check for empty manifest group here:
2088 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2072 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2089 # no new manifest will be created and the manifest group will
2073 # no new manifest will be created and the manifest group will
2090 # be empty during the pull
2074 # be empty during the pull
2091 source.manifestheader()
2075 source.manifestheader()
2092 self.manifest.addgroup(source, revmap, trp)
2076 self.manifest.addgroup(source, revmap, trp)
2093 self.ui.progress(_('manifests'), None)
2077 self.ui.progress(_('manifests'), None)
2094
2078
2095 needfiles = {}
2079 needfiles = {}
2096 if self.ui.configbool('server', 'validate', default=False):
2080 if self.ui.configbool('server', 'validate', default=False):
2097 # validate incoming csets have their manifests
2081 # validate incoming csets have their manifests
2098 for cset in xrange(clstart, clend):
2082 for cset in xrange(clstart, clend):
2099 mfest = self.changelog.read(self.changelog.node(cset))[0]
2083 mfest = self.changelog.read(self.changelog.node(cset))[0]
2100 mfest = self.manifest.readdelta(mfest)
2084 mfest = self.manifest.readdelta(mfest)
2101 # store file nodes we must see
2085 # store file nodes we must see
2102 for f, n in mfest.iteritems():
2086 for f, n in mfest.iteritems():
2103 needfiles.setdefault(f, set()).add(n)
2087 needfiles.setdefault(f, set()).add(n)
2104
2088
2105 # process the files
2089 # process the files
2106 self.ui.status(_("adding file changes\n"))
2090 self.ui.status(_("adding file changes\n"))
2107 pr.step = _('files')
2091 pr.step = _('files')
2108 pr.count = 1
2092 pr.count = 1
2109 pr.total = efiles
2093 pr.total = efiles
2110 source.callback = None
2094 source.callback = None
2111
2095
2112 while True:
2096 while True:
2113 chunkdata = source.filelogheader()
2097 chunkdata = source.filelogheader()
2114 if not chunkdata:
2098 if not chunkdata:
2115 break
2099 break
2116 f = chunkdata["filename"]
2100 f = chunkdata["filename"]
2117 self.ui.debug("adding %s revisions\n" % f)
2101 self.ui.debug("adding %s revisions\n" % f)
2118 pr()
2102 pr()
2119 fl = self.file(f)
2103 fl = self.file(f)
2120 o = len(fl)
2104 o = len(fl)
2121 if not fl.addgroup(source, revmap, trp):
2105 if not fl.addgroup(source, revmap, trp):
2122 raise util.Abort(_("received file revlog group is empty"))
2106 raise util.Abort(_("received file revlog group is empty"))
2123 revisions += len(fl) - o
2107 revisions += len(fl) - o
2124 files += 1
2108 files += 1
2125 if f in needfiles:
2109 if f in needfiles:
2126 needs = needfiles[f]
2110 needs = needfiles[f]
2127 for new in xrange(o, len(fl)):
2111 for new in xrange(o, len(fl)):
2128 n = fl.node(new)
2112 n = fl.node(new)
2129 if n in needs:
2113 if n in needs:
2130 needs.remove(n)
2114 needs.remove(n)
2131 if not needs:
2115 if not needs:
2132 del needfiles[f]
2116 del needfiles[f]
2133 self.ui.progress(_('files'), None)
2117 self.ui.progress(_('files'), None)
2134
2118
2135 for f, needs in needfiles.iteritems():
2119 for f, needs in needfiles.iteritems():
2136 fl = self.file(f)
2120 fl = self.file(f)
2137 for n in needs:
2121 for n in needs:
2138 try:
2122 try:
2139 fl.rev(n)
2123 fl.rev(n)
2140 except error.LookupError:
2124 except error.LookupError:
2141 raise util.Abort(
2125 raise util.Abort(
2142 _('missing file data for %s:%s - run hg verify') %
2126 _('missing file data for %s:%s - run hg verify') %
2143 (f, hex(n)))
2127 (f, hex(n)))
2144
2128
2145 dh = 0
2129 dh = 0
2146 if oldheads:
2130 if oldheads:
2147 heads = cl.heads()
2131 heads = cl.heads()
2148 dh = len(heads) - len(oldheads)
2132 dh = len(heads) - len(oldheads)
2149 for h in heads:
2133 for h in heads:
2150 if h not in oldheads and 'close' in self[h].extra():
2134 if h not in oldheads and 'close' in self[h].extra():
2151 dh -= 1
2135 dh -= 1
2152 htext = ""
2136 htext = ""
2153 if dh:
2137 if dh:
2154 htext = _(" (%+d heads)") % dh
2138 htext = _(" (%+d heads)") % dh
2155
2139
2156 self.ui.status(_("added %d changesets"
2140 self.ui.status(_("added %d changesets"
2157 " with %d changes to %d files%s\n")
2141 " with %d changes to %d files%s\n")
2158 % (changesets, revisions, files, htext))
2142 % (changesets, revisions, files, htext))
2159
2143
2160 if changesets > 0:
2144 if changesets > 0:
2161 p = lambda: cl.writepending() and self.root or ""
2145 p = lambda: cl.writepending() and self.root or ""
2162 self.hook('pretxnchangegroup', throw=True,
2146 self.hook('pretxnchangegroup', throw=True,
2163 node=hex(cl.node(clstart)), source=srctype,
2147 node=hex(cl.node(clstart)), source=srctype,
2164 url=url, pending=p)
2148 url=url, pending=p)
2165
2149
2166 added = [cl.node(r) for r in xrange(clstart, clend)]
2150 added = [cl.node(r) for r in xrange(clstart, clend)]
2167 publishing = self.ui.configbool('phases', 'publish', True)
2151 publishing = self.ui.configbool('phases', 'publish', True)
2168 if srctype == 'push':
2152 if srctype == 'push':
2169 # Old server can not push the boundary themself.
2153 # Old server can not push the boundary themself.
2170 # New server won't push the boundary if changeset already
2154 # New server won't push the boundary if changeset already
2171 # existed locally as secrete
2155 # existed locally as secrete
2172 #
2156 #
2173 # We should not use added here but the list of all change in
2157 # We should not use added here but the list of all change in
2174 # the bundle
2158 # the bundle
2175 if publishing:
2159 if publishing:
2176 phases.advanceboundary(self, phases.public, srccontent)
2160 phases.advanceboundary(self, phases.public, srccontent)
2177 else:
2161 else:
2178 phases.advanceboundary(self, phases.draft, srccontent)
2162 phases.advanceboundary(self, phases.draft, srccontent)
2179 phases.retractboundary(self, phases.draft, added)
2163 phases.retractboundary(self, phases.draft, added)
2180 elif srctype != 'strip':
2164 elif srctype != 'strip':
2181 # publishing only alter behavior during push
2165 # publishing only alter behavior during push
2182 #
2166 #
2183 # strip should not touch boundary at all
2167 # strip should not touch boundary at all
2184 phases.retractboundary(self, phases.draft, added)
2168 phases.retractboundary(self, phases.draft, added)
2185
2169
2186 # make changelog see real files again
2170 # make changelog see real files again
2187 cl.finalize(trp)
2171 cl.finalize(trp)
2188
2172
2189 tr.close()
2173 tr.close()
2190
2174
2191 if changesets > 0:
2175 if changesets > 0:
2192 def runhooks():
2176 def runhooks():
2193 # forcefully update the on-disk branch cache
2177 # forcefully update the on-disk branch cache
2194 self.ui.debug("updating the branch cache\n")
2178 self.ui.debug("updating the branch cache\n")
2195 self.updatebranchcache()
2179 self.updatebranchcache()
2196 self.hook("changegroup", node=hex(cl.node(clstart)),
2180 self.hook("changegroup", node=hex(cl.node(clstart)),
2197 source=srctype, url=url)
2181 source=srctype, url=url)
2198
2182
2199 for n in added:
2183 for n in added:
2200 self.hook("incoming", node=hex(n), source=srctype,
2184 self.hook("incoming", node=hex(n), source=srctype,
2201 url=url)
2185 url=url)
2202 self._afterlock(runhooks)
2186 self._afterlock(runhooks)
2203
2187
2204 finally:
2188 finally:
2205 tr.release()
2189 tr.release()
2206 # never return 0 here:
2190 # never return 0 here:
2207 if dh < 0:
2191 if dh < 0:
2208 return dh - 1
2192 return dh - 1
2209 else:
2193 else:
2210 return dh + 1
2194 return dh + 1
2211
2195
2212 def stream_in(self, remote, requirements):
2196 def stream_in(self, remote, requirements):
2213 lock = self.lock()
2197 lock = self.lock()
2214 try:
2198 try:
2215 fp = remote.stream_out()
2199 fp = remote.stream_out()
2216 l = fp.readline()
2200 l = fp.readline()
2217 try:
2201 try:
2218 resp = int(l)
2202 resp = int(l)
2219 except ValueError:
2203 except ValueError:
2220 raise error.ResponseError(
2204 raise error.ResponseError(
2221 _('Unexpected response from remote server:'), l)
2205 _('Unexpected response from remote server:'), l)
2222 if resp == 1:
2206 if resp == 1:
2223 raise util.Abort(_('operation forbidden by server'))
2207 raise util.Abort(_('operation forbidden by server'))
2224 elif resp == 2:
2208 elif resp == 2:
2225 raise util.Abort(_('locking the remote repository failed'))
2209 raise util.Abort(_('locking the remote repository failed'))
2226 elif resp != 0:
2210 elif resp != 0:
2227 raise util.Abort(_('the server sent an unknown error code'))
2211 raise util.Abort(_('the server sent an unknown error code'))
2228 self.ui.status(_('streaming all changes\n'))
2212 self.ui.status(_('streaming all changes\n'))
2229 l = fp.readline()
2213 l = fp.readline()
2230 try:
2214 try:
2231 total_files, total_bytes = map(int, l.split(' ', 1))
2215 total_files, total_bytes = map(int, l.split(' ', 1))
2232 except (ValueError, TypeError):
2216 except (ValueError, TypeError):
2233 raise error.ResponseError(
2217 raise error.ResponseError(
2234 _('Unexpected response from remote server:'), l)
2218 _('Unexpected response from remote server:'), l)
2235 self.ui.status(_('%d files to transfer, %s of data\n') %
2219 self.ui.status(_('%d files to transfer, %s of data\n') %
2236 (total_files, util.bytecount(total_bytes)))
2220 (total_files, util.bytecount(total_bytes)))
2237 start = time.time()
2221 start = time.time()
2238 for i in xrange(total_files):
2222 for i in xrange(total_files):
2239 # XXX doesn't support '\n' or '\r' in filenames
2223 # XXX doesn't support '\n' or '\r' in filenames
2240 l = fp.readline()
2224 l = fp.readline()
2241 try:
2225 try:
2242 name, size = l.split('\0', 1)
2226 name, size = l.split('\0', 1)
2243 size = int(size)
2227 size = int(size)
2244 except (ValueError, TypeError):
2228 except (ValueError, TypeError):
2245 raise error.ResponseError(
2229 raise error.ResponseError(
2246 _('Unexpected response from remote server:'), l)
2230 _('Unexpected response from remote server:'), l)
2247 if self.ui.debugflag:
2231 if self.ui.debugflag:
2248 self.ui.debug('adding %s (%s)\n' %
2232 self.ui.debug('adding %s (%s)\n' %
2249 (name, util.bytecount(size)))
2233 (name, util.bytecount(size)))
2250 # for backwards compat, name was partially encoded
2234 # for backwards compat, name was partially encoded
2251 ofp = self.sopener(store.decodedir(name), 'w')
2235 ofp = self.sopener(store.decodedir(name), 'w')
2252 for chunk in util.filechunkiter(fp, limit=size):
2236 for chunk in util.filechunkiter(fp, limit=size):
2253 ofp.write(chunk)
2237 ofp.write(chunk)
2254 ofp.close()
2238 ofp.close()
2255 elapsed = time.time() - start
2239 elapsed = time.time() - start
2256 if elapsed <= 0:
2240 if elapsed <= 0:
2257 elapsed = 0.001
2241 elapsed = 0.001
2258 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2242 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2259 (util.bytecount(total_bytes), elapsed,
2243 (util.bytecount(total_bytes), elapsed,
2260 util.bytecount(total_bytes / elapsed)))
2244 util.bytecount(total_bytes / elapsed)))
2261
2245
2262 # new requirements = old non-format requirements + new format-related
2246 # new requirements = old non-format requirements + new format-related
2263 # requirements from the streamed-in repository
2247 # requirements from the streamed-in repository
2264 requirements.update(set(self.requirements) - self.supportedformats)
2248 requirements.update(set(self.requirements) - self.supportedformats)
2265 self._applyrequirements(requirements)
2249 self._applyrequirements(requirements)
2266 self._writerequirements()
2250 self._writerequirements()
2267
2251
2268 self.invalidate()
2252 self.invalidate()
2269 return len(self.heads()) + 1
2253 return len(self.heads()) + 1
2270 finally:
2254 finally:
2271 lock.release()
2255 lock.release()
2272
2256
2273 def clone(self, remote, heads=[], stream=False):
2257 def clone(self, remote, heads=[], stream=False):
2274 '''clone remote repository.
2258 '''clone remote repository.
2275
2259
2276 keyword arguments:
2260 keyword arguments:
2277 heads: list of revs to clone (forces use of pull)
2261 heads: list of revs to clone (forces use of pull)
2278 stream: use streaming clone if possible'''
2262 stream: use streaming clone if possible'''
2279
2263
2280 # now, all clients that can request uncompressed clones can
2264 # now, all clients that can request uncompressed clones can
2281 # read repo formats supported by all servers that can serve
2265 # read repo formats supported by all servers that can serve
2282 # them.
2266 # them.
2283
2267
2284 # if revlog format changes, client will have to check version
2268 # if revlog format changes, client will have to check version
2285 # and format flags on "stream" capability, and use
2269 # and format flags on "stream" capability, and use
2286 # uncompressed only if compatible.
2270 # uncompressed only if compatible.
2287
2271
2288 if not stream:
2272 if not stream:
2289 # if the server explicitely prefer to stream (for fast LANs)
2273 # if the server explicitely prefer to stream (for fast LANs)
2290 stream = remote.capable('stream-preferred')
2274 stream = remote.capable('stream-preferred')
2291
2275
2292 if stream and not heads:
2276 if stream and not heads:
2293 # 'stream' means remote revlog format is revlogv1 only
2277 # 'stream' means remote revlog format is revlogv1 only
2294 if remote.capable('stream'):
2278 if remote.capable('stream'):
2295 return self.stream_in(remote, set(('revlogv1',)))
2279 return self.stream_in(remote, set(('revlogv1',)))
2296 # otherwise, 'streamreqs' contains the remote revlog format
2280 # otherwise, 'streamreqs' contains the remote revlog format
2297 streamreqs = remote.capable('streamreqs')
2281 streamreqs = remote.capable('streamreqs')
2298 if streamreqs:
2282 if streamreqs:
2299 streamreqs = set(streamreqs.split(','))
2283 streamreqs = set(streamreqs.split(','))
2300 # if we support it, stream in and adjust our requirements
2284 # if we support it, stream in and adjust our requirements
2301 if not streamreqs - self.supportedformats:
2285 if not streamreqs - self.supportedformats:
2302 return self.stream_in(remote, streamreqs)
2286 return self.stream_in(remote, streamreqs)
2303 return self.pull(remote, heads)
2287 return self.pull(remote, heads)
2304
2288
2305 def pushkey(self, namespace, key, old, new):
2289 def pushkey(self, namespace, key, old, new):
2306 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2290 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2307 old=old, new=new)
2291 old=old, new=new)
2308 ret = pushkey.push(self, namespace, key, old, new)
2292 ret = pushkey.push(self, namespace, key, old, new)
2309 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2293 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2310 ret=ret)
2294 ret=ret)
2311 return ret
2295 return ret
2312
2296
2313 def listkeys(self, namespace):
2297 def listkeys(self, namespace):
2314 self.hook('prelistkeys', throw=True, namespace=namespace)
2298 self.hook('prelistkeys', throw=True, namespace=namespace)
2315 values = pushkey.list(self, namespace)
2299 values = pushkey.list(self, namespace)
2316 self.hook('listkeys', namespace=namespace, values=values)
2300 self.hook('listkeys', namespace=namespace, values=values)
2317 return values
2301 return values
2318
2302
2319 def debugwireargs(self, one, two, three=None, four=None, five=None):
2303 def debugwireargs(self, one, two, three=None, four=None, five=None):
2320 '''used to test argument passing over the wire'''
2304 '''used to test argument passing over the wire'''
2321 return "%s %s %s %s %s" % (one, two, three, four, five)
2305 return "%s %s %s %s %s" % (one, two, three, four, five)
2322
2306
2323 def savecommitmessage(self, text):
2307 def savecommitmessage(self, text):
2324 fp = self.opener('last-message.txt', 'wb')
2308 fp = self.opener('last-message.txt', 'wb')
2325 try:
2309 try:
2326 fp.write(text)
2310 fp.write(text)
2327 finally:
2311 finally:
2328 fp.close()
2312 fp.close()
2329 return self.pathto(fp.name[len(self.root)+1:])
2313 return self.pathto(fp.name[len(self.root)+1:])
2330
2314
2331 # used to avoid circular references so destructors work
2315 # used to avoid circular references so destructors work
2332 def aftertrans(files):
2316 def aftertrans(files):
2333 renamefiles = [tuple(t) for t in files]
2317 renamefiles = [tuple(t) for t in files]
2334 def a():
2318 def a():
2335 for src, dest in renamefiles:
2319 for src, dest in renamefiles:
2336 try:
2320 try:
2337 util.rename(src, dest)
2321 util.rename(src, dest)
2338 except OSError: # journal file does not yet exist
2322 except OSError: # journal file does not yet exist
2339 pass
2323 pass
2340 return a
2324 return a
2341
2325
2342 def undoname(fn):
2326 def undoname(fn):
2343 base, name = os.path.split(fn)
2327 base, name = os.path.split(fn)
2344 assert name.startswith('journal')
2328 assert name.startswith('journal')
2345 return os.path.join(base, name.replace('journal', 'undo', 1))
2329 return os.path.join(base, name.replace('journal', 'undo', 1))
2346
2330
2347 def instance(ui, path, create):
2331 def instance(ui, path, create):
2348 return localrepository(ui, util.urllocalpath(path), create)
2332 return localrepository(ui, util.urllocalpath(path), create)
2349
2333
2350 def islocal(path):
2334 def islocal(path):
2351 return True
2335 return True
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now