##// END OF EJS Templates
patch: turn patch() touched files dict into a set
Patrick Mezard -
r14564:65f4512e default
parent child Browse files
Show More
@@ -1,3293 +1,3293 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 You will by default be managing a patch queue named "patches". You can
41 You will by default be managing a patch queue named "patches". You can
42 create other, independent patch queues with the :hg:`qqueue` command.
42 create other, independent patch queues with the :hg:`qqueue` command.
43 '''
43 '''
44
44
45 from mercurial.i18n import _
45 from mercurial.i18n import _
46 from mercurial.node import bin, hex, short, nullid, nullrev
46 from mercurial.node import bin, hex, short, nullid, nullrev
47 from mercurial.lock import release
47 from mercurial.lock import release
48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
49 from mercurial import repair, extensions, url, error
49 from mercurial import repair, extensions, url, error
50 from mercurial import patch as patchmod
50 from mercurial import patch as patchmod
51 import os, sys, re, errno, shutil
51 import os, sys, re, errno, shutil
52
52
53 commands.norepo += " qclone"
53 commands.norepo += " qclone"
54
54
55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
56
56
57 cmdtable = {}
57 cmdtable = {}
58 command = cmdutil.command(cmdtable)
58 command = cmdutil.command(cmdtable)
59
59
60 # Patch names looks like unix-file names.
60 # Patch names looks like unix-file names.
61 # They must be joinable with queue directory and result in the patch path.
61 # They must be joinable with queue directory and result in the patch path.
62 normname = util.normpath
62 normname = util.normpath
63
63
64 class statusentry(object):
64 class statusentry(object):
65 def __init__(self, node, name):
65 def __init__(self, node, name):
66 self.node, self.name = node, name
66 self.node, self.name = node, name
67 def __repr__(self):
67 def __repr__(self):
68 return hex(self.node) + ':' + self.name
68 return hex(self.node) + ':' + self.name
69
69
70 class patchheader(object):
70 class patchheader(object):
71 def __init__(self, pf, plainmode=False):
71 def __init__(self, pf, plainmode=False):
72 def eatdiff(lines):
72 def eatdiff(lines):
73 while lines:
73 while lines:
74 l = lines[-1]
74 l = lines[-1]
75 if (l.startswith("diff -") or
75 if (l.startswith("diff -") or
76 l.startswith("Index:") or
76 l.startswith("Index:") or
77 l.startswith("===========")):
77 l.startswith("===========")):
78 del lines[-1]
78 del lines[-1]
79 else:
79 else:
80 break
80 break
81 def eatempty(lines):
81 def eatempty(lines):
82 while lines:
82 while lines:
83 if not lines[-1].strip():
83 if not lines[-1].strip():
84 del lines[-1]
84 del lines[-1]
85 else:
85 else:
86 break
86 break
87
87
88 message = []
88 message = []
89 comments = []
89 comments = []
90 user = None
90 user = None
91 date = None
91 date = None
92 parent = None
92 parent = None
93 format = None
93 format = None
94 subject = None
94 subject = None
95 branch = None
95 branch = None
96 nodeid = None
96 nodeid = None
97 diffstart = 0
97 diffstart = 0
98
98
99 for line in file(pf):
99 for line in file(pf):
100 line = line.rstrip()
100 line = line.rstrip()
101 if (line.startswith('diff --git')
101 if (line.startswith('diff --git')
102 or (diffstart and line.startswith('+++ '))):
102 or (diffstart and line.startswith('+++ '))):
103 diffstart = 2
103 diffstart = 2
104 break
104 break
105 diffstart = 0 # reset
105 diffstart = 0 # reset
106 if line.startswith("--- "):
106 if line.startswith("--- "):
107 diffstart = 1
107 diffstart = 1
108 continue
108 continue
109 elif format == "hgpatch":
109 elif format == "hgpatch":
110 # parse values when importing the result of an hg export
110 # parse values when importing the result of an hg export
111 if line.startswith("# User "):
111 if line.startswith("# User "):
112 user = line[7:]
112 user = line[7:]
113 elif line.startswith("# Date "):
113 elif line.startswith("# Date "):
114 date = line[7:]
114 date = line[7:]
115 elif line.startswith("# Parent "):
115 elif line.startswith("# Parent "):
116 parent = line[9:].lstrip()
116 parent = line[9:].lstrip()
117 elif line.startswith("# Branch "):
117 elif line.startswith("# Branch "):
118 branch = line[9:]
118 branch = line[9:]
119 elif line.startswith("# Node ID "):
119 elif line.startswith("# Node ID "):
120 nodeid = line[10:]
120 nodeid = line[10:]
121 elif not line.startswith("# ") and line:
121 elif not line.startswith("# ") and line:
122 message.append(line)
122 message.append(line)
123 format = None
123 format = None
124 elif line == '# HG changeset patch':
124 elif line == '# HG changeset patch':
125 message = []
125 message = []
126 format = "hgpatch"
126 format = "hgpatch"
127 elif (format != "tagdone" and (line.startswith("Subject: ") or
127 elif (format != "tagdone" and (line.startswith("Subject: ") or
128 line.startswith("subject: "))):
128 line.startswith("subject: "))):
129 subject = line[9:]
129 subject = line[9:]
130 format = "tag"
130 format = "tag"
131 elif (format != "tagdone" and (line.startswith("From: ") or
131 elif (format != "tagdone" and (line.startswith("From: ") or
132 line.startswith("from: "))):
132 line.startswith("from: "))):
133 user = line[6:]
133 user = line[6:]
134 format = "tag"
134 format = "tag"
135 elif (format != "tagdone" and (line.startswith("Date: ") or
135 elif (format != "tagdone" and (line.startswith("Date: ") or
136 line.startswith("date: "))):
136 line.startswith("date: "))):
137 date = line[6:]
137 date = line[6:]
138 format = "tag"
138 format = "tag"
139 elif format == "tag" and line == "":
139 elif format == "tag" and line == "":
140 # when looking for tags (subject: from: etc) they
140 # when looking for tags (subject: from: etc) they
141 # end once you find a blank line in the source
141 # end once you find a blank line in the source
142 format = "tagdone"
142 format = "tagdone"
143 elif message or line:
143 elif message or line:
144 message.append(line)
144 message.append(line)
145 comments.append(line)
145 comments.append(line)
146
146
147 eatdiff(message)
147 eatdiff(message)
148 eatdiff(comments)
148 eatdiff(comments)
149 # Remember the exact starting line of the patch diffs before consuming
149 # Remember the exact starting line of the patch diffs before consuming
150 # empty lines, for external use by TortoiseHg and others
150 # empty lines, for external use by TortoiseHg and others
151 self.diffstartline = len(comments)
151 self.diffstartline = len(comments)
152 eatempty(message)
152 eatempty(message)
153 eatempty(comments)
153 eatempty(comments)
154
154
155 # make sure message isn't empty
155 # make sure message isn't empty
156 if format and format.startswith("tag") and subject:
156 if format and format.startswith("tag") and subject:
157 message.insert(0, "")
157 message.insert(0, "")
158 message.insert(0, subject)
158 message.insert(0, subject)
159
159
160 self.message = message
160 self.message = message
161 self.comments = comments
161 self.comments = comments
162 self.user = user
162 self.user = user
163 self.date = date
163 self.date = date
164 self.parent = parent
164 self.parent = parent
165 # nodeid and branch are for external use by TortoiseHg and others
165 # nodeid and branch are for external use by TortoiseHg and others
166 self.nodeid = nodeid
166 self.nodeid = nodeid
167 self.branch = branch
167 self.branch = branch
168 self.haspatch = diffstart > 1
168 self.haspatch = diffstart > 1
169 self.plainmode = plainmode
169 self.plainmode = plainmode
170
170
171 def setuser(self, user):
171 def setuser(self, user):
172 if not self.updateheader(['From: ', '# User '], user):
172 if not self.updateheader(['From: ', '# User '], user):
173 try:
173 try:
174 patchheaderat = self.comments.index('# HG changeset patch')
174 patchheaderat = self.comments.index('# HG changeset patch')
175 self.comments.insert(patchheaderat + 1, '# User ' + user)
175 self.comments.insert(patchheaderat + 1, '# User ' + user)
176 except ValueError:
176 except ValueError:
177 if self.plainmode or self._hasheader(['Date: ']):
177 if self.plainmode or self._hasheader(['Date: ']):
178 self.comments = ['From: ' + user] + self.comments
178 self.comments = ['From: ' + user] + self.comments
179 else:
179 else:
180 tmp = ['# HG changeset patch', '# User ' + user, '']
180 tmp = ['# HG changeset patch', '# User ' + user, '']
181 self.comments = tmp + self.comments
181 self.comments = tmp + self.comments
182 self.user = user
182 self.user = user
183
183
184 def setdate(self, date):
184 def setdate(self, date):
185 if not self.updateheader(['Date: ', '# Date '], date):
185 if not self.updateheader(['Date: ', '# Date '], date):
186 try:
186 try:
187 patchheaderat = self.comments.index('# HG changeset patch')
187 patchheaderat = self.comments.index('# HG changeset patch')
188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
189 except ValueError:
189 except ValueError:
190 if self.plainmode or self._hasheader(['From: ']):
190 if self.plainmode or self._hasheader(['From: ']):
191 self.comments = ['Date: ' + date] + self.comments
191 self.comments = ['Date: ' + date] + self.comments
192 else:
192 else:
193 tmp = ['# HG changeset patch', '# Date ' + date, '']
193 tmp = ['# HG changeset patch', '# Date ' + date, '']
194 self.comments = tmp + self.comments
194 self.comments = tmp + self.comments
195 self.date = date
195 self.date = date
196
196
197 def setparent(self, parent):
197 def setparent(self, parent):
198 if not self.updateheader(['# Parent '], parent):
198 if not self.updateheader(['# Parent '], parent):
199 try:
199 try:
200 patchheaderat = self.comments.index('# HG changeset patch')
200 patchheaderat = self.comments.index('# HG changeset patch')
201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
202 except ValueError:
202 except ValueError:
203 pass
203 pass
204 self.parent = parent
204 self.parent = parent
205
205
206 def setmessage(self, message):
206 def setmessage(self, message):
207 if self.comments:
207 if self.comments:
208 self._delmsg()
208 self._delmsg()
209 self.message = [message]
209 self.message = [message]
210 self.comments += self.message
210 self.comments += self.message
211
211
212 def updateheader(self, prefixes, new):
212 def updateheader(self, prefixes, new):
213 '''Update all references to a field in the patch header.
213 '''Update all references to a field in the patch header.
214 Return whether the field is present.'''
214 Return whether the field is present.'''
215 res = False
215 res = False
216 for prefix in prefixes:
216 for prefix in prefixes:
217 for i in xrange(len(self.comments)):
217 for i in xrange(len(self.comments)):
218 if self.comments[i].startswith(prefix):
218 if self.comments[i].startswith(prefix):
219 self.comments[i] = prefix + new
219 self.comments[i] = prefix + new
220 res = True
220 res = True
221 break
221 break
222 return res
222 return res
223
223
224 def _hasheader(self, prefixes):
224 def _hasheader(self, prefixes):
225 '''Check if a header starts with any of the given prefixes.'''
225 '''Check if a header starts with any of the given prefixes.'''
226 for prefix in prefixes:
226 for prefix in prefixes:
227 for comment in self.comments:
227 for comment in self.comments:
228 if comment.startswith(prefix):
228 if comment.startswith(prefix):
229 return True
229 return True
230 return False
230 return False
231
231
232 def __str__(self):
232 def __str__(self):
233 if not self.comments:
233 if not self.comments:
234 return ''
234 return ''
235 return '\n'.join(self.comments) + '\n\n'
235 return '\n'.join(self.comments) + '\n\n'
236
236
237 def _delmsg(self):
237 def _delmsg(self):
238 '''Remove existing message, keeping the rest of the comments fields.
238 '''Remove existing message, keeping the rest of the comments fields.
239 If comments contains 'subject: ', message will prepend
239 If comments contains 'subject: ', message will prepend
240 the field and a blank line.'''
240 the field and a blank line.'''
241 if self.message:
241 if self.message:
242 subj = 'subject: ' + self.message[0].lower()
242 subj = 'subject: ' + self.message[0].lower()
243 for i in xrange(len(self.comments)):
243 for i in xrange(len(self.comments)):
244 if subj == self.comments[i].lower():
244 if subj == self.comments[i].lower():
245 del self.comments[i]
245 del self.comments[i]
246 self.message = self.message[2:]
246 self.message = self.message[2:]
247 break
247 break
248 ci = 0
248 ci = 0
249 for mi in self.message:
249 for mi in self.message:
250 while mi != self.comments[ci]:
250 while mi != self.comments[ci]:
251 ci += 1
251 ci += 1
252 del self.comments[ci]
252 del self.comments[ci]
253
253
254 class queue(object):
254 class queue(object):
255 def __init__(self, ui, path, patchdir=None):
255 def __init__(self, ui, path, patchdir=None):
256 self.basepath = path
256 self.basepath = path
257 try:
257 try:
258 fh = open(os.path.join(path, 'patches.queue'))
258 fh = open(os.path.join(path, 'patches.queue'))
259 cur = fh.read().rstrip()
259 cur = fh.read().rstrip()
260 fh.close()
260 fh.close()
261 if not cur:
261 if not cur:
262 curpath = os.path.join(path, 'patches')
262 curpath = os.path.join(path, 'patches')
263 else:
263 else:
264 curpath = os.path.join(path, 'patches-' + cur)
264 curpath = os.path.join(path, 'patches-' + cur)
265 except IOError:
265 except IOError:
266 curpath = os.path.join(path, 'patches')
266 curpath = os.path.join(path, 'patches')
267 self.path = patchdir or curpath
267 self.path = patchdir or curpath
268 self.opener = scmutil.opener(self.path)
268 self.opener = scmutil.opener(self.path)
269 self.ui = ui
269 self.ui = ui
270 self.applied_dirty = 0
270 self.applied_dirty = 0
271 self.series_dirty = 0
271 self.series_dirty = 0
272 self.added = []
272 self.added = []
273 self.series_path = "series"
273 self.series_path = "series"
274 self.status_path = "status"
274 self.status_path = "status"
275 self.guards_path = "guards"
275 self.guards_path = "guards"
276 self.active_guards = None
276 self.active_guards = None
277 self.guards_dirty = False
277 self.guards_dirty = False
278 # Handle mq.git as a bool with extended values
278 # Handle mq.git as a bool with extended values
279 try:
279 try:
280 gitmode = ui.configbool('mq', 'git', None)
280 gitmode = ui.configbool('mq', 'git', None)
281 if gitmode is None:
281 if gitmode is None:
282 raise error.ConfigError()
282 raise error.ConfigError()
283 self.gitmode = gitmode and 'yes' or 'no'
283 self.gitmode = gitmode and 'yes' or 'no'
284 except error.ConfigError:
284 except error.ConfigError:
285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
286 self.plainmode = ui.configbool('mq', 'plain', False)
286 self.plainmode = ui.configbool('mq', 'plain', False)
287
287
288 @util.propertycache
288 @util.propertycache
289 def applied(self):
289 def applied(self):
290 if os.path.exists(self.join(self.status_path)):
290 if os.path.exists(self.join(self.status_path)):
291 def parselines(lines):
291 def parselines(lines):
292 for l in lines:
292 for l in lines:
293 entry = l.split(':', 1)
293 entry = l.split(':', 1)
294 if len(entry) > 1:
294 if len(entry) > 1:
295 n, name = entry
295 n, name = entry
296 yield statusentry(bin(n), name)
296 yield statusentry(bin(n), name)
297 elif l.strip():
297 elif l.strip():
298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
299 # else we ignore empty lines
299 # else we ignore empty lines
300 lines = self.opener.read(self.status_path).splitlines()
300 lines = self.opener.read(self.status_path).splitlines()
301 return list(parselines(lines))
301 return list(parselines(lines))
302 return []
302 return []
303
303
304 @util.propertycache
304 @util.propertycache
305 def full_series(self):
305 def full_series(self):
306 if os.path.exists(self.join(self.series_path)):
306 if os.path.exists(self.join(self.series_path)):
307 return self.opener.read(self.series_path).splitlines()
307 return self.opener.read(self.series_path).splitlines()
308 return []
308 return []
309
309
310 @util.propertycache
310 @util.propertycache
311 def series(self):
311 def series(self):
312 self.parse_series()
312 self.parse_series()
313 return self.series
313 return self.series
314
314
315 @util.propertycache
315 @util.propertycache
316 def series_guards(self):
316 def series_guards(self):
317 self.parse_series()
317 self.parse_series()
318 return self.series_guards
318 return self.series_guards
319
319
320 def invalidate(self):
320 def invalidate(self):
321 for a in 'applied full_series series series_guards'.split():
321 for a in 'applied full_series series series_guards'.split():
322 if a in self.__dict__:
322 if a in self.__dict__:
323 delattr(self, a)
323 delattr(self, a)
324 self.applied_dirty = 0
324 self.applied_dirty = 0
325 self.series_dirty = 0
325 self.series_dirty = 0
326 self.guards_dirty = False
326 self.guards_dirty = False
327 self.active_guards = None
327 self.active_guards = None
328
328
329 def diffopts(self, opts={}, patchfn=None):
329 def diffopts(self, opts={}, patchfn=None):
330 diffopts = patchmod.diffopts(self.ui, opts)
330 diffopts = patchmod.diffopts(self.ui, opts)
331 if self.gitmode == 'auto':
331 if self.gitmode == 'auto':
332 diffopts.upgrade = True
332 diffopts.upgrade = True
333 elif self.gitmode == 'keep':
333 elif self.gitmode == 'keep':
334 pass
334 pass
335 elif self.gitmode in ('yes', 'no'):
335 elif self.gitmode in ('yes', 'no'):
336 diffopts.git = self.gitmode == 'yes'
336 diffopts.git = self.gitmode == 'yes'
337 else:
337 else:
338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
339 ' got %s') % self.gitmode)
339 ' got %s') % self.gitmode)
340 if patchfn:
340 if patchfn:
341 diffopts = self.patchopts(diffopts, patchfn)
341 diffopts = self.patchopts(diffopts, patchfn)
342 return diffopts
342 return diffopts
343
343
344 def patchopts(self, diffopts, *patches):
344 def patchopts(self, diffopts, *patches):
345 """Return a copy of input diff options with git set to true if
345 """Return a copy of input diff options with git set to true if
346 referenced patch is a git patch and should be preserved as such.
346 referenced patch is a git patch and should be preserved as such.
347 """
347 """
348 diffopts = diffopts.copy()
348 diffopts = diffopts.copy()
349 if not diffopts.git and self.gitmode == 'keep':
349 if not diffopts.git and self.gitmode == 'keep':
350 for patchfn in patches:
350 for patchfn in patches:
351 patchf = self.opener(patchfn, 'r')
351 patchf = self.opener(patchfn, 'r')
352 # if the patch was a git patch, refresh it as a git patch
352 # if the patch was a git patch, refresh it as a git patch
353 for line in patchf:
353 for line in patchf:
354 if line.startswith('diff --git'):
354 if line.startswith('diff --git'):
355 diffopts.git = True
355 diffopts.git = True
356 break
356 break
357 patchf.close()
357 patchf.close()
358 return diffopts
358 return diffopts
359
359
360 def join(self, *p):
360 def join(self, *p):
361 return os.path.join(self.path, *p)
361 return os.path.join(self.path, *p)
362
362
363 def find_series(self, patch):
363 def find_series(self, patch):
364 def matchpatch(l):
364 def matchpatch(l):
365 l = l.split('#', 1)[0]
365 l = l.split('#', 1)[0]
366 return l.strip() == patch
366 return l.strip() == patch
367 for index, l in enumerate(self.full_series):
367 for index, l in enumerate(self.full_series):
368 if matchpatch(l):
368 if matchpatch(l):
369 return index
369 return index
370 return None
370 return None
371
371
372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
373
373
374 def parse_series(self):
374 def parse_series(self):
375 self.series = []
375 self.series = []
376 self.series_guards = []
376 self.series_guards = []
377 for l in self.full_series:
377 for l in self.full_series:
378 h = l.find('#')
378 h = l.find('#')
379 if h == -1:
379 if h == -1:
380 patch = l
380 patch = l
381 comment = ''
381 comment = ''
382 elif h == 0:
382 elif h == 0:
383 continue
383 continue
384 else:
384 else:
385 patch = l[:h]
385 patch = l[:h]
386 comment = l[h:]
386 comment = l[h:]
387 patch = patch.strip()
387 patch = patch.strip()
388 if patch:
388 if patch:
389 if patch in self.series:
389 if patch in self.series:
390 raise util.Abort(_('%s appears more than once in %s') %
390 raise util.Abort(_('%s appears more than once in %s') %
391 (patch, self.join(self.series_path)))
391 (patch, self.join(self.series_path)))
392 self.series.append(patch)
392 self.series.append(patch)
393 self.series_guards.append(self.guard_re.findall(comment))
393 self.series_guards.append(self.guard_re.findall(comment))
394
394
395 def check_guard(self, guard):
395 def check_guard(self, guard):
396 if not guard:
396 if not guard:
397 return _('guard cannot be an empty string')
397 return _('guard cannot be an empty string')
398 bad_chars = '# \t\r\n\f'
398 bad_chars = '# \t\r\n\f'
399 first = guard[0]
399 first = guard[0]
400 if first in '-+':
400 if first in '-+':
401 return (_('guard %r starts with invalid character: %r') %
401 return (_('guard %r starts with invalid character: %r') %
402 (guard, first))
402 (guard, first))
403 for c in bad_chars:
403 for c in bad_chars:
404 if c in guard:
404 if c in guard:
405 return _('invalid character in guard %r: %r') % (guard, c)
405 return _('invalid character in guard %r: %r') % (guard, c)
406
406
407 def set_active(self, guards):
407 def set_active(self, guards):
408 for guard in guards:
408 for guard in guards:
409 bad = self.check_guard(guard)
409 bad = self.check_guard(guard)
410 if bad:
410 if bad:
411 raise util.Abort(bad)
411 raise util.Abort(bad)
412 guards = sorted(set(guards))
412 guards = sorted(set(guards))
413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
414 self.active_guards = guards
414 self.active_guards = guards
415 self.guards_dirty = True
415 self.guards_dirty = True
416
416
417 def active(self):
417 def active(self):
418 if self.active_guards is None:
418 if self.active_guards is None:
419 self.active_guards = []
419 self.active_guards = []
420 try:
420 try:
421 guards = self.opener.read(self.guards_path).split()
421 guards = self.opener.read(self.guards_path).split()
422 except IOError, err:
422 except IOError, err:
423 if err.errno != errno.ENOENT:
423 if err.errno != errno.ENOENT:
424 raise
424 raise
425 guards = []
425 guards = []
426 for i, guard in enumerate(guards):
426 for i, guard in enumerate(guards):
427 bad = self.check_guard(guard)
427 bad = self.check_guard(guard)
428 if bad:
428 if bad:
429 self.ui.warn('%s:%d: %s\n' %
429 self.ui.warn('%s:%d: %s\n' %
430 (self.join(self.guards_path), i + 1, bad))
430 (self.join(self.guards_path), i + 1, bad))
431 else:
431 else:
432 self.active_guards.append(guard)
432 self.active_guards.append(guard)
433 return self.active_guards
433 return self.active_guards
434
434
435 def set_guards(self, idx, guards):
435 def set_guards(self, idx, guards):
436 for g in guards:
436 for g in guards:
437 if len(g) < 2:
437 if len(g) < 2:
438 raise util.Abort(_('guard %r too short') % g)
438 raise util.Abort(_('guard %r too short') % g)
439 if g[0] not in '-+':
439 if g[0] not in '-+':
440 raise util.Abort(_('guard %r starts with invalid char') % g)
440 raise util.Abort(_('guard %r starts with invalid char') % g)
441 bad = self.check_guard(g[1:])
441 bad = self.check_guard(g[1:])
442 if bad:
442 if bad:
443 raise util.Abort(bad)
443 raise util.Abort(bad)
444 drop = self.guard_re.sub('', self.full_series[idx])
444 drop = self.guard_re.sub('', self.full_series[idx])
445 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
445 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
446 self.parse_series()
446 self.parse_series()
447 self.series_dirty = True
447 self.series_dirty = True
448
448
449 def pushable(self, idx):
449 def pushable(self, idx):
450 if isinstance(idx, str):
450 if isinstance(idx, str):
451 idx = self.series.index(idx)
451 idx = self.series.index(idx)
452 patchguards = self.series_guards[idx]
452 patchguards = self.series_guards[idx]
453 if not patchguards:
453 if not patchguards:
454 return True, None
454 return True, None
455 guards = self.active()
455 guards = self.active()
456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
457 if exactneg:
457 if exactneg:
458 return False, repr(exactneg[0])
458 return False, repr(exactneg[0])
459 pos = [g for g in patchguards if g[0] == '+']
459 pos = [g for g in patchguards if g[0] == '+']
460 exactpos = [g for g in pos if g[1:] in guards]
460 exactpos = [g for g in pos if g[1:] in guards]
461 if pos:
461 if pos:
462 if exactpos:
462 if exactpos:
463 return True, repr(exactpos[0])
463 return True, repr(exactpos[0])
464 return False, ' '.join(map(repr, pos))
464 return False, ' '.join(map(repr, pos))
465 return True, ''
465 return True, ''
466
466
467 def explain_pushable(self, idx, all_patches=False):
467 def explain_pushable(self, idx, all_patches=False):
468 write = all_patches and self.ui.write or self.ui.warn
468 write = all_patches and self.ui.write or self.ui.warn
469 if all_patches or self.ui.verbose:
469 if all_patches or self.ui.verbose:
470 if isinstance(idx, str):
470 if isinstance(idx, str):
471 idx = self.series.index(idx)
471 idx = self.series.index(idx)
472 pushable, why = self.pushable(idx)
472 pushable, why = self.pushable(idx)
473 if all_patches and pushable:
473 if all_patches and pushable:
474 if why is None:
474 if why is None:
475 write(_('allowing %s - no guards in effect\n') %
475 write(_('allowing %s - no guards in effect\n') %
476 self.series[idx])
476 self.series[idx])
477 else:
477 else:
478 if not why:
478 if not why:
479 write(_('allowing %s - no matching negative guards\n') %
479 write(_('allowing %s - no matching negative guards\n') %
480 self.series[idx])
480 self.series[idx])
481 else:
481 else:
482 write(_('allowing %s - guarded by %s\n') %
482 write(_('allowing %s - guarded by %s\n') %
483 (self.series[idx], why))
483 (self.series[idx], why))
484 if not pushable:
484 if not pushable:
485 if why:
485 if why:
486 write(_('skipping %s - guarded by %s\n') %
486 write(_('skipping %s - guarded by %s\n') %
487 (self.series[idx], why))
487 (self.series[idx], why))
488 else:
488 else:
489 write(_('skipping %s - no matching guards\n') %
489 write(_('skipping %s - no matching guards\n') %
490 self.series[idx])
490 self.series[idx])
491
491
492 def save_dirty(self):
492 def save_dirty(self):
493 def write_list(items, path):
493 def write_list(items, path):
494 fp = self.opener(path, 'w')
494 fp = self.opener(path, 'w')
495 for i in items:
495 for i in items:
496 fp.write("%s\n" % i)
496 fp.write("%s\n" % i)
497 fp.close()
497 fp.close()
498 if self.applied_dirty:
498 if self.applied_dirty:
499 write_list(map(str, self.applied), self.status_path)
499 write_list(map(str, self.applied), self.status_path)
500 if self.series_dirty:
500 if self.series_dirty:
501 write_list(self.full_series, self.series_path)
501 write_list(self.full_series, self.series_path)
502 if self.guards_dirty:
502 if self.guards_dirty:
503 write_list(self.active_guards, self.guards_path)
503 write_list(self.active_guards, self.guards_path)
504 if self.added:
504 if self.added:
505 qrepo = self.qrepo()
505 qrepo = self.qrepo()
506 if qrepo:
506 if qrepo:
507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
508 self.added = []
508 self.added = []
509
509
510 def removeundo(self, repo):
510 def removeundo(self, repo):
511 undo = repo.sjoin('undo')
511 undo = repo.sjoin('undo')
512 if not os.path.exists(undo):
512 if not os.path.exists(undo):
513 return
513 return
514 try:
514 try:
515 os.unlink(undo)
515 os.unlink(undo)
516 except OSError, inst:
516 except OSError, inst:
517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
518
518
519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
520 fp=None, changes=None, opts={}):
520 fp=None, changes=None, opts={}):
521 stat = opts.get('stat')
521 stat = opts.get('stat')
522 m = scmutil.match(repo, files, opts)
522 m = scmutil.match(repo, files, opts)
523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
524 changes, stat, fp)
524 changes, stat, fp)
525
525
526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
527 # first try just applying the patch
527 # first try just applying the patch
528 (err, n) = self.apply(repo, [patch], update_status=False,
528 (err, n) = self.apply(repo, [patch], update_status=False,
529 strict=True, merge=rev)
529 strict=True, merge=rev)
530
530
531 if err == 0:
531 if err == 0:
532 return (err, n)
532 return (err, n)
533
533
534 if n is None:
534 if n is None:
535 raise util.Abort(_("apply failed for patch %s") % patch)
535 raise util.Abort(_("apply failed for patch %s") % patch)
536
536
537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
538
538
539 # apply failed, strip away that rev and merge.
539 # apply failed, strip away that rev and merge.
540 hg.clean(repo, head)
540 hg.clean(repo, head)
541 self.strip(repo, [n], update=False, backup='strip')
541 self.strip(repo, [n], update=False, backup='strip')
542
542
543 ctx = repo[rev]
543 ctx = repo[rev]
544 ret = hg.merge(repo, rev)
544 ret = hg.merge(repo, rev)
545 if ret:
545 if ret:
546 raise util.Abort(_("update returned %d") % ret)
546 raise util.Abort(_("update returned %d") % ret)
547 n = repo.commit(ctx.description(), ctx.user(), force=True)
547 n = repo.commit(ctx.description(), ctx.user(), force=True)
548 if n is None:
548 if n is None:
549 raise util.Abort(_("repo commit failed"))
549 raise util.Abort(_("repo commit failed"))
550 try:
550 try:
551 ph = patchheader(mergeq.join(patch), self.plainmode)
551 ph = patchheader(mergeq.join(patch), self.plainmode)
552 except:
552 except:
553 raise util.Abort(_("unable to read %s") % patch)
553 raise util.Abort(_("unable to read %s") % patch)
554
554
555 diffopts = self.patchopts(diffopts, patch)
555 diffopts = self.patchopts(diffopts, patch)
556 patchf = self.opener(patch, "w")
556 patchf = self.opener(patch, "w")
557 comments = str(ph)
557 comments = str(ph)
558 if comments:
558 if comments:
559 patchf.write(comments)
559 patchf.write(comments)
560 self.printdiff(repo, diffopts, head, n, fp=patchf)
560 self.printdiff(repo, diffopts, head, n, fp=patchf)
561 patchf.close()
561 patchf.close()
562 self.removeundo(repo)
562 self.removeundo(repo)
563 return (0, n)
563 return (0, n)
564
564
565 def qparents(self, repo, rev=None):
565 def qparents(self, repo, rev=None):
566 if rev is None:
566 if rev is None:
567 (p1, p2) = repo.dirstate.parents()
567 (p1, p2) = repo.dirstate.parents()
568 if p2 == nullid:
568 if p2 == nullid:
569 return p1
569 return p1
570 if not self.applied:
570 if not self.applied:
571 return None
571 return None
572 return self.applied[-1].node
572 return self.applied[-1].node
573 p1, p2 = repo.changelog.parents(rev)
573 p1, p2 = repo.changelog.parents(rev)
574 if p2 != nullid and p2 in [x.node for x in self.applied]:
574 if p2 != nullid and p2 in [x.node for x in self.applied]:
575 return p2
575 return p2
576 return p1
576 return p1
577
577
578 def mergepatch(self, repo, mergeq, series, diffopts):
578 def mergepatch(self, repo, mergeq, series, diffopts):
579 if not self.applied:
579 if not self.applied:
580 # each of the patches merged in will have two parents. This
580 # each of the patches merged in will have two parents. This
581 # can confuse the qrefresh, qdiff, and strip code because it
581 # can confuse the qrefresh, qdiff, and strip code because it
582 # needs to know which parent is actually in the patch queue.
582 # needs to know which parent is actually in the patch queue.
583 # so, we insert a merge marker with only one parent. This way
583 # so, we insert a merge marker with only one parent. This way
584 # the first patch in the queue is never a merge patch
584 # the first patch in the queue is never a merge patch
585 #
585 #
586 pname = ".hg.patches.merge.marker"
586 pname = ".hg.patches.merge.marker"
587 n = repo.commit('[mq]: merge marker', force=True)
587 n = repo.commit('[mq]: merge marker', force=True)
588 self.removeundo(repo)
588 self.removeundo(repo)
589 self.applied.append(statusentry(n, pname))
589 self.applied.append(statusentry(n, pname))
590 self.applied_dirty = 1
590 self.applied_dirty = 1
591
591
592 head = self.qparents(repo)
592 head = self.qparents(repo)
593
593
594 for patch in series:
594 for patch in series:
595 patch = mergeq.lookup(patch, strict=True)
595 patch = mergeq.lookup(patch, strict=True)
596 if not patch:
596 if not patch:
597 self.ui.warn(_("patch %s does not exist\n") % patch)
597 self.ui.warn(_("patch %s does not exist\n") % patch)
598 return (1, None)
598 return (1, None)
599 pushable, reason = self.pushable(patch)
599 pushable, reason = self.pushable(patch)
600 if not pushable:
600 if not pushable:
601 self.explain_pushable(patch, all_patches=True)
601 self.explain_pushable(patch, all_patches=True)
602 continue
602 continue
603 info = mergeq.isapplied(patch)
603 info = mergeq.isapplied(patch)
604 if not info:
604 if not info:
605 self.ui.warn(_("patch %s is not applied\n") % patch)
605 self.ui.warn(_("patch %s is not applied\n") % patch)
606 return (1, None)
606 return (1, None)
607 rev = info[1]
607 rev = info[1]
608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
609 if head:
609 if head:
610 self.applied.append(statusentry(head, patch))
610 self.applied.append(statusentry(head, patch))
611 self.applied_dirty = 1
611 self.applied_dirty = 1
612 if err:
612 if err:
613 return (err, head)
613 return (err, head)
614 self.save_dirty()
614 self.save_dirty()
615 return (0, head)
615 return (0, head)
616
616
617 def patch(self, repo, patchfile):
617 def patch(self, repo, patchfile):
618 '''Apply patchfile to the working directory.
618 '''Apply patchfile to the working directory.
619 patchfile: name of patch file'''
619 patchfile: name of patch file'''
620 files = {}
620 files = set()
621 try:
621 try:
622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
623 files=files, eolmode=None)
623 files=files, eolmode=None)
624 return (True, list(files), fuzz)
624 return (True, list(files), fuzz)
625 except Exception, inst:
625 except Exception, inst:
626 self.ui.note(str(inst) + '\n')
626 self.ui.note(str(inst) + '\n')
627 if not self.ui.verbose:
627 if not self.ui.verbose:
628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
629 return (False, list(files), False)
629 return (False, list(files), False)
630
630
631 def apply(self, repo, series, list=False, update_status=True,
631 def apply(self, repo, series, list=False, update_status=True,
632 strict=False, patchdir=None, merge=None, all_files=None):
632 strict=False, patchdir=None, merge=None, all_files=None):
633 wlock = lock = tr = None
633 wlock = lock = tr = None
634 try:
634 try:
635 wlock = repo.wlock()
635 wlock = repo.wlock()
636 lock = repo.lock()
636 lock = repo.lock()
637 tr = repo.transaction("qpush")
637 tr = repo.transaction("qpush")
638 try:
638 try:
639 ret = self._apply(repo, series, list, update_status,
639 ret = self._apply(repo, series, list, update_status,
640 strict, patchdir, merge, all_files=all_files)
640 strict, patchdir, merge, all_files=all_files)
641 tr.close()
641 tr.close()
642 self.save_dirty()
642 self.save_dirty()
643 return ret
643 return ret
644 except:
644 except:
645 try:
645 try:
646 tr.abort()
646 tr.abort()
647 finally:
647 finally:
648 repo.invalidate()
648 repo.invalidate()
649 repo.dirstate.invalidate()
649 repo.dirstate.invalidate()
650 raise
650 raise
651 finally:
651 finally:
652 release(tr, lock, wlock)
652 release(tr, lock, wlock)
653 self.removeundo(repo)
653 self.removeundo(repo)
654
654
655 def _apply(self, repo, series, list=False, update_status=True,
655 def _apply(self, repo, series, list=False, update_status=True,
656 strict=False, patchdir=None, merge=None, all_files=None):
656 strict=False, patchdir=None, merge=None, all_files=None):
657 '''returns (error, hash)
657 '''returns (error, hash)
658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
659 # TODO unify with commands.py
659 # TODO unify with commands.py
660 if not patchdir:
660 if not patchdir:
661 patchdir = self.path
661 patchdir = self.path
662 err = 0
662 err = 0
663 n = None
663 n = None
664 for patchname in series:
664 for patchname in series:
665 pushable, reason = self.pushable(patchname)
665 pushable, reason = self.pushable(patchname)
666 if not pushable:
666 if not pushable:
667 self.explain_pushable(patchname, all_patches=True)
667 self.explain_pushable(patchname, all_patches=True)
668 continue
668 continue
669 self.ui.status(_("applying %s\n") % patchname)
669 self.ui.status(_("applying %s\n") % patchname)
670 pf = os.path.join(patchdir, patchname)
670 pf = os.path.join(patchdir, patchname)
671
671
672 try:
672 try:
673 ph = patchheader(self.join(patchname), self.plainmode)
673 ph = patchheader(self.join(patchname), self.plainmode)
674 except IOError:
674 except IOError:
675 self.ui.warn(_("unable to read %s\n") % patchname)
675 self.ui.warn(_("unable to read %s\n") % patchname)
676 err = 1
676 err = 1
677 break
677 break
678
678
679 message = ph.message
679 message = ph.message
680 if not message:
680 if not message:
681 # The commit message should not be translated
681 # The commit message should not be translated
682 message = "imported patch %s\n" % patchname
682 message = "imported patch %s\n" % patchname
683 else:
683 else:
684 if list:
684 if list:
685 # The commit message should not be translated
685 # The commit message should not be translated
686 message.append("\nimported patch %s" % patchname)
686 message.append("\nimported patch %s" % patchname)
687 message = '\n'.join(message)
687 message = '\n'.join(message)
688
688
689 if ph.haspatch:
689 if ph.haspatch:
690 (patcherr, files, fuzz) = self.patch(repo, pf)
690 (patcherr, files, fuzz) = self.patch(repo, pf)
691 if all_files is not None:
691 if all_files is not None:
692 all_files.update(files)
692 all_files.update(files)
693 patcherr = not patcherr
693 patcherr = not patcherr
694 else:
694 else:
695 self.ui.warn(_("patch %s is empty\n") % patchname)
695 self.ui.warn(_("patch %s is empty\n") % patchname)
696 patcherr, files, fuzz = 0, [], 0
696 patcherr, files, fuzz = 0, [], 0
697
697
698 if merge and files:
698 if merge and files:
699 # Mark as removed/merged and update dirstate parent info
699 # Mark as removed/merged and update dirstate parent info
700 removed = []
700 removed = []
701 merged = []
701 merged = []
702 for f in files:
702 for f in files:
703 if os.path.lexists(repo.wjoin(f)):
703 if os.path.lexists(repo.wjoin(f)):
704 merged.append(f)
704 merged.append(f)
705 else:
705 else:
706 removed.append(f)
706 removed.append(f)
707 for f in removed:
707 for f in removed:
708 repo.dirstate.remove(f)
708 repo.dirstate.remove(f)
709 for f in merged:
709 for f in merged:
710 repo.dirstate.merge(f)
710 repo.dirstate.merge(f)
711 p1, p2 = repo.dirstate.parents()
711 p1, p2 = repo.dirstate.parents()
712 repo.dirstate.setparents(p1, merge)
712 repo.dirstate.setparents(p1, merge)
713
713
714 match = scmutil.matchfiles(repo, files or [])
714 match = scmutil.matchfiles(repo, files or [])
715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
716
716
717 if n is None:
717 if n is None:
718 raise util.Abort(_("repository commit failed"))
718 raise util.Abort(_("repository commit failed"))
719
719
720 if update_status:
720 if update_status:
721 self.applied.append(statusentry(n, patchname))
721 self.applied.append(statusentry(n, patchname))
722
722
723 if patcherr:
723 if patcherr:
724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
725 err = 2
725 err = 2
726 break
726 break
727
727
728 if fuzz and strict:
728 if fuzz and strict:
729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
730 err = 3
730 err = 3
731 break
731 break
732 return (err, n)
732 return (err, n)
733
733
734 def _cleanup(self, patches, numrevs, keep=False):
734 def _cleanup(self, patches, numrevs, keep=False):
735 if not keep:
735 if not keep:
736 r = self.qrepo()
736 r = self.qrepo()
737 if r:
737 if r:
738 r[None].forget(patches)
738 r[None].forget(patches)
739 for p in patches:
739 for p in patches:
740 os.unlink(self.join(p))
740 os.unlink(self.join(p))
741
741
742 if numrevs:
742 if numrevs:
743 qfinished = self.applied[:numrevs]
743 qfinished = self.applied[:numrevs]
744 del self.applied[:numrevs]
744 del self.applied[:numrevs]
745 self.applied_dirty = 1
745 self.applied_dirty = 1
746
746
747 unknown = []
747 unknown = []
748
748
749 for (i, p) in sorted([(self.find_series(p), p) for p in patches],
749 for (i, p) in sorted([(self.find_series(p), p) for p in patches],
750 reverse=True):
750 reverse=True):
751 if i is not None:
751 if i is not None:
752 del self.full_series[i]
752 del self.full_series[i]
753 else:
753 else:
754 unknown.append(p)
754 unknown.append(p)
755
755
756 if unknown:
756 if unknown:
757 if numrevs:
757 if numrevs:
758 rev = dict((entry.name, entry.node) for entry in qfinished)
758 rev = dict((entry.name, entry.node) for entry in qfinished)
759 for p in unknown:
759 for p in unknown:
760 msg = _('revision %s refers to unknown patches: %s\n')
760 msg = _('revision %s refers to unknown patches: %s\n')
761 self.ui.warn(msg % (short(rev[p]), p))
761 self.ui.warn(msg % (short(rev[p]), p))
762 else:
762 else:
763 msg = _('unknown patches: %s\n')
763 msg = _('unknown patches: %s\n')
764 raise util.Abort(''.join(msg % p for p in unknown))
764 raise util.Abort(''.join(msg % p for p in unknown))
765
765
766 self.parse_series()
766 self.parse_series()
767 self.series_dirty = 1
767 self.series_dirty = 1
768
768
769 def _revpatches(self, repo, revs):
769 def _revpatches(self, repo, revs):
770 firstrev = repo[self.applied[0].node].rev()
770 firstrev = repo[self.applied[0].node].rev()
771 patches = []
771 patches = []
772 for i, rev in enumerate(revs):
772 for i, rev in enumerate(revs):
773
773
774 if rev < firstrev:
774 if rev < firstrev:
775 raise util.Abort(_('revision %d is not managed') % rev)
775 raise util.Abort(_('revision %d is not managed') % rev)
776
776
777 ctx = repo[rev]
777 ctx = repo[rev]
778 base = self.applied[i].node
778 base = self.applied[i].node
779 if ctx.node() != base:
779 if ctx.node() != base:
780 msg = _('cannot delete revision %d above applied patches')
780 msg = _('cannot delete revision %d above applied patches')
781 raise util.Abort(msg % rev)
781 raise util.Abort(msg % rev)
782
782
783 patch = self.applied[i].name
783 patch = self.applied[i].name
784 for fmt in ('[mq]: %s', 'imported patch %s'):
784 for fmt in ('[mq]: %s', 'imported patch %s'):
785 if ctx.description() == fmt % patch:
785 if ctx.description() == fmt % patch:
786 msg = _('patch %s finalized without changeset message\n')
786 msg = _('patch %s finalized without changeset message\n')
787 repo.ui.status(msg % patch)
787 repo.ui.status(msg % patch)
788 break
788 break
789
789
790 patches.append(patch)
790 patches.append(patch)
791 return patches
791 return patches
792
792
793 def finish(self, repo, revs):
793 def finish(self, repo, revs):
794 patches = self._revpatches(repo, sorted(revs))
794 patches = self._revpatches(repo, sorted(revs))
795 self._cleanup(patches, len(patches))
795 self._cleanup(patches, len(patches))
796
796
797 def delete(self, repo, patches, opts):
797 def delete(self, repo, patches, opts):
798 if not patches and not opts.get('rev'):
798 if not patches and not opts.get('rev'):
799 raise util.Abort(_('qdelete requires at least one revision or '
799 raise util.Abort(_('qdelete requires at least one revision or '
800 'patch name'))
800 'patch name'))
801
801
802 realpatches = []
802 realpatches = []
803 for patch in patches:
803 for patch in patches:
804 patch = self.lookup(patch, strict=True)
804 patch = self.lookup(patch, strict=True)
805 info = self.isapplied(patch)
805 info = self.isapplied(patch)
806 if info:
806 if info:
807 raise util.Abort(_("cannot delete applied patch %s") % patch)
807 raise util.Abort(_("cannot delete applied patch %s") % patch)
808 if patch not in self.series:
808 if patch not in self.series:
809 raise util.Abort(_("patch %s not in series file") % patch)
809 raise util.Abort(_("patch %s not in series file") % patch)
810 if patch not in realpatches:
810 if patch not in realpatches:
811 realpatches.append(patch)
811 realpatches.append(patch)
812
812
813 numrevs = 0
813 numrevs = 0
814 if opts.get('rev'):
814 if opts.get('rev'):
815 if not self.applied:
815 if not self.applied:
816 raise util.Abort(_('no patches applied'))
816 raise util.Abort(_('no patches applied'))
817 revs = scmutil.revrange(repo, opts.get('rev'))
817 revs = scmutil.revrange(repo, opts.get('rev'))
818 if len(revs) > 1 and revs[0] > revs[1]:
818 if len(revs) > 1 and revs[0] > revs[1]:
819 revs.reverse()
819 revs.reverse()
820 revpatches = self._revpatches(repo, revs)
820 revpatches = self._revpatches(repo, revs)
821 realpatches += revpatches
821 realpatches += revpatches
822 numrevs = len(revpatches)
822 numrevs = len(revpatches)
823
823
824 self._cleanup(realpatches, numrevs, opts.get('keep'))
824 self._cleanup(realpatches, numrevs, opts.get('keep'))
825
825
826 def check_toppatch(self, repo):
826 def check_toppatch(self, repo):
827 if self.applied:
827 if self.applied:
828 top = self.applied[-1].node
828 top = self.applied[-1].node
829 patch = self.applied[-1].name
829 patch = self.applied[-1].name
830 pp = repo.dirstate.parents()
830 pp = repo.dirstate.parents()
831 if top not in pp:
831 if top not in pp:
832 raise util.Abort(_("working directory revision is not qtip"))
832 raise util.Abort(_("working directory revision is not qtip"))
833 return top, patch
833 return top, patch
834 return None, None
834 return None, None
835
835
836 def check_substate(self, repo):
836 def check_substate(self, repo):
837 '''return list of subrepos at a different revision than substate.
837 '''return list of subrepos at a different revision than substate.
838 Abort if any subrepos have uncommitted changes.'''
838 Abort if any subrepos have uncommitted changes.'''
839 inclsubs = []
839 inclsubs = []
840 wctx = repo[None]
840 wctx = repo[None]
841 for s in wctx.substate:
841 for s in wctx.substate:
842 if wctx.sub(s).dirty(True):
842 if wctx.sub(s).dirty(True):
843 raise util.Abort(
843 raise util.Abort(
844 _("uncommitted changes in subrepository %s") % s)
844 _("uncommitted changes in subrepository %s") % s)
845 elif wctx.sub(s).dirty():
845 elif wctx.sub(s).dirty():
846 inclsubs.append(s)
846 inclsubs.append(s)
847 return inclsubs
847 return inclsubs
848
848
849 def localchangesfound(self, refresh=True):
849 def localchangesfound(self, refresh=True):
850 if refresh:
850 if refresh:
851 raise util.Abort(_("local changes found, refresh first"))
851 raise util.Abort(_("local changes found, refresh first"))
852 else:
852 else:
853 raise util.Abort(_("local changes found"))
853 raise util.Abort(_("local changes found"))
854
854
855 def check_localchanges(self, repo, force=False, refresh=True):
855 def check_localchanges(self, repo, force=False, refresh=True):
856 m, a, r, d = repo.status()[:4]
856 m, a, r, d = repo.status()[:4]
857 if (m or a or r or d) and not force:
857 if (m or a or r or d) and not force:
858 self.localchangesfound(refresh)
858 self.localchangesfound(refresh)
859 return m, a, r, d
859 return m, a, r, d
860
860
861 _reserved = ('series', 'status', 'guards', '.', '..')
861 _reserved = ('series', 'status', 'guards', '.', '..')
862 def check_reserved_name(self, name):
862 def check_reserved_name(self, name):
863 if name in self._reserved:
863 if name in self._reserved:
864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
865 % name)
865 % name)
866 for prefix in ('.hg', '.mq'):
866 for prefix in ('.hg', '.mq'):
867 if name.startswith(prefix):
867 if name.startswith(prefix):
868 raise util.Abort(_('patch name cannot begin with "%s"')
868 raise util.Abort(_('patch name cannot begin with "%s"')
869 % prefix)
869 % prefix)
870 for c in ('#', ':'):
870 for c in ('#', ':'):
871 if c in name:
871 if c in name:
872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
873 % c)
873 % c)
874
874
875 def checkpatchname(self, name, force=False):
875 def checkpatchname(self, name, force=False):
876 self.check_reserved_name(name)
876 self.check_reserved_name(name)
877 if not force and os.path.exists(self.join(name)):
877 if not force and os.path.exists(self.join(name)):
878 if os.path.isdir(self.join(name)):
878 if os.path.isdir(self.join(name)):
879 raise util.Abort(_('"%s" already exists as a directory')
879 raise util.Abort(_('"%s" already exists as a directory')
880 % name)
880 % name)
881 else:
881 else:
882 raise util.Abort(_('patch "%s" already exists') % name)
882 raise util.Abort(_('patch "%s" already exists') % name)
883
883
884 def new(self, repo, patchfn, *pats, **opts):
884 def new(self, repo, patchfn, *pats, **opts):
885 """options:
885 """options:
886 msg: a string or a no-argument function returning a string
886 msg: a string or a no-argument function returning a string
887 """
887 """
888 msg = opts.get('msg')
888 msg = opts.get('msg')
889 user = opts.get('user')
889 user = opts.get('user')
890 date = opts.get('date')
890 date = opts.get('date')
891 if date:
891 if date:
892 date = util.parsedate(date)
892 date = util.parsedate(date)
893 diffopts = self.diffopts({'git': opts.get('git')})
893 diffopts = self.diffopts({'git': opts.get('git')})
894 if opts.get('checkname', True):
894 if opts.get('checkname', True):
895 self.checkpatchname(patchfn)
895 self.checkpatchname(patchfn)
896 inclsubs = self.check_substate(repo)
896 inclsubs = self.check_substate(repo)
897 if inclsubs:
897 if inclsubs:
898 inclsubs.append('.hgsubstate')
898 inclsubs.append('.hgsubstate')
899 if opts.get('include') or opts.get('exclude') or pats:
899 if opts.get('include') or opts.get('exclude') or pats:
900 if inclsubs:
900 if inclsubs:
901 pats = list(pats or []) + inclsubs
901 pats = list(pats or []) + inclsubs
902 match = scmutil.match(repo, pats, opts)
902 match = scmutil.match(repo, pats, opts)
903 # detect missing files in pats
903 # detect missing files in pats
904 def badfn(f, msg):
904 def badfn(f, msg):
905 if f != '.hgsubstate': # .hgsubstate is auto-created
905 if f != '.hgsubstate': # .hgsubstate is auto-created
906 raise util.Abort('%s: %s' % (f, msg))
906 raise util.Abort('%s: %s' % (f, msg))
907 match.bad = badfn
907 match.bad = badfn
908 m, a, r, d = repo.status(match=match)[:4]
908 m, a, r, d = repo.status(match=match)[:4]
909 else:
909 else:
910 m, a, r, d = self.check_localchanges(repo, force=True)
910 m, a, r, d = self.check_localchanges(repo, force=True)
911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
912 if len(repo[None].parents()) > 1:
912 if len(repo[None].parents()) > 1:
913 raise util.Abort(_('cannot manage merge changesets'))
913 raise util.Abort(_('cannot manage merge changesets'))
914 commitfiles = m + a + r
914 commitfiles = m + a + r
915 self.check_toppatch(repo)
915 self.check_toppatch(repo)
916 insert = self.full_series_end()
916 insert = self.full_series_end()
917 wlock = repo.wlock()
917 wlock = repo.wlock()
918 try:
918 try:
919 try:
919 try:
920 # if patch file write fails, abort early
920 # if patch file write fails, abort early
921 p = self.opener(patchfn, "w")
921 p = self.opener(patchfn, "w")
922 except IOError, e:
922 except IOError, e:
923 raise util.Abort(_('cannot write patch "%s": %s')
923 raise util.Abort(_('cannot write patch "%s": %s')
924 % (patchfn, e.strerror))
924 % (patchfn, e.strerror))
925 try:
925 try:
926 if self.plainmode:
926 if self.plainmode:
927 if user:
927 if user:
928 p.write("From: " + user + "\n")
928 p.write("From: " + user + "\n")
929 if not date:
929 if not date:
930 p.write("\n")
930 p.write("\n")
931 if date:
931 if date:
932 p.write("Date: %d %d\n\n" % date)
932 p.write("Date: %d %d\n\n" % date)
933 else:
933 else:
934 p.write("# HG changeset patch\n")
934 p.write("# HG changeset patch\n")
935 p.write("# Parent "
935 p.write("# Parent "
936 + hex(repo[None].p1().node()) + "\n")
936 + hex(repo[None].p1().node()) + "\n")
937 if user:
937 if user:
938 p.write("# User " + user + "\n")
938 p.write("# User " + user + "\n")
939 if date:
939 if date:
940 p.write("# Date %s %s\n\n" % date)
940 p.write("# Date %s %s\n\n" % date)
941 if hasattr(msg, '__call__'):
941 if hasattr(msg, '__call__'):
942 msg = msg()
942 msg = msg()
943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
944 n = repo.commit(commitmsg, user, date, match=match, force=True)
944 n = repo.commit(commitmsg, user, date, match=match, force=True)
945 if n is None:
945 if n is None:
946 raise util.Abort(_("repo commit failed"))
946 raise util.Abort(_("repo commit failed"))
947 try:
947 try:
948 self.full_series[insert:insert] = [patchfn]
948 self.full_series[insert:insert] = [patchfn]
949 self.applied.append(statusentry(n, patchfn))
949 self.applied.append(statusentry(n, patchfn))
950 self.parse_series()
950 self.parse_series()
951 self.series_dirty = 1
951 self.series_dirty = 1
952 self.applied_dirty = 1
952 self.applied_dirty = 1
953 if msg:
953 if msg:
954 msg = msg + "\n\n"
954 msg = msg + "\n\n"
955 p.write(msg)
955 p.write(msg)
956 if commitfiles:
956 if commitfiles:
957 parent = self.qparents(repo, n)
957 parent = self.qparents(repo, n)
958 chunks = patchmod.diff(repo, node1=parent, node2=n,
958 chunks = patchmod.diff(repo, node1=parent, node2=n,
959 match=match, opts=diffopts)
959 match=match, opts=diffopts)
960 for chunk in chunks:
960 for chunk in chunks:
961 p.write(chunk)
961 p.write(chunk)
962 p.close()
962 p.close()
963 wlock.release()
963 wlock.release()
964 wlock = None
964 wlock = None
965 r = self.qrepo()
965 r = self.qrepo()
966 if r:
966 if r:
967 r[None].add([patchfn])
967 r[None].add([patchfn])
968 except:
968 except:
969 repo.rollback()
969 repo.rollback()
970 raise
970 raise
971 except Exception:
971 except Exception:
972 patchpath = self.join(patchfn)
972 patchpath = self.join(patchfn)
973 try:
973 try:
974 os.unlink(patchpath)
974 os.unlink(patchpath)
975 except:
975 except:
976 self.ui.warn(_('error unlinking %s\n') % patchpath)
976 self.ui.warn(_('error unlinking %s\n') % patchpath)
977 raise
977 raise
978 self.removeundo(repo)
978 self.removeundo(repo)
979 finally:
979 finally:
980 release(wlock)
980 release(wlock)
981
981
982 def strip(self, repo, revs, update=True, backup="all", force=None):
982 def strip(self, repo, revs, update=True, backup="all", force=None):
983 wlock = lock = None
983 wlock = lock = None
984 try:
984 try:
985 wlock = repo.wlock()
985 wlock = repo.wlock()
986 lock = repo.lock()
986 lock = repo.lock()
987
987
988 if update:
988 if update:
989 self.check_localchanges(repo, force=force, refresh=False)
989 self.check_localchanges(repo, force=force, refresh=False)
990 urev = self.qparents(repo, revs[0])
990 urev = self.qparents(repo, revs[0])
991 hg.clean(repo, urev)
991 hg.clean(repo, urev)
992 repo.dirstate.write()
992 repo.dirstate.write()
993
993
994 self.removeundo(repo)
994 self.removeundo(repo)
995 for rev in revs:
995 for rev in revs:
996 repair.strip(self.ui, repo, rev, backup)
996 repair.strip(self.ui, repo, rev, backup)
997 # strip may have unbundled a set of backed up revisions after
997 # strip may have unbundled a set of backed up revisions after
998 # the actual strip
998 # the actual strip
999 self.removeundo(repo)
999 self.removeundo(repo)
1000 finally:
1000 finally:
1001 release(lock, wlock)
1001 release(lock, wlock)
1002
1002
1003 def isapplied(self, patch):
1003 def isapplied(self, patch):
1004 """returns (index, rev, patch)"""
1004 """returns (index, rev, patch)"""
1005 for i, a in enumerate(self.applied):
1005 for i, a in enumerate(self.applied):
1006 if a.name == patch:
1006 if a.name == patch:
1007 return (i, a.node, a.name)
1007 return (i, a.node, a.name)
1008 return None
1008 return None
1009
1009
1010 # if the exact patch name does not exist, we try a few
1010 # if the exact patch name does not exist, we try a few
1011 # variations. If strict is passed, we try only #1
1011 # variations. If strict is passed, we try only #1
1012 #
1012 #
1013 # 1) a number to indicate an offset in the series file
1013 # 1) a number to indicate an offset in the series file
1014 # 2) a unique substring of the patch name was given
1014 # 2) a unique substring of the patch name was given
1015 # 3) patchname[-+]num to indicate an offset in the series file
1015 # 3) patchname[-+]num to indicate an offset in the series file
1016 def lookup(self, patch, strict=False):
1016 def lookup(self, patch, strict=False):
1017 patch = patch and str(patch)
1017 patch = patch and str(patch)
1018
1018
1019 def partial_name(s):
1019 def partial_name(s):
1020 if s in self.series:
1020 if s in self.series:
1021 return s
1021 return s
1022 matches = [x for x in self.series if s in x]
1022 matches = [x for x in self.series if s in x]
1023 if len(matches) > 1:
1023 if len(matches) > 1:
1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1025 for m in matches:
1025 for m in matches:
1026 self.ui.warn(' %s\n' % m)
1026 self.ui.warn(' %s\n' % m)
1027 return None
1027 return None
1028 if matches:
1028 if matches:
1029 return matches[0]
1029 return matches[0]
1030 if self.series and self.applied:
1030 if self.series and self.applied:
1031 if s == 'qtip':
1031 if s == 'qtip':
1032 return self.series[self.series_end(True)-1]
1032 return self.series[self.series_end(True)-1]
1033 if s == 'qbase':
1033 if s == 'qbase':
1034 return self.series[0]
1034 return self.series[0]
1035 return None
1035 return None
1036
1036
1037 if patch is None:
1037 if patch is None:
1038 return None
1038 return None
1039 if patch in self.series:
1039 if patch in self.series:
1040 return patch
1040 return patch
1041
1041
1042 if not os.path.isfile(self.join(patch)):
1042 if not os.path.isfile(self.join(patch)):
1043 try:
1043 try:
1044 sno = int(patch)
1044 sno = int(patch)
1045 except (ValueError, OverflowError):
1045 except (ValueError, OverflowError):
1046 pass
1046 pass
1047 else:
1047 else:
1048 if -len(self.series) <= sno < len(self.series):
1048 if -len(self.series) <= sno < len(self.series):
1049 return self.series[sno]
1049 return self.series[sno]
1050
1050
1051 if not strict:
1051 if not strict:
1052 res = partial_name(patch)
1052 res = partial_name(patch)
1053 if res:
1053 if res:
1054 return res
1054 return res
1055 minus = patch.rfind('-')
1055 minus = patch.rfind('-')
1056 if minus >= 0:
1056 if minus >= 0:
1057 res = partial_name(patch[:minus])
1057 res = partial_name(patch[:minus])
1058 if res:
1058 if res:
1059 i = self.series.index(res)
1059 i = self.series.index(res)
1060 try:
1060 try:
1061 off = int(patch[minus + 1:] or 1)
1061 off = int(patch[minus + 1:] or 1)
1062 except (ValueError, OverflowError):
1062 except (ValueError, OverflowError):
1063 pass
1063 pass
1064 else:
1064 else:
1065 if i - off >= 0:
1065 if i - off >= 0:
1066 return self.series[i - off]
1066 return self.series[i - off]
1067 plus = patch.rfind('+')
1067 plus = patch.rfind('+')
1068 if plus >= 0:
1068 if plus >= 0:
1069 res = partial_name(patch[:plus])
1069 res = partial_name(patch[:plus])
1070 if res:
1070 if res:
1071 i = self.series.index(res)
1071 i = self.series.index(res)
1072 try:
1072 try:
1073 off = int(patch[plus + 1:] or 1)
1073 off = int(patch[plus + 1:] or 1)
1074 except (ValueError, OverflowError):
1074 except (ValueError, OverflowError):
1075 pass
1075 pass
1076 else:
1076 else:
1077 if i + off < len(self.series):
1077 if i + off < len(self.series):
1078 return self.series[i + off]
1078 return self.series[i + off]
1079 raise util.Abort(_("patch %s not in series") % patch)
1079 raise util.Abort(_("patch %s not in series") % patch)
1080
1080
1081 def push(self, repo, patch=None, force=False, list=False,
1081 def push(self, repo, patch=None, force=False, list=False,
1082 mergeq=None, all=False, move=False, exact=False):
1082 mergeq=None, all=False, move=False, exact=False):
1083 diffopts = self.diffopts()
1083 diffopts = self.diffopts()
1084 wlock = repo.wlock()
1084 wlock = repo.wlock()
1085 try:
1085 try:
1086 heads = []
1086 heads = []
1087 for b, ls in repo.branchmap().iteritems():
1087 for b, ls in repo.branchmap().iteritems():
1088 heads += ls
1088 heads += ls
1089 if not heads:
1089 if not heads:
1090 heads = [nullid]
1090 heads = [nullid]
1091 if repo.dirstate.p1() not in heads and not exact:
1091 if repo.dirstate.p1() not in heads and not exact:
1092 self.ui.status(_("(working directory not at a head)\n"))
1092 self.ui.status(_("(working directory not at a head)\n"))
1093
1093
1094 if not self.series:
1094 if not self.series:
1095 self.ui.warn(_('no patches in series\n'))
1095 self.ui.warn(_('no patches in series\n'))
1096 return 0
1096 return 0
1097
1097
1098 patch = self.lookup(patch)
1098 patch = self.lookup(patch)
1099 # Suppose our series file is: A B C and the current 'top'
1099 # Suppose our series file is: A B C and the current 'top'
1100 # patch is B. qpush C should be performed (moving forward)
1100 # patch is B. qpush C should be performed (moving forward)
1101 # qpush B is a NOP (no change) qpush A is an error (can't
1101 # qpush B is a NOP (no change) qpush A is an error (can't
1102 # go backwards with qpush)
1102 # go backwards with qpush)
1103 if patch:
1103 if patch:
1104 info = self.isapplied(patch)
1104 info = self.isapplied(patch)
1105 if info and info[0] >= len(self.applied) - 1:
1105 if info and info[0] >= len(self.applied) - 1:
1106 self.ui.warn(
1106 self.ui.warn(
1107 _('qpush: %s is already at the top\n') % patch)
1107 _('qpush: %s is already at the top\n') % patch)
1108 return 0
1108 return 0
1109
1109
1110 pushable, reason = self.pushable(patch)
1110 pushable, reason = self.pushable(patch)
1111 if pushable:
1111 if pushable:
1112 if self.series.index(patch) < self.series_end():
1112 if self.series.index(patch) < self.series_end():
1113 raise util.Abort(
1113 raise util.Abort(
1114 _("cannot push to a previous patch: %s") % patch)
1114 _("cannot push to a previous patch: %s") % patch)
1115 else:
1115 else:
1116 if reason:
1116 if reason:
1117 reason = _('guarded by %s') % reason
1117 reason = _('guarded by %s') % reason
1118 else:
1118 else:
1119 reason = _('no matching guards')
1119 reason = _('no matching guards')
1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1121 return 1
1121 return 1
1122 elif all:
1122 elif all:
1123 patch = self.series[-1]
1123 patch = self.series[-1]
1124 if self.isapplied(patch):
1124 if self.isapplied(patch):
1125 self.ui.warn(_('all patches are currently applied\n'))
1125 self.ui.warn(_('all patches are currently applied\n'))
1126 return 0
1126 return 0
1127
1127
1128 # Following the above example, starting at 'top' of B:
1128 # Following the above example, starting at 'top' of B:
1129 # qpush should be performed (pushes C), but a subsequent
1129 # qpush should be performed (pushes C), but a subsequent
1130 # qpush without an argument is an error (nothing to
1130 # qpush without an argument is an error (nothing to
1131 # apply). This allows a loop of "...while hg qpush..." to
1131 # apply). This allows a loop of "...while hg qpush..." to
1132 # work as it detects an error when done
1132 # work as it detects an error when done
1133 start = self.series_end()
1133 start = self.series_end()
1134 if start == len(self.series):
1134 if start == len(self.series):
1135 self.ui.warn(_('patch series already fully applied\n'))
1135 self.ui.warn(_('patch series already fully applied\n'))
1136 return 1
1136 return 1
1137
1137
1138 if exact:
1138 if exact:
1139 if move:
1139 if move:
1140 raise util.Abort(_("cannot use --exact and --move together"))
1140 raise util.Abort(_("cannot use --exact and --move together"))
1141 if self.applied:
1141 if self.applied:
1142 raise util.Abort(_("cannot push --exact with applied patches"))
1142 raise util.Abort(_("cannot push --exact with applied patches"))
1143 root = self.series[start]
1143 root = self.series[start]
1144 target = patchheader(self.join(root), self.plainmode).parent
1144 target = patchheader(self.join(root), self.plainmode).parent
1145 if not target:
1145 if not target:
1146 raise util.Abort(_("%s does not have a parent recorded" % root))
1146 raise util.Abort(_("%s does not have a parent recorded" % root))
1147 if not repo[target] == repo['.']:
1147 if not repo[target] == repo['.']:
1148 hg.update(repo, target)
1148 hg.update(repo, target)
1149
1149
1150 if move:
1150 if move:
1151 if not patch:
1151 if not patch:
1152 raise util.Abort(_("please specify the patch to move"))
1152 raise util.Abort(_("please specify the patch to move"))
1153 for i, rpn in enumerate(self.full_series[start:]):
1153 for i, rpn in enumerate(self.full_series[start:]):
1154 # strip markers for patch guards
1154 # strip markers for patch guards
1155 if self.guard_re.split(rpn, 1)[0] == patch:
1155 if self.guard_re.split(rpn, 1)[0] == patch:
1156 break
1156 break
1157 index = start + i
1157 index = start + i
1158 assert index < len(self.full_series)
1158 assert index < len(self.full_series)
1159 fullpatch = self.full_series[index]
1159 fullpatch = self.full_series[index]
1160 del self.full_series[index]
1160 del self.full_series[index]
1161 self.full_series.insert(start, fullpatch)
1161 self.full_series.insert(start, fullpatch)
1162 self.parse_series()
1162 self.parse_series()
1163 self.series_dirty = 1
1163 self.series_dirty = 1
1164
1164
1165 self.applied_dirty = 1
1165 self.applied_dirty = 1
1166 if start > 0:
1166 if start > 0:
1167 self.check_toppatch(repo)
1167 self.check_toppatch(repo)
1168 if not patch:
1168 if not patch:
1169 patch = self.series[start]
1169 patch = self.series[start]
1170 end = start + 1
1170 end = start + 1
1171 else:
1171 else:
1172 end = self.series.index(patch, start) + 1
1172 end = self.series.index(patch, start) + 1
1173
1173
1174 s = self.series[start:end]
1174 s = self.series[start:end]
1175
1175
1176 if not force:
1176 if not force:
1177 mm, aa, rr, dd = repo.status()[:4]
1177 mm, aa, rr, dd = repo.status()[:4]
1178 wcfiles = set(mm + aa + rr + dd)
1178 wcfiles = set(mm + aa + rr + dd)
1179 if wcfiles:
1179 if wcfiles:
1180 for patchname in s:
1180 for patchname in s:
1181 pf = os.path.join(self.path, patchname)
1181 pf = os.path.join(self.path, patchname)
1182 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1182 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1183 if wcfiles.intersection(patchfiles):
1183 if wcfiles.intersection(patchfiles):
1184 self.localchangesfound(self.applied)
1184 self.localchangesfound(self.applied)
1185 elif mergeq:
1185 elif mergeq:
1186 self.check_localchanges(refresh=self.applied)
1186 self.check_localchanges(refresh=self.applied)
1187
1187
1188 all_files = set()
1188 all_files = set()
1189 try:
1189 try:
1190 if mergeq:
1190 if mergeq:
1191 ret = self.mergepatch(repo, mergeq, s, diffopts)
1191 ret = self.mergepatch(repo, mergeq, s, diffopts)
1192 else:
1192 else:
1193 ret = self.apply(repo, s, list, all_files=all_files)
1193 ret = self.apply(repo, s, list, all_files=all_files)
1194 except:
1194 except:
1195 self.ui.warn(_('cleaning up working directory...'))
1195 self.ui.warn(_('cleaning up working directory...'))
1196 node = repo.dirstate.p1()
1196 node = repo.dirstate.p1()
1197 hg.revert(repo, node, None)
1197 hg.revert(repo, node, None)
1198 # only remove unknown files that we know we touched or
1198 # only remove unknown files that we know we touched or
1199 # created while patching
1199 # created while patching
1200 for f in all_files:
1200 for f in all_files:
1201 if f not in repo.dirstate:
1201 if f not in repo.dirstate:
1202 try:
1202 try:
1203 util.unlinkpath(repo.wjoin(f))
1203 util.unlinkpath(repo.wjoin(f))
1204 except OSError, inst:
1204 except OSError, inst:
1205 if inst.errno != errno.ENOENT:
1205 if inst.errno != errno.ENOENT:
1206 raise
1206 raise
1207 self.ui.warn(_('done\n'))
1207 self.ui.warn(_('done\n'))
1208 raise
1208 raise
1209
1209
1210 if not self.applied:
1210 if not self.applied:
1211 return ret[0]
1211 return ret[0]
1212 top = self.applied[-1].name
1212 top = self.applied[-1].name
1213 if ret[0] and ret[0] > 1:
1213 if ret[0] and ret[0] > 1:
1214 msg = _("errors during apply, please fix and refresh %s\n")
1214 msg = _("errors during apply, please fix and refresh %s\n")
1215 self.ui.write(msg % top)
1215 self.ui.write(msg % top)
1216 else:
1216 else:
1217 self.ui.write(_("now at: %s\n") % top)
1217 self.ui.write(_("now at: %s\n") % top)
1218 return ret[0]
1218 return ret[0]
1219
1219
1220 finally:
1220 finally:
1221 wlock.release()
1221 wlock.release()
1222
1222
1223 def pop(self, repo, patch=None, force=False, update=True, all=False):
1223 def pop(self, repo, patch=None, force=False, update=True, all=False):
1224 wlock = repo.wlock()
1224 wlock = repo.wlock()
1225 try:
1225 try:
1226 if patch:
1226 if patch:
1227 # index, rev, patch
1227 # index, rev, patch
1228 info = self.isapplied(patch)
1228 info = self.isapplied(patch)
1229 if not info:
1229 if not info:
1230 patch = self.lookup(patch)
1230 patch = self.lookup(patch)
1231 info = self.isapplied(patch)
1231 info = self.isapplied(patch)
1232 if not info:
1232 if not info:
1233 raise util.Abort(_("patch %s is not applied") % patch)
1233 raise util.Abort(_("patch %s is not applied") % patch)
1234
1234
1235 if not self.applied:
1235 if not self.applied:
1236 # Allow qpop -a to work repeatedly,
1236 # Allow qpop -a to work repeatedly,
1237 # but not qpop without an argument
1237 # but not qpop without an argument
1238 self.ui.warn(_("no patches applied\n"))
1238 self.ui.warn(_("no patches applied\n"))
1239 return not all
1239 return not all
1240
1240
1241 if all:
1241 if all:
1242 start = 0
1242 start = 0
1243 elif patch:
1243 elif patch:
1244 start = info[0] + 1
1244 start = info[0] + 1
1245 else:
1245 else:
1246 start = len(self.applied) - 1
1246 start = len(self.applied) - 1
1247
1247
1248 if start >= len(self.applied):
1248 if start >= len(self.applied):
1249 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1249 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1250 return
1250 return
1251
1251
1252 if not update:
1252 if not update:
1253 parents = repo.dirstate.parents()
1253 parents = repo.dirstate.parents()
1254 rr = [x.node for x in self.applied]
1254 rr = [x.node for x in self.applied]
1255 for p in parents:
1255 for p in parents:
1256 if p in rr:
1256 if p in rr:
1257 self.ui.warn(_("qpop: forcing dirstate update\n"))
1257 self.ui.warn(_("qpop: forcing dirstate update\n"))
1258 update = True
1258 update = True
1259 else:
1259 else:
1260 parents = [p.node() for p in repo[None].parents()]
1260 parents = [p.node() for p in repo[None].parents()]
1261 needupdate = False
1261 needupdate = False
1262 for entry in self.applied[start:]:
1262 for entry in self.applied[start:]:
1263 if entry.node in parents:
1263 if entry.node in parents:
1264 needupdate = True
1264 needupdate = True
1265 break
1265 break
1266 update = needupdate
1266 update = needupdate
1267
1267
1268 self.applied_dirty = 1
1268 self.applied_dirty = 1
1269 end = len(self.applied)
1269 end = len(self.applied)
1270 rev = self.applied[start].node
1270 rev = self.applied[start].node
1271 if update:
1271 if update:
1272 top = self.check_toppatch(repo)[0]
1272 top = self.check_toppatch(repo)[0]
1273
1273
1274 try:
1274 try:
1275 heads = repo.changelog.heads(rev)
1275 heads = repo.changelog.heads(rev)
1276 except error.LookupError:
1276 except error.LookupError:
1277 node = short(rev)
1277 node = short(rev)
1278 raise util.Abort(_('trying to pop unknown node %s') % node)
1278 raise util.Abort(_('trying to pop unknown node %s') % node)
1279
1279
1280 if heads != [self.applied[-1].node]:
1280 if heads != [self.applied[-1].node]:
1281 raise util.Abort(_("popping would remove a revision not "
1281 raise util.Abort(_("popping would remove a revision not "
1282 "managed by this patch queue"))
1282 "managed by this patch queue"))
1283
1283
1284 # we know there are no local changes, so we can make a simplified
1284 # we know there are no local changes, so we can make a simplified
1285 # form of hg.update.
1285 # form of hg.update.
1286 if update:
1286 if update:
1287 qp = self.qparents(repo, rev)
1287 qp = self.qparents(repo, rev)
1288 ctx = repo[qp]
1288 ctx = repo[qp]
1289 m, a, r, d = repo.status(qp, top)[:4]
1289 m, a, r, d = repo.status(qp, top)[:4]
1290 parentfiles = set(m + a + r + d)
1290 parentfiles = set(m + a + r + d)
1291 if not force and parentfiles:
1291 if not force and parentfiles:
1292 mm, aa, rr, dd = repo.status()[:4]
1292 mm, aa, rr, dd = repo.status()[:4]
1293 wcfiles = set(mm + aa + rr + dd)
1293 wcfiles = set(mm + aa + rr + dd)
1294 if wcfiles.intersection(parentfiles):
1294 if wcfiles.intersection(parentfiles):
1295 self.localchangesfound()
1295 self.localchangesfound()
1296 if d:
1296 if d:
1297 raise util.Abort(_("deletions found between repo revs"))
1297 raise util.Abort(_("deletions found between repo revs"))
1298 for f in a:
1298 for f in a:
1299 try:
1299 try:
1300 util.unlinkpath(repo.wjoin(f))
1300 util.unlinkpath(repo.wjoin(f))
1301 except OSError, e:
1301 except OSError, e:
1302 if e.errno != errno.ENOENT:
1302 if e.errno != errno.ENOENT:
1303 raise
1303 raise
1304 repo.dirstate.drop(f)
1304 repo.dirstate.drop(f)
1305 for f in m + r:
1305 for f in m + r:
1306 fctx = ctx[f]
1306 fctx = ctx[f]
1307 repo.wwrite(f, fctx.data(), fctx.flags())
1307 repo.wwrite(f, fctx.data(), fctx.flags())
1308 repo.dirstate.normal(f)
1308 repo.dirstate.normal(f)
1309 repo.dirstate.setparents(qp, nullid)
1309 repo.dirstate.setparents(qp, nullid)
1310 for patch in reversed(self.applied[start:end]):
1310 for patch in reversed(self.applied[start:end]):
1311 self.ui.status(_("popping %s\n") % patch.name)
1311 self.ui.status(_("popping %s\n") % patch.name)
1312 del self.applied[start:end]
1312 del self.applied[start:end]
1313 self.strip(repo, [rev], update=False, backup='strip')
1313 self.strip(repo, [rev], update=False, backup='strip')
1314 if self.applied:
1314 if self.applied:
1315 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1315 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1316 else:
1316 else:
1317 self.ui.write(_("patch queue now empty\n"))
1317 self.ui.write(_("patch queue now empty\n"))
1318 finally:
1318 finally:
1319 wlock.release()
1319 wlock.release()
1320
1320
1321 def diff(self, repo, pats, opts):
1321 def diff(self, repo, pats, opts):
1322 top, patch = self.check_toppatch(repo)
1322 top, patch = self.check_toppatch(repo)
1323 if not top:
1323 if not top:
1324 self.ui.write(_("no patches applied\n"))
1324 self.ui.write(_("no patches applied\n"))
1325 return
1325 return
1326 qp = self.qparents(repo, top)
1326 qp = self.qparents(repo, top)
1327 if opts.get('reverse'):
1327 if opts.get('reverse'):
1328 node1, node2 = None, qp
1328 node1, node2 = None, qp
1329 else:
1329 else:
1330 node1, node2 = qp, None
1330 node1, node2 = qp, None
1331 diffopts = self.diffopts(opts, patch)
1331 diffopts = self.diffopts(opts, patch)
1332 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1332 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1333
1333
1334 def refresh(self, repo, pats=None, **opts):
1334 def refresh(self, repo, pats=None, **opts):
1335 if not self.applied:
1335 if not self.applied:
1336 self.ui.write(_("no patches applied\n"))
1336 self.ui.write(_("no patches applied\n"))
1337 return 1
1337 return 1
1338 msg = opts.get('msg', '').rstrip()
1338 msg = opts.get('msg', '').rstrip()
1339 newuser = opts.get('user')
1339 newuser = opts.get('user')
1340 newdate = opts.get('date')
1340 newdate = opts.get('date')
1341 if newdate:
1341 if newdate:
1342 newdate = '%d %d' % util.parsedate(newdate)
1342 newdate = '%d %d' % util.parsedate(newdate)
1343 wlock = repo.wlock()
1343 wlock = repo.wlock()
1344
1344
1345 try:
1345 try:
1346 self.check_toppatch(repo)
1346 self.check_toppatch(repo)
1347 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1347 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1348 if repo.changelog.heads(top) != [top]:
1348 if repo.changelog.heads(top) != [top]:
1349 raise util.Abort(_("cannot refresh a revision with children"))
1349 raise util.Abort(_("cannot refresh a revision with children"))
1350
1350
1351 inclsubs = self.check_substate(repo)
1351 inclsubs = self.check_substate(repo)
1352
1352
1353 cparents = repo.changelog.parents(top)
1353 cparents = repo.changelog.parents(top)
1354 patchparent = self.qparents(repo, top)
1354 patchparent = self.qparents(repo, top)
1355 ph = patchheader(self.join(patchfn), self.plainmode)
1355 ph = patchheader(self.join(patchfn), self.plainmode)
1356 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1356 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1357 if msg:
1357 if msg:
1358 ph.setmessage(msg)
1358 ph.setmessage(msg)
1359 if newuser:
1359 if newuser:
1360 ph.setuser(newuser)
1360 ph.setuser(newuser)
1361 if newdate:
1361 if newdate:
1362 ph.setdate(newdate)
1362 ph.setdate(newdate)
1363 ph.setparent(hex(patchparent))
1363 ph.setparent(hex(patchparent))
1364
1364
1365 # only commit new patch when write is complete
1365 # only commit new patch when write is complete
1366 patchf = self.opener(patchfn, 'w', atomictemp=True)
1366 patchf = self.opener(patchfn, 'w', atomictemp=True)
1367
1367
1368 comments = str(ph)
1368 comments = str(ph)
1369 if comments:
1369 if comments:
1370 patchf.write(comments)
1370 patchf.write(comments)
1371
1371
1372 # update the dirstate in place, strip off the qtip commit
1372 # update the dirstate in place, strip off the qtip commit
1373 # and then commit.
1373 # and then commit.
1374 #
1374 #
1375 # this should really read:
1375 # this should really read:
1376 # mm, dd, aa = repo.status(top, patchparent)[:3]
1376 # mm, dd, aa = repo.status(top, patchparent)[:3]
1377 # but we do it backwards to take advantage of manifest/chlog
1377 # but we do it backwards to take advantage of manifest/chlog
1378 # caching against the next repo.status call
1378 # caching against the next repo.status call
1379 mm, aa, dd = repo.status(patchparent, top)[:3]
1379 mm, aa, dd = repo.status(patchparent, top)[:3]
1380 changes = repo.changelog.read(top)
1380 changes = repo.changelog.read(top)
1381 man = repo.manifest.read(changes[0])
1381 man = repo.manifest.read(changes[0])
1382 aaa = aa[:]
1382 aaa = aa[:]
1383 matchfn = scmutil.match(repo, pats, opts)
1383 matchfn = scmutil.match(repo, pats, opts)
1384 # in short mode, we only diff the files included in the
1384 # in short mode, we only diff the files included in the
1385 # patch already plus specified files
1385 # patch already plus specified files
1386 if opts.get('short'):
1386 if opts.get('short'):
1387 # if amending a patch, we start with existing
1387 # if amending a patch, we start with existing
1388 # files plus specified files - unfiltered
1388 # files plus specified files - unfiltered
1389 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1389 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1390 # filter with inc/exl options
1390 # filter with inc/exl options
1391 matchfn = scmutil.match(repo, opts=opts)
1391 matchfn = scmutil.match(repo, opts=opts)
1392 else:
1392 else:
1393 match = scmutil.matchall(repo)
1393 match = scmutil.matchall(repo)
1394 m, a, r, d = repo.status(match=match)[:4]
1394 m, a, r, d = repo.status(match=match)[:4]
1395 mm = set(mm)
1395 mm = set(mm)
1396 aa = set(aa)
1396 aa = set(aa)
1397 dd = set(dd)
1397 dd = set(dd)
1398
1398
1399 # we might end up with files that were added between
1399 # we might end up with files that were added between
1400 # qtip and the dirstate parent, but then changed in the
1400 # qtip and the dirstate parent, but then changed in the
1401 # local dirstate. in this case, we want them to only
1401 # local dirstate. in this case, we want them to only
1402 # show up in the added section
1402 # show up in the added section
1403 for x in m:
1403 for x in m:
1404 if x not in aa:
1404 if x not in aa:
1405 mm.add(x)
1405 mm.add(x)
1406 # we might end up with files added by the local dirstate that
1406 # we might end up with files added by the local dirstate that
1407 # were deleted by the patch. In this case, they should only
1407 # were deleted by the patch. In this case, they should only
1408 # show up in the changed section.
1408 # show up in the changed section.
1409 for x in a:
1409 for x in a:
1410 if x in dd:
1410 if x in dd:
1411 dd.remove(x)
1411 dd.remove(x)
1412 mm.add(x)
1412 mm.add(x)
1413 else:
1413 else:
1414 aa.add(x)
1414 aa.add(x)
1415 # make sure any files deleted in the local dirstate
1415 # make sure any files deleted in the local dirstate
1416 # are not in the add or change column of the patch
1416 # are not in the add or change column of the patch
1417 forget = []
1417 forget = []
1418 for x in d + r:
1418 for x in d + r:
1419 if x in aa:
1419 if x in aa:
1420 aa.remove(x)
1420 aa.remove(x)
1421 forget.append(x)
1421 forget.append(x)
1422 continue
1422 continue
1423 else:
1423 else:
1424 mm.discard(x)
1424 mm.discard(x)
1425 dd.add(x)
1425 dd.add(x)
1426
1426
1427 m = list(mm)
1427 m = list(mm)
1428 r = list(dd)
1428 r = list(dd)
1429 a = list(aa)
1429 a = list(aa)
1430 c = [filter(matchfn, l) for l in (m, a, r)]
1430 c = [filter(matchfn, l) for l in (m, a, r)]
1431 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1431 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1432 chunks = patchmod.diff(repo, patchparent, match=match,
1432 chunks = patchmod.diff(repo, patchparent, match=match,
1433 changes=c, opts=diffopts)
1433 changes=c, opts=diffopts)
1434 for chunk in chunks:
1434 for chunk in chunks:
1435 patchf.write(chunk)
1435 patchf.write(chunk)
1436
1436
1437 try:
1437 try:
1438 if diffopts.git or diffopts.upgrade:
1438 if diffopts.git or diffopts.upgrade:
1439 copies = {}
1439 copies = {}
1440 for dst in a:
1440 for dst in a:
1441 src = repo.dirstate.copied(dst)
1441 src = repo.dirstate.copied(dst)
1442 # during qfold, the source file for copies may
1442 # during qfold, the source file for copies may
1443 # be removed. Treat this as a simple add.
1443 # be removed. Treat this as a simple add.
1444 if src is not None and src in repo.dirstate:
1444 if src is not None and src in repo.dirstate:
1445 copies.setdefault(src, []).append(dst)
1445 copies.setdefault(src, []).append(dst)
1446 repo.dirstate.add(dst)
1446 repo.dirstate.add(dst)
1447 # remember the copies between patchparent and qtip
1447 # remember the copies between patchparent and qtip
1448 for dst in aaa:
1448 for dst in aaa:
1449 f = repo.file(dst)
1449 f = repo.file(dst)
1450 src = f.renamed(man[dst])
1450 src = f.renamed(man[dst])
1451 if src:
1451 if src:
1452 copies.setdefault(src[0], []).extend(
1452 copies.setdefault(src[0], []).extend(
1453 copies.get(dst, []))
1453 copies.get(dst, []))
1454 if dst in a:
1454 if dst in a:
1455 copies[src[0]].append(dst)
1455 copies[src[0]].append(dst)
1456 # we can't copy a file created by the patch itself
1456 # we can't copy a file created by the patch itself
1457 if dst in copies:
1457 if dst in copies:
1458 del copies[dst]
1458 del copies[dst]
1459 for src, dsts in copies.iteritems():
1459 for src, dsts in copies.iteritems():
1460 for dst in dsts:
1460 for dst in dsts:
1461 repo.dirstate.copy(src, dst)
1461 repo.dirstate.copy(src, dst)
1462 else:
1462 else:
1463 for dst in a:
1463 for dst in a:
1464 repo.dirstate.add(dst)
1464 repo.dirstate.add(dst)
1465 # Drop useless copy information
1465 # Drop useless copy information
1466 for f in list(repo.dirstate.copies()):
1466 for f in list(repo.dirstate.copies()):
1467 repo.dirstate.copy(None, f)
1467 repo.dirstate.copy(None, f)
1468 for f in r:
1468 for f in r:
1469 repo.dirstate.remove(f)
1469 repo.dirstate.remove(f)
1470 # if the patch excludes a modified file, mark that
1470 # if the patch excludes a modified file, mark that
1471 # file with mtime=0 so status can see it.
1471 # file with mtime=0 so status can see it.
1472 mm = []
1472 mm = []
1473 for i in xrange(len(m)-1, -1, -1):
1473 for i in xrange(len(m)-1, -1, -1):
1474 if not matchfn(m[i]):
1474 if not matchfn(m[i]):
1475 mm.append(m[i])
1475 mm.append(m[i])
1476 del m[i]
1476 del m[i]
1477 for f in m:
1477 for f in m:
1478 repo.dirstate.normal(f)
1478 repo.dirstate.normal(f)
1479 for f in mm:
1479 for f in mm:
1480 repo.dirstate.normallookup(f)
1480 repo.dirstate.normallookup(f)
1481 for f in forget:
1481 for f in forget:
1482 repo.dirstate.drop(f)
1482 repo.dirstate.drop(f)
1483
1483
1484 if not msg:
1484 if not msg:
1485 if not ph.message:
1485 if not ph.message:
1486 message = "[mq]: %s\n" % patchfn
1486 message = "[mq]: %s\n" % patchfn
1487 else:
1487 else:
1488 message = "\n".join(ph.message)
1488 message = "\n".join(ph.message)
1489 else:
1489 else:
1490 message = msg
1490 message = msg
1491
1491
1492 user = ph.user or changes[1]
1492 user = ph.user or changes[1]
1493
1493
1494 # assumes strip can roll itself back if interrupted
1494 # assumes strip can roll itself back if interrupted
1495 repo.dirstate.setparents(*cparents)
1495 repo.dirstate.setparents(*cparents)
1496 self.applied.pop()
1496 self.applied.pop()
1497 self.applied_dirty = 1
1497 self.applied_dirty = 1
1498 self.strip(repo, [top], update=False,
1498 self.strip(repo, [top], update=False,
1499 backup='strip')
1499 backup='strip')
1500 except:
1500 except:
1501 repo.dirstate.invalidate()
1501 repo.dirstate.invalidate()
1502 raise
1502 raise
1503
1503
1504 try:
1504 try:
1505 # might be nice to attempt to roll back strip after this
1505 # might be nice to attempt to roll back strip after this
1506 n = repo.commit(message, user, ph.date, match=match,
1506 n = repo.commit(message, user, ph.date, match=match,
1507 force=True)
1507 force=True)
1508 # only write patch after a successful commit
1508 # only write patch after a successful commit
1509 patchf.rename()
1509 patchf.rename()
1510 self.applied.append(statusentry(n, patchfn))
1510 self.applied.append(statusentry(n, patchfn))
1511 except:
1511 except:
1512 ctx = repo[cparents[0]]
1512 ctx = repo[cparents[0]]
1513 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1513 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1514 self.save_dirty()
1514 self.save_dirty()
1515 self.ui.warn(_('refresh interrupted while patch was popped! '
1515 self.ui.warn(_('refresh interrupted while patch was popped! '
1516 '(revert --all, qpush to recover)\n'))
1516 '(revert --all, qpush to recover)\n'))
1517 raise
1517 raise
1518 finally:
1518 finally:
1519 wlock.release()
1519 wlock.release()
1520 self.removeundo(repo)
1520 self.removeundo(repo)
1521
1521
1522 def init(self, repo, create=False):
1522 def init(self, repo, create=False):
1523 if not create and os.path.isdir(self.path):
1523 if not create and os.path.isdir(self.path):
1524 raise util.Abort(_("patch queue directory already exists"))
1524 raise util.Abort(_("patch queue directory already exists"))
1525 try:
1525 try:
1526 os.mkdir(self.path)
1526 os.mkdir(self.path)
1527 except OSError, inst:
1527 except OSError, inst:
1528 if inst.errno != errno.EEXIST or not create:
1528 if inst.errno != errno.EEXIST or not create:
1529 raise
1529 raise
1530 if create:
1530 if create:
1531 return self.qrepo(create=True)
1531 return self.qrepo(create=True)
1532
1532
1533 def unapplied(self, repo, patch=None):
1533 def unapplied(self, repo, patch=None):
1534 if patch and patch not in self.series:
1534 if patch and patch not in self.series:
1535 raise util.Abort(_("patch %s is not in series file") % patch)
1535 raise util.Abort(_("patch %s is not in series file") % patch)
1536 if not patch:
1536 if not patch:
1537 start = self.series_end()
1537 start = self.series_end()
1538 else:
1538 else:
1539 start = self.series.index(patch) + 1
1539 start = self.series.index(patch) + 1
1540 unapplied = []
1540 unapplied = []
1541 for i in xrange(start, len(self.series)):
1541 for i in xrange(start, len(self.series)):
1542 pushable, reason = self.pushable(i)
1542 pushable, reason = self.pushable(i)
1543 if pushable:
1543 if pushable:
1544 unapplied.append((i, self.series[i]))
1544 unapplied.append((i, self.series[i]))
1545 self.explain_pushable(i)
1545 self.explain_pushable(i)
1546 return unapplied
1546 return unapplied
1547
1547
1548 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1548 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1549 summary=False):
1549 summary=False):
1550 def displayname(pfx, patchname, state):
1550 def displayname(pfx, patchname, state):
1551 if pfx:
1551 if pfx:
1552 self.ui.write(pfx)
1552 self.ui.write(pfx)
1553 if summary:
1553 if summary:
1554 ph = patchheader(self.join(patchname), self.plainmode)
1554 ph = patchheader(self.join(patchname), self.plainmode)
1555 msg = ph.message and ph.message[0] or ''
1555 msg = ph.message and ph.message[0] or ''
1556 if self.ui.formatted():
1556 if self.ui.formatted():
1557 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1557 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1558 if width > 0:
1558 if width > 0:
1559 msg = util.ellipsis(msg, width)
1559 msg = util.ellipsis(msg, width)
1560 else:
1560 else:
1561 msg = ''
1561 msg = ''
1562 self.ui.write(patchname, label='qseries.' + state)
1562 self.ui.write(patchname, label='qseries.' + state)
1563 self.ui.write(': ')
1563 self.ui.write(': ')
1564 self.ui.write(msg, label='qseries.message.' + state)
1564 self.ui.write(msg, label='qseries.message.' + state)
1565 else:
1565 else:
1566 self.ui.write(patchname, label='qseries.' + state)
1566 self.ui.write(patchname, label='qseries.' + state)
1567 self.ui.write('\n')
1567 self.ui.write('\n')
1568
1568
1569 applied = set([p.name for p in self.applied])
1569 applied = set([p.name for p in self.applied])
1570 if length is None:
1570 if length is None:
1571 length = len(self.series) - start
1571 length = len(self.series) - start
1572 if not missing:
1572 if not missing:
1573 if self.ui.verbose:
1573 if self.ui.verbose:
1574 idxwidth = len(str(start + length - 1))
1574 idxwidth = len(str(start + length - 1))
1575 for i in xrange(start, start + length):
1575 for i in xrange(start, start + length):
1576 patch = self.series[i]
1576 patch = self.series[i]
1577 if patch in applied:
1577 if patch in applied:
1578 char, state = 'A', 'applied'
1578 char, state = 'A', 'applied'
1579 elif self.pushable(i)[0]:
1579 elif self.pushable(i)[0]:
1580 char, state = 'U', 'unapplied'
1580 char, state = 'U', 'unapplied'
1581 else:
1581 else:
1582 char, state = 'G', 'guarded'
1582 char, state = 'G', 'guarded'
1583 pfx = ''
1583 pfx = ''
1584 if self.ui.verbose:
1584 if self.ui.verbose:
1585 pfx = '%*d %s ' % (idxwidth, i, char)
1585 pfx = '%*d %s ' % (idxwidth, i, char)
1586 elif status and status != char:
1586 elif status and status != char:
1587 continue
1587 continue
1588 displayname(pfx, patch, state)
1588 displayname(pfx, patch, state)
1589 else:
1589 else:
1590 msng_list = []
1590 msng_list = []
1591 for root, dirs, files in os.walk(self.path):
1591 for root, dirs, files in os.walk(self.path):
1592 d = root[len(self.path) + 1:]
1592 d = root[len(self.path) + 1:]
1593 for f in files:
1593 for f in files:
1594 fl = os.path.join(d, f)
1594 fl = os.path.join(d, f)
1595 if (fl not in self.series and
1595 if (fl not in self.series and
1596 fl not in (self.status_path, self.series_path,
1596 fl not in (self.status_path, self.series_path,
1597 self.guards_path)
1597 self.guards_path)
1598 and not fl.startswith('.')):
1598 and not fl.startswith('.')):
1599 msng_list.append(fl)
1599 msng_list.append(fl)
1600 for x in sorted(msng_list):
1600 for x in sorted(msng_list):
1601 pfx = self.ui.verbose and ('D ') or ''
1601 pfx = self.ui.verbose and ('D ') or ''
1602 displayname(pfx, x, 'missing')
1602 displayname(pfx, x, 'missing')
1603
1603
1604 def issaveline(self, l):
1604 def issaveline(self, l):
1605 if l.name == '.hg.patches.save.line':
1605 if l.name == '.hg.patches.save.line':
1606 return True
1606 return True
1607
1607
1608 def qrepo(self, create=False):
1608 def qrepo(self, create=False):
1609 ui = self.ui.copy()
1609 ui = self.ui.copy()
1610 ui.setconfig('paths', 'default', '', overlay=False)
1610 ui.setconfig('paths', 'default', '', overlay=False)
1611 ui.setconfig('paths', 'default-push', '', overlay=False)
1611 ui.setconfig('paths', 'default-push', '', overlay=False)
1612 if create or os.path.isdir(self.join(".hg")):
1612 if create or os.path.isdir(self.join(".hg")):
1613 return hg.repository(ui, path=self.path, create=create)
1613 return hg.repository(ui, path=self.path, create=create)
1614
1614
1615 def restore(self, repo, rev, delete=None, qupdate=None):
1615 def restore(self, repo, rev, delete=None, qupdate=None):
1616 desc = repo[rev].description().strip()
1616 desc = repo[rev].description().strip()
1617 lines = desc.splitlines()
1617 lines = desc.splitlines()
1618 i = 0
1618 i = 0
1619 datastart = None
1619 datastart = None
1620 series = []
1620 series = []
1621 applied = []
1621 applied = []
1622 qpp = None
1622 qpp = None
1623 for i, line in enumerate(lines):
1623 for i, line in enumerate(lines):
1624 if line == 'Patch Data:':
1624 if line == 'Patch Data:':
1625 datastart = i + 1
1625 datastart = i + 1
1626 elif line.startswith('Dirstate:'):
1626 elif line.startswith('Dirstate:'):
1627 l = line.rstrip()
1627 l = line.rstrip()
1628 l = l[10:].split(' ')
1628 l = l[10:].split(' ')
1629 qpp = [bin(x) for x in l]
1629 qpp = [bin(x) for x in l]
1630 elif datastart is not None:
1630 elif datastart is not None:
1631 l = line.rstrip()
1631 l = line.rstrip()
1632 n, name = l.split(':', 1)
1632 n, name = l.split(':', 1)
1633 if n:
1633 if n:
1634 applied.append(statusentry(bin(n), name))
1634 applied.append(statusentry(bin(n), name))
1635 else:
1635 else:
1636 series.append(l)
1636 series.append(l)
1637 if datastart is None:
1637 if datastart is None:
1638 self.ui.warn(_("No saved patch data found\n"))
1638 self.ui.warn(_("No saved patch data found\n"))
1639 return 1
1639 return 1
1640 self.ui.warn(_("restoring status: %s\n") % lines[0])
1640 self.ui.warn(_("restoring status: %s\n") % lines[0])
1641 self.full_series = series
1641 self.full_series = series
1642 self.applied = applied
1642 self.applied = applied
1643 self.parse_series()
1643 self.parse_series()
1644 self.series_dirty = 1
1644 self.series_dirty = 1
1645 self.applied_dirty = 1
1645 self.applied_dirty = 1
1646 heads = repo.changelog.heads()
1646 heads = repo.changelog.heads()
1647 if delete:
1647 if delete:
1648 if rev not in heads:
1648 if rev not in heads:
1649 self.ui.warn(_("save entry has children, leaving it alone\n"))
1649 self.ui.warn(_("save entry has children, leaving it alone\n"))
1650 else:
1650 else:
1651 self.ui.warn(_("removing save entry %s\n") % short(rev))
1651 self.ui.warn(_("removing save entry %s\n") % short(rev))
1652 pp = repo.dirstate.parents()
1652 pp = repo.dirstate.parents()
1653 if rev in pp:
1653 if rev in pp:
1654 update = True
1654 update = True
1655 else:
1655 else:
1656 update = False
1656 update = False
1657 self.strip(repo, [rev], update=update, backup='strip')
1657 self.strip(repo, [rev], update=update, backup='strip')
1658 if qpp:
1658 if qpp:
1659 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1659 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1660 (short(qpp[0]), short(qpp[1])))
1660 (short(qpp[0]), short(qpp[1])))
1661 if qupdate:
1661 if qupdate:
1662 self.ui.status(_("updating queue directory\n"))
1662 self.ui.status(_("updating queue directory\n"))
1663 r = self.qrepo()
1663 r = self.qrepo()
1664 if not r:
1664 if not r:
1665 self.ui.warn(_("Unable to load queue repository\n"))
1665 self.ui.warn(_("Unable to load queue repository\n"))
1666 return 1
1666 return 1
1667 hg.clean(r, qpp[0])
1667 hg.clean(r, qpp[0])
1668
1668
1669 def save(self, repo, msg=None):
1669 def save(self, repo, msg=None):
1670 if not self.applied:
1670 if not self.applied:
1671 self.ui.warn(_("save: no patches applied, exiting\n"))
1671 self.ui.warn(_("save: no patches applied, exiting\n"))
1672 return 1
1672 return 1
1673 if self.issaveline(self.applied[-1]):
1673 if self.issaveline(self.applied[-1]):
1674 self.ui.warn(_("status is already saved\n"))
1674 self.ui.warn(_("status is already saved\n"))
1675 return 1
1675 return 1
1676
1676
1677 if not msg:
1677 if not msg:
1678 msg = _("hg patches saved state")
1678 msg = _("hg patches saved state")
1679 else:
1679 else:
1680 msg = "hg patches: " + msg.rstrip('\r\n')
1680 msg = "hg patches: " + msg.rstrip('\r\n')
1681 r = self.qrepo()
1681 r = self.qrepo()
1682 if r:
1682 if r:
1683 pp = r.dirstate.parents()
1683 pp = r.dirstate.parents()
1684 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1684 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1685 msg += "\n\nPatch Data:\n"
1685 msg += "\n\nPatch Data:\n"
1686 msg += ''.join('%s\n' % x for x in self.applied)
1686 msg += ''.join('%s\n' % x for x in self.applied)
1687 msg += ''.join(':%s\n' % x for x in self.full_series)
1687 msg += ''.join(':%s\n' % x for x in self.full_series)
1688 n = repo.commit(msg, force=True)
1688 n = repo.commit(msg, force=True)
1689 if not n:
1689 if not n:
1690 self.ui.warn(_("repo commit failed\n"))
1690 self.ui.warn(_("repo commit failed\n"))
1691 return 1
1691 return 1
1692 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1692 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1693 self.applied_dirty = 1
1693 self.applied_dirty = 1
1694 self.removeundo(repo)
1694 self.removeundo(repo)
1695
1695
1696 def full_series_end(self):
1696 def full_series_end(self):
1697 if self.applied:
1697 if self.applied:
1698 p = self.applied[-1].name
1698 p = self.applied[-1].name
1699 end = self.find_series(p)
1699 end = self.find_series(p)
1700 if end is None:
1700 if end is None:
1701 return len(self.full_series)
1701 return len(self.full_series)
1702 return end + 1
1702 return end + 1
1703 return 0
1703 return 0
1704
1704
1705 def series_end(self, all_patches=False):
1705 def series_end(self, all_patches=False):
1706 """If all_patches is False, return the index of the next pushable patch
1706 """If all_patches is False, return the index of the next pushable patch
1707 in the series, or the series length. If all_patches is True, return the
1707 in the series, or the series length. If all_patches is True, return the
1708 index of the first patch past the last applied one.
1708 index of the first patch past the last applied one.
1709 """
1709 """
1710 end = 0
1710 end = 0
1711 def next(start):
1711 def next(start):
1712 if all_patches or start >= len(self.series):
1712 if all_patches or start >= len(self.series):
1713 return start
1713 return start
1714 for i in xrange(start, len(self.series)):
1714 for i in xrange(start, len(self.series)):
1715 p, reason = self.pushable(i)
1715 p, reason = self.pushable(i)
1716 if p:
1716 if p:
1717 break
1717 break
1718 self.explain_pushable(i)
1718 self.explain_pushable(i)
1719 return i
1719 return i
1720 if self.applied:
1720 if self.applied:
1721 p = self.applied[-1].name
1721 p = self.applied[-1].name
1722 try:
1722 try:
1723 end = self.series.index(p)
1723 end = self.series.index(p)
1724 except ValueError:
1724 except ValueError:
1725 return 0
1725 return 0
1726 return next(end + 1)
1726 return next(end + 1)
1727 return next(end)
1727 return next(end)
1728
1728
1729 def appliedname(self, index):
1729 def appliedname(self, index):
1730 pname = self.applied[index].name
1730 pname = self.applied[index].name
1731 if not self.ui.verbose:
1731 if not self.ui.verbose:
1732 p = pname
1732 p = pname
1733 else:
1733 else:
1734 p = str(self.series.index(pname)) + " " + pname
1734 p = str(self.series.index(pname)) + " " + pname
1735 return p
1735 return p
1736
1736
1737 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1737 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1738 force=None, git=False):
1738 force=None, git=False):
1739 def checkseries(patchname):
1739 def checkseries(patchname):
1740 if patchname in self.series:
1740 if patchname in self.series:
1741 raise util.Abort(_('patch %s is already in the series file')
1741 raise util.Abort(_('patch %s is already in the series file')
1742 % patchname)
1742 % patchname)
1743
1743
1744 if rev:
1744 if rev:
1745 if files:
1745 if files:
1746 raise util.Abort(_('option "-r" not valid when importing '
1746 raise util.Abort(_('option "-r" not valid when importing '
1747 'files'))
1747 'files'))
1748 rev = scmutil.revrange(repo, rev)
1748 rev = scmutil.revrange(repo, rev)
1749 rev.sort(reverse=True)
1749 rev.sort(reverse=True)
1750 if (len(files) > 1 or len(rev) > 1) and patchname:
1750 if (len(files) > 1 or len(rev) > 1) and patchname:
1751 raise util.Abort(_('option "-n" not valid when importing multiple '
1751 raise util.Abort(_('option "-n" not valid when importing multiple '
1752 'patches'))
1752 'patches'))
1753 if rev:
1753 if rev:
1754 # If mq patches are applied, we can only import revisions
1754 # If mq patches are applied, we can only import revisions
1755 # that form a linear path to qbase.
1755 # that form a linear path to qbase.
1756 # Otherwise, they should form a linear path to a head.
1756 # Otherwise, they should form a linear path to a head.
1757 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1757 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1758 if len(heads) > 1:
1758 if len(heads) > 1:
1759 raise util.Abort(_('revision %d is the root of more than one '
1759 raise util.Abort(_('revision %d is the root of more than one '
1760 'branch') % rev[-1])
1760 'branch') % rev[-1])
1761 if self.applied:
1761 if self.applied:
1762 base = repo.changelog.node(rev[0])
1762 base = repo.changelog.node(rev[0])
1763 if base in [n.node for n in self.applied]:
1763 if base in [n.node for n in self.applied]:
1764 raise util.Abort(_('revision %d is already managed')
1764 raise util.Abort(_('revision %d is already managed')
1765 % rev[0])
1765 % rev[0])
1766 if heads != [self.applied[-1].node]:
1766 if heads != [self.applied[-1].node]:
1767 raise util.Abort(_('revision %d is not the parent of '
1767 raise util.Abort(_('revision %d is not the parent of '
1768 'the queue') % rev[0])
1768 'the queue') % rev[0])
1769 base = repo.changelog.rev(self.applied[0].node)
1769 base = repo.changelog.rev(self.applied[0].node)
1770 lastparent = repo.changelog.parentrevs(base)[0]
1770 lastparent = repo.changelog.parentrevs(base)[0]
1771 else:
1771 else:
1772 if heads != [repo.changelog.node(rev[0])]:
1772 if heads != [repo.changelog.node(rev[0])]:
1773 raise util.Abort(_('revision %d has unmanaged children')
1773 raise util.Abort(_('revision %d has unmanaged children')
1774 % rev[0])
1774 % rev[0])
1775 lastparent = None
1775 lastparent = None
1776
1776
1777 diffopts = self.diffopts({'git': git})
1777 diffopts = self.diffopts({'git': git})
1778 for r in rev:
1778 for r in rev:
1779 p1, p2 = repo.changelog.parentrevs(r)
1779 p1, p2 = repo.changelog.parentrevs(r)
1780 n = repo.changelog.node(r)
1780 n = repo.changelog.node(r)
1781 if p2 != nullrev:
1781 if p2 != nullrev:
1782 raise util.Abort(_('cannot import merge revision %d') % r)
1782 raise util.Abort(_('cannot import merge revision %d') % r)
1783 if lastparent and lastparent != r:
1783 if lastparent and lastparent != r:
1784 raise util.Abort(_('revision %d is not the parent of %d')
1784 raise util.Abort(_('revision %d is not the parent of %d')
1785 % (r, lastparent))
1785 % (r, lastparent))
1786 lastparent = p1
1786 lastparent = p1
1787
1787
1788 if not patchname:
1788 if not patchname:
1789 patchname = normname('%d.diff' % r)
1789 patchname = normname('%d.diff' % r)
1790 checkseries(patchname)
1790 checkseries(patchname)
1791 self.checkpatchname(patchname, force)
1791 self.checkpatchname(patchname, force)
1792 self.full_series.insert(0, patchname)
1792 self.full_series.insert(0, patchname)
1793
1793
1794 patchf = self.opener(patchname, "w")
1794 patchf = self.opener(patchname, "w")
1795 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1795 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1796 patchf.close()
1796 patchf.close()
1797
1797
1798 se = statusentry(n, patchname)
1798 se = statusentry(n, patchname)
1799 self.applied.insert(0, se)
1799 self.applied.insert(0, se)
1800
1800
1801 self.added.append(patchname)
1801 self.added.append(patchname)
1802 patchname = None
1802 patchname = None
1803 self.parse_series()
1803 self.parse_series()
1804 self.applied_dirty = 1
1804 self.applied_dirty = 1
1805 self.series_dirty = True
1805 self.series_dirty = True
1806
1806
1807 for i, filename in enumerate(files):
1807 for i, filename in enumerate(files):
1808 if existing:
1808 if existing:
1809 if filename == '-':
1809 if filename == '-':
1810 raise util.Abort(_('-e is incompatible with import from -'))
1810 raise util.Abort(_('-e is incompatible with import from -'))
1811 filename = normname(filename)
1811 filename = normname(filename)
1812 self.check_reserved_name(filename)
1812 self.check_reserved_name(filename)
1813 originpath = self.join(filename)
1813 originpath = self.join(filename)
1814 if not os.path.isfile(originpath):
1814 if not os.path.isfile(originpath):
1815 raise util.Abort(_("patch %s does not exist") % filename)
1815 raise util.Abort(_("patch %s does not exist") % filename)
1816
1816
1817 if patchname:
1817 if patchname:
1818 self.checkpatchname(patchname, force)
1818 self.checkpatchname(patchname, force)
1819
1819
1820 self.ui.write(_('renaming %s to %s\n')
1820 self.ui.write(_('renaming %s to %s\n')
1821 % (filename, patchname))
1821 % (filename, patchname))
1822 util.rename(originpath, self.join(patchname))
1822 util.rename(originpath, self.join(patchname))
1823 else:
1823 else:
1824 patchname = filename
1824 patchname = filename
1825
1825
1826 else:
1826 else:
1827 if filename == '-' and not patchname:
1827 if filename == '-' and not patchname:
1828 raise util.Abort(_('need --name to import a patch from -'))
1828 raise util.Abort(_('need --name to import a patch from -'))
1829 elif not patchname:
1829 elif not patchname:
1830 patchname = normname(os.path.basename(filename.rstrip('/')))
1830 patchname = normname(os.path.basename(filename.rstrip('/')))
1831 self.checkpatchname(patchname, force)
1831 self.checkpatchname(patchname, force)
1832 try:
1832 try:
1833 if filename == '-':
1833 if filename == '-':
1834 text = sys.stdin.read()
1834 text = sys.stdin.read()
1835 else:
1835 else:
1836 fp = url.open(self.ui, filename)
1836 fp = url.open(self.ui, filename)
1837 text = fp.read()
1837 text = fp.read()
1838 fp.close()
1838 fp.close()
1839 except (OSError, IOError):
1839 except (OSError, IOError):
1840 raise util.Abort(_("unable to read file %s") % filename)
1840 raise util.Abort(_("unable to read file %s") % filename)
1841 patchf = self.opener(patchname, "w")
1841 patchf = self.opener(patchname, "w")
1842 patchf.write(text)
1842 patchf.write(text)
1843 patchf.close()
1843 patchf.close()
1844 if not force:
1844 if not force:
1845 checkseries(patchname)
1845 checkseries(patchname)
1846 if patchname not in self.series:
1846 if patchname not in self.series:
1847 index = self.full_series_end() + i
1847 index = self.full_series_end() + i
1848 self.full_series[index:index] = [patchname]
1848 self.full_series[index:index] = [patchname]
1849 self.parse_series()
1849 self.parse_series()
1850 self.series_dirty = True
1850 self.series_dirty = True
1851 self.ui.warn(_("adding %s to series file\n") % patchname)
1851 self.ui.warn(_("adding %s to series file\n") % patchname)
1852 self.added.append(patchname)
1852 self.added.append(patchname)
1853 patchname = None
1853 patchname = None
1854
1854
1855 self.removeundo(repo)
1855 self.removeundo(repo)
1856
1856
1857 @command("qdelete|qremove|qrm",
1857 @command("qdelete|qremove|qrm",
1858 [('k', 'keep', None, _('keep patch file')),
1858 [('k', 'keep', None, _('keep patch file')),
1859 ('r', 'rev', [],
1859 ('r', 'rev', [],
1860 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1860 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1861 _('hg qdelete [-k] [PATCH]...'))
1861 _('hg qdelete [-k] [PATCH]...'))
1862 def delete(ui, repo, *patches, **opts):
1862 def delete(ui, repo, *patches, **opts):
1863 """remove patches from queue
1863 """remove patches from queue
1864
1864
1865 The patches must not be applied, and at least one patch is required. With
1865 The patches must not be applied, and at least one patch is required. With
1866 -k/--keep, the patch files are preserved in the patch directory.
1866 -k/--keep, the patch files are preserved in the patch directory.
1867
1867
1868 To stop managing a patch and move it into permanent history,
1868 To stop managing a patch and move it into permanent history,
1869 use the :hg:`qfinish` command."""
1869 use the :hg:`qfinish` command."""
1870 q = repo.mq
1870 q = repo.mq
1871 q.delete(repo, patches, opts)
1871 q.delete(repo, patches, opts)
1872 q.save_dirty()
1872 q.save_dirty()
1873 return 0
1873 return 0
1874
1874
1875 @command("qapplied",
1875 @command("qapplied",
1876 [('1', 'last', None, _('show only the last patch'))
1876 [('1', 'last', None, _('show only the last patch'))
1877 ] + seriesopts,
1877 ] + seriesopts,
1878 _('hg qapplied [-1] [-s] [PATCH]'))
1878 _('hg qapplied [-1] [-s] [PATCH]'))
1879 def applied(ui, repo, patch=None, **opts):
1879 def applied(ui, repo, patch=None, **opts):
1880 """print the patches already applied
1880 """print the patches already applied
1881
1881
1882 Returns 0 on success."""
1882 Returns 0 on success."""
1883
1883
1884 q = repo.mq
1884 q = repo.mq
1885
1885
1886 if patch:
1886 if patch:
1887 if patch not in q.series:
1887 if patch not in q.series:
1888 raise util.Abort(_("patch %s is not in series file") % patch)
1888 raise util.Abort(_("patch %s is not in series file") % patch)
1889 end = q.series.index(patch) + 1
1889 end = q.series.index(patch) + 1
1890 else:
1890 else:
1891 end = q.series_end(True)
1891 end = q.series_end(True)
1892
1892
1893 if opts.get('last') and not end:
1893 if opts.get('last') and not end:
1894 ui.write(_("no patches applied\n"))
1894 ui.write(_("no patches applied\n"))
1895 return 1
1895 return 1
1896 elif opts.get('last') and end == 1:
1896 elif opts.get('last') and end == 1:
1897 ui.write(_("only one patch applied\n"))
1897 ui.write(_("only one patch applied\n"))
1898 return 1
1898 return 1
1899 elif opts.get('last'):
1899 elif opts.get('last'):
1900 start = end - 2
1900 start = end - 2
1901 end = 1
1901 end = 1
1902 else:
1902 else:
1903 start = 0
1903 start = 0
1904
1904
1905 q.qseries(repo, length=end, start=start, status='A',
1905 q.qseries(repo, length=end, start=start, status='A',
1906 summary=opts.get('summary'))
1906 summary=opts.get('summary'))
1907
1907
1908
1908
1909 @command("qunapplied",
1909 @command("qunapplied",
1910 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1910 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1911 _('hg qunapplied [-1] [-s] [PATCH]'))
1911 _('hg qunapplied [-1] [-s] [PATCH]'))
1912 def unapplied(ui, repo, patch=None, **opts):
1912 def unapplied(ui, repo, patch=None, **opts):
1913 """print the patches not yet applied
1913 """print the patches not yet applied
1914
1914
1915 Returns 0 on success."""
1915 Returns 0 on success."""
1916
1916
1917 q = repo.mq
1917 q = repo.mq
1918 if patch:
1918 if patch:
1919 if patch not in q.series:
1919 if patch not in q.series:
1920 raise util.Abort(_("patch %s is not in series file") % patch)
1920 raise util.Abort(_("patch %s is not in series file") % patch)
1921 start = q.series.index(patch) + 1
1921 start = q.series.index(patch) + 1
1922 else:
1922 else:
1923 start = q.series_end(True)
1923 start = q.series_end(True)
1924
1924
1925 if start == len(q.series) and opts.get('first'):
1925 if start == len(q.series) and opts.get('first'):
1926 ui.write(_("all patches applied\n"))
1926 ui.write(_("all patches applied\n"))
1927 return 1
1927 return 1
1928
1928
1929 length = opts.get('first') and 1 or None
1929 length = opts.get('first') and 1 or None
1930 q.qseries(repo, start=start, length=length, status='U',
1930 q.qseries(repo, start=start, length=length, status='U',
1931 summary=opts.get('summary'))
1931 summary=opts.get('summary'))
1932
1932
1933 @command("qimport",
1933 @command("qimport",
1934 [('e', 'existing', None, _('import file in patch directory')),
1934 [('e', 'existing', None, _('import file in patch directory')),
1935 ('n', 'name', '',
1935 ('n', 'name', '',
1936 _('name of patch file'), _('NAME')),
1936 _('name of patch file'), _('NAME')),
1937 ('f', 'force', None, _('overwrite existing files')),
1937 ('f', 'force', None, _('overwrite existing files')),
1938 ('r', 'rev', [],
1938 ('r', 'rev', [],
1939 _('place existing revisions under mq control'), _('REV')),
1939 _('place existing revisions under mq control'), _('REV')),
1940 ('g', 'git', None, _('use git extended diff format')),
1940 ('g', 'git', None, _('use git extended diff format')),
1941 ('P', 'push', None, _('qpush after importing'))],
1941 ('P', 'push', None, _('qpush after importing'))],
1942 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1942 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1943 def qimport(ui, repo, *filename, **opts):
1943 def qimport(ui, repo, *filename, **opts):
1944 """import a patch
1944 """import a patch
1945
1945
1946 The patch is inserted into the series after the last applied
1946 The patch is inserted into the series after the last applied
1947 patch. If no patches have been applied, qimport prepends the patch
1947 patch. If no patches have been applied, qimport prepends the patch
1948 to the series.
1948 to the series.
1949
1949
1950 The patch will have the same name as its source file unless you
1950 The patch will have the same name as its source file unless you
1951 give it a new one with -n/--name.
1951 give it a new one with -n/--name.
1952
1952
1953 You can register an existing patch inside the patch directory with
1953 You can register an existing patch inside the patch directory with
1954 the -e/--existing flag.
1954 the -e/--existing flag.
1955
1955
1956 With -f/--force, an existing patch of the same name will be
1956 With -f/--force, an existing patch of the same name will be
1957 overwritten.
1957 overwritten.
1958
1958
1959 An existing changeset may be placed under mq control with -r/--rev
1959 An existing changeset may be placed under mq control with -r/--rev
1960 (e.g. qimport --rev tip -n patch will place tip under mq control).
1960 (e.g. qimport --rev tip -n patch will place tip under mq control).
1961 With -g/--git, patches imported with --rev will use the git diff
1961 With -g/--git, patches imported with --rev will use the git diff
1962 format. See the diffs help topic for information on why this is
1962 format. See the diffs help topic for information on why this is
1963 important for preserving rename/copy information and permission
1963 important for preserving rename/copy information and permission
1964 changes. Use :hg:`qfinish` to remove changesets from mq control.
1964 changes. Use :hg:`qfinish` to remove changesets from mq control.
1965
1965
1966 To import a patch from standard input, pass - as the patch file.
1966 To import a patch from standard input, pass - as the patch file.
1967 When importing from standard input, a patch name must be specified
1967 When importing from standard input, a patch name must be specified
1968 using the --name flag.
1968 using the --name flag.
1969
1969
1970 To import an existing patch while renaming it::
1970 To import an existing patch while renaming it::
1971
1971
1972 hg qimport -e existing-patch -n new-name
1972 hg qimport -e existing-patch -n new-name
1973
1973
1974 Returns 0 if import succeeded.
1974 Returns 0 if import succeeded.
1975 """
1975 """
1976 q = repo.mq
1976 q = repo.mq
1977 try:
1977 try:
1978 q.qimport(repo, filename, patchname=opts.get('name'),
1978 q.qimport(repo, filename, patchname=opts.get('name'),
1979 existing=opts.get('existing'), force=opts.get('force'),
1979 existing=opts.get('existing'), force=opts.get('force'),
1980 rev=opts.get('rev'), git=opts.get('git'))
1980 rev=opts.get('rev'), git=opts.get('git'))
1981 finally:
1981 finally:
1982 q.save_dirty()
1982 q.save_dirty()
1983
1983
1984 if opts.get('push') and not opts.get('rev'):
1984 if opts.get('push') and not opts.get('rev'):
1985 return q.push(repo, None)
1985 return q.push(repo, None)
1986 return 0
1986 return 0
1987
1987
1988 def qinit(ui, repo, create):
1988 def qinit(ui, repo, create):
1989 """initialize a new queue repository
1989 """initialize a new queue repository
1990
1990
1991 This command also creates a series file for ordering patches, and
1991 This command also creates a series file for ordering patches, and
1992 an mq-specific .hgignore file in the queue repository, to exclude
1992 an mq-specific .hgignore file in the queue repository, to exclude
1993 the status and guards files (these contain mostly transient state).
1993 the status and guards files (these contain mostly transient state).
1994
1994
1995 Returns 0 if initialization succeeded."""
1995 Returns 0 if initialization succeeded."""
1996 q = repo.mq
1996 q = repo.mq
1997 r = q.init(repo, create)
1997 r = q.init(repo, create)
1998 q.save_dirty()
1998 q.save_dirty()
1999 if r:
1999 if r:
2000 if not os.path.exists(r.wjoin('.hgignore')):
2000 if not os.path.exists(r.wjoin('.hgignore')):
2001 fp = r.wopener('.hgignore', 'w')
2001 fp = r.wopener('.hgignore', 'w')
2002 fp.write('^\\.hg\n')
2002 fp.write('^\\.hg\n')
2003 fp.write('^\\.mq\n')
2003 fp.write('^\\.mq\n')
2004 fp.write('syntax: glob\n')
2004 fp.write('syntax: glob\n')
2005 fp.write('status\n')
2005 fp.write('status\n')
2006 fp.write('guards\n')
2006 fp.write('guards\n')
2007 fp.close()
2007 fp.close()
2008 if not os.path.exists(r.wjoin('series')):
2008 if not os.path.exists(r.wjoin('series')):
2009 r.wopener('series', 'w').close()
2009 r.wopener('series', 'w').close()
2010 r[None].add(['.hgignore', 'series'])
2010 r[None].add(['.hgignore', 'series'])
2011 commands.add(ui, r)
2011 commands.add(ui, r)
2012 return 0
2012 return 0
2013
2013
2014 @command("^qinit",
2014 @command("^qinit",
2015 [('c', 'create-repo', None, _('create queue repository'))],
2015 [('c', 'create-repo', None, _('create queue repository'))],
2016 _('hg qinit [-c]'))
2016 _('hg qinit [-c]'))
2017 def init(ui, repo, **opts):
2017 def init(ui, repo, **opts):
2018 """init a new queue repository (DEPRECATED)
2018 """init a new queue repository (DEPRECATED)
2019
2019
2020 The queue repository is unversioned by default. If
2020 The queue repository is unversioned by default. If
2021 -c/--create-repo is specified, qinit will create a separate nested
2021 -c/--create-repo is specified, qinit will create a separate nested
2022 repository for patches (qinit -c may also be run later to convert
2022 repository for patches (qinit -c may also be run later to convert
2023 an unversioned patch repository into a versioned one). You can use
2023 an unversioned patch repository into a versioned one). You can use
2024 qcommit to commit changes to this queue repository.
2024 qcommit to commit changes to this queue repository.
2025
2025
2026 This command is deprecated. Without -c, it's implied by other relevant
2026 This command is deprecated. Without -c, it's implied by other relevant
2027 commands. With -c, use :hg:`init --mq` instead."""
2027 commands. With -c, use :hg:`init --mq` instead."""
2028 return qinit(ui, repo, create=opts.get('create_repo'))
2028 return qinit(ui, repo, create=opts.get('create_repo'))
2029
2029
2030 @command("qclone",
2030 @command("qclone",
2031 [('', 'pull', None, _('use pull protocol to copy metadata')),
2031 [('', 'pull', None, _('use pull protocol to copy metadata')),
2032 ('U', 'noupdate', None, _('do not update the new working directories')),
2032 ('U', 'noupdate', None, _('do not update the new working directories')),
2033 ('', 'uncompressed', None,
2033 ('', 'uncompressed', None,
2034 _('use uncompressed transfer (fast over LAN)')),
2034 _('use uncompressed transfer (fast over LAN)')),
2035 ('p', 'patches', '',
2035 ('p', 'patches', '',
2036 _('location of source patch repository'), _('REPO')),
2036 _('location of source patch repository'), _('REPO')),
2037 ] + commands.remoteopts,
2037 ] + commands.remoteopts,
2038 _('hg qclone [OPTION]... SOURCE [DEST]'))
2038 _('hg qclone [OPTION]... SOURCE [DEST]'))
2039 def clone(ui, source, dest=None, **opts):
2039 def clone(ui, source, dest=None, **opts):
2040 '''clone main and patch repository at same time
2040 '''clone main and patch repository at same time
2041
2041
2042 If source is local, destination will have no patches applied. If
2042 If source is local, destination will have no patches applied. If
2043 source is remote, this command can not check if patches are
2043 source is remote, this command can not check if patches are
2044 applied in source, so cannot guarantee that patches are not
2044 applied in source, so cannot guarantee that patches are not
2045 applied in destination. If you clone remote repository, be sure
2045 applied in destination. If you clone remote repository, be sure
2046 before that it has no patches applied.
2046 before that it has no patches applied.
2047
2047
2048 Source patch repository is looked for in <src>/.hg/patches by
2048 Source patch repository is looked for in <src>/.hg/patches by
2049 default. Use -p <url> to change.
2049 default. Use -p <url> to change.
2050
2050
2051 The patch directory must be a nested Mercurial repository, as
2051 The patch directory must be a nested Mercurial repository, as
2052 would be created by :hg:`init --mq`.
2052 would be created by :hg:`init --mq`.
2053
2053
2054 Return 0 on success.
2054 Return 0 on success.
2055 '''
2055 '''
2056 def patchdir(repo):
2056 def patchdir(repo):
2057 url = repo.url()
2057 url = repo.url()
2058 if url.endswith('/'):
2058 if url.endswith('/'):
2059 url = url[:-1]
2059 url = url[:-1]
2060 return url + '/.hg/patches'
2060 return url + '/.hg/patches'
2061 if dest is None:
2061 if dest is None:
2062 dest = hg.defaultdest(source)
2062 dest = hg.defaultdest(source)
2063 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2063 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2064 if opts.get('patches'):
2064 if opts.get('patches'):
2065 patchespath = ui.expandpath(opts.get('patches'))
2065 patchespath = ui.expandpath(opts.get('patches'))
2066 else:
2066 else:
2067 patchespath = patchdir(sr)
2067 patchespath = patchdir(sr)
2068 try:
2068 try:
2069 hg.repository(ui, patchespath)
2069 hg.repository(ui, patchespath)
2070 except error.RepoError:
2070 except error.RepoError:
2071 raise util.Abort(_('versioned patch repository not found'
2071 raise util.Abort(_('versioned patch repository not found'
2072 ' (see init --mq)'))
2072 ' (see init --mq)'))
2073 qbase, destrev = None, None
2073 qbase, destrev = None, None
2074 if sr.local():
2074 if sr.local():
2075 if sr.mq.applied:
2075 if sr.mq.applied:
2076 qbase = sr.mq.applied[0].node
2076 qbase = sr.mq.applied[0].node
2077 if not hg.islocal(dest):
2077 if not hg.islocal(dest):
2078 heads = set(sr.heads())
2078 heads = set(sr.heads())
2079 destrev = list(heads.difference(sr.heads(qbase)))
2079 destrev = list(heads.difference(sr.heads(qbase)))
2080 destrev.append(sr.changelog.parents(qbase)[0])
2080 destrev.append(sr.changelog.parents(qbase)[0])
2081 elif sr.capable('lookup'):
2081 elif sr.capable('lookup'):
2082 try:
2082 try:
2083 qbase = sr.lookup('qbase')
2083 qbase = sr.lookup('qbase')
2084 except error.RepoError:
2084 except error.RepoError:
2085 pass
2085 pass
2086 ui.note(_('cloning main repository\n'))
2086 ui.note(_('cloning main repository\n'))
2087 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2087 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2088 pull=opts.get('pull'),
2088 pull=opts.get('pull'),
2089 rev=destrev,
2089 rev=destrev,
2090 update=False,
2090 update=False,
2091 stream=opts.get('uncompressed'))
2091 stream=opts.get('uncompressed'))
2092 ui.note(_('cloning patch repository\n'))
2092 ui.note(_('cloning patch repository\n'))
2093 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2093 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2094 pull=opts.get('pull'), update=not opts.get('noupdate'),
2094 pull=opts.get('pull'), update=not opts.get('noupdate'),
2095 stream=opts.get('uncompressed'))
2095 stream=opts.get('uncompressed'))
2096 if dr.local():
2096 if dr.local():
2097 if qbase:
2097 if qbase:
2098 ui.note(_('stripping applied patches from destination '
2098 ui.note(_('stripping applied patches from destination '
2099 'repository\n'))
2099 'repository\n'))
2100 dr.mq.strip(dr, [qbase], update=False, backup=None)
2100 dr.mq.strip(dr, [qbase], update=False, backup=None)
2101 if not opts.get('noupdate'):
2101 if not opts.get('noupdate'):
2102 ui.note(_('updating destination repository\n'))
2102 ui.note(_('updating destination repository\n'))
2103 hg.update(dr, dr.changelog.tip())
2103 hg.update(dr, dr.changelog.tip())
2104
2104
2105 @command("qcommit|qci",
2105 @command("qcommit|qci",
2106 commands.table["^commit|ci"][1],
2106 commands.table["^commit|ci"][1],
2107 _('hg qcommit [OPTION]... [FILE]...'))
2107 _('hg qcommit [OPTION]... [FILE]...'))
2108 def commit(ui, repo, *pats, **opts):
2108 def commit(ui, repo, *pats, **opts):
2109 """commit changes in the queue repository (DEPRECATED)
2109 """commit changes in the queue repository (DEPRECATED)
2110
2110
2111 This command is deprecated; use :hg:`commit --mq` instead."""
2111 This command is deprecated; use :hg:`commit --mq` instead."""
2112 q = repo.mq
2112 q = repo.mq
2113 r = q.qrepo()
2113 r = q.qrepo()
2114 if not r:
2114 if not r:
2115 raise util.Abort('no queue repository')
2115 raise util.Abort('no queue repository')
2116 commands.commit(r.ui, r, *pats, **opts)
2116 commands.commit(r.ui, r, *pats, **opts)
2117
2117
2118 @command("qseries",
2118 @command("qseries",
2119 [('m', 'missing', None, _('print patches not in series')),
2119 [('m', 'missing', None, _('print patches not in series')),
2120 ] + seriesopts,
2120 ] + seriesopts,
2121 _('hg qseries [-ms]'))
2121 _('hg qseries [-ms]'))
2122 def series(ui, repo, **opts):
2122 def series(ui, repo, **opts):
2123 """print the entire series file
2123 """print the entire series file
2124
2124
2125 Returns 0 on success."""
2125 Returns 0 on success."""
2126 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2126 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2127 return 0
2127 return 0
2128
2128
2129 @command("qtop", seriesopts, _('hg qtop [-s]'))
2129 @command("qtop", seriesopts, _('hg qtop [-s]'))
2130 def top(ui, repo, **opts):
2130 def top(ui, repo, **opts):
2131 """print the name of the current patch
2131 """print the name of the current patch
2132
2132
2133 Returns 0 on success."""
2133 Returns 0 on success."""
2134 q = repo.mq
2134 q = repo.mq
2135 t = q.applied and q.series_end(True) or 0
2135 t = q.applied and q.series_end(True) or 0
2136 if t:
2136 if t:
2137 q.qseries(repo, start=t - 1, length=1, status='A',
2137 q.qseries(repo, start=t - 1, length=1, status='A',
2138 summary=opts.get('summary'))
2138 summary=opts.get('summary'))
2139 else:
2139 else:
2140 ui.write(_("no patches applied\n"))
2140 ui.write(_("no patches applied\n"))
2141 return 1
2141 return 1
2142
2142
2143 @command("qnext", seriesopts, _('hg qnext [-s]'))
2143 @command("qnext", seriesopts, _('hg qnext [-s]'))
2144 def next(ui, repo, **opts):
2144 def next(ui, repo, **opts):
2145 """print the name of the next patch
2145 """print the name of the next patch
2146
2146
2147 Returns 0 on success."""
2147 Returns 0 on success."""
2148 q = repo.mq
2148 q = repo.mq
2149 end = q.series_end()
2149 end = q.series_end()
2150 if end == len(q.series):
2150 if end == len(q.series):
2151 ui.write(_("all patches applied\n"))
2151 ui.write(_("all patches applied\n"))
2152 return 1
2152 return 1
2153 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2153 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2154
2154
2155 @command("qprev", seriesopts, _('hg qprev [-s]'))
2155 @command("qprev", seriesopts, _('hg qprev [-s]'))
2156 def prev(ui, repo, **opts):
2156 def prev(ui, repo, **opts):
2157 """print the name of the previous patch
2157 """print the name of the previous patch
2158
2158
2159 Returns 0 on success."""
2159 Returns 0 on success."""
2160 q = repo.mq
2160 q = repo.mq
2161 l = len(q.applied)
2161 l = len(q.applied)
2162 if l == 1:
2162 if l == 1:
2163 ui.write(_("only one patch applied\n"))
2163 ui.write(_("only one patch applied\n"))
2164 return 1
2164 return 1
2165 if not l:
2165 if not l:
2166 ui.write(_("no patches applied\n"))
2166 ui.write(_("no patches applied\n"))
2167 return 1
2167 return 1
2168 q.qseries(repo, start=l - 2, length=1, status='A',
2168 q.qseries(repo, start=l - 2, length=1, status='A',
2169 summary=opts.get('summary'))
2169 summary=opts.get('summary'))
2170
2170
2171 def setupheaderopts(ui, opts):
2171 def setupheaderopts(ui, opts):
2172 if not opts.get('user') and opts.get('currentuser'):
2172 if not opts.get('user') and opts.get('currentuser'):
2173 opts['user'] = ui.username()
2173 opts['user'] = ui.username()
2174 if not opts.get('date') and opts.get('currentdate'):
2174 if not opts.get('date') and opts.get('currentdate'):
2175 opts['date'] = "%d %d" % util.makedate()
2175 opts['date'] = "%d %d" % util.makedate()
2176
2176
2177 @command("^qnew",
2177 @command("^qnew",
2178 [('e', 'edit', None, _('edit commit message')),
2178 [('e', 'edit', None, _('edit commit message')),
2179 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2179 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2180 ('g', 'git', None, _('use git extended diff format')),
2180 ('g', 'git', None, _('use git extended diff format')),
2181 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2181 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2182 ('u', 'user', '',
2182 ('u', 'user', '',
2183 _('add "From: <USER>" to patch'), _('USER')),
2183 _('add "From: <USER>" to patch'), _('USER')),
2184 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2184 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2185 ('d', 'date', '',
2185 ('d', 'date', '',
2186 _('add "Date: <DATE>" to patch'), _('DATE'))
2186 _('add "Date: <DATE>" to patch'), _('DATE'))
2187 ] + commands.walkopts + commands.commitopts,
2187 ] + commands.walkopts + commands.commitopts,
2188 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2188 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2189 def new(ui, repo, patch, *args, **opts):
2189 def new(ui, repo, patch, *args, **opts):
2190 """create a new patch
2190 """create a new patch
2191
2191
2192 qnew creates a new patch on top of the currently-applied patch (if
2192 qnew creates a new patch on top of the currently-applied patch (if
2193 any). The patch will be initialized with any outstanding changes
2193 any). The patch will be initialized with any outstanding changes
2194 in the working directory. You may also use -I/--include,
2194 in the working directory. You may also use -I/--include,
2195 -X/--exclude, and/or a list of files after the patch name to add
2195 -X/--exclude, and/or a list of files after the patch name to add
2196 only changes to matching files to the new patch, leaving the rest
2196 only changes to matching files to the new patch, leaving the rest
2197 as uncommitted modifications.
2197 as uncommitted modifications.
2198
2198
2199 -u/--user and -d/--date can be used to set the (given) user and
2199 -u/--user and -d/--date can be used to set the (given) user and
2200 date, respectively. -U/--currentuser and -D/--currentdate set user
2200 date, respectively. -U/--currentuser and -D/--currentdate set user
2201 to current user and date to current date.
2201 to current user and date to current date.
2202
2202
2203 -e/--edit, -m/--message or -l/--logfile set the patch header as
2203 -e/--edit, -m/--message or -l/--logfile set the patch header as
2204 well as the commit message. If none is specified, the header is
2204 well as the commit message. If none is specified, the header is
2205 empty and the commit message is '[mq]: PATCH'.
2205 empty and the commit message is '[mq]: PATCH'.
2206
2206
2207 Use the -g/--git option to keep the patch in the git extended diff
2207 Use the -g/--git option to keep the patch in the git extended diff
2208 format. Read the diffs help topic for more information on why this
2208 format. Read the diffs help topic for more information on why this
2209 is important for preserving permission changes and copy/rename
2209 is important for preserving permission changes and copy/rename
2210 information.
2210 information.
2211
2211
2212 Returns 0 on successful creation of a new patch.
2212 Returns 0 on successful creation of a new patch.
2213 """
2213 """
2214 msg = cmdutil.logmessage(opts)
2214 msg = cmdutil.logmessage(opts)
2215 def getmsg():
2215 def getmsg():
2216 return ui.edit(msg, opts.get('user') or ui.username())
2216 return ui.edit(msg, opts.get('user') or ui.username())
2217 q = repo.mq
2217 q = repo.mq
2218 opts['msg'] = msg
2218 opts['msg'] = msg
2219 if opts.get('edit'):
2219 if opts.get('edit'):
2220 opts['msg'] = getmsg
2220 opts['msg'] = getmsg
2221 else:
2221 else:
2222 opts['msg'] = msg
2222 opts['msg'] = msg
2223 setupheaderopts(ui, opts)
2223 setupheaderopts(ui, opts)
2224 q.new(repo, patch, *args, **opts)
2224 q.new(repo, patch, *args, **opts)
2225 q.save_dirty()
2225 q.save_dirty()
2226 return 0
2226 return 0
2227
2227
2228 @command("^qrefresh",
2228 @command("^qrefresh",
2229 [('e', 'edit', None, _('edit commit message')),
2229 [('e', 'edit', None, _('edit commit message')),
2230 ('g', 'git', None, _('use git extended diff format')),
2230 ('g', 'git', None, _('use git extended diff format')),
2231 ('s', 'short', None,
2231 ('s', 'short', None,
2232 _('refresh only files already in the patch and specified files')),
2232 _('refresh only files already in the patch and specified files')),
2233 ('U', 'currentuser', None,
2233 ('U', 'currentuser', None,
2234 _('add/update author field in patch with current user')),
2234 _('add/update author field in patch with current user')),
2235 ('u', 'user', '',
2235 ('u', 'user', '',
2236 _('add/update author field in patch with given user'), _('USER')),
2236 _('add/update author field in patch with given user'), _('USER')),
2237 ('D', 'currentdate', None,
2237 ('D', 'currentdate', None,
2238 _('add/update date field in patch with current date')),
2238 _('add/update date field in patch with current date')),
2239 ('d', 'date', '',
2239 ('d', 'date', '',
2240 _('add/update date field in patch with given date'), _('DATE'))
2240 _('add/update date field in patch with given date'), _('DATE'))
2241 ] + commands.walkopts + commands.commitopts,
2241 ] + commands.walkopts + commands.commitopts,
2242 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2242 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2243 def refresh(ui, repo, *pats, **opts):
2243 def refresh(ui, repo, *pats, **opts):
2244 """update the current patch
2244 """update the current patch
2245
2245
2246 If any file patterns are provided, the refreshed patch will
2246 If any file patterns are provided, the refreshed patch will
2247 contain only the modifications that match those patterns; the
2247 contain only the modifications that match those patterns; the
2248 remaining modifications will remain in the working directory.
2248 remaining modifications will remain in the working directory.
2249
2249
2250 If -s/--short is specified, files currently included in the patch
2250 If -s/--short is specified, files currently included in the patch
2251 will be refreshed just like matched files and remain in the patch.
2251 will be refreshed just like matched files and remain in the patch.
2252
2252
2253 If -e/--edit is specified, Mercurial will start your configured editor for
2253 If -e/--edit is specified, Mercurial will start your configured editor for
2254 you to enter a message. In case qrefresh fails, you will find a backup of
2254 you to enter a message. In case qrefresh fails, you will find a backup of
2255 your message in ``.hg/last-message.txt``.
2255 your message in ``.hg/last-message.txt``.
2256
2256
2257 hg add/remove/copy/rename work as usual, though you might want to
2257 hg add/remove/copy/rename work as usual, though you might want to
2258 use git-style patches (-g/--git or [diff] git=1) to track copies
2258 use git-style patches (-g/--git or [diff] git=1) to track copies
2259 and renames. See the diffs help topic for more information on the
2259 and renames. See the diffs help topic for more information on the
2260 git diff format.
2260 git diff format.
2261
2261
2262 Returns 0 on success.
2262 Returns 0 on success.
2263 """
2263 """
2264 q = repo.mq
2264 q = repo.mq
2265 message = cmdutil.logmessage(opts)
2265 message = cmdutil.logmessage(opts)
2266 if opts.get('edit'):
2266 if opts.get('edit'):
2267 if not q.applied:
2267 if not q.applied:
2268 ui.write(_("no patches applied\n"))
2268 ui.write(_("no patches applied\n"))
2269 return 1
2269 return 1
2270 if message:
2270 if message:
2271 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2271 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2272 patch = q.applied[-1].name
2272 patch = q.applied[-1].name
2273 ph = patchheader(q.join(patch), q.plainmode)
2273 ph = patchheader(q.join(patch), q.plainmode)
2274 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2274 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2275 # We don't want to lose the patch message if qrefresh fails (issue2062)
2275 # We don't want to lose the patch message if qrefresh fails (issue2062)
2276 repo.savecommitmessage(message)
2276 repo.savecommitmessage(message)
2277 setupheaderopts(ui, opts)
2277 setupheaderopts(ui, opts)
2278 ret = q.refresh(repo, pats, msg=message, **opts)
2278 ret = q.refresh(repo, pats, msg=message, **opts)
2279 q.save_dirty()
2279 q.save_dirty()
2280 return ret
2280 return ret
2281
2281
2282 @command("^qdiff",
2282 @command("^qdiff",
2283 commands.diffopts + commands.diffopts2 + commands.walkopts,
2283 commands.diffopts + commands.diffopts2 + commands.walkopts,
2284 _('hg qdiff [OPTION]... [FILE]...'))
2284 _('hg qdiff [OPTION]... [FILE]...'))
2285 def diff(ui, repo, *pats, **opts):
2285 def diff(ui, repo, *pats, **opts):
2286 """diff of the current patch and subsequent modifications
2286 """diff of the current patch and subsequent modifications
2287
2287
2288 Shows a diff which includes the current patch as well as any
2288 Shows a diff which includes the current patch as well as any
2289 changes which have been made in the working directory since the
2289 changes which have been made in the working directory since the
2290 last refresh (thus showing what the current patch would become
2290 last refresh (thus showing what the current patch would become
2291 after a qrefresh).
2291 after a qrefresh).
2292
2292
2293 Use :hg:`diff` if you only want to see the changes made since the
2293 Use :hg:`diff` if you only want to see the changes made since the
2294 last qrefresh, or :hg:`export qtip` if you want to see changes
2294 last qrefresh, or :hg:`export qtip` if you want to see changes
2295 made by the current patch without including changes made since the
2295 made by the current patch without including changes made since the
2296 qrefresh.
2296 qrefresh.
2297
2297
2298 Returns 0 on success.
2298 Returns 0 on success.
2299 """
2299 """
2300 repo.mq.diff(repo, pats, opts)
2300 repo.mq.diff(repo, pats, opts)
2301 return 0
2301 return 0
2302
2302
2303 @command('qfold',
2303 @command('qfold',
2304 [('e', 'edit', None, _('edit patch header')),
2304 [('e', 'edit', None, _('edit patch header')),
2305 ('k', 'keep', None, _('keep folded patch files')),
2305 ('k', 'keep', None, _('keep folded patch files')),
2306 ] + commands.commitopts,
2306 ] + commands.commitopts,
2307 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2307 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2308 def fold(ui, repo, *files, **opts):
2308 def fold(ui, repo, *files, **opts):
2309 """fold the named patches into the current patch
2309 """fold the named patches into the current patch
2310
2310
2311 Patches must not yet be applied. Each patch will be successively
2311 Patches must not yet be applied. Each patch will be successively
2312 applied to the current patch in the order given. If all the
2312 applied to the current patch in the order given. If all the
2313 patches apply successfully, the current patch will be refreshed
2313 patches apply successfully, the current patch will be refreshed
2314 with the new cumulative patch, and the folded patches will be
2314 with the new cumulative patch, and the folded patches will be
2315 deleted. With -k/--keep, the folded patch files will not be
2315 deleted. With -k/--keep, the folded patch files will not be
2316 removed afterwards.
2316 removed afterwards.
2317
2317
2318 The header for each folded patch will be concatenated with the
2318 The header for each folded patch will be concatenated with the
2319 current patch header, separated by a line of ``* * *``.
2319 current patch header, separated by a line of ``* * *``.
2320
2320
2321 Returns 0 on success."""
2321 Returns 0 on success."""
2322
2322
2323 q = repo.mq
2323 q = repo.mq
2324
2324
2325 if not files:
2325 if not files:
2326 raise util.Abort(_('qfold requires at least one patch name'))
2326 raise util.Abort(_('qfold requires at least one patch name'))
2327 if not q.check_toppatch(repo)[0]:
2327 if not q.check_toppatch(repo)[0]:
2328 raise util.Abort(_('no patches applied'))
2328 raise util.Abort(_('no patches applied'))
2329 q.check_localchanges(repo)
2329 q.check_localchanges(repo)
2330
2330
2331 message = cmdutil.logmessage(opts)
2331 message = cmdutil.logmessage(opts)
2332 if opts.get('edit'):
2332 if opts.get('edit'):
2333 if message:
2333 if message:
2334 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2334 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2335
2335
2336 parent = q.lookup('qtip')
2336 parent = q.lookup('qtip')
2337 patches = []
2337 patches = []
2338 messages = []
2338 messages = []
2339 for f in files:
2339 for f in files:
2340 p = q.lookup(f)
2340 p = q.lookup(f)
2341 if p in patches or p == parent:
2341 if p in patches or p == parent:
2342 ui.warn(_('Skipping already folded patch %s\n') % p)
2342 ui.warn(_('Skipping already folded patch %s\n') % p)
2343 if q.isapplied(p):
2343 if q.isapplied(p):
2344 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2344 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2345 patches.append(p)
2345 patches.append(p)
2346
2346
2347 for p in patches:
2347 for p in patches:
2348 if not message:
2348 if not message:
2349 ph = patchheader(q.join(p), q.plainmode)
2349 ph = patchheader(q.join(p), q.plainmode)
2350 if ph.message:
2350 if ph.message:
2351 messages.append(ph.message)
2351 messages.append(ph.message)
2352 pf = q.join(p)
2352 pf = q.join(p)
2353 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2353 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2354 if not patchsuccess:
2354 if not patchsuccess:
2355 raise util.Abort(_('error folding patch %s') % p)
2355 raise util.Abort(_('error folding patch %s') % p)
2356
2356
2357 if not message:
2357 if not message:
2358 ph = patchheader(q.join(parent), q.plainmode)
2358 ph = patchheader(q.join(parent), q.plainmode)
2359 message, user = ph.message, ph.user
2359 message, user = ph.message, ph.user
2360 for msg in messages:
2360 for msg in messages:
2361 message.append('* * *')
2361 message.append('* * *')
2362 message.extend(msg)
2362 message.extend(msg)
2363 message = '\n'.join(message)
2363 message = '\n'.join(message)
2364
2364
2365 if opts.get('edit'):
2365 if opts.get('edit'):
2366 message = ui.edit(message, user or ui.username())
2366 message = ui.edit(message, user or ui.username())
2367
2367
2368 diffopts = q.patchopts(q.diffopts(), *patches)
2368 diffopts = q.patchopts(q.diffopts(), *patches)
2369 q.refresh(repo, msg=message, git=diffopts.git)
2369 q.refresh(repo, msg=message, git=diffopts.git)
2370 q.delete(repo, patches, opts)
2370 q.delete(repo, patches, opts)
2371 q.save_dirty()
2371 q.save_dirty()
2372
2372
2373 @command("qgoto",
2373 @command("qgoto",
2374 [('f', 'force', None, _('overwrite any local changes'))],
2374 [('f', 'force', None, _('overwrite any local changes'))],
2375 _('hg qgoto [OPTION]... PATCH'))
2375 _('hg qgoto [OPTION]... PATCH'))
2376 def goto(ui, repo, patch, **opts):
2376 def goto(ui, repo, patch, **opts):
2377 '''push or pop patches until named patch is at top of stack
2377 '''push or pop patches until named patch is at top of stack
2378
2378
2379 Returns 0 on success.'''
2379 Returns 0 on success.'''
2380 q = repo.mq
2380 q = repo.mq
2381 patch = q.lookup(patch)
2381 patch = q.lookup(patch)
2382 if q.isapplied(patch):
2382 if q.isapplied(patch):
2383 ret = q.pop(repo, patch, force=opts.get('force'))
2383 ret = q.pop(repo, patch, force=opts.get('force'))
2384 else:
2384 else:
2385 ret = q.push(repo, patch, force=opts.get('force'))
2385 ret = q.push(repo, patch, force=opts.get('force'))
2386 q.save_dirty()
2386 q.save_dirty()
2387 return ret
2387 return ret
2388
2388
2389 @command("qguard",
2389 @command("qguard",
2390 [('l', 'list', None, _('list all patches and guards')),
2390 [('l', 'list', None, _('list all patches and guards')),
2391 ('n', 'none', None, _('drop all guards'))],
2391 ('n', 'none', None, _('drop all guards'))],
2392 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2392 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2393 def guard(ui, repo, *args, **opts):
2393 def guard(ui, repo, *args, **opts):
2394 '''set or print guards for a patch
2394 '''set or print guards for a patch
2395
2395
2396 Guards control whether a patch can be pushed. A patch with no
2396 Guards control whether a patch can be pushed. A patch with no
2397 guards is always pushed. A patch with a positive guard ("+foo") is
2397 guards is always pushed. A patch with a positive guard ("+foo") is
2398 pushed only if the :hg:`qselect` command has activated it. A patch with
2398 pushed only if the :hg:`qselect` command has activated it. A patch with
2399 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2399 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2400 has activated it.
2400 has activated it.
2401
2401
2402 With no arguments, print the currently active guards.
2402 With no arguments, print the currently active guards.
2403 With arguments, set guards for the named patch.
2403 With arguments, set guards for the named patch.
2404
2404
2405 .. note::
2405 .. note::
2406 Specifying negative guards now requires '--'.
2406 Specifying negative guards now requires '--'.
2407
2407
2408 To set guards on another patch::
2408 To set guards on another patch::
2409
2409
2410 hg qguard other.patch -- +2.6.17 -stable
2410 hg qguard other.patch -- +2.6.17 -stable
2411
2411
2412 Returns 0 on success.
2412 Returns 0 on success.
2413 '''
2413 '''
2414 def status(idx):
2414 def status(idx):
2415 guards = q.series_guards[idx] or ['unguarded']
2415 guards = q.series_guards[idx] or ['unguarded']
2416 if q.series[idx] in applied:
2416 if q.series[idx] in applied:
2417 state = 'applied'
2417 state = 'applied'
2418 elif q.pushable(idx)[0]:
2418 elif q.pushable(idx)[0]:
2419 state = 'unapplied'
2419 state = 'unapplied'
2420 else:
2420 else:
2421 state = 'guarded'
2421 state = 'guarded'
2422 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2422 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2423 ui.write('%s: ' % ui.label(q.series[idx], label))
2423 ui.write('%s: ' % ui.label(q.series[idx], label))
2424
2424
2425 for i, guard in enumerate(guards):
2425 for i, guard in enumerate(guards):
2426 if guard.startswith('+'):
2426 if guard.startswith('+'):
2427 ui.write(guard, label='qguard.positive')
2427 ui.write(guard, label='qguard.positive')
2428 elif guard.startswith('-'):
2428 elif guard.startswith('-'):
2429 ui.write(guard, label='qguard.negative')
2429 ui.write(guard, label='qguard.negative')
2430 else:
2430 else:
2431 ui.write(guard, label='qguard.unguarded')
2431 ui.write(guard, label='qguard.unguarded')
2432 if i != len(guards) - 1:
2432 if i != len(guards) - 1:
2433 ui.write(' ')
2433 ui.write(' ')
2434 ui.write('\n')
2434 ui.write('\n')
2435 q = repo.mq
2435 q = repo.mq
2436 applied = set(p.name for p in q.applied)
2436 applied = set(p.name for p in q.applied)
2437 patch = None
2437 patch = None
2438 args = list(args)
2438 args = list(args)
2439 if opts.get('list'):
2439 if opts.get('list'):
2440 if args or opts.get('none'):
2440 if args or opts.get('none'):
2441 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2441 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2442 for i in xrange(len(q.series)):
2442 for i in xrange(len(q.series)):
2443 status(i)
2443 status(i)
2444 return
2444 return
2445 if not args or args[0][0:1] in '-+':
2445 if not args or args[0][0:1] in '-+':
2446 if not q.applied:
2446 if not q.applied:
2447 raise util.Abort(_('no patches applied'))
2447 raise util.Abort(_('no patches applied'))
2448 patch = q.applied[-1].name
2448 patch = q.applied[-1].name
2449 if patch is None and args[0][0:1] not in '-+':
2449 if patch is None and args[0][0:1] not in '-+':
2450 patch = args.pop(0)
2450 patch = args.pop(0)
2451 if patch is None:
2451 if patch is None:
2452 raise util.Abort(_('no patch to work with'))
2452 raise util.Abort(_('no patch to work with'))
2453 if args or opts.get('none'):
2453 if args or opts.get('none'):
2454 idx = q.find_series(patch)
2454 idx = q.find_series(patch)
2455 if idx is None:
2455 if idx is None:
2456 raise util.Abort(_('no patch named %s') % patch)
2456 raise util.Abort(_('no patch named %s') % patch)
2457 q.set_guards(idx, args)
2457 q.set_guards(idx, args)
2458 q.save_dirty()
2458 q.save_dirty()
2459 else:
2459 else:
2460 status(q.series.index(q.lookup(patch)))
2460 status(q.series.index(q.lookup(patch)))
2461
2461
2462 @command("qheader", [], _('hg qheader [PATCH]'))
2462 @command("qheader", [], _('hg qheader [PATCH]'))
2463 def header(ui, repo, patch=None):
2463 def header(ui, repo, patch=None):
2464 """print the header of the topmost or specified patch
2464 """print the header of the topmost or specified patch
2465
2465
2466 Returns 0 on success."""
2466 Returns 0 on success."""
2467 q = repo.mq
2467 q = repo.mq
2468
2468
2469 if patch:
2469 if patch:
2470 patch = q.lookup(patch)
2470 patch = q.lookup(patch)
2471 else:
2471 else:
2472 if not q.applied:
2472 if not q.applied:
2473 ui.write(_('no patches applied\n'))
2473 ui.write(_('no patches applied\n'))
2474 return 1
2474 return 1
2475 patch = q.lookup('qtip')
2475 patch = q.lookup('qtip')
2476 ph = patchheader(q.join(patch), q.plainmode)
2476 ph = patchheader(q.join(patch), q.plainmode)
2477
2477
2478 ui.write('\n'.join(ph.message) + '\n')
2478 ui.write('\n'.join(ph.message) + '\n')
2479
2479
2480 def lastsavename(path):
2480 def lastsavename(path):
2481 (directory, base) = os.path.split(path)
2481 (directory, base) = os.path.split(path)
2482 names = os.listdir(directory)
2482 names = os.listdir(directory)
2483 namere = re.compile("%s.([0-9]+)" % base)
2483 namere = re.compile("%s.([0-9]+)" % base)
2484 maxindex = None
2484 maxindex = None
2485 maxname = None
2485 maxname = None
2486 for f in names:
2486 for f in names:
2487 m = namere.match(f)
2487 m = namere.match(f)
2488 if m:
2488 if m:
2489 index = int(m.group(1))
2489 index = int(m.group(1))
2490 if maxindex is None or index > maxindex:
2490 if maxindex is None or index > maxindex:
2491 maxindex = index
2491 maxindex = index
2492 maxname = f
2492 maxname = f
2493 if maxname:
2493 if maxname:
2494 return (os.path.join(directory, maxname), maxindex)
2494 return (os.path.join(directory, maxname), maxindex)
2495 return (None, None)
2495 return (None, None)
2496
2496
2497 def savename(path):
2497 def savename(path):
2498 (last, index) = lastsavename(path)
2498 (last, index) = lastsavename(path)
2499 if last is None:
2499 if last is None:
2500 index = 0
2500 index = 0
2501 newpath = path + ".%d" % (index + 1)
2501 newpath = path + ".%d" % (index + 1)
2502 return newpath
2502 return newpath
2503
2503
2504 @command("^qpush",
2504 @command("^qpush",
2505 [('f', 'force', None, _('apply on top of local changes')),
2505 [('f', 'force', None, _('apply on top of local changes')),
2506 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2506 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2507 ('l', 'list', None, _('list patch name in commit text')),
2507 ('l', 'list', None, _('list patch name in commit text')),
2508 ('a', 'all', None, _('apply all patches')),
2508 ('a', 'all', None, _('apply all patches')),
2509 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2509 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2510 ('n', 'name', '',
2510 ('n', 'name', '',
2511 _('merge queue name (DEPRECATED)'), _('NAME')),
2511 _('merge queue name (DEPRECATED)'), _('NAME')),
2512 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2512 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2513 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2513 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2514 def push(ui, repo, patch=None, **opts):
2514 def push(ui, repo, patch=None, **opts):
2515 """push the next patch onto the stack
2515 """push the next patch onto the stack
2516
2516
2517 When -f/--force is applied, all local changes in patched files
2517 When -f/--force is applied, all local changes in patched files
2518 will be lost.
2518 will be lost.
2519
2519
2520 Return 0 on success.
2520 Return 0 on success.
2521 """
2521 """
2522 q = repo.mq
2522 q = repo.mq
2523 mergeq = None
2523 mergeq = None
2524
2524
2525 if opts.get('merge'):
2525 if opts.get('merge'):
2526 if opts.get('name'):
2526 if opts.get('name'):
2527 newpath = repo.join(opts.get('name'))
2527 newpath = repo.join(opts.get('name'))
2528 else:
2528 else:
2529 newpath, i = lastsavename(q.path)
2529 newpath, i = lastsavename(q.path)
2530 if not newpath:
2530 if not newpath:
2531 ui.warn(_("no saved queues found, please use -n\n"))
2531 ui.warn(_("no saved queues found, please use -n\n"))
2532 return 1
2532 return 1
2533 mergeq = queue(ui, repo.join(""), newpath)
2533 mergeq = queue(ui, repo.join(""), newpath)
2534 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2534 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2535 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2535 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2536 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2536 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2537 exact=opts.get('exact'))
2537 exact=opts.get('exact'))
2538 return ret
2538 return ret
2539
2539
2540 @command("^qpop",
2540 @command("^qpop",
2541 [('a', 'all', None, _('pop all patches')),
2541 [('a', 'all', None, _('pop all patches')),
2542 ('n', 'name', '',
2542 ('n', 'name', '',
2543 _('queue name to pop (DEPRECATED)'), _('NAME')),
2543 _('queue name to pop (DEPRECATED)'), _('NAME')),
2544 ('f', 'force', None, _('forget any local changes to patched files'))],
2544 ('f', 'force', None, _('forget any local changes to patched files'))],
2545 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2545 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2546 def pop(ui, repo, patch=None, **opts):
2546 def pop(ui, repo, patch=None, **opts):
2547 """pop the current patch off the stack
2547 """pop the current patch off the stack
2548
2548
2549 By default, pops off the top of the patch stack. If given a patch
2549 By default, pops off the top of the patch stack. If given a patch
2550 name, keeps popping off patches until the named patch is at the
2550 name, keeps popping off patches until the named patch is at the
2551 top of the stack.
2551 top of the stack.
2552
2552
2553 Return 0 on success.
2553 Return 0 on success.
2554 """
2554 """
2555 localupdate = True
2555 localupdate = True
2556 if opts.get('name'):
2556 if opts.get('name'):
2557 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2557 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2558 ui.warn(_('using patch queue: %s\n') % q.path)
2558 ui.warn(_('using patch queue: %s\n') % q.path)
2559 localupdate = False
2559 localupdate = False
2560 else:
2560 else:
2561 q = repo.mq
2561 q = repo.mq
2562 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2562 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2563 all=opts.get('all'))
2563 all=opts.get('all'))
2564 q.save_dirty()
2564 q.save_dirty()
2565 return ret
2565 return ret
2566
2566
2567 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2567 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2568 def rename(ui, repo, patch, name=None, **opts):
2568 def rename(ui, repo, patch, name=None, **opts):
2569 """rename a patch
2569 """rename a patch
2570
2570
2571 With one argument, renames the current patch to PATCH1.
2571 With one argument, renames the current patch to PATCH1.
2572 With two arguments, renames PATCH1 to PATCH2.
2572 With two arguments, renames PATCH1 to PATCH2.
2573
2573
2574 Returns 0 on success."""
2574 Returns 0 on success."""
2575
2575
2576 q = repo.mq
2576 q = repo.mq
2577
2577
2578 if not name:
2578 if not name:
2579 name = patch
2579 name = patch
2580 patch = None
2580 patch = None
2581
2581
2582 if patch:
2582 if patch:
2583 patch = q.lookup(patch)
2583 patch = q.lookup(patch)
2584 else:
2584 else:
2585 if not q.applied:
2585 if not q.applied:
2586 ui.write(_('no patches applied\n'))
2586 ui.write(_('no patches applied\n'))
2587 return
2587 return
2588 patch = q.lookup('qtip')
2588 patch = q.lookup('qtip')
2589 absdest = q.join(name)
2589 absdest = q.join(name)
2590 if os.path.isdir(absdest):
2590 if os.path.isdir(absdest):
2591 name = normname(os.path.join(name, os.path.basename(patch)))
2591 name = normname(os.path.join(name, os.path.basename(patch)))
2592 absdest = q.join(name)
2592 absdest = q.join(name)
2593 q.checkpatchname(name)
2593 q.checkpatchname(name)
2594
2594
2595 ui.note(_('renaming %s to %s\n') % (patch, name))
2595 ui.note(_('renaming %s to %s\n') % (patch, name))
2596 i = q.find_series(patch)
2596 i = q.find_series(patch)
2597 guards = q.guard_re.findall(q.full_series[i])
2597 guards = q.guard_re.findall(q.full_series[i])
2598 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2598 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2599 q.parse_series()
2599 q.parse_series()
2600 q.series_dirty = 1
2600 q.series_dirty = 1
2601
2601
2602 info = q.isapplied(patch)
2602 info = q.isapplied(patch)
2603 if info:
2603 if info:
2604 q.applied[info[0]] = statusentry(info[1], name)
2604 q.applied[info[0]] = statusentry(info[1], name)
2605 q.applied_dirty = 1
2605 q.applied_dirty = 1
2606
2606
2607 destdir = os.path.dirname(absdest)
2607 destdir = os.path.dirname(absdest)
2608 if not os.path.isdir(destdir):
2608 if not os.path.isdir(destdir):
2609 os.makedirs(destdir)
2609 os.makedirs(destdir)
2610 util.rename(q.join(patch), absdest)
2610 util.rename(q.join(patch), absdest)
2611 r = q.qrepo()
2611 r = q.qrepo()
2612 if r and patch in r.dirstate:
2612 if r and patch in r.dirstate:
2613 wctx = r[None]
2613 wctx = r[None]
2614 wlock = r.wlock()
2614 wlock = r.wlock()
2615 try:
2615 try:
2616 if r.dirstate[patch] == 'a':
2616 if r.dirstate[patch] == 'a':
2617 r.dirstate.drop(patch)
2617 r.dirstate.drop(patch)
2618 r.dirstate.add(name)
2618 r.dirstate.add(name)
2619 else:
2619 else:
2620 if r.dirstate[name] == 'r':
2620 if r.dirstate[name] == 'r':
2621 wctx.undelete([name])
2621 wctx.undelete([name])
2622 wctx.copy(patch, name)
2622 wctx.copy(patch, name)
2623 wctx.forget([patch])
2623 wctx.forget([patch])
2624 finally:
2624 finally:
2625 wlock.release()
2625 wlock.release()
2626
2626
2627 q.save_dirty()
2627 q.save_dirty()
2628
2628
2629 @command("qrestore",
2629 @command("qrestore",
2630 [('d', 'delete', None, _('delete save entry')),
2630 [('d', 'delete', None, _('delete save entry')),
2631 ('u', 'update', None, _('update queue working directory'))],
2631 ('u', 'update', None, _('update queue working directory'))],
2632 _('hg qrestore [-d] [-u] REV'))
2632 _('hg qrestore [-d] [-u] REV'))
2633 def restore(ui, repo, rev, **opts):
2633 def restore(ui, repo, rev, **opts):
2634 """restore the queue state saved by a revision (DEPRECATED)
2634 """restore the queue state saved by a revision (DEPRECATED)
2635
2635
2636 This command is deprecated, use :hg:`rebase` instead."""
2636 This command is deprecated, use :hg:`rebase` instead."""
2637 rev = repo.lookup(rev)
2637 rev = repo.lookup(rev)
2638 q = repo.mq
2638 q = repo.mq
2639 q.restore(repo, rev, delete=opts.get('delete'),
2639 q.restore(repo, rev, delete=opts.get('delete'),
2640 qupdate=opts.get('update'))
2640 qupdate=opts.get('update'))
2641 q.save_dirty()
2641 q.save_dirty()
2642 return 0
2642 return 0
2643
2643
2644 @command("qsave",
2644 @command("qsave",
2645 [('c', 'copy', None, _('copy patch directory')),
2645 [('c', 'copy', None, _('copy patch directory')),
2646 ('n', 'name', '',
2646 ('n', 'name', '',
2647 _('copy directory name'), _('NAME')),
2647 _('copy directory name'), _('NAME')),
2648 ('e', 'empty', None, _('clear queue status file')),
2648 ('e', 'empty', None, _('clear queue status file')),
2649 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2649 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2650 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2650 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2651 def save(ui, repo, **opts):
2651 def save(ui, repo, **opts):
2652 """save current queue state (DEPRECATED)
2652 """save current queue state (DEPRECATED)
2653
2653
2654 This command is deprecated, use :hg:`rebase` instead."""
2654 This command is deprecated, use :hg:`rebase` instead."""
2655 q = repo.mq
2655 q = repo.mq
2656 message = cmdutil.logmessage(opts)
2656 message = cmdutil.logmessage(opts)
2657 ret = q.save(repo, msg=message)
2657 ret = q.save(repo, msg=message)
2658 if ret:
2658 if ret:
2659 return ret
2659 return ret
2660 q.save_dirty()
2660 q.save_dirty()
2661 if opts.get('copy'):
2661 if opts.get('copy'):
2662 path = q.path
2662 path = q.path
2663 if opts.get('name'):
2663 if opts.get('name'):
2664 newpath = os.path.join(q.basepath, opts.get('name'))
2664 newpath = os.path.join(q.basepath, opts.get('name'))
2665 if os.path.exists(newpath):
2665 if os.path.exists(newpath):
2666 if not os.path.isdir(newpath):
2666 if not os.path.isdir(newpath):
2667 raise util.Abort(_('destination %s exists and is not '
2667 raise util.Abort(_('destination %s exists and is not '
2668 'a directory') % newpath)
2668 'a directory') % newpath)
2669 if not opts.get('force'):
2669 if not opts.get('force'):
2670 raise util.Abort(_('destination %s exists, '
2670 raise util.Abort(_('destination %s exists, '
2671 'use -f to force') % newpath)
2671 'use -f to force') % newpath)
2672 else:
2672 else:
2673 newpath = savename(path)
2673 newpath = savename(path)
2674 ui.warn(_("copy %s to %s\n") % (path, newpath))
2674 ui.warn(_("copy %s to %s\n") % (path, newpath))
2675 util.copyfiles(path, newpath)
2675 util.copyfiles(path, newpath)
2676 if opts.get('empty'):
2676 if opts.get('empty'):
2677 try:
2677 try:
2678 os.unlink(q.join(q.status_path))
2678 os.unlink(q.join(q.status_path))
2679 except:
2679 except:
2680 pass
2680 pass
2681 return 0
2681 return 0
2682
2682
2683 @command("strip",
2683 @command("strip",
2684 [('f', 'force', None, _('force removal of changesets, discard '
2684 [('f', 'force', None, _('force removal of changesets, discard '
2685 'uncommitted changes (no backup)')),
2685 'uncommitted changes (no backup)')),
2686 ('b', 'backup', None, _('bundle only changesets with local revision'
2686 ('b', 'backup', None, _('bundle only changesets with local revision'
2687 ' number greater than REV which are not'
2687 ' number greater than REV which are not'
2688 ' descendants of REV (DEPRECATED)')),
2688 ' descendants of REV (DEPRECATED)')),
2689 ('n', 'no-backup', None, _('no backups')),
2689 ('n', 'no-backup', None, _('no backups')),
2690 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2690 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2691 ('k', 'keep', None, _("do not modify working copy during strip"))],
2691 ('k', 'keep', None, _("do not modify working copy during strip"))],
2692 _('hg strip [-k] [-f] [-n] REV...'))
2692 _('hg strip [-k] [-f] [-n] REV...'))
2693 def strip(ui, repo, *revs, **opts):
2693 def strip(ui, repo, *revs, **opts):
2694 """strip changesets and all their descendants from the repository
2694 """strip changesets and all their descendants from the repository
2695
2695
2696 The strip command removes the specified changesets and all their
2696 The strip command removes the specified changesets and all their
2697 descendants. If the working directory has uncommitted changes, the
2697 descendants. If the working directory has uncommitted changes, the
2698 operation is aborted unless the --force flag is supplied, in which
2698 operation is aborted unless the --force flag is supplied, in which
2699 case changes will be discarded.
2699 case changes will be discarded.
2700
2700
2701 If a parent of the working directory is stripped, then the working
2701 If a parent of the working directory is stripped, then the working
2702 directory will automatically be updated to the most recent
2702 directory will automatically be updated to the most recent
2703 available ancestor of the stripped parent after the operation
2703 available ancestor of the stripped parent after the operation
2704 completes.
2704 completes.
2705
2705
2706 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2706 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2707 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2707 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2708 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2708 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2709 where BUNDLE is the bundle file created by the strip. Note that
2709 where BUNDLE is the bundle file created by the strip. Note that
2710 the local revision numbers will in general be different after the
2710 the local revision numbers will in general be different after the
2711 restore.
2711 restore.
2712
2712
2713 Use the --no-backup option to discard the backup bundle once the
2713 Use the --no-backup option to discard the backup bundle once the
2714 operation completes.
2714 operation completes.
2715
2715
2716 Return 0 on success.
2716 Return 0 on success.
2717 """
2717 """
2718 backup = 'all'
2718 backup = 'all'
2719 if opts.get('backup'):
2719 if opts.get('backup'):
2720 backup = 'strip'
2720 backup = 'strip'
2721 elif opts.get('no_backup') or opts.get('nobackup'):
2721 elif opts.get('no_backup') or opts.get('nobackup'):
2722 backup = 'none'
2722 backup = 'none'
2723
2723
2724 cl = repo.changelog
2724 cl = repo.changelog
2725 revs = set(scmutil.revrange(repo, revs))
2725 revs = set(scmutil.revrange(repo, revs))
2726 if not revs:
2726 if not revs:
2727 raise util.Abort(_('empty revision set'))
2727 raise util.Abort(_('empty revision set'))
2728
2728
2729 descendants = set(cl.descendants(*revs))
2729 descendants = set(cl.descendants(*revs))
2730 strippedrevs = revs.union(descendants)
2730 strippedrevs = revs.union(descendants)
2731 roots = revs.difference(descendants)
2731 roots = revs.difference(descendants)
2732
2732
2733 update = False
2733 update = False
2734 # if one of the wdir parent is stripped we'll need
2734 # if one of the wdir parent is stripped we'll need
2735 # to update away to an earlier revision
2735 # to update away to an earlier revision
2736 for p in repo.dirstate.parents():
2736 for p in repo.dirstate.parents():
2737 if p != nullid and cl.rev(p) in strippedrevs:
2737 if p != nullid and cl.rev(p) in strippedrevs:
2738 update = True
2738 update = True
2739 break
2739 break
2740
2740
2741 rootnodes = set(cl.node(r) for r in roots)
2741 rootnodes = set(cl.node(r) for r in roots)
2742
2742
2743 q = repo.mq
2743 q = repo.mq
2744 if q.applied:
2744 if q.applied:
2745 # refresh queue state if we're about to strip
2745 # refresh queue state if we're about to strip
2746 # applied patches
2746 # applied patches
2747 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2747 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2748 q.applied_dirty = True
2748 q.applied_dirty = True
2749 start = 0
2749 start = 0
2750 end = len(q.applied)
2750 end = len(q.applied)
2751 for i, statusentry in enumerate(q.applied):
2751 for i, statusentry in enumerate(q.applied):
2752 if statusentry.node in rootnodes:
2752 if statusentry.node in rootnodes:
2753 # if one of the stripped roots is an applied
2753 # if one of the stripped roots is an applied
2754 # patch, only part of the queue is stripped
2754 # patch, only part of the queue is stripped
2755 start = i
2755 start = i
2756 break
2756 break
2757 del q.applied[start:end]
2757 del q.applied[start:end]
2758 q.save_dirty()
2758 q.save_dirty()
2759
2759
2760 revs = list(rootnodes)
2760 revs = list(rootnodes)
2761 if update and opts.get('keep'):
2761 if update and opts.get('keep'):
2762 wlock = repo.wlock()
2762 wlock = repo.wlock()
2763 try:
2763 try:
2764 urev = repo.mq.qparents(repo, revs[0])
2764 urev = repo.mq.qparents(repo, revs[0])
2765 repo.dirstate.rebuild(urev, repo[urev].manifest())
2765 repo.dirstate.rebuild(urev, repo[urev].manifest())
2766 repo.dirstate.write()
2766 repo.dirstate.write()
2767 update = False
2767 update = False
2768 finally:
2768 finally:
2769 wlock.release()
2769 wlock.release()
2770
2770
2771 repo.mq.strip(repo, revs, backup=backup, update=update,
2771 repo.mq.strip(repo, revs, backup=backup, update=update,
2772 force=opts.get('force'))
2772 force=opts.get('force'))
2773 return 0
2773 return 0
2774
2774
2775 @command("qselect",
2775 @command("qselect",
2776 [('n', 'none', None, _('disable all guards')),
2776 [('n', 'none', None, _('disable all guards')),
2777 ('s', 'series', None, _('list all guards in series file')),
2777 ('s', 'series', None, _('list all guards in series file')),
2778 ('', 'pop', None, _('pop to before first guarded applied patch')),
2778 ('', 'pop', None, _('pop to before first guarded applied patch')),
2779 ('', 'reapply', None, _('pop, then reapply patches'))],
2779 ('', 'reapply', None, _('pop, then reapply patches'))],
2780 _('hg qselect [OPTION]... [GUARD]...'))
2780 _('hg qselect [OPTION]... [GUARD]...'))
2781 def select(ui, repo, *args, **opts):
2781 def select(ui, repo, *args, **opts):
2782 '''set or print guarded patches to push
2782 '''set or print guarded patches to push
2783
2783
2784 Use the :hg:`qguard` command to set or print guards on patch, then use
2784 Use the :hg:`qguard` command to set or print guards on patch, then use
2785 qselect to tell mq which guards to use. A patch will be pushed if
2785 qselect to tell mq which guards to use. A patch will be pushed if
2786 it has no guards or any positive guards match the currently
2786 it has no guards or any positive guards match the currently
2787 selected guard, but will not be pushed if any negative guards
2787 selected guard, but will not be pushed if any negative guards
2788 match the current guard. For example::
2788 match the current guard. For example::
2789
2789
2790 qguard foo.patch -- -stable (negative guard)
2790 qguard foo.patch -- -stable (negative guard)
2791 qguard bar.patch +stable (positive guard)
2791 qguard bar.patch +stable (positive guard)
2792 qselect stable
2792 qselect stable
2793
2793
2794 This activates the "stable" guard. mq will skip foo.patch (because
2794 This activates the "stable" guard. mq will skip foo.patch (because
2795 it has a negative match) but push bar.patch (because it has a
2795 it has a negative match) but push bar.patch (because it has a
2796 positive match).
2796 positive match).
2797
2797
2798 With no arguments, prints the currently active guards.
2798 With no arguments, prints the currently active guards.
2799 With one argument, sets the active guard.
2799 With one argument, sets the active guard.
2800
2800
2801 Use -n/--none to deactivate guards (no other arguments needed).
2801 Use -n/--none to deactivate guards (no other arguments needed).
2802 When no guards are active, patches with positive guards are
2802 When no guards are active, patches with positive guards are
2803 skipped and patches with negative guards are pushed.
2803 skipped and patches with negative guards are pushed.
2804
2804
2805 qselect can change the guards on applied patches. It does not pop
2805 qselect can change the guards on applied patches. It does not pop
2806 guarded patches by default. Use --pop to pop back to the last
2806 guarded patches by default. Use --pop to pop back to the last
2807 applied patch that is not guarded. Use --reapply (which implies
2807 applied patch that is not guarded. Use --reapply (which implies
2808 --pop) to push back to the current patch afterwards, but skip
2808 --pop) to push back to the current patch afterwards, but skip
2809 guarded patches.
2809 guarded patches.
2810
2810
2811 Use -s/--series to print a list of all guards in the series file
2811 Use -s/--series to print a list of all guards in the series file
2812 (no other arguments needed). Use -v for more information.
2812 (no other arguments needed). Use -v for more information.
2813
2813
2814 Returns 0 on success.'''
2814 Returns 0 on success.'''
2815
2815
2816 q = repo.mq
2816 q = repo.mq
2817 guards = q.active()
2817 guards = q.active()
2818 if args or opts.get('none'):
2818 if args or opts.get('none'):
2819 old_unapplied = q.unapplied(repo)
2819 old_unapplied = q.unapplied(repo)
2820 old_guarded = [i for i in xrange(len(q.applied)) if
2820 old_guarded = [i for i in xrange(len(q.applied)) if
2821 not q.pushable(i)[0]]
2821 not q.pushable(i)[0]]
2822 q.set_active(args)
2822 q.set_active(args)
2823 q.save_dirty()
2823 q.save_dirty()
2824 if not args:
2824 if not args:
2825 ui.status(_('guards deactivated\n'))
2825 ui.status(_('guards deactivated\n'))
2826 if not opts.get('pop') and not opts.get('reapply'):
2826 if not opts.get('pop') and not opts.get('reapply'):
2827 unapplied = q.unapplied(repo)
2827 unapplied = q.unapplied(repo)
2828 guarded = [i for i in xrange(len(q.applied))
2828 guarded = [i for i in xrange(len(q.applied))
2829 if not q.pushable(i)[0]]
2829 if not q.pushable(i)[0]]
2830 if len(unapplied) != len(old_unapplied):
2830 if len(unapplied) != len(old_unapplied):
2831 ui.status(_('number of unguarded, unapplied patches has '
2831 ui.status(_('number of unguarded, unapplied patches has '
2832 'changed from %d to %d\n') %
2832 'changed from %d to %d\n') %
2833 (len(old_unapplied), len(unapplied)))
2833 (len(old_unapplied), len(unapplied)))
2834 if len(guarded) != len(old_guarded):
2834 if len(guarded) != len(old_guarded):
2835 ui.status(_('number of guarded, applied patches has changed '
2835 ui.status(_('number of guarded, applied patches has changed '
2836 'from %d to %d\n') %
2836 'from %d to %d\n') %
2837 (len(old_guarded), len(guarded)))
2837 (len(old_guarded), len(guarded)))
2838 elif opts.get('series'):
2838 elif opts.get('series'):
2839 guards = {}
2839 guards = {}
2840 noguards = 0
2840 noguards = 0
2841 for gs in q.series_guards:
2841 for gs in q.series_guards:
2842 if not gs:
2842 if not gs:
2843 noguards += 1
2843 noguards += 1
2844 for g in gs:
2844 for g in gs:
2845 guards.setdefault(g, 0)
2845 guards.setdefault(g, 0)
2846 guards[g] += 1
2846 guards[g] += 1
2847 if ui.verbose:
2847 if ui.verbose:
2848 guards['NONE'] = noguards
2848 guards['NONE'] = noguards
2849 guards = guards.items()
2849 guards = guards.items()
2850 guards.sort(key=lambda x: x[0][1:])
2850 guards.sort(key=lambda x: x[0][1:])
2851 if guards:
2851 if guards:
2852 ui.note(_('guards in series file:\n'))
2852 ui.note(_('guards in series file:\n'))
2853 for guard, count in guards:
2853 for guard, count in guards:
2854 ui.note('%2d ' % count)
2854 ui.note('%2d ' % count)
2855 ui.write(guard, '\n')
2855 ui.write(guard, '\n')
2856 else:
2856 else:
2857 ui.note(_('no guards in series file\n'))
2857 ui.note(_('no guards in series file\n'))
2858 else:
2858 else:
2859 if guards:
2859 if guards:
2860 ui.note(_('active guards:\n'))
2860 ui.note(_('active guards:\n'))
2861 for g in guards:
2861 for g in guards:
2862 ui.write(g, '\n')
2862 ui.write(g, '\n')
2863 else:
2863 else:
2864 ui.write(_('no active guards\n'))
2864 ui.write(_('no active guards\n'))
2865 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2865 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2866 popped = False
2866 popped = False
2867 if opts.get('pop') or opts.get('reapply'):
2867 if opts.get('pop') or opts.get('reapply'):
2868 for i in xrange(len(q.applied)):
2868 for i in xrange(len(q.applied)):
2869 pushable, reason = q.pushable(i)
2869 pushable, reason = q.pushable(i)
2870 if not pushable:
2870 if not pushable:
2871 ui.status(_('popping guarded patches\n'))
2871 ui.status(_('popping guarded patches\n'))
2872 popped = True
2872 popped = True
2873 if i == 0:
2873 if i == 0:
2874 q.pop(repo, all=True)
2874 q.pop(repo, all=True)
2875 else:
2875 else:
2876 q.pop(repo, i - 1)
2876 q.pop(repo, i - 1)
2877 break
2877 break
2878 if popped:
2878 if popped:
2879 try:
2879 try:
2880 if reapply:
2880 if reapply:
2881 ui.status(_('reapplying unguarded patches\n'))
2881 ui.status(_('reapplying unguarded patches\n'))
2882 q.push(repo, reapply)
2882 q.push(repo, reapply)
2883 finally:
2883 finally:
2884 q.save_dirty()
2884 q.save_dirty()
2885
2885
2886 @command("qfinish",
2886 @command("qfinish",
2887 [('a', 'applied', None, _('finish all applied changesets'))],
2887 [('a', 'applied', None, _('finish all applied changesets'))],
2888 _('hg qfinish [-a] [REV]...'))
2888 _('hg qfinish [-a] [REV]...'))
2889 def finish(ui, repo, *revrange, **opts):
2889 def finish(ui, repo, *revrange, **opts):
2890 """move applied patches into repository history
2890 """move applied patches into repository history
2891
2891
2892 Finishes the specified revisions (corresponding to applied
2892 Finishes the specified revisions (corresponding to applied
2893 patches) by moving them out of mq control into regular repository
2893 patches) by moving them out of mq control into regular repository
2894 history.
2894 history.
2895
2895
2896 Accepts a revision range or the -a/--applied option. If --applied
2896 Accepts a revision range or the -a/--applied option. If --applied
2897 is specified, all applied mq revisions are removed from mq
2897 is specified, all applied mq revisions are removed from mq
2898 control. Otherwise, the given revisions must be at the base of the
2898 control. Otherwise, the given revisions must be at the base of the
2899 stack of applied patches.
2899 stack of applied patches.
2900
2900
2901 This can be especially useful if your changes have been applied to
2901 This can be especially useful if your changes have been applied to
2902 an upstream repository, or if you are about to push your changes
2902 an upstream repository, or if you are about to push your changes
2903 to upstream.
2903 to upstream.
2904
2904
2905 Returns 0 on success.
2905 Returns 0 on success.
2906 """
2906 """
2907 if not opts.get('applied') and not revrange:
2907 if not opts.get('applied') and not revrange:
2908 raise util.Abort(_('no revisions specified'))
2908 raise util.Abort(_('no revisions specified'))
2909 elif opts.get('applied'):
2909 elif opts.get('applied'):
2910 revrange = ('qbase::qtip',) + revrange
2910 revrange = ('qbase::qtip',) + revrange
2911
2911
2912 q = repo.mq
2912 q = repo.mq
2913 if not q.applied:
2913 if not q.applied:
2914 ui.status(_('no patches applied\n'))
2914 ui.status(_('no patches applied\n'))
2915 return 0
2915 return 0
2916
2916
2917 revs = scmutil.revrange(repo, revrange)
2917 revs = scmutil.revrange(repo, revrange)
2918 q.finish(repo, revs)
2918 q.finish(repo, revs)
2919 q.save_dirty()
2919 q.save_dirty()
2920 return 0
2920 return 0
2921
2921
2922 @command("qqueue",
2922 @command("qqueue",
2923 [('l', 'list', False, _('list all available queues')),
2923 [('l', 'list', False, _('list all available queues')),
2924 ('c', 'create', False, _('create new queue')),
2924 ('c', 'create', False, _('create new queue')),
2925 ('', 'rename', False, _('rename active queue')),
2925 ('', 'rename', False, _('rename active queue')),
2926 ('', 'delete', False, _('delete reference to queue')),
2926 ('', 'delete', False, _('delete reference to queue')),
2927 ('', 'purge', False, _('delete queue, and remove patch dir')),
2927 ('', 'purge', False, _('delete queue, and remove patch dir')),
2928 ],
2928 ],
2929 _('[OPTION] [QUEUE]'))
2929 _('[OPTION] [QUEUE]'))
2930 def qqueue(ui, repo, name=None, **opts):
2930 def qqueue(ui, repo, name=None, **opts):
2931 '''manage multiple patch queues
2931 '''manage multiple patch queues
2932
2932
2933 Supports switching between different patch queues, as well as creating
2933 Supports switching between different patch queues, as well as creating
2934 new patch queues and deleting existing ones.
2934 new patch queues and deleting existing ones.
2935
2935
2936 Omitting a queue name or specifying -l/--list will show you the registered
2936 Omitting a queue name or specifying -l/--list will show you the registered
2937 queues - by default the "normal" patches queue is registered. The currently
2937 queues - by default the "normal" patches queue is registered. The currently
2938 active queue will be marked with "(active)".
2938 active queue will be marked with "(active)".
2939
2939
2940 To create a new queue, use -c/--create. The queue is automatically made
2940 To create a new queue, use -c/--create. The queue is automatically made
2941 active, except in the case where there are applied patches from the
2941 active, except in the case where there are applied patches from the
2942 currently active queue in the repository. Then the queue will only be
2942 currently active queue in the repository. Then the queue will only be
2943 created and switching will fail.
2943 created and switching will fail.
2944
2944
2945 To delete an existing queue, use --delete. You cannot delete the currently
2945 To delete an existing queue, use --delete. You cannot delete the currently
2946 active queue.
2946 active queue.
2947
2947
2948 Returns 0 on success.
2948 Returns 0 on success.
2949 '''
2949 '''
2950
2950
2951 q = repo.mq
2951 q = repo.mq
2952
2952
2953 _defaultqueue = 'patches'
2953 _defaultqueue = 'patches'
2954 _allqueues = 'patches.queues'
2954 _allqueues = 'patches.queues'
2955 _activequeue = 'patches.queue'
2955 _activequeue = 'patches.queue'
2956
2956
2957 def _getcurrent():
2957 def _getcurrent():
2958 cur = os.path.basename(q.path)
2958 cur = os.path.basename(q.path)
2959 if cur.startswith('patches-'):
2959 if cur.startswith('patches-'):
2960 cur = cur[8:]
2960 cur = cur[8:]
2961 return cur
2961 return cur
2962
2962
2963 def _noqueues():
2963 def _noqueues():
2964 try:
2964 try:
2965 fh = repo.opener(_allqueues, 'r')
2965 fh = repo.opener(_allqueues, 'r')
2966 fh.close()
2966 fh.close()
2967 except IOError:
2967 except IOError:
2968 return True
2968 return True
2969
2969
2970 return False
2970 return False
2971
2971
2972 def _getqueues():
2972 def _getqueues():
2973 current = _getcurrent()
2973 current = _getcurrent()
2974
2974
2975 try:
2975 try:
2976 fh = repo.opener(_allqueues, 'r')
2976 fh = repo.opener(_allqueues, 'r')
2977 queues = [queue.strip() for queue in fh if queue.strip()]
2977 queues = [queue.strip() for queue in fh if queue.strip()]
2978 fh.close()
2978 fh.close()
2979 if current not in queues:
2979 if current not in queues:
2980 queues.append(current)
2980 queues.append(current)
2981 except IOError:
2981 except IOError:
2982 queues = [_defaultqueue]
2982 queues = [_defaultqueue]
2983
2983
2984 return sorted(queues)
2984 return sorted(queues)
2985
2985
2986 def _setactive(name):
2986 def _setactive(name):
2987 if q.applied:
2987 if q.applied:
2988 raise util.Abort(_('patches applied - cannot set new queue active'))
2988 raise util.Abort(_('patches applied - cannot set new queue active'))
2989 _setactivenocheck(name)
2989 _setactivenocheck(name)
2990
2990
2991 def _setactivenocheck(name):
2991 def _setactivenocheck(name):
2992 fh = repo.opener(_activequeue, 'w')
2992 fh = repo.opener(_activequeue, 'w')
2993 if name != 'patches':
2993 if name != 'patches':
2994 fh.write(name)
2994 fh.write(name)
2995 fh.close()
2995 fh.close()
2996
2996
2997 def _addqueue(name):
2997 def _addqueue(name):
2998 fh = repo.opener(_allqueues, 'a')
2998 fh = repo.opener(_allqueues, 'a')
2999 fh.write('%s\n' % (name,))
2999 fh.write('%s\n' % (name,))
3000 fh.close()
3000 fh.close()
3001
3001
3002 def _queuedir(name):
3002 def _queuedir(name):
3003 if name == 'patches':
3003 if name == 'patches':
3004 return repo.join('patches')
3004 return repo.join('patches')
3005 else:
3005 else:
3006 return repo.join('patches-' + name)
3006 return repo.join('patches-' + name)
3007
3007
3008 def _validname(name):
3008 def _validname(name):
3009 for n in name:
3009 for n in name:
3010 if n in ':\\/.':
3010 if n in ':\\/.':
3011 return False
3011 return False
3012 return True
3012 return True
3013
3013
3014 def _delete(name):
3014 def _delete(name):
3015 if name not in existing:
3015 if name not in existing:
3016 raise util.Abort(_('cannot delete queue that does not exist'))
3016 raise util.Abort(_('cannot delete queue that does not exist'))
3017
3017
3018 current = _getcurrent()
3018 current = _getcurrent()
3019
3019
3020 if name == current:
3020 if name == current:
3021 raise util.Abort(_('cannot delete currently active queue'))
3021 raise util.Abort(_('cannot delete currently active queue'))
3022
3022
3023 fh = repo.opener('patches.queues.new', 'w')
3023 fh = repo.opener('patches.queues.new', 'w')
3024 for queue in existing:
3024 for queue in existing:
3025 if queue == name:
3025 if queue == name:
3026 continue
3026 continue
3027 fh.write('%s\n' % (queue,))
3027 fh.write('%s\n' % (queue,))
3028 fh.close()
3028 fh.close()
3029 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3029 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3030
3030
3031 if not name or opts.get('list'):
3031 if not name or opts.get('list'):
3032 current = _getcurrent()
3032 current = _getcurrent()
3033 for queue in _getqueues():
3033 for queue in _getqueues():
3034 ui.write('%s' % (queue,))
3034 ui.write('%s' % (queue,))
3035 if queue == current and not ui.quiet:
3035 if queue == current and not ui.quiet:
3036 ui.write(_(' (active)\n'))
3036 ui.write(_(' (active)\n'))
3037 else:
3037 else:
3038 ui.write('\n')
3038 ui.write('\n')
3039 return
3039 return
3040
3040
3041 if not _validname(name):
3041 if not _validname(name):
3042 raise util.Abort(
3042 raise util.Abort(
3043 _('invalid queue name, may not contain the characters ":\\/."'))
3043 _('invalid queue name, may not contain the characters ":\\/."'))
3044
3044
3045 existing = _getqueues()
3045 existing = _getqueues()
3046
3046
3047 if opts.get('create'):
3047 if opts.get('create'):
3048 if name in existing:
3048 if name in existing:
3049 raise util.Abort(_('queue "%s" already exists') % name)
3049 raise util.Abort(_('queue "%s" already exists') % name)
3050 if _noqueues():
3050 if _noqueues():
3051 _addqueue(_defaultqueue)
3051 _addqueue(_defaultqueue)
3052 _addqueue(name)
3052 _addqueue(name)
3053 _setactive(name)
3053 _setactive(name)
3054 elif opts.get('rename'):
3054 elif opts.get('rename'):
3055 current = _getcurrent()
3055 current = _getcurrent()
3056 if name == current:
3056 if name == current:
3057 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3057 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3058 if name in existing:
3058 if name in existing:
3059 raise util.Abort(_('queue "%s" already exists') % name)
3059 raise util.Abort(_('queue "%s" already exists') % name)
3060
3060
3061 olddir = _queuedir(current)
3061 olddir = _queuedir(current)
3062 newdir = _queuedir(name)
3062 newdir = _queuedir(name)
3063
3063
3064 if os.path.exists(newdir):
3064 if os.path.exists(newdir):
3065 raise util.Abort(_('non-queue directory "%s" already exists') %
3065 raise util.Abort(_('non-queue directory "%s" already exists') %
3066 newdir)
3066 newdir)
3067
3067
3068 fh = repo.opener('patches.queues.new', 'w')
3068 fh = repo.opener('patches.queues.new', 'w')
3069 for queue in existing:
3069 for queue in existing:
3070 if queue == current:
3070 if queue == current:
3071 fh.write('%s\n' % (name,))
3071 fh.write('%s\n' % (name,))
3072 if os.path.exists(olddir):
3072 if os.path.exists(olddir):
3073 util.rename(olddir, newdir)
3073 util.rename(olddir, newdir)
3074 else:
3074 else:
3075 fh.write('%s\n' % (queue,))
3075 fh.write('%s\n' % (queue,))
3076 fh.close()
3076 fh.close()
3077 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3077 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3078 _setactivenocheck(name)
3078 _setactivenocheck(name)
3079 elif opts.get('delete'):
3079 elif opts.get('delete'):
3080 _delete(name)
3080 _delete(name)
3081 elif opts.get('purge'):
3081 elif opts.get('purge'):
3082 if name in existing:
3082 if name in existing:
3083 _delete(name)
3083 _delete(name)
3084 qdir = _queuedir(name)
3084 qdir = _queuedir(name)
3085 if os.path.exists(qdir):
3085 if os.path.exists(qdir):
3086 shutil.rmtree(qdir)
3086 shutil.rmtree(qdir)
3087 else:
3087 else:
3088 if name not in existing:
3088 if name not in existing:
3089 raise util.Abort(_('use --create to create a new queue'))
3089 raise util.Abort(_('use --create to create a new queue'))
3090 _setactive(name)
3090 _setactive(name)
3091
3091
3092 def reposetup(ui, repo):
3092 def reposetup(ui, repo):
3093 class mqrepo(repo.__class__):
3093 class mqrepo(repo.__class__):
3094 @util.propertycache
3094 @util.propertycache
3095 def mq(self):
3095 def mq(self):
3096 return queue(self.ui, self.join(""))
3096 return queue(self.ui, self.join(""))
3097
3097
3098 def abort_if_wdir_patched(self, errmsg, force=False):
3098 def abort_if_wdir_patched(self, errmsg, force=False):
3099 if self.mq.applied and not force:
3099 if self.mq.applied and not force:
3100 parents = self.dirstate.parents()
3100 parents = self.dirstate.parents()
3101 patches = [s.node for s in self.mq.applied]
3101 patches = [s.node for s in self.mq.applied]
3102 if parents[0] in patches or parents[1] in patches:
3102 if parents[0] in patches or parents[1] in patches:
3103 raise util.Abort(errmsg)
3103 raise util.Abort(errmsg)
3104
3104
3105 def commit(self, text="", user=None, date=None, match=None,
3105 def commit(self, text="", user=None, date=None, match=None,
3106 force=False, editor=False, extra={}):
3106 force=False, editor=False, extra={}):
3107 self.abort_if_wdir_patched(
3107 self.abort_if_wdir_patched(
3108 _('cannot commit over an applied mq patch'),
3108 _('cannot commit over an applied mq patch'),
3109 force)
3109 force)
3110
3110
3111 return super(mqrepo, self).commit(text, user, date, match, force,
3111 return super(mqrepo, self).commit(text, user, date, match, force,
3112 editor, extra)
3112 editor, extra)
3113
3113
3114 def checkpush(self, force, revs):
3114 def checkpush(self, force, revs):
3115 if self.mq.applied and not force:
3115 if self.mq.applied and not force:
3116 haspatches = True
3116 haspatches = True
3117 if revs:
3117 if revs:
3118 # Assume applied patches have no non-patch descendants
3118 # Assume applied patches have no non-patch descendants
3119 # and are not on remote already. If they appear in the
3119 # and are not on remote already. If they appear in the
3120 # set of resolved 'revs', bail out.
3120 # set of resolved 'revs', bail out.
3121 applied = set(e.node for e in self.mq.applied)
3121 applied = set(e.node for e in self.mq.applied)
3122 haspatches = bool([n for n in revs if n in applied])
3122 haspatches = bool([n for n in revs if n in applied])
3123 if haspatches:
3123 if haspatches:
3124 raise util.Abort(_('source has mq patches applied'))
3124 raise util.Abort(_('source has mq patches applied'))
3125 super(mqrepo, self).checkpush(force, revs)
3125 super(mqrepo, self).checkpush(force, revs)
3126
3126
3127 def _findtags(self):
3127 def _findtags(self):
3128 '''augment tags from base class with patch tags'''
3128 '''augment tags from base class with patch tags'''
3129 result = super(mqrepo, self)._findtags()
3129 result = super(mqrepo, self)._findtags()
3130
3130
3131 q = self.mq
3131 q = self.mq
3132 if not q.applied:
3132 if not q.applied:
3133 return result
3133 return result
3134
3134
3135 mqtags = [(patch.node, patch.name) for patch in q.applied]
3135 mqtags = [(patch.node, patch.name) for patch in q.applied]
3136
3136
3137 try:
3137 try:
3138 self.changelog.rev(mqtags[-1][0])
3138 self.changelog.rev(mqtags[-1][0])
3139 except error.RepoLookupError:
3139 except error.RepoLookupError:
3140 self.ui.warn(_('mq status file refers to unknown node %s\n')
3140 self.ui.warn(_('mq status file refers to unknown node %s\n')
3141 % short(mqtags[-1][0]))
3141 % short(mqtags[-1][0]))
3142 return result
3142 return result
3143
3143
3144 mqtags.append((mqtags[-1][0], 'qtip'))
3144 mqtags.append((mqtags[-1][0], 'qtip'))
3145 mqtags.append((mqtags[0][0], 'qbase'))
3145 mqtags.append((mqtags[0][0], 'qbase'))
3146 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3146 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3147 tags = result[0]
3147 tags = result[0]
3148 for patch in mqtags:
3148 for patch in mqtags:
3149 if patch[1] in tags:
3149 if patch[1] in tags:
3150 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3150 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3151 % patch[1])
3151 % patch[1])
3152 else:
3152 else:
3153 tags[patch[1]] = patch[0]
3153 tags[patch[1]] = patch[0]
3154
3154
3155 return result
3155 return result
3156
3156
3157 def _branchtags(self, partial, lrev):
3157 def _branchtags(self, partial, lrev):
3158 q = self.mq
3158 q = self.mq
3159 if not q.applied:
3159 if not q.applied:
3160 return super(mqrepo, self)._branchtags(partial, lrev)
3160 return super(mqrepo, self)._branchtags(partial, lrev)
3161
3161
3162 cl = self.changelog
3162 cl = self.changelog
3163 qbasenode = q.applied[0].node
3163 qbasenode = q.applied[0].node
3164 try:
3164 try:
3165 qbase = cl.rev(qbasenode)
3165 qbase = cl.rev(qbasenode)
3166 except error.LookupError:
3166 except error.LookupError:
3167 self.ui.warn(_('mq status file refers to unknown node %s\n')
3167 self.ui.warn(_('mq status file refers to unknown node %s\n')
3168 % short(qbasenode))
3168 % short(qbasenode))
3169 return super(mqrepo, self)._branchtags(partial, lrev)
3169 return super(mqrepo, self)._branchtags(partial, lrev)
3170
3170
3171 start = lrev + 1
3171 start = lrev + 1
3172 if start < qbase:
3172 if start < qbase:
3173 # update the cache (excluding the patches) and save it
3173 # update the cache (excluding the patches) and save it
3174 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3174 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3175 self._updatebranchcache(partial, ctxgen)
3175 self._updatebranchcache(partial, ctxgen)
3176 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3176 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3177 start = qbase
3177 start = qbase
3178 # if start = qbase, the cache is as updated as it should be.
3178 # if start = qbase, the cache is as updated as it should be.
3179 # if start > qbase, the cache includes (part of) the patches.
3179 # if start > qbase, the cache includes (part of) the patches.
3180 # we might as well use it, but we won't save it.
3180 # we might as well use it, but we won't save it.
3181
3181
3182 # update the cache up to the tip
3182 # update the cache up to the tip
3183 ctxgen = (self[r] for r in xrange(start, len(cl)))
3183 ctxgen = (self[r] for r in xrange(start, len(cl)))
3184 self._updatebranchcache(partial, ctxgen)
3184 self._updatebranchcache(partial, ctxgen)
3185
3185
3186 return partial
3186 return partial
3187
3187
3188 if repo.local():
3188 if repo.local():
3189 repo.__class__ = mqrepo
3189 repo.__class__ = mqrepo
3190
3190
3191 def mqimport(orig, ui, repo, *args, **kwargs):
3191 def mqimport(orig, ui, repo, *args, **kwargs):
3192 if (hasattr(repo, 'abort_if_wdir_patched')
3192 if (hasattr(repo, 'abort_if_wdir_patched')
3193 and not kwargs.get('no_commit', False)):
3193 and not kwargs.get('no_commit', False)):
3194 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3194 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3195 kwargs.get('force'))
3195 kwargs.get('force'))
3196 return orig(ui, repo, *args, **kwargs)
3196 return orig(ui, repo, *args, **kwargs)
3197
3197
3198 def mqinit(orig, ui, *args, **kwargs):
3198 def mqinit(orig, ui, *args, **kwargs):
3199 mq = kwargs.pop('mq', None)
3199 mq = kwargs.pop('mq', None)
3200
3200
3201 if not mq:
3201 if not mq:
3202 return orig(ui, *args, **kwargs)
3202 return orig(ui, *args, **kwargs)
3203
3203
3204 if args:
3204 if args:
3205 repopath = args[0]
3205 repopath = args[0]
3206 if not hg.islocal(repopath):
3206 if not hg.islocal(repopath):
3207 raise util.Abort(_('only a local queue repository '
3207 raise util.Abort(_('only a local queue repository '
3208 'may be initialized'))
3208 'may be initialized'))
3209 else:
3209 else:
3210 repopath = cmdutil.findrepo(os.getcwd())
3210 repopath = cmdutil.findrepo(os.getcwd())
3211 if not repopath:
3211 if not repopath:
3212 raise util.Abort(_('there is no Mercurial repository here '
3212 raise util.Abort(_('there is no Mercurial repository here '
3213 '(.hg not found)'))
3213 '(.hg not found)'))
3214 repo = hg.repository(ui, repopath)
3214 repo = hg.repository(ui, repopath)
3215 return qinit(ui, repo, True)
3215 return qinit(ui, repo, True)
3216
3216
3217 def mqcommand(orig, ui, repo, *args, **kwargs):
3217 def mqcommand(orig, ui, repo, *args, **kwargs):
3218 """Add --mq option to operate on patch repository instead of main"""
3218 """Add --mq option to operate on patch repository instead of main"""
3219
3219
3220 # some commands do not like getting unknown options
3220 # some commands do not like getting unknown options
3221 mq = kwargs.pop('mq', None)
3221 mq = kwargs.pop('mq', None)
3222
3222
3223 if not mq:
3223 if not mq:
3224 return orig(ui, repo, *args, **kwargs)
3224 return orig(ui, repo, *args, **kwargs)
3225
3225
3226 q = repo.mq
3226 q = repo.mq
3227 r = q.qrepo()
3227 r = q.qrepo()
3228 if not r:
3228 if not r:
3229 raise util.Abort(_('no queue repository'))
3229 raise util.Abort(_('no queue repository'))
3230 return orig(r.ui, r, *args, **kwargs)
3230 return orig(r.ui, r, *args, **kwargs)
3231
3231
3232 def summary(orig, ui, repo, *args, **kwargs):
3232 def summary(orig, ui, repo, *args, **kwargs):
3233 r = orig(ui, repo, *args, **kwargs)
3233 r = orig(ui, repo, *args, **kwargs)
3234 q = repo.mq
3234 q = repo.mq
3235 m = []
3235 m = []
3236 a, u = len(q.applied), len(q.unapplied(repo))
3236 a, u = len(q.applied), len(q.unapplied(repo))
3237 if a:
3237 if a:
3238 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3238 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3239 if u:
3239 if u:
3240 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3240 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3241 if m:
3241 if m:
3242 ui.write("mq: %s\n" % ', '.join(m))
3242 ui.write("mq: %s\n" % ', '.join(m))
3243 else:
3243 else:
3244 ui.note(_("mq: (empty queue)\n"))
3244 ui.note(_("mq: (empty queue)\n"))
3245 return r
3245 return r
3246
3246
3247 def revsetmq(repo, subset, x):
3247 def revsetmq(repo, subset, x):
3248 """``mq()``
3248 """``mq()``
3249 Changesets managed by MQ.
3249 Changesets managed by MQ.
3250 """
3250 """
3251 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3251 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3252 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3252 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3253 return [r for r in subset if r in applied]
3253 return [r for r in subset if r in applied]
3254
3254
3255 def extsetup(ui):
3255 def extsetup(ui):
3256 revset.symbols['mq'] = revsetmq
3256 revset.symbols['mq'] = revsetmq
3257
3257
3258 # tell hggettext to extract docstrings from these functions:
3258 # tell hggettext to extract docstrings from these functions:
3259 i18nfunctions = [revsetmq]
3259 i18nfunctions = [revsetmq]
3260
3260
3261 def uisetup(ui):
3261 def uisetup(ui):
3262 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3262 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3263
3263
3264 extensions.wrapcommand(commands.table, 'import', mqimport)
3264 extensions.wrapcommand(commands.table, 'import', mqimport)
3265 extensions.wrapcommand(commands.table, 'summary', summary)
3265 extensions.wrapcommand(commands.table, 'summary', summary)
3266
3266
3267 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3267 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3268 entry[1].extend(mqopt)
3268 entry[1].extend(mqopt)
3269
3269
3270 nowrap = set(commands.norepo.split(" "))
3270 nowrap = set(commands.norepo.split(" "))
3271
3271
3272 def dotable(cmdtable):
3272 def dotable(cmdtable):
3273 for cmd in cmdtable.keys():
3273 for cmd in cmdtable.keys():
3274 cmd = cmdutil.parsealiases(cmd)[0]
3274 cmd = cmdutil.parsealiases(cmd)[0]
3275 if cmd in nowrap:
3275 if cmd in nowrap:
3276 continue
3276 continue
3277 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3277 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3278 entry[1].extend(mqopt)
3278 entry[1].extend(mqopt)
3279
3279
3280 dotable(commands.table)
3280 dotable(commands.table)
3281
3281
3282 for extname, extmodule in extensions.extensions():
3282 for extname, extmodule in extensions.extensions():
3283 if extmodule.__file__ != __file__:
3283 if extmodule.__file__ != __file__:
3284 dotable(getattr(extmodule, 'cmdtable', {}))
3284 dotable(getattr(extmodule, 'cmdtable', {}))
3285
3285
3286
3286
3287 colortable = {'qguard.negative': 'red',
3287 colortable = {'qguard.negative': 'red',
3288 'qguard.positive': 'yellow',
3288 'qguard.positive': 'yellow',
3289 'qguard.unguarded': 'green',
3289 'qguard.unguarded': 'green',
3290 'qseries.applied': 'blue bold underline',
3290 'qseries.applied': 'blue bold underline',
3291 'qseries.guarded': 'black bold',
3291 'qseries.guarded': 'black bold',
3292 'qseries.missing': 'red bold',
3292 'qseries.missing': 'red bold',
3293 'qseries.unapplied': 'black bold'}
3293 'qseries.unapplied': 'black bold'}
@@ -1,632 +1,632 b''
1 # Patch transplanting extension for Mercurial
1 # Patch transplanting extension for Mercurial
2 #
2 #
3 # Copyright 2006, 2007 Brendan Cully <brendan@kublai.com>
3 # Copyright 2006, 2007 Brendan Cully <brendan@kublai.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 '''command to transplant changesets from another branch
8 '''command to transplant changesets from another branch
9
9
10 This extension allows you to transplant patches from another branch.
10 This extension allows you to transplant patches from another branch.
11
11
12 Transplanted patches are recorded in .hg/transplant/transplants, as a
12 Transplanted patches are recorded in .hg/transplant/transplants, as a
13 map from a changeset hash to its hash in the source repository.
13 map from a changeset hash to its hash in the source repository.
14 '''
14 '''
15
15
16 from mercurial.i18n import _
16 from mercurial.i18n import _
17 import os, tempfile
17 import os, tempfile
18 from mercurial.node import short
18 from mercurial.node import short
19 from mercurial import bundlerepo, hg, merge, match
19 from mercurial import bundlerepo, hg, merge, match
20 from mercurial import patch, revlog, scmutil, util, error, cmdutil
20 from mercurial import patch, revlog, scmutil, util, error, cmdutil
21 from mercurial import revset, templatekw
21 from mercurial import revset, templatekw
22
22
23 cmdtable = {}
23 cmdtable = {}
24 command = cmdutil.command(cmdtable)
24 command = cmdutil.command(cmdtable)
25
25
26 class transplantentry(object):
26 class transplantentry(object):
27 def __init__(self, lnode, rnode):
27 def __init__(self, lnode, rnode):
28 self.lnode = lnode
28 self.lnode = lnode
29 self.rnode = rnode
29 self.rnode = rnode
30
30
31 class transplants(object):
31 class transplants(object):
32 def __init__(self, path=None, transplantfile=None, opener=None):
32 def __init__(self, path=None, transplantfile=None, opener=None):
33 self.path = path
33 self.path = path
34 self.transplantfile = transplantfile
34 self.transplantfile = transplantfile
35 self.opener = opener
35 self.opener = opener
36
36
37 if not opener:
37 if not opener:
38 self.opener = scmutil.opener(self.path)
38 self.opener = scmutil.opener(self.path)
39 self.transplants = {}
39 self.transplants = {}
40 self.dirty = False
40 self.dirty = False
41 self.read()
41 self.read()
42
42
43 def read(self):
43 def read(self):
44 abspath = os.path.join(self.path, self.transplantfile)
44 abspath = os.path.join(self.path, self.transplantfile)
45 if self.transplantfile and os.path.exists(abspath):
45 if self.transplantfile and os.path.exists(abspath):
46 for line in self.opener.read(self.transplantfile).splitlines():
46 for line in self.opener.read(self.transplantfile).splitlines():
47 lnode, rnode = map(revlog.bin, line.split(':'))
47 lnode, rnode = map(revlog.bin, line.split(':'))
48 list = self.transplants.setdefault(rnode, [])
48 list = self.transplants.setdefault(rnode, [])
49 list.append(transplantentry(lnode, rnode))
49 list.append(transplantentry(lnode, rnode))
50
50
51 def write(self):
51 def write(self):
52 if self.dirty and self.transplantfile:
52 if self.dirty and self.transplantfile:
53 if not os.path.isdir(self.path):
53 if not os.path.isdir(self.path):
54 os.mkdir(self.path)
54 os.mkdir(self.path)
55 fp = self.opener(self.transplantfile, 'w')
55 fp = self.opener(self.transplantfile, 'w')
56 for list in self.transplants.itervalues():
56 for list in self.transplants.itervalues():
57 for t in list:
57 for t in list:
58 l, r = map(revlog.hex, (t.lnode, t.rnode))
58 l, r = map(revlog.hex, (t.lnode, t.rnode))
59 fp.write(l + ':' + r + '\n')
59 fp.write(l + ':' + r + '\n')
60 fp.close()
60 fp.close()
61 self.dirty = False
61 self.dirty = False
62
62
63 def get(self, rnode):
63 def get(self, rnode):
64 return self.transplants.get(rnode) or []
64 return self.transplants.get(rnode) or []
65
65
66 def set(self, lnode, rnode):
66 def set(self, lnode, rnode):
67 list = self.transplants.setdefault(rnode, [])
67 list = self.transplants.setdefault(rnode, [])
68 list.append(transplantentry(lnode, rnode))
68 list.append(transplantentry(lnode, rnode))
69 self.dirty = True
69 self.dirty = True
70
70
71 def remove(self, transplant):
71 def remove(self, transplant):
72 list = self.transplants.get(transplant.rnode)
72 list = self.transplants.get(transplant.rnode)
73 if list:
73 if list:
74 del list[list.index(transplant)]
74 del list[list.index(transplant)]
75 self.dirty = True
75 self.dirty = True
76
76
77 class transplanter(object):
77 class transplanter(object):
78 def __init__(self, ui, repo):
78 def __init__(self, ui, repo):
79 self.ui = ui
79 self.ui = ui
80 self.path = repo.join('transplant')
80 self.path = repo.join('transplant')
81 self.opener = scmutil.opener(self.path)
81 self.opener = scmutil.opener(self.path)
82 self.transplants = transplants(self.path, 'transplants',
82 self.transplants = transplants(self.path, 'transplants',
83 opener=self.opener)
83 opener=self.opener)
84
84
85 def applied(self, repo, node, parent):
85 def applied(self, repo, node, parent):
86 '''returns True if a node is already an ancestor of parent
86 '''returns True if a node is already an ancestor of parent
87 or has already been transplanted'''
87 or has already been transplanted'''
88 if hasnode(repo, node):
88 if hasnode(repo, node):
89 if node in repo.changelog.reachable(parent, stop=node):
89 if node in repo.changelog.reachable(parent, stop=node):
90 return True
90 return True
91 for t in self.transplants.get(node):
91 for t in self.transplants.get(node):
92 # it might have been stripped
92 # it might have been stripped
93 if not hasnode(repo, t.lnode):
93 if not hasnode(repo, t.lnode):
94 self.transplants.remove(t)
94 self.transplants.remove(t)
95 return False
95 return False
96 if t.lnode in repo.changelog.reachable(parent, stop=t.lnode):
96 if t.lnode in repo.changelog.reachable(parent, stop=t.lnode):
97 return True
97 return True
98 return False
98 return False
99
99
100 def apply(self, repo, source, revmap, merges, opts={}):
100 def apply(self, repo, source, revmap, merges, opts={}):
101 '''apply the revisions in revmap one by one in revision order'''
101 '''apply the revisions in revmap one by one in revision order'''
102 revs = sorted(revmap)
102 revs = sorted(revmap)
103 p1, p2 = repo.dirstate.parents()
103 p1, p2 = repo.dirstate.parents()
104 pulls = []
104 pulls = []
105 diffopts = patch.diffopts(self.ui, opts)
105 diffopts = patch.diffopts(self.ui, opts)
106 diffopts.git = True
106 diffopts.git = True
107
107
108 lock = wlock = None
108 lock = wlock = None
109 try:
109 try:
110 wlock = repo.wlock()
110 wlock = repo.wlock()
111 lock = repo.lock()
111 lock = repo.lock()
112 for rev in revs:
112 for rev in revs:
113 node = revmap[rev]
113 node = revmap[rev]
114 revstr = '%s:%s' % (rev, short(node))
114 revstr = '%s:%s' % (rev, short(node))
115
115
116 if self.applied(repo, node, p1):
116 if self.applied(repo, node, p1):
117 self.ui.warn(_('skipping already applied revision %s\n') %
117 self.ui.warn(_('skipping already applied revision %s\n') %
118 revstr)
118 revstr)
119 continue
119 continue
120
120
121 parents = source.changelog.parents(node)
121 parents = source.changelog.parents(node)
122 if not opts.get('filter'):
122 if not opts.get('filter'):
123 # If the changeset parent is the same as the
123 # If the changeset parent is the same as the
124 # wdir's parent, just pull it.
124 # wdir's parent, just pull it.
125 if parents[0] == p1:
125 if parents[0] == p1:
126 pulls.append(node)
126 pulls.append(node)
127 p1 = node
127 p1 = node
128 continue
128 continue
129 if pulls:
129 if pulls:
130 if source != repo:
130 if source != repo:
131 repo.pull(source, heads=pulls)
131 repo.pull(source, heads=pulls)
132 merge.update(repo, pulls[-1], False, False, None)
132 merge.update(repo, pulls[-1], False, False, None)
133 p1, p2 = repo.dirstate.parents()
133 p1, p2 = repo.dirstate.parents()
134 pulls = []
134 pulls = []
135
135
136 domerge = False
136 domerge = False
137 if node in merges:
137 if node in merges:
138 # pulling all the merge revs at once would mean we
138 # pulling all the merge revs at once would mean we
139 # couldn't transplant after the latest even if
139 # couldn't transplant after the latest even if
140 # transplants before them fail.
140 # transplants before them fail.
141 domerge = True
141 domerge = True
142 if not hasnode(repo, node):
142 if not hasnode(repo, node):
143 repo.pull(source, heads=[node])
143 repo.pull(source, heads=[node])
144
144
145 if parents[1] != revlog.nullid:
145 if parents[1] != revlog.nullid:
146 self.ui.note(_('skipping merge changeset %s:%s\n')
146 self.ui.note(_('skipping merge changeset %s:%s\n')
147 % (rev, short(node)))
147 % (rev, short(node)))
148 patchfile = None
148 patchfile = None
149 else:
149 else:
150 fd, patchfile = tempfile.mkstemp(prefix='hg-transplant-')
150 fd, patchfile = tempfile.mkstemp(prefix='hg-transplant-')
151 fp = os.fdopen(fd, 'w')
151 fp = os.fdopen(fd, 'w')
152 gen = patch.diff(source, parents[0], node, opts=diffopts)
152 gen = patch.diff(source, parents[0], node, opts=diffopts)
153 for chunk in gen:
153 for chunk in gen:
154 fp.write(chunk)
154 fp.write(chunk)
155 fp.close()
155 fp.close()
156
156
157 del revmap[rev]
157 del revmap[rev]
158 if patchfile or domerge:
158 if patchfile or domerge:
159 try:
159 try:
160 n = self.applyone(repo, node,
160 n = self.applyone(repo, node,
161 source.changelog.read(node),
161 source.changelog.read(node),
162 patchfile, merge=domerge,
162 patchfile, merge=domerge,
163 log=opts.get('log'),
163 log=opts.get('log'),
164 filter=opts.get('filter'))
164 filter=opts.get('filter'))
165 if n and domerge:
165 if n and domerge:
166 self.ui.status(_('%s merged at %s\n') % (revstr,
166 self.ui.status(_('%s merged at %s\n') % (revstr,
167 short(n)))
167 short(n)))
168 elif n:
168 elif n:
169 self.ui.status(_('%s transplanted to %s\n')
169 self.ui.status(_('%s transplanted to %s\n')
170 % (short(node),
170 % (short(node),
171 short(n)))
171 short(n)))
172 finally:
172 finally:
173 if patchfile:
173 if patchfile:
174 os.unlink(patchfile)
174 os.unlink(patchfile)
175 if pulls:
175 if pulls:
176 repo.pull(source, heads=pulls)
176 repo.pull(source, heads=pulls)
177 merge.update(repo, pulls[-1], False, False, None)
177 merge.update(repo, pulls[-1], False, False, None)
178 finally:
178 finally:
179 self.saveseries(revmap, merges)
179 self.saveseries(revmap, merges)
180 self.transplants.write()
180 self.transplants.write()
181 lock.release()
181 lock.release()
182 wlock.release()
182 wlock.release()
183
183
184 def filter(self, filter, node, changelog, patchfile):
184 def filter(self, filter, node, changelog, patchfile):
185 '''arbitrarily rewrite changeset before applying it'''
185 '''arbitrarily rewrite changeset before applying it'''
186
186
187 self.ui.status(_('filtering %s\n') % patchfile)
187 self.ui.status(_('filtering %s\n') % patchfile)
188 user, date, msg = (changelog[1], changelog[2], changelog[4])
188 user, date, msg = (changelog[1], changelog[2], changelog[4])
189 fd, headerfile = tempfile.mkstemp(prefix='hg-transplant-')
189 fd, headerfile = tempfile.mkstemp(prefix='hg-transplant-')
190 fp = os.fdopen(fd, 'w')
190 fp = os.fdopen(fd, 'w')
191 fp.write("# HG changeset patch\n")
191 fp.write("# HG changeset patch\n")
192 fp.write("# User %s\n" % user)
192 fp.write("# User %s\n" % user)
193 fp.write("# Date %d %d\n" % date)
193 fp.write("# Date %d %d\n" % date)
194 fp.write(msg + '\n')
194 fp.write(msg + '\n')
195 fp.close()
195 fp.close()
196
196
197 try:
197 try:
198 util.system('%s %s %s' % (filter, util.shellquote(headerfile),
198 util.system('%s %s %s' % (filter, util.shellquote(headerfile),
199 util.shellquote(patchfile)),
199 util.shellquote(patchfile)),
200 environ={'HGUSER': changelog[1],
200 environ={'HGUSER': changelog[1],
201 'HGREVISION': revlog.hex(node),
201 'HGREVISION': revlog.hex(node),
202 },
202 },
203 onerr=util.Abort, errprefix=_('filter failed'))
203 onerr=util.Abort, errprefix=_('filter failed'))
204 user, date, msg = self.parselog(file(headerfile))[1:4]
204 user, date, msg = self.parselog(file(headerfile))[1:4]
205 finally:
205 finally:
206 os.unlink(headerfile)
206 os.unlink(headerfile)
207
207
208 return (user, date, msg)
208 return (user, date, msg)
209
209
210 def applyone(self, repo, node, cl, patchfile, merge=False, log=False,
210 def applyone(self, repo, node, cl, patchfile, merge=False, log=False,
211 filter=None):
211 filter=None):
212 '''apply the patch in patchfile to the repository as a transplant'''
212 '''apply the patch in patchfile to the repository as a transplant'''
213 (manifest, user, (time, timezone), files, message) = cl[:5]
213 (manifest, user, (time, timezone), files, message) = cl[:5]
214 date = "%d %d" % (time, timezone)
214 date = "%d %d" % (time, timezone)
215 extra = {'transplant_source': node}
215 extra = {'transplant_source': node}
216 if filter:
216 if filter:
217 (user, date, message) = self.filter(filter, node, cl, patchfile)
217 (user, date, message) = self.filter(filter, node, cl, patchfile)
218
218
219 if log:
219 if log:
220 # we don't translate messages inserted into commits
220 # we don't translate messages inserted into commits
221 message += '\n(transplanted from %s)' % revlog.hex(node)
221 message += '\n(transplanted from %s)' % revlog.hex(node)
222
222
223 self.ui.status(_('applying %s\n') % short(node))
223 self.ui.status(_('applying %s\n') % short(node))
224 self.ui.note('%s %s\n%s\n' % (user, date, message))
224 self.ui.note('%s %s\n%s\n' % (user, date, message))
225
225
226 if not patchfile and not merge:
226 if not patchfile and not merge:
227 raise util.Abort(_('can only omit patchfile if merging'))
227 raise util.Abort(_('can only omit patchfile if merging'))
228 if patchfile:
228 if patchfile:
229 try:
229 try:
230 files = {}
230 files = set()
231 patch.patch(self.ui, repo, patchfile, files=files, eolmode=None)
231 patch.patch(self.ui, repo, patchfile, files=files, eolmode=None)
232 files = list(files)
232 files = list(files)
233 if not files:
233 if not files:
234 self.ui.warn(_('%s: empty changeset') % revlog.hex(node))
234 self.ui.warn(_('%s: empty changeset') % revlog.hex(node))
235 return None
235 return None
236 except Exception, inst:
236 except Exception, inst:
237 seriespath = os.path.join(self.path, 'series')
237 seriespath = os.path.join(self.path, 'series')
238 if os.path.exists(seriespath):
238 if os.path.exists(seriespath):
239 os.unlink(seriespath)
239 os.unlink(seriespath)
240 p1 = repo.dirstate.p1()
240 p1 = repo.dirstate.p1()
241 p2 = node
241 p2 = node
242 self.log(user, date, message, p1, p2, merge=merge)
242 self.log(user, date, message, p1, p2, merge=merge)
243 self.ui.write(str(inst) + '\n')
243 self.ui.write(str(inst) + '\n')
244 raise util.Abort(_('fix up the merge and run '
244 raise util.Abort(_('fix up the merge and run '
245 'hg transplant --continue'))
245 'hg transplant --continue'))
246 else:
246 else:
247 files = None
247 files = None
248 if merge:
248 if merge:
249 p1, p2 = repo.dirstate.parents()
249 p1, p2 = repo.dirstate.parents()
250 repo.dirstate.setparents(p1, node)
250 repo.dirstate.setparents(p1, node)
251 m = match.always(repo.root, '')
251 m = match.always(repo.root, '')
252 else:
252 else:
253 m = match.exact(repo.root, '', files)
253 m = match.exact(repo.root, '', files)
254
254
255 n = repo.commit(message, user, date, extra=extra, match=m)
255 n = repo.commit(message, user, date, extra=extra, match=m)
256 if not n:
256 if not n:
257 # Crash here to prevent an unclear crash later, in
257 # Crash here to prevent an unclear crash later, in
258 # transplants.write(). This can happen if patch.patch()
258 # transplants.write(). This can happen if patch.patch()
259 # does nothing but claims success or if repo.status() fails
259 # does nothing but claims success or if repo.status() fails
260 # to report changes done by patch.patch(). These both
260 # to report changes done by patch.patch(). These both
261 # appear to be bugs in other parts of Mercurial, but dying
261 # appear to be bugs in other parts of Mercurial, but dying
262 # here, as soon as we can detect the problem, is preferable
262 # here, as soon as we can detect the problem, is preferable
263 # to silently dropping changesets on the floor.
263 # to silently dropping changesets on the floor.
264 raise RuntimeError('nothing committed after transplant')
264 raise RuntimeError('nothing committed after transplant')
265 if not merge:
265 if not merge:
266 self.transplants.set(n, node)
266 self.transplants.set(n, node)
267
267
268 return n
268 return n
269
269
270 def resume(self, repo, source, opts=None):
270 def resume(self, repo, source, opts=None):
271 '''recover last transaction and apply remaining changesets'''
271 '''recover last transaction and apply remaining changesets'''
272 if os.path.exists(os.path.join(self.path, 'journal')):
272 if os.path.exists(os.path.join(self.path, 'journal')):
273 n, node = self.recover(repo)
273 n, node = self.recover(repo)
274 self.ui.status(_('%s transplanted as %s\n') % (short(node),
274 self.ui.status(_('%s transplanted as %s\n') % (short(node),
275 short(n)))
275 short(n)))
276 seriespath = os.path.join(self.path, 'series')
276 seriespath = os.path.join(self.path, 'series')
277 if not os.path.exists(seriespath):
277 if not os.path.exists(seriespath):
278 self.transplants.write()
278 self.transplants.write()
279 return
279 return
280 nodes, merges = self.readseries()
280 nodes, merges = self.readseries()
281 revmap = {}
281 revmap = {}
282 for n in nodes:
282 for n in nodes:
283 revmap[source.changelog.rev(n)] = n
283 revmap[source.changelog.rev(n)] = n
284 os.unlink(seriespath)
284 os.unlink(seriespath)
285
285
286 self.apply(repo, source, revmap, merges, opts)
286 self.apply(repo, source, revmap, merges, opts)
287
287
288 def recover(self, repo):
288 def recover(self, repo):
289 '''commit working directory using journal metadata'''
289 '''commit working directory using journal metadata'''
290 node, user, date, message, parents = self.readlog()
290 node, user, date, message, parents = self.readlog()
291 merge = len(parents) == 2
291 merge = len(parents) == 2
292
292
293 if not user or not date or not message or not parents[0]:
293 if not user or not date or not message or not parents[0]:
294 raise util.Abort(_('transplant log file is corrupt'))
294 raise util.Abort(_('transplant log file is corrupt'))
295
295
296 extra = {'transplant_source': node}
296 extra = {'transplant_source': node}
297 wlock = repo.wlock()
297 wlock = repo.wlock()
298 try:
298 try:
299 p1, p2 = repo.dirstate.parents()
299 p1, p2 = repo.dirstate.parents()
300 if p1 != parents[0]:
300 if p1 != parents[0]:
301 raise util.Abort(
301 raise util.Abort(
302 _('working dir not at transplant parent %s') %
302 _('working dir not at transplant parent %s') %
303 revlog.hex(parents[0]))
303 revlog.hex(parents[0]))
304 if merge:
304 if merge:
305 repo.dirstate.setparents(p1, parents[1])
305 repo.dirstate.setparents(p1, parents[1])
306 n = repo.commit(message, user, date, extra=extra)
306 n = repo.commit(message, user, date, extra=extra)
307 if not n:
307 if not n:
308 raise util.Abort(_('commit failed'))
308 raise util.Abort(_('commit failed'))
309 if not merge:
309 if not merge:
310 self.transplants.set(n, node)
310 self.transplants.set(n, node)
311 self.unlog()
311 self.unlog()
312
312
313 return n, node
313 return n, node
314 finally:
314 finally:
315 wlock.release()
315 wlock.release()
316
316
317 def readseries(self):
317 def readseries(self):
318 nodes = []
318 nodes = []
319 merges = []
319 merges = []
320 cur = nodes
320 cur = nodes
321 for line in self.opener.read('series').splitlines():
321 for line in self.opener.read('series').splitlines():
322 if line.startswith('# Merges'):
322 if line.startswith('# Merges'):
323 cur = merges
323 cur = merges
324 continue
324 continue
325 cur.append(revlog.bin(line))
325 cur.append(revlog.bin(line))
326
326
327 return (nodes, merges)
327 return (nodes, merges)
328
328
329 def saveseries(self, revmap, merges):
329 def saveseries(self, revmap, merges):
330 if not revmap:
330 if not revmap:
331 return
331 return
332
332
333 if not os.path.isdir(self.path):
333 if not os.path.isdir(self.path):
334 os.mkdir(self.path)
334 os.mkdir(self.path)
335 series = self.opener('series', 'w')
335 series = self.opener('series', 'w')
336 for rev in sorted(revmap):
336 for rev in sorted(revmap):
337 series.write(revlog.hex(revmap[rev]) + '\n')
337 series.write(revlog.hex(revmap[rev]) + '\n')
338 if merges:
338 if merges:
339 series.write('# Merges\n')
339 series.write('# Merges\n')
340 for m in merges:
340 for m in merges:
341 series.write(revlog.hex(m) + '\n')
341 series.write(revlog.hex(m) + '\n')
342 series.close()
342 series.close()
343
343
344 def parselog(self, fp):
344 def parselog(self, fp):
345 parents = []
345 parents = []
346 message = []
346 message = []
347 node = revlog.nullid
347 node = revlog.nullid
348 inmsg = False
348 inmsg = False
349 user = None
349 user = None
350 date = None
350 date = None
351 for line in fp.read().splitlines():
351 for line in fp.read().splitlines():
352 if inmsg:
352 if inmsg:
353 message.append(line)
353 message.append(line)
354 elif line.startswith('# User '):
354 elif line.startswith('# User '):
355 user = line[7:]
355 user = line[7:]
356 elif line.startswith('# Date '):
356 elif line.startswith('# Date '):
357 date = line[7:]
357 date = line[7:]
358 elif line.startswith('# Node ID '):
358 elif line.startswith('# Node ID '):
359 node = revlog.bin(line[10:])
359 node = revlog.bin(line[10:])
360 elif line.startswith('# Parent '):
360 elif line.startswith('# Parent '):
361 parents.append(revlog.bin(line[9:]))
361 parents.append(revlog.bin(line[9:]))
362 elif not line.startswith('# '):
362 elif not line.startswith('# '):
363 inmsg = True
363 inmsg = True
364 message.append(line)
364 message.append(line)
365 if None in (user, date):
365 if None in (user, date):
366 raise util.Abort(_("filter corrupted changeset (no user or date)"))
366 raise util.Abort(_("filter corrupted changeset (no user or date)"))
367 return (node, user, date, '\n'.join(message), parents)
367 return (node, user, date, '\n'.join(message), parents)
368
368
369 def log(self, user, date, message, p1, p2, merge=False):
369 def log(self, user, date, message, p1, p2, merge=False):
370 '''journal changelog metadata for later recover'''
370 '''journal changelog metadata for later recover'''
371
371
372 if not os.path.isdir(self.path):
372 if not os.path.isdir(self.path):
373 os.mkdir(self.path)
373 os.mkdir(self.path)
374 fp = self.opener('journal', 'w')
374 fp = self.opener('journal', 'w')
375 fp.write('# User %s\n' % user)
375 fp.write('# User %s\n' % user)
376 fp.write('# Date %s\n' % date)
376 fp.write('# Date %s\n' % date)
377 fp.write('# Node ID %s\n' % revlog.hex(p2))
377 fp.write('# Node ID %s\n' % revlog.hex(p2))
378 fp.write('# Parent ' + revlog.hex(p1) + '\n')
378 fp.write('# Parent ' + revlog.hex(p1) + '\n')
379 if merge:
379 if merge:
380 fp.write('# Parent ' + revlog.hex(p2) + '\n')
380 fp.write('# Parent ' + revlog.hex(p2) + '\n')
381 fp.write(message.rstrip() + '\n')
381 fp.write(message.rstrip() + '\n')
382 fp.close()
382 fp.close()
383
383
384 def readlog(self):
384 def readlog(self):
385 return self.parselog(self.opener('journal'))
385 return self.parselog(self.opener('journal'))
386
386
387 def unlog(self):
387 def unlog(self):
388 '''remove changelog journal'''
388 '''remove changelog journal'''
389 absdst = os.path.join(self.path, 'journal')
389 absdst = os.path.join(self.path, 'journal')
390 if os.path.exists(absdst):
390 if os.path.exists(absdst):
391 os.unlink(absdst)
391 os.unlink(absdst)
392
392
393 def transplantfilter(self, repo, source, root):
393 def transplantfilter(self, repo, source, root):
394 def matchfn(node):
394 def matchfn(node):
395 if self.applied(repo, node, root):
395 if self.applied(repo, node, root):
396 return False
396 return False
397 if source.changelog.parents(node)[1] != revlog.nullid:
397 if source.changelog.parents(node)[1] != revlog.nullid:
398 return False
398 return False
399 extra = source.changelog.read(node)[5]
399 extra = source.changelog.read(node)[5]
400 cnode = extra.get('transplant_source')
400 cnode = extra.get('transplant_source')
401 if cnode and self.applied(repo, cnode, root):
401 if cnode and self.applied(repo, cnode, root):
402 return False
402 return False
403 return True
403 return True
404
404
405 return matchfn
405 return matchfn
406
406
407 def hasnode(repo, node):
407 def hasnode(repo, node):
408 try:
408 try:
409 return repo.changelog.rev(node) is not None
409 return repo.changelog.rev(node) is not None
410 except error.RevlogError:
410 except error.RevlogError:
411 return False
411 return False
412
412
413 def browserevs(ui, repo, nodes, opts):
413 def browserevs(ui, repo, nodes, opts):
414 '''interactively transplant changesets'''
414 '''interactively transplant changesets'''
415 def browsehelp(ui):
415 def browsehelp(ui):
416 ui.write(_('y: transplant this changeset\n'
416 ui.write(_('y: transplant this changeset\n'
417 'n: skip this changeset\n'
417 'n: skip this changeset\n'
418 'm: merge at this changeset\n'
418 'm: merge at this changeset\n'
419 'p: show patch\n'
419 'p: show patch\n'
420 'c: commit selected changesets\n'
420 'c: commit selected changesets\n'
421 'q: cancel transplant\n'
421 'q: cancel transplant\n'
422 '?: show this help\n'))
422 '?: show this help\n'))
423
423
424 displayer = cmdutil.show_changeset(ui, repo, opts)
424 displayer = cmdutil.show_changeset(ui, repo, opts)
425 transplants = []
425 transplants = []
426 merges = []
426 merges = []
427 for node in nodes:
427 for node in nodes:
428 displayer.show(repo[node])
428 displayer.show(repo[node])
429 action = None
429 action = None
430 while not action:
430 while not action:
431 action = ui.prompt(_('apply changeset? [ynmpcq?]:'))
431 action = ui.prompt(_('apply changeset? [ynmpcq?]:'))
432 if action == '?':
432 if action == '?':
433 browsehelp(ui)
433 browsehelp(ui)
434 action = None
434 action = None
435 elif action == 'p':
435 elif action == 'p':
436 parent = repo.changelog.parents(node)[0]
436 parent = repo.changelog.parents(node)[0]
437 for chunk in patch.diff(repo, parent, node):
437 for chunk in patch.diff(repo, parent, node):
438 ui.write(chunk)
438 ui.write(chunk)
439 action = None
439 action = None
440 elif action not in ('y', 'n', 'm', 'c', 'q'):
440 elif action not in ('y', 'n', 'm', 'c', 'q'):
441 ui.write(_('no such option\n'))
441 ui.write(_('no such option\n'))
442 action = None
442 action = None
443 if action == 'y':
443 if action == 'y':
444 transplants.append(node)
444 transplants.append(node)
445 elif action == 'm':
445 elif action == 'm':
446 merges.append(node)
446 merges.append(node)
447 elif action == 'c':
447 elif action == 'c':
448 break
448 break
449 elif action == 'q':
449 elif action == 'q':
450 transplants = ()
450 transplants = ()
451 merges = ()
451 merges = ()
452 break
452 break
453 displayer.close()
453 displayer.close()
454 return (transplants, merges)
454 return (transplants, merges)
455
455
456 @command('transplant',
456 @command('transplant',
457 [('s', 'source', '', _('pull patches from REPO'), _('REPO')),
457 [('s', 'source', '', _('pull patches from REPO'), _('REPO')),
458 ('b', 'branch', [],
458 ('b', 'branch', [],
459 _('pull patches from branch BRANCH'), _('BRANCH')),
459 _('pull patches from branch BRANCH'), _('BRANCH')),
460 ('a', 'all', None, _('pull all changesets up to BRANCH')),
460 ('a', 'all', None, _('pull all changesets up to BRANCH')),
461 ('p', 'prune', [], _('skip over REV'), _('REV')),
461 ('p', 'prune', [], _('skip over REV'), _('REV')),
462 ('m', 'merge', [], _('merge at REV'), _('REV')),
462 ('m', 'merge', [], _('merge at REV'), _('REV')),
463 ('', 'log', None, _('append transplant info to log message')),
463 ('', 'log', None, _('append transplant info to log message')),
464 ('c', 'continue', None, _('continue last transplant session '
464 ('c', 'continue', None, _('continue last transplant session '
465 'after repair')),
465 'after repair')),
466 ('', 'filter', '',
466 ('', 'filter', '',
467 _('filter changesets through command'), _('CMD'))],
467 _('filter changesets through command'), _('CMD'))],
468 _('hg transplant [-s REPO] [-b BRANCH [-a]] [-p REV] '
468 _('hg transplant [-s REPO] [-b BRANCH [-a]] [-p REV] '
469 '[-m REV] [REV]...'))
469 '[-m REV] [REV]...'))
470 def transplant(ui, repo, *revs, **opts):
470 def transplant(ui, repo, *revs, **opts):
471 '''transplant changesets from another branch
471 '''transplant changesets from another branch
472
472
473 Selected changesets will be applied on top of the current working
473 Selected changesets will be applied on top of the current working
474 directory with the log of the original changeset. The changesets
474 directory with the log of the original changeset. The changesets
475 are copied and will thus appear twice in the history. Use the
475 are copied and will thus appear twice in the history. Use the
476 rebase extension instead if you want to move a whole branch of
476 rebase extension instead if you want to move a whole branch of
477 unpublished changesets.
477 unpublished changesets.
478
478
479 If --log is specified, log messages will have a comment appended
479 If --log is specified, log messages will have a comment appended
480 of the form::
480 of the form::
481
481
482 (transplanted from CHANGESETHASH)
482 (transplanted from CHANGESETHASH)
483
483
484 You can rewrite the changelog message with the --filter option.
484 You can rewrite the changelog message with the --filter option.
485 Its argument will be invoked with the current changelog message as
485 Its argument will be invoked with the current changelog message as
486 $1 and the patch as $2.
486 $1 and the patch as $2.
487
487
488 If --source/-s is specified, selects changesets from the named
488 If --source/-s is specified, selects changesets from the named
489 repository. If --branch/-b is specified, selects changesets from
489 repository. If --branch/-b is specified, selects changesets from
490 the branch holding the named revision, up to that revision. If
490 the branch holding the named revision, up to that revision. If
491 --all/-a is specified, all changesets on the branch will be
491 --all/-a is specified, all changesets on the branch will be
492 transplanted, otherwise you will be prompted to select the
492 transplanted, otherwise you will be prompted to select the
493 changesets you want.
493 changesets you want.
494
494
495 :hg:`transplant --branch REVISION --all` will transplant the
495 :hg:`transplant --branch REVISION --all` will transplant the
496 selected branch (up to the named revision) onto your current
496 selected branch (up to the named revision) onto your current
497 working directory.
497 working directory.
498
498
499 You can optionally mark selected transplanted changesets as merge
499 You can optionally mark selected transplanted changesets as merge
500 changesets. You will not be prompted to transplant any ancestors
500 changesets. You will not be prompted to transplant any ancestors
501 of a merged transplant, and you can merge descendants of them
501 of a merged transplant, and you can merge descendants of them
502 normally instead of transplanting them.
502 normally instead of transplanting them.
503
503
504 If no merges or revisions are provided, :hg:`transplant` will
504 If no merges or revisions are provided, :hg:`transplant` will
505 start an interactive changeset browser.
505 start an interactive changeset browser.
506
506
507 If a changeset application fails, you can fix the merge by hand
507 If a changeset application fails, you can fix the merge by hand
508 and then resume where you left off by calling :hg:`transplant
508 and then resume where you left off by calling :hg:`transplant
509 --continue/-c`.
509 --continue/-c`.
510 '''
510 '''
511 def incwalk(repo, csets, match=util.always):
511 def incwalk(repo, csets, match=util.always):
512 for node in csets:
512 for node in csets:
513 if match(node):
513 if match(node):
514 yield node
514 yield node
515
515
516 def transplantwalk(repo, root, branches, match=util.always):
516 def transplantwalk(repo, root, branches, match=util.always):
517 if not branches:
517 if not branches:
518 branches = repo.heads()
518 branches = repo.heads()
519 ancestors = []
519 ancestors = []
520 for branch in branches:
520 for branch in branches:
521 ancestors.append(repo.changelog.ancestor(root, branch))
521 ancestors.append(repo.changelog.ancestor(root, branch))
522 for node in repo.changelog.nodesbetween(ancestors, branches)[0]:
522 for node in repo.changelog.nodesbetween(ancestors, branches)[0]:
523 if match(node):
523 if match(node):
524 yield node
524 yield node
525
525
526 def checkopts(opts, revs):
526 def checkopts(opts, revs):
527 if opts.get('continue'):
527 if opts.get('continue'):
528 if opts.get('branch') or opts.get('all') or opts.get('merge'):
528 if opts.get('branch') or opts.get('all') or opts.get('merge'):
529 raise util.Abort(_('--continue is incompatible with '
529 raise util.Abort(_('--continue is incompatible with '
530 'branch, all or merge'))
530 'branch, all or merge'))
531 return
531 return
532 if not (opts.get('source') or revs or
532 if not (opts.get('source') or revs or
533 opts.get('merge') or opts.get('branch')):
533 opts.get('merge') or opts.get('branch')):
534 raise util.Abort(_('no source URL, branch tag or revision '
534 raise util.Abort(_('no source URL, branch tag or revision '
535 'list provided'))
535 'list provided'))
536 if opts.get('all'):
536 if opts.get('all'):
537 if not opts.get('branch'):
537 if not opts.get('branch'):
538 raise util.Abort(_('--all requires a branch revision'))
538 raise util.Abort(_('--all requires a branch revision'))
539 if revs:
539 if revs:
540 raise util.Abort(_('--all is incompatible with a '
540 raise util.Abort(_('--all is incompatible with a '
541 'revision list'))
541 'revision list'))
542
542
543 checkopts(opts, revs)
543 checkopts(opts, revs)
544
544
545 if not opts.get('log'):
545 if not opts.get('log'):
546 opts['log'] = ui.config('transplant', 'log')
546 opts['log'] = ui.config('transplant', 'log')
547 if not opts.get('filter'):
547 if not opts.get('filter'):
548 opts['filter'] = ui.config('transplant', 'filter')
548 opts['filter'] = ui.config('transplant', 'filter')
549
549
550 tp = transplanter(ui, repo)
550 tp = transplanter(ui, repo)
551
551
552 p1, p2 = repo.dirstate.parents()
552 p1, p2 = repo.dirstate.parents()
553 if len(repo) > 0 and p1 == revlog.nullid:
553 if len(repo) > 0 and p1 == revlog.nullid:
554 raise util.Abort(_('no revision checked out'))
554 raise util.Abort(_('no revision checked out'))
555 if not opts.get('continue'):
555 if not opts.get('continue'):
556 if p2 != revlog.nullid:
556 if p2 != revlog.nullid:
557 raise util.Abort(_('outstanding uncommitted merges'))
557 raise util.Abort(_('outstanding uncommitted merges'))
558 m, a, r, d = repo.status()[:4]
558 m, a, r, d = repo.status()[:4]
559 if m or a or r or d:
559 if m or a or r or d:
560 raise util.Abort(_('outstanding local changes'))
560 raise util.Abort(_('outstanding local changes'))
561
561
562 sourcerepo = opts.get('source')
562 sourcerepo = opts.get('source')
563 if sourcerepo:
563 if sourcerepo:
564 source = hg.peer(ui, opts, ui.expandpath(sourcerepo))
564 source = hg.peer(ui, opts, ui.expandpath(sourcerepo))
565 branches = map(source.lookup, opts.get('branch', ()))
565 branches = map(source.lookup, opts.get('branch', ()))
566 source, csets, cleanupfn = bundlerepo.getremotechanges(ui, repo, source,
566 source, csets, cleanupfn = bundlerepo.getremotechanges(ui, repo, source,
567 onlyheads=branches, force=True)
567 onlyheads=branches, force=True)
568 else:
568 else:
569 source = repo
569 source = repo
570 branches = map(source.lookup, opts.get('branch', ()))
570 branches = map(source.lookup, opts.get('branch', ()))
571 cleanupfn = None
571 cleanupfn = None
572
572
573 try:
573 try:
574 if opts.get('continue'):
574 if opts.get('continue'):
575 tp.resume(repo, source, opts)
575 tp.resume(repo, source, opts)
576 return
576 return
577
577
578 tf = tp.transplantfilter(repo, source, p1)
578 tf = tp.transplantfilter(repo, source, p1)
579 if opts.get('prune'):
579 if opts.get('prune'):
580 prune = [source.lookup(r)
580 prune = [source.lookup(r)
581 for r in scmutil.revrange(source, opts.get('prune'))]
581 for r in scmutil.revrange(source, opts.get('prune'))]
582 matchfn = lambda x: tf(x) and x not in prune
582 matchfn = lambda x: tf(x) and x not in prune
583 else:
583 else:
584 matchfn = tf
584 matchfn = tf
585 merges = map(source.lookup, opts.get('merge', ()))
585 merges = map(source.lookup, opts.get('merge', ()))
586 revmap = {}
586 revmap = {}
587 if revs:
587 if revs:
588 for r in scmutil.revrange(source, revs):
588 for r in scmutil.revrange(source, revs):
589 revmap[int(r)] = source.lookup(r)
589 revmap[int(r)] = source.lookup(r)
590 elif opts.get('all') or not merges:
590 elif opts.get('all') or not merges:
591 if source != repo:
591 if source != repo:
592 alltransplants = incwalk(source, csets, match=matchfn)
592 alltransplants = incwalk(source, csets, match=matchfn)
593 else:
593 else:
594 alltransplants = transplantwalk(source, p1, branches,
594 alltransplants = transplantwalk(source, p1, branches,
595 match=matchfn)
595 match=matchfn)
596 if opts.get('all'):
596 if opts.get('all'):
597 revs = alltransplants
597 revs = alltransplants
598 else:
598 else:
599 revs, newmerges = browserevs(ui, source, alltransplants, opts)
599 revs, newmerges = browserevs(ui, source, alltransplants, opts)
600 merges.extend(newmerges)
600 merges.extend(newmerges)
601 for r in revs:
601 for r in revs:
602 revmap[source.changelog.rev(r)] = r
602 revmap[source.changelog.rev(r)] = r
603 for r in merges:
603 for r in merges:
604 revmap[source.changelog.rev(r)] = r
604 revmap[source.changelog.rev(r)] = r
605
605
606 tp.apply(repo, source, revmap, merges, opts)
606 tp.apply(repo, source, revmap, merges, opts)
607 finally:
607 finally:
608 if cleanupfn:
608 if cleanupfn:
609 cleanupfn()
609 cleanupfn()
610
610
611 def revsettransplanted(repo, subset, x):
611 def revsettransplanted(repo, subset, x):
612 """``transplanted([set])``
612 """``transplanted([set])``
613 Transplanted changesets in set, or all transplanted changesets.
613 Transplanted changesets in set, or all transplanted changesets.
614 """
614 """
615 if x:
615 if x:
616 s = revset.getset(repo, subset, x)
616 s = revset.getset(repo, subset, x)
617 else:
617 else:
618 s = subset
618 s = subset
619 return [r for r in s if repo[r].extra().get('transplant_source')]
619 return [r for r in s if repo[r].extra().get('transplant_source')]
620
620
621 def kwtransplanted(repo, ctx, **args):
621 def kwtransplanted(repo, ctx, **args):
622 """:transplanted: String. The node identifier of the transplanted
622 """:transplanted: String. The node identifier of the transplanted
623 changeset if any."""
623 changeset if any."""
624 n = ctx.extra().get('transplant_source')
624 n = ctx.extra().get('transplant_source')
625 return n and revlog.hex(n) or ''
625 return n and revlog.hex(n) or ''
626
626
627 def extsetup(ui):
627 def extsetup(ui):
628 revset.symbols['transplanted'] = revsettransplanted
628 revset.symbols['transplanted'] = revsettransplanted
629 templatekw.keywords['transplanted'] = kwtransplanted
629 templatekw.keywords['transplanted'] = kwtransplanted
630
630
631 # tell hggettext to extract docstrings from these functions:
631 # tell hggettext to extract docstrings from these functions:
632 i18nfunctions = [revsettransplanted, kwtransplanted]
632 i18nfunctions = [revsettransplanted, kwtransplanted]
@@ -1,5075 +1,5075 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, sys, difflib, time, tempfile, errno
11 import os, re, sys, 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, sshserver, hbisect, hgweb, hgweb.server
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 import merge as mergemod
15 import merge as mergemod
16 import minirst, revset, fileset
16 import minirst, revset, fileset
17 import dagparser, context, simplemerge
17 import dagparser, context, simplemerge
18 import random, setdiscovery, treediscovery, dagutil
18 import random, setdiscovery, treediscovery, dagutil
19
19
20 table = {}
20 table = {}
21
21
22 command = cmdutil.command(table)
22 command = cmdutil.command(table)
23
23
24 # common command options
24 # common command options
25
25
26 globalopts = [
26 globalopts = [
27 ('R', 'repository', '',
27 ('R', 'repository', '',
28 _('repository root directory or name of overlay bundle file'),
28 _('repository root directory or name of overlay bundle file'),
29 _('REPO')),
29 _('REPO')),
30 ('', 'cwd', '',
30 ('', 'cwd', '',
31 _('change working directory'), _('DIR')),
31 _('change working directory'), _('DIR')),
32 ('y', 'noninteractive', None,
32 ('y', 'noninteractive', None,
33 _('do not prompt, assume \'yes\' for any required answers')),
33 _('do not prompt, assume \'yes\' for any required answers')),
34 ('q', 'quiet', None, _('suppress output')),
34 ('q', 'quiet', None, _('suppress output')),
35 ('v', 'verbose', None, _('enable additional output')),
35 ('v', 'verbose', None, _('enable additional output')),
36 ('', 'config', [],
36 ('', 'config', [],
37 _('set/override config option (use \'section.name=value\')'),
37 _('set/override config option (use \'section.name=value\')'),
38 _('CONFIG')),
38 _('CONFIG')),
39 ('', 'debug', None, _('enable debugging output')),
39 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debugger', None, _('start debugger')),
40 ('', 'debugger', None, _('start debugger')),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 _('ENCODE')),
42 _('ENCODE')),
43 ('', 'encodingmode', encoding.encodingmode,
43 ('', 'encodingmode', encoding.encodingmode,
44 _('set the charset encoding mode'), _('MODE')),
44 _('set the charset encoding mode'), _('MODE')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'time', None, _('time how long the command takes')),
46 ('', 'time', None, _('time how long the command takes')),
47 ('', 'profile', None, _('print command execution profile')),
47 ('', 'profile', None, _('print command execution profile')),
48 ('', 'version', None, _('output version information and exit')),
48 ('', 'version', None, _('output version information and exit')),
49 ('h', 'help', None, _('display help and exit')),
49 ('h', 'help', None, _('display help and exit')),
50 ]
50 ]
51
51
52 dryrunopts = [('n', 'dry-run', None,
52 dryrunopts = [('n', 'dry-run', None,
53 _('do not perform actions, just print output'))]
53 _('do not perform actions, just print output'))]
54
54
55 remoteopts = [
55 remoteopts = [
56 ('e', 'ssh', '',
56 ('e', 'ssh', '',
57 _('specify ssh command to use'), _('CMD')),
57 _('specify ssh command to use'), _('CMD')),
58 ('', 'remotecmd', '',
58 ('', 'remotecmd', '',
59 _('specify hg command to run on the remote side'), _('CMD')),
59 _('specify hg command to run on the remote side'), _('CMD')),
60 ('', 'insecure', None,
60 ('', 'insecure', None,
61 _('do not verify server certificate (ignoring web.cacerts config)')),
61 _('do not verify server certificate (ignoring web.cacerts config)')),
62 ]
62 ]
63
63
64 walkopts = [
64 walkopts = [
65 ('I', 'include', [],
65 ('I', 'include', [],
66 _('include names matching the given patterns'), _('PATTERN')),
66 _('include names matching the given patterns'), _('PATTERN')),
67 ('X', 'exclude', [],
67 ('X', 'exclude', [],
68 _('exclude names matching the given patterns'), _('PATTERN')),
68 _('exclude names matching the given patterns'), _('PATTERN')),
69 ]
69 ]
70
70
71 commitopts = [
71 commitopts = [
72 ('m', 'message', '',
72 ('m', 'message', '',
73 _('use text as commit message'), _('TEXT')),
73 _('use text as commit message'), _('TEXT')),
74 ('l', 'logfile', '',
74 ('l', 'logfile', '',
75 _('read commit message from file'), _('FILE')),
75 _('read commit message from file'), _('FILE')),
76 ]
76 ]
77
77
78 commitopts2 = [
78 commitopts2 = [
79 ('d', 'date', '',
79 ('d', 'date', '',
80 _('record the specified date as commit date'), _('DATE')),
80 _('record the specified date as commit date'), _('DATE')),
81 ('u', 'user', '',
81 ('u', 'user', '',
82 _('record the specified user as committer'), _('USER')),
82 _('record the specified user as committer'), _('USER')),
83 ]
83 ]
84
84
85 templateopts = [
85 templateopts = [
86 ('', 'style', '',
86 ('', 'style', '',
87 _('display using template map file'), _('STYLE')),
87 _('display using template map file'), _('STYLE')),
88 ('', 'template', '',
88 ('', 'template', '',
89 _('display with template'), _('TEMPLATE')),
89 _('display with template'), _('TEMPLATE')),
90 ]
90 ]
91
91
92 logopts = [
92 logopts = [
93 ('p', 'patch', None, _('show patch')),
93 ('p', 'patch', None, _('show patch')),
94 ('g', 'git', None, _('use git extended diff format')),
94 ('g', 'git', None, _('use git extended diff format')),
95 ('l', 'limit', '',
95 ('l', 'limit', '',
96 _('limit number of changes displayed'), _('NUM')),
96 _('limit number of changes displayed'), _('NUM')),
97 ('M', 'no-merges', None, _('do not show merges')),
97 ('M', 'no-merges', None, _('do not show merges')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ] + templateopts
99 ] + templateopts
100
100
101 diffopts = [
101 diffopts = [
102 ('a', 'text', None, _('treat all files as text')),
102 ('a', 'text', None, _('treat all files as text')),
103 ('g', 'git', None, _('use git extended diff format')),
103 ('g', 'git', None, _('use git extended diff format')),
104 ('', 'nodates', None, _('omit dates from diff headers'))
104 ('', 'nodates', None, _('omit dates from diff headers'))
105 ]
105 ]
106
106
107 diffopts2 = [
107 diffopts2 = [
108 ('p', 'show-function', None, _('show which function each change is in')),
108 ('p', 'show-function', None, _('show which function each change is in')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
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 ('U', 'unified', '',
116 ('U', 'unified', '',
117 _('number of lines of context to show'), _('NUM')),
117 _('number of lines of context to show'), _('NUM')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ]
119 ]
120
120
121 similarityopts = [
121 similarityopts = [
122 ('s', 'similarity', '',
122 ('s', 'similarity', '',
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
124 ]
124 ]
125
125
126 subrepoopts = [
126 subrepoopts = [
127 ('S', 'subrepos', None,
127 ('S', 'subrepos', None,
128 _('recurse into subrepositories'))
128 _('recurse into subrepositories'))
129 ]
129 ]
130
130
131 # Commands start here, listed alphabetically
131 # Commands start here, listed alphabetically
132
132
133 @command('^add',
133 @command('^add',
134 walkopts + subrepoopts + dryrunopts,
134 walkopts + subrepoopts + dryrunopts,
135 _('[OPTION]... [FILE]...'))
135 _('[OPTION]... [FILE]...'))
136 def add(ui, repo, *pats, **opts):
136 def add(ui, repo, *pats, **opts):
137 """add the specified files on the next commit
137 """add the specified files on the next commit
138
138
139 Schedule files to be version controlled and added to the
139 Schedule files to be version controlled and added to the
140 repository.
140 repository.
141
141
142 The files will be added to the repository at the next commit. To
142 The files will be added to the repository at the next commit. To
143 undo an add before that, see :hg:`forget`.
143 undo an add before that, see :hg:`forget`.
144
144
145 If no names are given, add all files to the repository.
145 If no names are given, add all files to the repository.
146
146
147 .. container:: verbose
147 .. container:: verbose
148
148
149 An example showing how new (unknown) files are added
149 An example showing how new (unknown) files are added
150 automatically by :hg:`add`::
150 automatically by :hg:`add`::
151
151
152 $ ls
152 $ ls
153 foo.c
153 foo.c
154 $ hg status
154 $ hg status
155 ? foo.c
155 ? foo.c
156 $ hg add
156 $ hg add
157 adding foo.c
157 adding foo.c
158 $ hg status
158 $ hg status
159 A foo.c
159 A foo.c
160
160
161 Returns 0 if all files are successfully added.
161 Returns 0 if all files are successfully added.
162 """
162 """
163
163
164 m = scmutil.match(repo, pats, opts)
164 m = scmutil.match(repo, pats, opts)
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
166 opts.get('subrepos'), prefix="")
166 opts.get('subrepos'), prefix="")
167 return rejected and 1 or 0
167 return rejected and 1 or 0
168
168
169 @command('addremove',
169 @command('addremove',
170 similarityopts + walkopts + dryrunopts,
170 similarityopts + walkopts + dryrunopts,
171 _('[OPTION]... [FILE]...'))
171 _('[OPTION]... [FILE]...'))
172 def addremove(ui, repo, *pats, **opts):
172 def addremove(ui, repo, *pats, **opts):
173 """add all new files, delete all missing files
173 """add all new files, delete all missing files
174
174
175 Add all new files and remove all missing files from the
175 Add all new files and remove all missing files from the
176 repository.
176 repository.
177
177
178 New files are ignored if they match any of the patterns in
178 New files are ignored if they match any of the patterns in
179 ``.hgignore``. As with add, these changes take effect at the next
179 ``.hgignore``. As with add, these changes take effect at the next
180 commit.
180 commit.
181
181
182 Use the -s/--similarity option to detect renamed files. With a
182 Use the -s/--similarity option to detect renamed files. With a
183 parameter greater than 0, this compares every removed file with
183 parameter greater than 0, this compares every removed file with
184 every added file and records those similar enough as renames. This
184 every added file and records those similar enough as renames. This
185 option takes a percentage between 0 (disabled) and 100 (files must
185 option takes a percentage between 0 (disabled) and 100 (files must
186 be identical) as its parameter. Detecting renamed files this way
186 be identical) as its parameter. Detecting renamed files this way
187 can be expensive. After using this option, :hg:`status -C` can be
187 can be expensive. After using this option, :hg:`status -C` can be
188 used to check which files were identified as moved or renamed.
188 used to check which files were identified as moved or renamed.
189
189
190 Returns 0 if all files are successfully added.
190 Returns 0 if all files are successfully added.
191 """
191 """
192 try:
192 try:
193 sim = float(opts.get('similarity') or 100)
193 sim = float(opts.get('similarity') or 100)
194 except ValueError:
194 except ValueError:
195 raise util.Abort(_('similarity must be a number'))
195 raise util.Abort(_('similarity must be a number'))
196 if sim < 0 or sim > 100:
196 if sim < 0 or sim > 100:
197 raise util.Abort(_('similarity must be between 0 and 100'))
197 raise util.Abort(_('similarity must be between 0 and 100'))
198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
199
199
200 @command('^annotate|blame',
200 @command('^annotate|blame',
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
202 ('', 'follow', None,
202 ('', 'follow', None,
203 _('follow copies/renames and list the filename (DEPRECATED)')),
203 _('follow copies/renames and list the filename (DEPRECATED)')),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
205 ('a', 'text', None, _('treat all files as text')),
205 ('a', 'text', None, _('treat all files as text')),
206 ('u', 'user', None, _('list the author (long with -v)')),
206 ('u', 'user', None, _('list the author (long with -v)')),
207 ('f', 'file', None, _('list the filename')),
207 ('f', 'file', None, _('list the filename')),
208 ('d', 'date', None, _('list the date (short with -q)')),
208 ('d', 'date', None, _('list the date (short with -q)')),
209 ('n', 'number', None, _('list the revision number (default)')),
209 ('n', 'number', None, _('list the revision number (default)')),
210 ('c', 'changeset', None, _('list the changeset')),
210 ('c', 'changeset', None, _('list the changeset')),
211 ('l', 'line-number', None, _('show line number at the first appearance'))
211 ('l', 'line-number', None, _('show line number at the first appearance'))
212 ] + walkopts,
212 ] + walkopts,
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
214 def annotate(ui, repo, *pats, **opts):
214 def annotate(ui, repo, *pats, **opts):
215 """show changeset information by line for each file
215 """show changeset information by line for each file
216
216
217 List changes in files, showing the revision id responsible for
217 List changes in files, showing the revision id responsible for
218 each line
218 each line
219
219
220 This command is useful for discovering when a change was made and
220 This command is useful for discovering when a change was made and
221 by whom.
221 by whom.
222
222
223 Without the -a/--text option, annotate will avoid processing files
223 Without the -a/--text option, annotate will avoid processing files
224 it detects as binary. With -a, annotate will annotate the file
224 it detects as binary. With -a, annotate will annotate the file
225 anyway, although the results will probably be neither useful
225 anyway, although the results will probably be neither useful
226 nor desirable.
226 nor desirable.
227
227
228 Returns 0 on success.
228 Returns 0 on success.
229 """
229 """
230 if opts.get('follow'):
230 if opts.get('follow'):
231 # --follow is deprecated and now just an alias for -f/--file
231 # --follow is deprecated and now just an alias for -f/--file
232 # to mimic the behavior of Mercurial before version 1.5
232 # to mimic the behavior of Mercurial before version 1.5
233 opts['file'] = True
233 opts['file'] = True
234
234
235 datefunc = ui.quiet and util.shortdate or util.datestr
235 datefunc = ui.quiet and util.shortdate or util.datestr
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
237
237
238 if not pats:
238 if not pats:
239 raise util.Abort(_('at least one filename or pattern is required'))
239 raise util.Abort(_('at least one filename or pattern is required'))
240
240
241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
242 ('number', ' ', lambda x: str(x[0].rev())),
242 ('number', ' ', lambda x: str(x[0].rev())),
243 ('changeset', ' ', lambda x: short(x[0].node())),
243 ('changeset', ' ', lambda x: short(x[0].node())),
244 ('date', ' ', getdate),
244 ('date', ' ', getdate),
245 ('file', ' ', lambda x: x[0].path()),
245 ('file', ' ', lambda x: x[0].path()),
246 ('line_number', ':', lambda x: str(x[1])),
246 ('line_number', ':', lambda x: str(x[1])),
247 ]
247 ]
248
248
249 if (not opts.get('user') and not opts.get('changeset')
249 if (not opts.get('user') and not opts.get('changeset')
250 and not opts.get('date') and not opts.get('file')):
250 and not opts.get('date') and not opts.get('file')):
251 opts['number'] = True
251 opts['number'] = True
252
252
253 linenumber = opts.get('line_number') is not None
253 linenumber = opts.get('line_number') is not None
254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
255 raise util.Abort(_('at least one of -n/-c is required for -l'))
255 raise util.Abort(_('at least one of -n/-c is required for -l'))
256
256
257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
259
259
260 def bad(x, y):
260 def bad(x, y):
261 raise util.Abort("%s: %s" % (x, y))
261 raise util.Abort("%s: %s" % (x, y))
262
262
263 ctx = scmutil.revsingle(repo, opts.get('rev'))
263 ctx = scmutil.revsingle(repo, opts.get('rev'))
264 m = scmutil.match(repo, pats, opts)
264 m = scmutil.match(repo, pats, opts)
265 m.bad = bad
265 m.bad = bad
266 follow = not opts.get('no_follow')
266 follow = not opts.get('no_follow')
267 for abs in ctx.walk(m):
267 for abs in ctx.walk(m):
268 fctx = ctx[abs]
268 fctx = ctx[abs]
269 if not opts.get('text') and util.binary(fctx.data()):
269 if not opts.get('text') and util.binary(fctx.data()):
270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
271 continue
271 continue
272
272
273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
274 pieces = []
274 pieces = []
275
275
276 for f, sep in funcmap:
276 for f, sep in funcmap:
277 l = [f(n) for n, dummy in lines]
277 l = [f(n) for n, dummy in lines]
278 if l:
278 if l:
279 sized = [(x, encoding.colwidth(x)) for x in l]
279 sized = [(x, encoding.colwidth(x)) for x in l]
280 ml = max([w for x, w in sized])
280 ml = max([w for x, w in sized])
281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
282 for x, w in sized])
282 for x, w in sized])
283
283
284 if pieces:
284 if pieces:
285 for p, l in zip(zip(*pieces), lines):
285 for p, l in zip(zip(*pieces), lines):
286 ui.write("%s: %s" % ("".join(p), l[1]))
286 ui.write("%s: %s" % ("".join(p), l[1]))
287
287
288 @command('archive',
288 @command('archive',
289 [('', 'no-decode', None, _('do not pass files through decoders')),
289 [('', 'no-decode', None, _('do not pass files through decoders')),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
291 _('PREFIX')),
291 _('PREFIX')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
294 ] + subrepoopts + walkopts,
294 ] + subrepoopts + walkopts,
295 _('[OPTION]... DEST'))
295 _('[OPTION]... DEST'))
296 def archive(ui, repo, dest, **opts):
296 def archive(ui, repo, dest, **opts):
297 '''create an unversioned archive of a repository revision
297 '''create an unversioned archive of a repository revision
298
298
299 By default, the revision used is the parent of the working
299 By default, the revision used is the parent of the working
300 directory; use -r/--rev to specify a different revision.
300 directory; use -r/--rev to specify a different revision.
301
301
302 The archive type is automatically detected based on file
302 The archive type is automatically detected based on file
303 extension (or override using -t/--type).
303 extension (or override using -t/--type).
304
304
305 Valid types are:
305 Valid types are:
306
306
307 :``files``: a directory full of files (default)
307 :``files``: a directory full of files (default)
308 :``tar``: tar archive, uncompressed
308 :``tar``: tar archive, uncompressed
309 :``tbz2``: tar archive, compressed using bzip2
309 :``tbz2``: tar archive, compressed using bzip2
310 :``tgz``: tar archive, compressed using gzip
310 :``tgz``: tar archive, compressed using gzip
311 :``uzip``: zip archive, uncompressed
311 :``uzip``: zip archive, uncompressed
312 :``zip``: zip archive, compressed using deflate
312 :``zip``: zip archive, compressed using deflate
313
313
314 The exact name of the destination archive or directory is given
314 The exact name of the destination archive or directory is given
315 using a format string; see :hg:`help export` for details.
315 using a format string; see :hg:`help export` for details.
316
316
317 Each member added to an archive file has a directory prefix
317 Each member added to an archive file has a directory prefix
318 prepended. Use -p/--prefix to specify a format string for the
318 prepended. Use -p/--prefix to specify a format string for the
319 prefix. The default is the basename of the archive, with suffixes
319 prefix. The default is the basename of the archive, with suffixes
320 removed.
320 removed.
321
321
322 Returns 0 on success.
322 Returns 0 on success.
323 '''
323 '''
324
324
325 ctx = scmutil.revsingle(repo, opts.get('rev'))
325 ctx = scmutil.revsingle(repo, opts.get('rev'))
326 if not ctx:
326 if not ctx:
327 raise util.Abort(_('no working directory: please specify a revision'))
327 raise util.Abort(_('no working directory: please specify a revision'))
328 node = ctx.node()
328 node = ctx.node()
329 dest = cmdutil.makefilename(repo, dest, node)
329 dest = cmdutil.makefilename(repo, dest, node)
330 if os.path.realpath(dest) == repo.root:
330 if os.path.realpath(dest) == repo.root:
331 raise util.Abort(_('repository root cannot be destination'))
331 raise util.Abort(_('repository root cannot be destination'))
332
332
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
334 prefix = opts.get('prefix')
334 prefix = opts.get('prefix')
335
335
336 if dest == '-':
336 if dest == '-':
337 if kind == 'files':
337 if kind == 'files':
338 raise util.Abort(_('cannot archive plain files to stdout'))
338 raise util.Abort(_('cannot archive plain files to stdout'))
339 dest = sys.stdout
339 dest = sys.stdout
340 if not prefix:
340 if not prefix:
341 prefix = os.path.basename(repo.root) + '-%h'
341 prefix = os.path.basename(repo.root) + '-%h'
342
342
343 prefix = cmdutil.makefilename(repo, prefix, node)
343 prefix = cmdutil.makefilename(repo, prefix, node)
344 matchfn = scmutil.match(repo, [], opts)
344 matchfn = scmutil.match(repo, [], opts)
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
346 matchfn, prefix, subrepos=opts.get('subrepos'))
346 matchfn, prefix, subrepos=opts.get('subrepos'))
347
347
348 @command('backout',
348 @command('backout',
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
351 ('t', 'tool', '', _('specify merge tool')),
351 ('t', 'tool', '', _('specify merge tool')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
353 ] + walkopts + commitopts + commitopts2,
353 ] + walkopts + commitopts + commitopts2,
354 _('[OPTION]... [-r] REV'))
354 _('[OPTION]... [-r] REV'))
355 def backout(ui, repo, node=None, rev=None, **opts):
355 def backout(ui, repo, node=None, rev=None, **opts):
356 '''reverse effect of earlier changeset
356 '''reverse effect of earlier changeset
357
357
358 Prepare a new changeset with the effect of REV undone in the
358 Prepare a new changeset with the effect of REV undone in the
359 current working directory.
359 current working directory.
360
360
361 If REV is the parent of the working directory, then this new changeset
361 If REV is the parent of the working directory, then this new changeset
362 is committed automatically. Otherwise, hg needs to merge the
362 is committed automatically. Otherwise, hg needs to merge the
363 changes and the merged result is left uncommitted.
363 changes and the merged result is left uncommitted.
364
364
365 By default, the pending changeset will have one parent,
365 By default, the pending changeset will have one parent,
366 maintaining a linear history. With --merge, the pending changeset
366 maintaining a linear history. With --merge, the pending changeset
367 will instead have two parents: the old parent of the working
367 will instead have two parents: the old parent of the working
368 directory and a new child of REV that simply undoes REV.
368 directory and a new child of REV that simply undoes REV.
369
369
370 Before version 1.7, the behavior without --merge was equivalent to
370 Before version 1.7, the behavior without --merge was equivalent to
371 specifying --merge followed by :hg:`update --clean .` to cancel
371 specifying --merge followed by :hg:`update --clean .` to cancel
372 the merge and leave the child of REV as a head to be merged
372 the merge and leave the child of REV as a head to be merged
373 separately.
373 separately.
374
374
375 See :hg:`help dates` for a list of formats valid for -d/--date.
375 See :hg:`help dates` for a list of formats valid for -d/--date.
376
376
377 Returns 0 on success.
377 Returns 0 on success.
378 '''
378 '''
379 if rev and node:
379 if rev and node:
380 raise util.Abort(_("please specify just one revision"))
380 raise util.Abort(_("please specify just one revision"))
381
381
382 if not rev:
382 if not rev:
383 rev = node
383 rev = node
384
384
385 if not rev:
385 if not rev:
386 raise util.Abort(_("please specify a revision to backout"))
386 raise util.Abort(_("please specify a revision to backout"))
387
387
388 date = opts.get('date')
388 date = opts.get('date')
389 if date:
389 if date:
390 opts['date'] = util.parsedate(date)
390 opts['date'] = util.parsedate(date)
391
391
392 cmdutil.bailifchanged(repo)
392 cmdutil.bailifchanged(repo)
393 node = scmutil.revsingle(repo, rev).node()
393 node = scmutil.revsingle(repo, rev).node()
394
394
395 op1, op2 = repo.dirstate.parents()
395 op1, op2 = repo.dirstate.parents()
396 a = repo.changelog.ancestor(op1, node)
396 a = repo.changelog.ancestor(op1, node)
397 if a != node:
397 if a != node:
398 raise util.Abort(_('cannot backout change on a different branch'))
398 raise util.Abort(_('cannot backout change on a different branch'))
399
399
400 p1, p2 = repo.changelog.parents(node)
400 p1, p2 = repo.changelog.parents(node)
401 if p1 == nullid:
401 if p1 == nullid:
402 raise util.Abort(_('cannot backout a change with no parents'))
402 raise util.Abort(_('cannot backout a change with no parents'))
403 if p2 != nullid:
403 if p2 != nullid:
404 if not opts.get('parent'):
404 if not opts.get('parent'):
405 raise util.Abort(_('cannot backout a merge changeset without '
405 raise util.Abort(_('cannot backout a merge changeset without '
406 '--parent'))
406 '--parent'))
407 p = repo.lookup(opts['parent'])
407 p = repo.lookup(opts['parent'])
408 if p not in (p1, p2):
408 if p not in (p1, p2):
409 raise util.Abort(_('%s is not a parent of %s') %
409 raise util.Abort(_('%s is not a parent of %s') %
410 (short(p), short(node)))
410 (short(p), short(node)))
411 parent = p
411 parent = p
412 else:
412 else:
413 if opts.get('parent'):
413 if opts.get('parent'):
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
415 parent = p1
415 parent = p1
416
416
417 # the backout should appear on the same branch
417 # the backout should appear on the same branch
418 branch = repo.dirstate.branch()
418 branch = repo.dirstate.branch()
419 hg.clean(repo, node, show_stats=False)
419 hg.clean(repo, node, show_stats=False)
420 repo.dirstate.setbranch(branch)
420 repo.dirstate.setbranch(branch)
421 revert_opts = opts.copy()
421 revert_opts = opts.copy()
422 revert_opts['date'] = None
422 revert_opts['date'] = None
423 revert_opts['all'] = True
423 revert_opts['all'] = True
424 revert_opts['rev'] = hex(parent)
424 revert_opts['rev'] = hex(parent)
425 revert_opts['no_backup'] = None
425 revert_opts['no_backup'] = None
426 revert(ui, repo, **revert_opts)
426 revert(ui, repo, **revert_opts)
427 if not opts.get('merge') and op1 != node:
427 if not opts.get('merge') and op1 != node:
428 try:
428 try:
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
430 return hg.update(repo, op1)
430 return hg.update(repo, op1)
431 finally:
431 finally:
432 ui.setconfig('ui', 'forcemerge', '')
432 ui.setconfig('ui', 'forcemerge', '')
433
433
434 commit_opts = opts.copy()
434 commit_opts = opts.copy()
435 commit_opts['addremove'] = False
435 commit_opts['addremove'] = False
436 if not commit_opts['message'] and not commit_opts['logfile']:
436 if not commit_opts['message'] and not commit_opts['logfile']:
437 # we don't translate commit messages
437 # we don't translate commit messages
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
439 commit_opts['force_editor'] = True
439 commit_opts['force_editor'] = True
440 commit(ui, repo, **commit_opts)
440 commit(ui, repo, **commit_opts)
441 def nice(node):
441 def nice(node):
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
443 ui.status(_('changeset %s backs out changeset %s\n') %
443 ui.status(_('changeset %s backs out changeset %s\n') %
444 (nice(repo.changelog.tip()), nice(node)))
444 (nice(repo.changelog.tip()), nice(node)))
445 if opts.get('merge') and op1 != node:
445 if opts.get('merge') and op1 != node:
446 hg.clean(repo, op1, show_stats=False)
446 hg.clean(repo, op1, show_stats=False)
447 ui.status(_('merging with changeset %s\n')
447 ui.status(_('merging with changeset %s\n')
448 % nice(repo.changelog.tip()))
448 % nice(repo.changelog.tip()))
449 try:
449 try:
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 return hg.merge(repo, hex(repo.changelog.tip()))
451 return hg.merge(repo, hex(repo.changelog.tip()))
452 finally:
452 finally:
453 ui.setconfig('ui', 'forcemerge', '')
453 ui.setconfig('ui', 'forcemerge', '')
454 return 0
454 return 0
455
455
456 @command('bisect',
456 @command('bisect',
457 [('r', 'reset', False, _('reset bisect state')),
457 [('r', 'reset', False, _('reset bisect state')),
458 ('g', 'good', False, _('mark changeset good')),
458 ('g', 'good', False, _('mark changeset good')),
459 ('b', 'bad', False, _('mark changeset bad')),
459 ('b', 'bad', False, _('mark changeset bad')),
460 ('s', 'skip', False, _('skip testing changeset')),
460 ('s', 'skip', False, _('skip testing changeset')),
461 ('e', 'extend', False, _('extend the bisect range')),
461 ('e', 'extend', False, _('extend the bisect range')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
463 ('U', 'noupdate', False, _('do not update to target'))],
463 ('U', 'noupdate', False, _('do not update to target'))],
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
465 def bisect(ui, repo, rev=None, extra=None, command=None,
465 def bisect(ui, repo, rev=None, extra=None, command=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
467 noupdate=None):
467 noupdate=None):
468 """subdivision search of changesets
468 """subdivision search of changesets
469
469
470 This command helps to find changesets which introduce problems. To
470 This command helps to find changesets which introduce problems. To
471 use, mark the earliest changeset you know exhibits the problem as
471 use, mark the earliest changeset you know exhibits the problem as
472 bad, then mark the latest changeset which is free from the problem
472 bad, then mark the latest changeset which is free from the problem
473 as good. Bisect will update your working directory to a revision
473 as good. Bisect will update your working directory to a revision
474 for testing (unless the -U/--noupdate option is specified). Once
474 for testing (unless the -U/--noupdate option is specified). Once
475 you have performed tests, mark the working directory as good or
475 you have performed tests, mark the working directory as good or
476 bad, and bisect will either update to another candidate changeset
476 bad, and bisect will either update to another candidate changeset
477 or announce that it has found the bad revision.
477 or announce that it has found the bad revision.
478
478
479 As a shortcut, you can also use the revision argument to mark a
479 As a shortcut, you can also use the revision argument to mark a
480 revision as good or bad without checking it out first.
480 revision as good or bad without checking it out first.
481
481
482 If you supply a command, it will be used for automatic bisection.
482 If you supply a command, it will be used for automatic bisection.
483 Its exit status will be used to mark revisions as good or bad:
483 Its exit status will be used to mark revisions as good or bad:
484 status 0 means good, 125 means to skip the revision, 127
484 status 0 means good, 125 means to skip the revision, 127
485 (command not found) will abort the bisection, and any other
485 (command not found) will abort the bisection, and any other
486 non-zero exit status means the revision is bad.
486 non-zero exit status means the revision is bad.
487
487
488 Returns 0 on success.
488 Returns 0 on success.
489 """
489 """
490 def extendbisectrange(nodes, good):
490 def extendbisectrange(nodes, good):
491 # bisect is incomplete when it ends on a merge node and
491 # bisect is incomplete when it ends on a merge node and
492 # one of the parent was not checked.
492 # one of the parent was not checked.
493 parents = repo[nodes[0]].parents()
493 parents = repo[nodes[0]].parents()
494 if len(parents) > 1:
494 if len(parents) > 1:
495 side = good and state['bad'] or state['good']
495 side = good and state['bad'] or state['good']
496 num = len(set(i.node() for i in parents) & set(side))
496 num = len(set(i.node() for i in parents) & set(side))
497 if num == 1:
497 if num == 1:
498 return parents[0].ancestor(parents[1])
498 return parents[0].ancestor(parents[1])
499 return None
499 return None
500
500
501 def print_result(nodes, good):
501 def print_result(nodes, good):
502 displayer = cmdutil.show_changeset(ui, repo, {})
502 displayer = cmdutil.show_changeset(ui, repo, {})
503 if len(nodes) == 1:
503 if len(nodes) == 1:
504 # narrowed it down to a single revision
504 # narrowed it down to a single revision
505 if good:
505 if good:
506 ui.write(_("The first good revision is:\n"))
506 ui.write(_("The first good revision is:\n"))
507 else:
507 else:
508 ui.write(_("The first bad revision is:\n"))
508 ui.write(_("The first bad revision is:\n"))
509 displayer.show(repo[nodes[0]])
509 displayer.show(repo[nodes[0]])
510 extendnode = extendbisectrange(nodes, good)
510 extendnode = extendbisectrange(nodes, good)
511 if extendnode is not None:
511 if extendnode is not None:
512 ui.write(_('Not all ancestors of this changeset have been'
512 ui.write(_('Not all ancestors of this changeset have been'
513 ' checked.\nUse bisect --extend to continue the '
513 ' checked.\nUse bisect --extend to continue the '
514 'bisection from\nthe common ancestor, %s.\n')
514 'bisection from\nthe common ancestor, %s.\n')
515 % extendnode)
515 % extendnode)
516 else:
516 else:
517 # multiple possible revisions
517 # multiple possible revisions
518 if good:
518 if good:
519 ui.write(_("Due to skipped revisions, the first "
519 ui.write(_("Due to skipped revisions, the first "
520 "good revision could be any of:\n"))
520 "good revision could be any of:\n"))
521 else:
521 else:
522 ui.write(_("Due to skipped revisions, the first "
522 ui.write(_("Due to skipped revisions, the first "
523 "bad revision could be any of:\n"))
523 "bad revision could be any of:\n"))
524 for n in nodes:
524 for n in nodes:
525 displayer.show(repo[n])
525 displayer.show(repo[n])
526 displayer.close()
526 displayer.close()
527
527
528 def check_state(state, interactive=True):
528 def check_state(state, interactive=True):
529 if not state['good'] or not state['bad']:
529 if not state['good'] or not state['bad']:
530 if (good or bad or skip or reset) and interactive:
530 if (good or bad or skip or reset) and interactive:
531 return
531 return
532 if not state['good']:
532 if not state['good']:
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
534 else:
534 else:
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
536 return True
536 return True
537
537
538 # backward compatibility
538 # backward compatibility
539 if rev in "good bad reset init".split():
539 if rev in "good bad reset init".split():
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
541 cmd, rev, extra = rev, extra, None
541 cmd, rev, extra = rev, extra, None
542 if cmd == "good":
542 if cmd == "good":
543 good = True
543 good = True
544 elif cmd == "bad":
544 elif cmd == "bad":
545 bad = True
545 bad = True
546 else:
546 else:
547 reset = True
547 reset = True
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
549 raise util.Abort(_('incompatible arguments'))
549 raise util.Abort(_('incompatible arguments'))
550
550
551 if reset:
551 if reset:
552 p = repo.join("bisect.state")
552 p = repo.join("bisect.state")
553 if os.path.exists(p):
553 if os.path.exists(p):
554 os.unlink(p)
554 os.unlink(p)
555 return
555 return
556
556
557 state = hbisect.load_state(repo)
557 state = hbisect.load_state(repo)
558
558
559 if command:
559 if command:
560 changesets = 1
560 changesets = 1
561 try:
561 try:
562 while changesets:
562 while changesets:
563 # update state
563 # update state
564 status = util.system(command)
564 status = util.system(command)
565 if status == 125:
565 if status == 125:
566 transition = "skip"
566 transition = "skip"
567 elif status == 0:
567 elif status == 0:
568 transition = "good"
568 transition = "good"
569 # status < 0 means process was killed
569 # status < 0 means process was killed
570 elif status == 127:
570 elif status == 127:
571 raise util.Abort(_("failed to execute %s") % command)
571 raise util.Abort(_("failed to execute %s") % command)
572 elif status < 0:
572 elif status < 0:
573 raise util.Abort(_("%s killed") % command)
573 raise util.Abort(_("%s killed") % command)
574 else:
574 else:
575 transition = "bad"
575 transition = "bad"
576 ctx = scmutil.revsingle(repo, rev)
576 ctx = scmutil.revsingle(repo, rev)
577 rev = None # clear for future iterations
577 rev = None # clear for future iterations
578 state[transition].append(ctx.node())
578 state[transition].append(ctx.node())
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
580 check_state(state, interactive=False)
580 check_state(state, interactive=False)
581 # bisect
581 # bisect
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
583 # update to next check
583 # update to next check
584 cmdutil.bailifchanged(repo)
584 cmdutil.bailifchanged(repo)
585 hg.clean(repo, nodes[0], show_stats=False)
585 hg.clean(repo, nodes[0], show_stats=False)
586 finally:
586 finally:
587 hbisect.save_state(repo, state)
587 hbisect.save_state(repo, state)
588 print_result(nodes, good)
588 print_result(nodes, good)
589 return
589 return
590
590
591 # update state
591 # update state
592
592
593 if rev:
593 if rev:
594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
595 else:
595 else:
596 nodes = [repo.lookup('.')]
596 nodes = [repo.lookup('.')]
597
597
598 if good or bad or skip:
598 if good or bad or skip:
599 if good:
599 if good:
600 state['good'] += nodes
600 state['good'] += nodes
601 elif bad:
601 elif bad:
602 state['bad'] += nodes
602 state['bad'] += nodes
603 elif skip:
603 elif skip:
604 state['skip'] += nodes
604 state['skip'] += nodes
605 hbisect.save_state(repo, state)
605 hbisect.save_state(repo, state)
606
606
607 if not check_state(state):
607 if not check_state(state):
608 return
608 return
609
609
610 # actually bisect
610 # actually bisect
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
612 if extend:
612 if extend:
613 if not changesets:
613 if not changesets:
614 extendnode = extendbisectrange(nodes, good)
614 extendnode = extendbisectrange(nodes, good)
615 if extendnode is not None:
615 if extendnode is not None:
616 ui.write(_("Extending search to changeset %d:%s\n"
616 ui.write(_("Extending search to changeset %d:%s\n"
617 % (extendnode.rev(), extendnode)))
617 % (extendnode.rev(), extendnode)))
618 if noupdate:
618 if noupdate:
619 return
619 return
620 cmdutil.bailifchanged(repo)
620 cmdutil.bailifchanged(repo)
621 return hg.clean(repo, extendnode.node())
621 return hg.clean(repo, extendnode.node())
622 raise util.Abort(_("nothing to extend"))
622 raise util.Abort(_("nothing to extend"))
623
623
624 if changesets == 0:
624 if changesets == 0:
625 print_result(nodes, good)
625 print_result(nodes, good)
626 else:
626 else:
627 assert len(nodes) == 1 # only a single node can be tested next
627 assert len(nodes) == 1 # only a single node can be tested next
628 node = nodes[0]
628 node = nodes[0]
629 # compute the approximate number of remaining tests
629 # compute the approximate number of remaining tests
630 tests, size = 0, 2
630 tests, size = 0, 2
631 while size <= changesets:
631 while size <= changesets:
632 tests, size = tests + 1, size * 2
632 tests, size = tests + 1, size * 2
633 rev = repo.changelog.rev(node)
633 rev = repo.changelog.rev(node)
634 ui.write(_("Testing changeset %d:%s "
634 ui.write(_("Testing changeset %d:%s "
635 "(%d changesets remaining, ~%d tests)\n")
635 "(%d changesets remaining, ~%d tests)\n")
636 % (rev, short(node), changesets, tests))
636 % (rev, short(node), changesets, tests))
637 if not noupdate:
637 if not noupdate:
638 cmdutil.bailifchanged(repo)
638 cmdutil.bailifchanged(repo)
639 return hg.clean(repo, node)
639 return hg.clean(repo, node)
640
640
641 @command('bookmarks',
641 @command('bookmarks',
642 [('f', 'force', False, _('force')),
642 [('f', 'force', False, _('force')),
643 ('r', 'rev', '', _('revision'), _('REV')),
643 ('r', 'rev', '', _('revision'), _('REV')),
644 ('d', 'delete', False, _('delete a given bookmark')),
644 ('d', 'delete', False, _('delete a given bookmark')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
649 rename=None, inactive=False):
649 rename=None, inactive=False):
650 '''track a line of development with movable markers
650 '''track a line of development with movable markers
651
651
652 Bookmarks are pointers to certain commits that move when
652 Bookmarks are pointers to certain commits that move when
653 committing. Bookmarks are local. They can be renamed, copied and
653 committing. Bookmarks are local. They can be renamed, copied and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
655 :hg:`update` to merge and update respectively to a given bookmark.
655 :hg:`update` to merge and update respectively to a given bookmark.
656
656
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
658 directory's parent revision with the given name. If you specify
658 directory's parent revision with the given name. If you specify
659 a revision using -r REV (where REV may be an existing bookmark),
659 a revision using -r REV (where REV may be an existing bookmark),
660 the bookmark is assigned to that revision.
660 the bookmark is assigned to that revision.
661
661
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
663 push` and :hg:`help pull`). This requires both the local and remote
663 push` and :hg:`help pull`). This requires both the local and remote
664 repositories to support bookmarks. For versions prior to 1.8, this means
664 repositories to support bookmarks. For versions prior to 1.8, this means
665 the bookmarks extension must be enabled.
665 the bookmarks extension must be enabled.
666 '''
666 '''
667 hexfn = ui.debugflag and hex or short
667 hexfn = ui.debugflag and hex or short
668 marks = repo._bookmarks
668 marks = repo._bookmarks
669 cur = repo.changectx('.').node()
669 cur = repo.changectx('.').node()
670
670
671 if rename:
671 if rename:
672 if rename not in marks:
672 if rename not in marks:
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
674 if mark in marks and not force:
674 if mark in marks and not force:
675 raise util.Abort(_("bookmark '%s' already exists "
675 raise util.Abort(_("bookmark '%s' already exists "
676 "(use -f to force)") % mark)
676 "(use -f to force)") % mark)
677 if mark is None:
677 if mark is None:
678 raise util.Abort(_("new bookmark name required"))
678 raise util.Abort(_("new bookmark name required"))
679 marks[mark] = marks[rename]
679 marks[mark] = marks[rename]
680 if repo._bookmarkcurrent == rename and not inactive:
680 if repo._bookmarkcurrent == rename and not inactive:
681 bookmarks.setcurrent(repo, mark)
681 bookmarks.setcurrent(repo, mark)
682 del marks[rename]
682 del marks[rename]
683 bookmarks.write(repo)
683 bookmarks.write(repo)
684 return
684 return
685
685
686 if delete:
686 if delete:
687 if mark is None:
687 if mark is None:
688 raise util.Abort(_("bookmark name required"))
688 raise util.Abort(_("bookmark name required"))
689 if mark not in marks:
689 if mark not in marks:
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
691 if mark == repo._bookmarkcurrent:
691 if mark == repo._bookmarkcurrent:
692 bookmarks.setcurrent(repo, None)
692 bookmarks.setcurrent(repo, None)
693 del marks[mark]
693 del marks[mark]
694 bookmarks.write(repo)
694 bookmarks.write(repo)
695 return
695 return
696
696
697 if mark is not None:
697 if mark is not None:
698 if "\n" in mark:
698 if "\n" in mark:
699 raise util.Abort(_("bookmark name cannot contain newlines"))
699 raise util.Abort(_("bookmark name cannot contain newlines"))
700 mark = mark.strip()
700 mark = mark.strip()
701 if not mark:
701 if not mark:
702 raise util.Abort(_("bookmark names cannot consist entirely of "
702 raise util.Abort(_("bookmark names cannot consist entirely of "
703 "whitespace"))
703 "whitespace"))
704 if inactive and mark == repo._bookmarkcurrent:
704 if inactive and mark == repo._bookmarkcurrent:
705 bookmarks.setcurrent(repo, None)
705 bookmarks.setcurrent(repo, None)
706 return
706 return
707 if mark in marks and not force:
707 if mark in marks and not force:
708 raise util.Abort(_("bookmark '%s' already exists "
708 raise util.Abort(_("bookmark '%s' already exists "
709 "(use -f to force)") % mark)
709 "(use -f to force)") % mark)
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
711 and not force):
711 and not force):
712 raise util.Abort(
712 raise util.Abort(
713 _("a bookmark cannot have the name of an existing branch"))
713 _("a bookmark cannot have the name of an existing branch"))
714 if rev:
714 if rev:
715 marks[mark] = repo.lookup(rev)
715 marks[mark] = repo.lookup(rev)
716 else:
716 else:
717 marks[mark] = repo.changectx('.').node()
717 marks[mark] = repo.changectx('.').node()
718 if not inactive and repo.changectx('.').node() == marks[mark]:
718 if not inactive and repo.changectx('.').node() == marks[mark]:
719 bookmarks.setcurrent(repo, mark)
719 bookmarks.setcurrent(repo, mark)
720 bookmarks.write(repo)
720 bookmarks.write(repo)
721 return
721 return
722
722
723 if mark is None:
723 if mark is None:
724 if rev:
724 if rev:
725 raise util.Abort(_("bookmark name required"))
725 raise util.Abort(_("bookmark name required"))
726 if len(marks) == 0:
726 if len(marks) == 0:
727 ui.status(_("no bookmarks set\n"))
727 ui.status(_("no bookmarks set\n"))
728 else:
728 else:
729 for bmark, n in sorted(marks.iteritems()):
729 for bmark, n in sorted(marks.iteritems()):
730 current = repo._bookmarkcurrent
730 current = repo._bookmarkcurrent
731 if bmark == current and n == cur:
731 if bmark == current and n == cur:
732 prefix, label = '*', 'bookmarks.current'
732 prefix, label = '*', 'bookmarks.current'
733 else:
733 else:
734 prefix, label = ' ', ''
734 prefix, label = ' ', ''
735
735
736 if ui.quiet:
736 if ui.quiet:
737 ui.write("%s\n" % bmark, label=label)
737 ui.write("%s\n" % bmark, label=label)
738 else:
738 else:
739 ui.write(" %s %-25s %d:%s\n" % (
739 ui.write(" %s %-25s %d:%s\n" % (
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
741 label=label)
741 label=label)
742 return
742 return
743
743
744 @command('branch',
744 @command('branch',
745 [('f', 'force', None,
745 [('f', 'force', None,
746 _('set branch name even if it shadows an existing branch')),
746 _('set branch name even if it shadows an existing branch')),
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
748 _('[-fC] [NAME]'))
748 _('[-fC] [NAME]'))
749 def branch(ui, repo, label=None, **opts):
749 def branch(ui, repo, label=None, **opts):
750 """set or show the current branch name
750 """set or show the current branch name
751
751
752 With no argument, show the current branch name. With one argument,
752 With no argument, show the current branch name. With one argument,
753 set the working directory branch name (the branch will not exist
753 set the working directory branch name (the branch will not exist
754 in the repository until the next commit). Standard practice
754 in the repository until the next commit). Standard practice
755 recommends that primary development take place on the 'default'
755 recommends that primary development take place on the 'default'
756 branch.
756 branch.
757
757
758 Unless -f/--force is specified, branch will not let you set a
758 Unless -f/--force is specified, branch will not let you set a
759 branch name that already exists, even if it's inactive.
759 branch name that already exists, even if it's inactive.
760
760
761 Use -C/--clean to reset the working directory branch to that of
761 Use -C/--clean to reset the working directory branch to that of
762 the parent of the working directory, negating a previous branch
762 the parent of the working directory, negating a previous branch
763 change.
763 change.
764
764
765 Use the command :hg:`update` to switch to an existing branch. Use
765 Use the command :hg:`update` to switch to an existing branch. Use
766 :hg:`commit --close-branch` to mark this branch as closed.
766 :hg:`commit --close-branch` to mark this branch as closed.
767
767
768 Returns 0 on success.
768 Returns 0 on success.
769 """
769 """
770
770
771 if opts.get('clean'):
771 if opts.get('clean'):
772 label = repo[None].p1().branch()
772 label = repo[None].p1().branch()
773 repo.dirstate.setbranch(label)
773 repo.dirstate.setbranch(label)
774 ui.status(_('reset working directory to branch %s\n') % label)
774 ui.status(_('reset working directory to branch %s\n') % label)
775 elif label:
775 elif label:
776 if not opts.get('force') and label in repo.branchtags():
776 if not opts.get('force') and label in repo.branchtags():
777 if label not in [p.branch() for p in repo.parents()]:
777 if label not in [p.branch() for p in repo.parents()]:
778 raise util.Abort(_('a branch of the same name already exists'),
778 raise util.Abort(_('a branch of the same name already exists'),
779 # i18n: "it" refers to an existing branch
779 # i18n: "it" refers to an existing branch
780 hint=_("use 'hg update' to switch to it"))
780 hint=_("use 'hg update' to switch to it"))
781 repo.dirstate.setbranch(label)
781 repo.dirstate.setbranch(label)
782 ui.status(_('marked working directory as branch %s\n') % label)
782 ui.status(_('marked working directory as branch %s\n') % label)
783 else:
783 else:
784 ui.write("%s\n" % repo.dirstate.branch())
784 ui.write("%s\n" % repo.dirstate.branch())
785
785
786 @command('branches',
786 @command('branches',
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
788 ('c', 'closed', False, _('show normal and closed branches'))],
788 ('c', 'closed', False, _('show normal and closed branches'))],
789 _('[-ac]'))
789 _('[-ac]'))
790 def branches(ui, repo, active=False, closed=False):
790 def branches(ui, repo, active=False, closed=False):
791 """list repository named branches
791 """list repository named branches
792
792
793 List the repository's named branches, indicating which ones are
793 List the repository's named branches, indicating which ones are
794 inactive. If -c/--closed is specified, also list branches which have
794 inactive. If -c/--closed is specified, also list branches which have
795 been marked closed (see :hg:`commit --close-branch`).
795 been marked closed (see :hg:`commit --close-branch`).
796
796
797 If -a/--active is specified, only show active branches. A branch
797 If -a/--active is specified, only show active branches. A branch
798 is considered active if it contains repository heads.
798 is considered active if it contains repository heads.
799
799
800 Use the command :hg:`update` to switch to an existing branch.
800 Use the command :hg:`update` to switch to an existing branch.
801
801
802 Returns 0.
802 Returns 0.
803 """
803 """
804
804
805 hexfunc = ui.debugflag and hex or short
805 hexfunc = ui.debugflag and hex or short
806 activebranches = [repo[n].branch() for n in repo.heads()]
806 activebranches = [repo[n].branch() for n in repo.heads()]
807 def testactive(tag, node):
807 def testactive(tag, node):
808 realhead = tag in activebranches
808 realhead = tag in activebranches
809 open = node in repo.branchheads(tag, closed=False)
809 open = node in repo.branchheads(tag, closed=False)
810 return realhead and open
810 return realhead and open
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
812 for tag, node in repo.branchtags().items()],
812 for tag, node in repo.branchtags().items()],
813 reverse=True)
813 reverse=True)
814
814
815 for isactive, node, tag in branches:
815 for isactive, node, tag in branches:
816 if (not active) or isactive:
816 if (not active) or isactive:
817 if ui.quiet:
817 if ui.quiet:
818 ui.write("%s\n" % tag)
818 ui.write("%s\n" % tag)
819 else:
819 else:
820 hn = repo.lookup(node)
820 hn = repo.lookup(node)
821 if isactive:
821 if isactive:
822 label = 'branches.active'
822 label = 'branches.active'
823 notice = ''
823 notice = ''
824 elif hn not in repo.branchheads(tag, closed=False):
824 elif hn not in repo.branchheads(tag, closed=False):
825 if not closed:
825 if not closed:
826 continue
826 continue
827 label = 'branches.closed'
827 label = 'branches.closed'
828 notice = _(' (closed)')
828 notice = _(' (closed)')
829 else:
829 else:
830 label = 'branches.inactive'
830 label = 'branches.inactive'
831 notice = _(' (inactive)')
831 notice = _(' (inactive)')
832 if tag == repo.dirstate.branch():
832 if tag == repo.dirstate.branch():
833 label = 'branches.current'
833 label = 'branches.current'
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
836 tag = ui.label(tag, label)
836 tag = ui.label(tag, label)
837 ui.write("%s %s%s\n" % (tag, rev, notice))
837 ui.write("%s %s%s\n" % (tag, rev, notice))
838
838
839 @command('bundle',
839 @command('bundle',
840 [('f', 'force', None, _('run even when the destination is unrelated')),
840 [('f', 'force', None, _('run even when the destination is unrelated')),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
842 _('REV')),
842 _('REV')),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
844 _('BRANCH')),
844 _('BRANCH')),
845 ('', 'base', [],
845 ('', 'base', [],
846 _('a base changeset assumed to be available at the destination'),
846 _('a base changeset assumed to be available at the destination'),
847 _('REV')),
847 _('REV')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
850 ] + remoteopts,
850 ] + remoteopts,
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
852 def bundle(ui, repo, fname, dest=None, **opts):
852 def bundle(ui, repo, fname, dest=None, **opts):
853 """create a changegroup file
853 """create a changegroup file
854
854
855 Generate a compressed changegroup file collecting changesets not
855 Generate a compressed changegroup file collecting changesets not
856 known to be in another repository.
856 known to be in another repository.
857
857
858 If you omit the destination repository, then hg assumes the
858 If you omit the destination repository, then hg assumes the
859 destination will have all the nodes you specify with --base
859 destination will have all the nodes you specify with --base
860 parameters. To create a bundle containing all changesets, use
860 parameters. To create a bundle containing all changesets, use
861 -a/--all (or --base null).
861 -a/--all (or --base null).
862
862
863 You can change compression method with the -t/--type option.
863 You can change compression method with the -t/--type option.
864 The available compression methods are: none, bzip2, and
864 The available compression methods are: none, bzip2, and
865 gzip (by default, bundles are compressed using bzip2).
865 gzip (by default, bundles are compressed using bzip2).
866
866
867 The bundle file can then be transferred using conventional means
867 The bundle file can then be transferred using conventional means
868 and applied to another repository with the unbundle or pull
868 and applied to another repository with the unbundle or pull
869 command. This is useful when direct push and pull are not
869 command. This is useful when direct push and pull are not
870 available or when exporting an entire repository is undesirable.
870 available or when exporting an entire repository is undesirable.
871
871
872 Applying bundles preserves all changeset contents including
872 Applying bundles preserves all changeset contents including
873 permissions, copy/rename information, and revision history.
873 permissions, copy/rename information, and revision history.
874
874
875 Returns 0 on success, 1 if no changes found.
875 Returns 0 on success, 1 if no changes found.
876 """
876 """
877 revs = None
877 revs = None
878 if 'rev' in opts:
878 if 'rev' in opts:
879 revs = scmutil.revrange(repo, opts['rev'])
879 revs = scmutil.revrange(repo, opts['rev'])
880
880
881 if opts.get('all'):
881 if opts.get('all'):
882 base = ['null']
882 base = ['null']
883 else:
883 else:
884 base = scmutil.revrange(repo, opts.get('base'))
884 base = scmutil.revrange(repo, opts.get('base'))
885 if base:
885 if base:
886 if dest:
886 if dest:
887 raise util.Abort(_("--base is incompatible with specifying "
887 raise util.Abort(_("--base is incompatible with specifying "
888 "a destination"))
888 "a destination"))
889 common = [repo.lookup(rev) for rev in base]
889 common = [repo.lookup(rev) for rev in base]
890 heads = revs and map(repo.lookup, revs) or revs
890 heads = revs and map(repo.lookup, revs) or revs
891 else:
891 else:
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
894 other = hg.peer(repo, opts, dest)
894 other = hg.peer(repo, opts, dest)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
896 heads = revs and map(repo.lookup, revs) or revs
896 heads = revs and map(repo.lookup, revs) or revs
897 common, outheads = discovery.findcommonoutgoing(repo, other,
897 common, outheads = discovery.findcommonoutgoing(repo, other,
898 onlyheads=heads,
898 onlyheads=heads,
899 force=opts.get('force'))
899 force=opts.get('force'))
900
900
901 cg = repo.getbundle('bundle', common=common, heads=heads)
901 cg = repo.getbundle('bundle', common=common, heads=heads)
902 if not cg:
902 if not cg:
903 ui.status(_("no changes found\n"))
903 ui.status(_("no changes found\n"))
904 return 1
904 return 1
905
905
906 bundletype = opts.get('type', 'bzip2').lower()
906 bundletype = opts.get('type', 'bzip2').lower()
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
908 bundletype = btypes.get(bundletype)
908 bundletype = btypes.get(bundletype)
909 if bundletype not in changegroup.bundletypes:
909 if bundletype not in changegroup.bundletypes:
910 raise util.Abort(_('unknown bundle type specified with --type'))
910 raise util.Abort(_('unknown bundle type specified with --type'))
911
911
912 changegroup.writebundle(cg, fname, bundletype)
912 changegroup.writebundle(cg, fname, bundletype)
913
913
914 @command('cat',
914 @command('cat',
915 [('o', 'output', '',
915 [('o', 'output', '',
916 _('print output to file with formatted name'), _('FORMAT')),
916 _('print output to file with formatted name'), _('FORMAT')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
918 ('', 'decode', None, _('apply any matching decode filter')),
918 ('', 'decode', None, _('apply any matching decode filter')),
919 ] + walkopts,
919 ] + walkopts,
920 _('[OPTION]... FILE...'))
920 _('[OPTION]... FILE...'))
921 def cat(ui, repo, file1, *pats, **opts):
921 def cat(ui, repo, file1, *pats, **opts):
922 """output the current or given revision of files
922 """output the current or given revision of files
923
923
924 Print the specified files as they were at the given revision. If
924 Print the specified files as they were at the given revision. If
925 no revision is given, the parent of the working directory is used,
925 no revision is given, the parent of the working directory is used,
926 or tip if no revision is checked out.
926 or tip if no revision is checked out.
927
927
928 Output may be to a file, in which case the name of the file is
928 Output may be to a file, in which case the name of the file is
929 given using a format string. The formatting rules are the same as
929 given using a format string. The formatting rules are the same as
930 for the export command, with the following additions:
930 for the export command, with the following additions:
931
931
932 :``%s``: basename of file being printed
932 :``%s``: basename of file being printed
933 :``%d``: dirname of file being printed, or '.' if in repository root
933 :``%d``: dirname of file being printed, or '.' if in repository root
934 :``%p``: root-relative path name of file being printed
934 :``%p``: root-relative path name of file being printed
935
935
936 Returns 0 on success.
936 Returns 0 on success.
937 """
937 """
938 ctx = scmutil.revsingle(repo, opts.get('rev'))
938 ctx = scmutil.revsingle(repo, opts.get('rev'))
939 err = 1
939 err = 1
940 m = scmutil.match(repo, (file1,) + pats, opts)
940 m = scmutil.match(repo, (file1,) + pats, opts)
941 for abs in ctx.walk(m):
941 for abs in ctx.walk(m):
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
943 pathname=abs)
943 pathname=abs)
944 data = ctx[abs].data()
944 data = ctx[abs].data()
945 if opts.get('decode'):
945 if opts.get('decode'):
946 data = repo.wwritedata(abs, data)
946 data = repo.wwritedata(abs, data)
947 fp.write(data)
947 fp.write(data)
948 fp.close()
948 fp.close()
949 err = 0
949 err = 0
950 return err
950 return err
951
951
952 @command('^clone',
952 @command('^clone',
953 [('U', 'noupdate', None,
953 [('U', 'noupdate', None,
954 _('the clone will include an empty working copy (only a repository)')),
954 _('the clone will include an empty working copy (only a repository)')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
960 ] + remoteopts,
960 ] + remoteopts,
961 _('[OPTION]... SOURCE [DEST]'))
961 _('[OPTION]... SOURCE [DEST]'))
962 def clone(ui, source, dest=None, **opts):
962 def clone(ui, source, dest=None, **opts):
963 """make a copy of an existing repository
963 """make a copy of an existing repository
964
964
965 Create a copy of an existing repository in a new directory.
965 Create a copy of an existing repository in a new directory.
966
966
967 If no destination directory name is specified, it defaults to the
967 If no destination directory name is specified, it defaults to the
968 basename of the source.
968 basename of the source.
969
969
970 The location of the source is added to the new repository's
970 The location of the source is added to the new repository's
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
972
972
973 See :hg:`help urls` for valid source format details.
973 See :hg:`help urls` for valid source format details.
974
974
975 It is possible to specify an ``ssh://`` URL as the destination, but no
975 It is possible to specify an ``ssh://`` URL as the destination, but no
976 ``.hg/hgrc`` and working directory will be created on the remote side.
976 ``.hg/hgrc`` and working directory will be created on the remote side.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
978
978
979 A set of changesets (tags, or branch names) to pull may be specified
979 A set of changesets (tags, or branch names) to pull may be specified
980 by listing each changeset (tag, or branch name) with -r/--rev.
980 by listing each changeset (tag, or branch name) with -r/--rev.
981 If -r/--rev is used, the cloned repository will contain only a subset
981 If -r/--rev is used, the cloned repository will contain only a subset
982 of the changesets of the source repository. Only the set of changesets
982 of the changesets of the source repository. Only the set of changesets
983 defined by all -r/--rev options (including all their ancestors)
983 defined by all -r/--rev options (including all their ancestors)
984 will be pulled into the destination repository.
984 will be pulled into the destination repository.
985 No subsequent changesets (including subsequent tags) will be present
985 No subsequent changesets (including subsequent tags) will be present
986 in the destination.
986 in the destination.
987
987
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
989 local source repositories.
989 local source repositories.
990
990
991 For efficiency, hardlinks are used for cloning whenever the source
991 For efficiency, hardlinks are used for cloning whenever the source
992 and destination are on the same filesystem (note this applies only
992 and destination are on the same filesystem (note this applies only
993 to the repository data, not to the working directory). Some
993 to the repository data, not to the working directory). Some
994 filesystems, such as AFS, implement hardlinking incorrectly, but
994 filesystems, such as AFS, implement hardlinking incorrectly, but
995 do not report errors. In these cases, use the --pull option to
995 do not report errors. In these cases, use the --pull option to
996 avoid hardlinking.
996 avoid hardlinking.
997
997
998 In some cases, you can clone repositories and the working directory
998 In some cases, you can clone repositories and the working directory
999 using full hardlinks with ::
999 using full hardlinks with ::
1000
1000
1001 $ cp -al REPO REPOCLONE
1001 $ cp -al REPO REPOCLONE
1002
1002
1003 This is the fastest way to clone, but it is not always safe. The
1003 This is the fastest way to clone, but it is not always safe. The
1004 operation is not atomic (making sure REPO is not modified during
1004 operation is not atomic (making sure REPO is not modified during
1005 the operation is up to you) and you have to make sure your editor
1005 the operation is up to you) and you have to make sure your editor
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1007 this is not compatible with certain extensions that place their
1007 this is not compatible with certain extensions that place their
1008 metadata under the .hg directory, such as mq.
1008 metadata under the .hg directory, such as mq.
1009
1009
1010 Mercurial will update the working directory to the first applicable
1010 Mercurial will update the working directory to the first applicable
1011 revision from this list:
1011 revision from this list:
1012
1012
1013 a) null if -U or the source repository has no changesets
1013 a) null if -U or the source repository has no changesets
1014 b) if -u . and the source repository is local, the first parent of
1014 b) if -u . and the source repository is local, the first parent of
1015 the source repository's working directory
1015 the source repository's working directory
1016 c) the changeset specified with -u (if a branch name, this means the
1016 c) the changeset specified with -u (if a branch name, this means the
1017 latest head of that branch)
1017 latest head of that branch)
1018 d) the changeset specified with -r
1018 d) the changeset specified with -r
1019 e) the tipmost head specified with -b
1019 e) the tipmost head specified with -b
1020 f) the tipmost head specified with the url#branch source syntax
1020 f) the tipmost head specified with the url#branch source syntax
1021 g) the tipmost head of the default branch
1021 g) the tipmost head of the default branch
1022 h) tip
1022 h) tip
1023
1023
1024 Returns 0 on success.
1024 Returns 0 on success.
1025 """
1025 """
1026 if opts.get('noupdate') and opts.get('updaterev'):
1026 if opts.get('noupdate') and opts.get('updaterev'):
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1028
1028
1029 r = hg.clone(ui, opts, source, dest,
1029 r = hg.clone(ui, opts, source, dest,
1030 pull=opts.get('pull'),
1030 pull=opts.get('pull'),
1031 stream=opts.get('uncompressed'),
1031 stream=opts.get('uncompressed'),
1032 rev=opts.get('rev'),
1032 rev=opts.get('rev'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1034 branch=opts.get('branch'))
1034 branch=opts.get('branch'))
1035
1035
1036 return r is None
1036 return r is None
1037
1037
1038 @command('^commit|ci',
1038 @command('^commit|ci',
1039 [('A', 'addremove', None,
1039 [('A', 'addremove', None,
1040 _('mark new/missing files as added/removed before committing')),
1040 _('mark new/missing files as added/removed before committing')),
1041 ('', 'close-branch', None,
1041 ('', 'close-branch', None,
1042 _('mark a branch as closed, hiding it from the branch list')),
1042 _('mark a branch as closed, hiding it from the branch list')),
1043 ] + walkopts + commitopts + commitopts2,
1043 ] + walkopts + commitopts + commitopts2,
1044 _('[OPTION]... [FILE]...'))
1044 _('[OPTION]... [FILE]...'))
1045 def commit(ui, repo, *pats, **opts):
1045 def commit(ui, repo, *pats, **opts):
1046 """commit the specified files or all outstanding changes
1046 """commit the specified files or all outstanding changes
1047
1047
1048 Commit changes to the given files into the repository. Unlike a
1048 Commit changes to the given files into the repository. Unlike a
1049 centralized SCM, this operation is a local operation. See
1049 centralized SCM, this operation is a local operation. See
1050 :hg:`push` for a way to actively distribute your changes.
1050 :hg:`push` for a way to actively distribute your changes.
1051
1051
1052 If a list of files is omitted, all changes reported by :hg:`status`
1052 If a list of files is omitted, all changes reported by :hg:`status`
1053 will be committed.
1053 will be committed.
1054
1054
1055 If you are committing the result of a merge, do not provide any
1055 If you are committing the result of a merge, do not provide any
1056 filenames or -I/-X filters.
1056 filenames or -I/-X filters.
1057
1057
1058 If no commit message is specified, Mercurial starts your
1058 If no commit message is specified, Mercurial starts your
1059 configured editor where you can enter a message. In case your
1059 configured editor where you can enter a message. In case your
1060 commit fails, you will find a backup of your message in
1060 commit fails, you will find a backup of your message in
1061 ``.hg/last-message.txt``.
1061 ``.hg/last-message.txt``.
1062
1062
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1064
1064
1065 Returns 0 on success, 1 if nothing changed.
1065 Returns 0 on success, 1 if nothing changed.
1066 """
1066 """
1067 extra = {}
1067 extra = {}
1068 if opts.get('close_branch'):
1068 if opts.get('close_branch'):
1069 if repo['.'].node() not in repo.branchheads():
1069 if repo['.'].node() not in repo.branchheads():
1070 # The topo heads set is included in the branch heads set of the
1070 # The topo heads set is included in the branch heads set of the
1071 # current branch, so it's sufficient to test branchheads
1071 # current branch, so it's sufficient to test branchheads
1072 raise util.Abort(_('can only close branch heads'))
1072 raise util.Abort(_('can only close branch heads'))
1073 extra['close'] = 1
1073 extra['close'] = 1
1074 e = cmdutil.commiteditor
1074 e = cmdutil.commiteditor
1075 if opts.get('force_editor'):
1075 if opts.get('force_editor'):
1076 e = cmdutil.commitforceeditor
1076 e = cmdutil.commitforceeditor
1077
1077
1078 def commitfunc(ui, repo, message, match, opts):
1078 def commitfunc(ui, repo, message, match, opts):
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1080 editor=e, extra=extra)
1080 editor=e, extra=extra)
1081
1081
1082 branch = repo[None].branch()
1082 branch = repo[None].branch()
1083 bheads = repo.branchheads(branch)
1083 bheads = repo.branchheads(branch)
1084
1084
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1086 if not node:
1086 if not node:
1087 stat = repo.status(match=scmutil.match(repo, pats, opts))
1087 stat = repo.status(match=scmutil.match(repo, pats, opts))
1088 if stat[3]:
1088 if stat[3]:
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1090 % len(stat[3]))
1090 % len(stat[3]))
1091 else:
1091 else:
1092 ui.status(_("nothing changed\n"))
1092 ui.status(_("nothing changed\n"))
1093 return 1
1093 return 1
1094
1094
1095 ctx = repo[node]
1095 ctx = repo[node]
1096 parents = ctx.parents()
1096 parents = ctx.parents()
1097
1097
1098 if bheads and not [x for x in parents
1098 if bheads and not [x for x in parents
1099 if x.node() in bheads and x.branch() == branch]:
1099 if x.node() in bheads and x.branch() == branch]:
1100 ui.status(_('created new head\n'))
1100 ui.status(_('created new head\n'))
1101 # The message is not printed for initial roots. For the other
1101 # The message is not printed for initial roots. For the other
1102 # changesets, it is printed in the following situations:
1102 # changesets, it is printed in the following situations:
1103 #
1103 #
1104 # Par column: for the 2 parents with ...
1104 # Par column: for the 2 parents with ...
1105 # N: null or no parent
1105 # N: null or no parent
1106 # B: parent is on another named branch
1106 # B: parent is on another named branch
1107 # C: parent is a regular non head changeset
1107 # C: parent is a regular non head changeset
1108 # H: parent was a branch head of the current branch
1108 # H: parent was a branch head of the current branch
1109 # Msg column: whether we print "created new head" message
1109 # Msg column: whether we print "created new head" message
1110 # In the following, it is assumed that there already exists some
1110 # In the following, it is assumed that there already exists some
1111 # initial branch heads of the current branch, otherwise nothing is
1111 # initial branch heads of the current branch, otherwise nothing is
1112 # printed anyway.
1112 # printed anyway.
1113 #
1113 #
1114 # Par Msg Comment
1114 # Par Msg Comment
1115 # NN y additional topo root
1115 # NN y additional topo root
1116 #
1116 #
1117 # BN y additional branch root
1117 # BN y additional branch root
1118 # CN y additional topo head
1118 # CN y additional topo head
1119 # HN n usual case
1119 # HN n usual case
1120 #
1120 #
1121 # BB y weird additional branch root
1121 # BB y weird additional branch root
1122 # CB y branch merge
1122 # CB y branch merge
1123 # HB n merge with named branch
1123 # HB n merge with named branch
1124 #
1124 #
1125 # CC y additional head from merge
1125 # CC y additional head from merge
1126 # CH n merge with a head
1126 # CH n merge with a head
1127 #
1127 #
1128 # HH n head merge: head count decreases
1128 # HH n head merge: head count decreases
1129
1129
1130 if not opts.get('close_branch'):
1130 if not opts.get('close_branch'):
1131 for r in parents:
1131 for r in parents:
1132 if r.extra().get('close') and r.branch() == branch:
1132 if r.extra().get('close') and r.branch() == branch:
1133 ui.status(_('reopening closed branch head %d\n') % r)
1133 ui.status(_('reopening closed branch head %d\n') % r)
1134
1134
1135 if ui.debugflag:
1135 if ui.debugflag:
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1137 elif ui.verbose:
1137 elif ui.verbose:
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1139
1139
1140 @command('copy|cp',
1140 @command('copy|cp',
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1143 ] + walkopts + dryrunopts,
1143 ] + walkopts + dryrunopts,
1144 _('[OPTION]... [SOURCE]... DEST'))
1144 _('[OPTION]... [SOURCE]... DEST'))
1145 def copy(ui, repo, *pats, **opts):
1145 def copy(ui, repo, *pats, **opts):
1146 """mark files as copied for the next commit
1146 """mark files as copied for the next commit
1147
1147
1148 Mark dest as having copies of source files. If dest is a
1148 Mark dest as having copies of source files. If dest is a
1149 directory, copies are put in that directory. If dest is a file,
1149 directory, copies are put in that directory. If dest is a file,
1150 the source must be a single file.
1150 the source must be a single file.
1151
1151
1152 By default, this command copies the contents of files as they
1152 By default, this command copies the contents of files as they
1153 exist in the working directory. If invoked with -A/--after, the
1153 exist in the working directory. If invoked with -A/--after, the
1154 operation is recorded, but no copying is performed.
1154 operation is recorded, but no copying is performed.
1155
1155
1156 This command takes effect with the next commit. To undo a copy
1156 This command takes effect with the next commit. To undo a copy
1157 before that, see :hg:`revert`.
1157 before that, see :hg:`revert`.
1158
1158
1159 Returns 0 on success, 1 if errors are encountered.
1159 Returns 0 on success, 1 if errors are encountered.
1160 """
1160 """
1161 wlock = repo.wlock(False)
1161 wlock = repo.wlock(False)
1162 try:
1162 try:
1163 return cmdutil.copy(ui, repo, pats, opts)
1163 return cmdutil.copy(ui, repo, pats, opts)
1164 finally:
1164 finally:
1165 wlock.release()
1165 wlock.release()
1166
1166
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1168 def debugancestor(ui, repo, *args):
1168 def debugancestor(ui, repo, *args):
1169 """find the ancestor revision of two revisions in a given index"""
1169 """find the ancestor revision of two revisions in a given index"""
1170 if len(args) == 3:
1170 if len(args) == 3:
1171 index, rev1, rev2 = args
1171 index, rev1, rev2 = args
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1173 lookup = r.lookup
1173 lookup = r.lookup
1174 elif len(args) == 2:
1174 elif len(args) == 2:
1175 if not repo:
1175 if not repo:
1176 raise util.Abort(_("there is no Mercurial repository here "
1176 raise util.Abort(_("there is no Mercurial repository here "
1177 "(.hg not found)"))
1177 "(.hg not found)"))
1178 rev1, rev2 = args
1178 rev1, rev2 = args
1179 r = repo.changelog
1179 r = repo.changelog
1180 lookup = repo.lookup
1180 lookup = repo.lookup
1181 else:
1181 else:
1182 raise util.Abort(_('either two or three arguments required'))
1182 raise util.Abort(_('either two or three arguments required'))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1185
1185
1186 @command('debugbuilddag',
1186 @command('debugbuilddag',
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1190 _('[OPTION]... [TEXT]'))
1190 _('[OPTION]... [TEXT]'))
1191 def debugbuilddag(ui, repo, text=None,
1191 def debugbuilddag(ui, repo, text=None,
1192 mergeable_file=False,
1192 mergeable_file=False,
1193 overwritten_file=False,
1193 overwritten_file=False,
1194 new_file=False):
1194 new_file=False):
1195 """builds a repo with a given DAG from scratch in the current empty repo
1195 """builds a repo with a given DAG from scratch in the current empty repo
1196
1196
1197 The description of the DAG is read from stdin if not given on the
1197 The description of the DAG is read from stdin if not given on the
1198 command line.
1198 command line.
1199
1199
1200 Elements:
1200 Elements:
1201
1201
1202 - "+n" is a linear run of n nodes based on the current default parent
1202 - "+n" is a linear run of n nodes based on the current default parent
1203 - "." is a single node based on the current default parent
1203 - "." is a single node based on the current default parent
1204 - "$" resets the default parent to null (implied at the start);
1204 - "$" resets the default parent to null (implied at the start);
1205 otherwise the default parent is always the last node created
1205 otherwise the default parent is always the last node created
1206 - "<p" sets the default parent to the backref p
1206 - "<p" sets the default parent to the backref p
1207 - "*p" is a fork at parent p, which is a backref
1207 - "*p" is a fork at parent p, which is a backref
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1209 - "/p2" is a merge of the preceding node and p2
1209 - "/p2" is a merge of the preceding node and p2
1210 - ":tag" defines a local tag for the preceding node
1210 - ":tag" defines a local tag for the preceding node
1211 - "@branch" sets the named branch for subsequent nodes
1211 - "@branch" sets the named branch for subsequent nodes
1212 - "#...\\n" is a comment up to the end of the line
1212 - "#...\\n" is a comment up to the end of the line
1213
1213
1214 Whitespace between the above elements is ignored.
1214 Whitespace between the above elements is ignored.
1215
1215
1216 A backref is either
1216 A backref is either
1217
1217
1218 - a number n, which references the node curr-n, where curr is the current
1218 - a number n, which references the node curr-n, where curr is the current
1219 node, or
1219 node, or
1220 - the name of a local tag you placed earlier using ":tag", or
1220 - the name of a local tag you placed earlier using ":tag", or
1221 - empty to denote the default parent.
1221 - empty to denote the default parent.
1222
1222
1223 All string valued-elements are either strictly alphanumeric, or must
1223 All string valued-elements are either strictly alphanumeric, or must
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1225 """
1225 """
1226
1226
1227 if text is None:
1227 if text is None:
1228 ui.status(_("reading DAG from stdin\n"))
1228 ui.status(_("reading DAG from stdin\n"))
1229 text = sys.stdin.read()
1229 text = sys.stdin.read()
1230
1230
1231 cl = repo.changelog
1231 cl = repo.changelog
1232 if len(cl) > 0:
1232 if len(cl) > 0:
1233 raise util.Abort(_('repository is not empty'))
1233 raise util.Abort(_('repository is not empty'))
1234
1234
1235 # determine number of revs in DAG
1235 # determine number of revs in DAG
1236 total = 0
1236 total = 0
1237 for type, data in dagparser.parsedag(text):
1237 for type, data in dagparser.parsedag(text):
1238 if type == 'n':
1238 if type == 'n':
1239 total += 1
1239 total += 1
1240
1240
1241 if mergeable_file:
1241 if mergeable_file:
1242 linesperrev = 2
1242 linesperrev = 2
1243 # make a file with k lines per rev
1243 # make a file with k lines per rev
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1245 initialmergedlines.append("")
1245 initialmergedlines.append("")
1246
1246
1247 tags = []
1247 tags = []
1248
1248
1249 tr = repo.transaction("builddag")
1249 tr = repo.transaction("builddag")
1250 try:
1250 try:
1251
1251
1252 at = -1
1252 at = -1
1253 atbranch = 'default'
1253 atbranch = 'default'
1254 nodeids = []
1254 nodeids = []
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1256 for type, data in dagparser.parsedag(text):
1256 for type, data in dagparser.parsedag(text):
1257 if type == 'n':
1257 if type == 'n':
1258 ui.note('node %s\n' % str(data))
1258 ui.note('node %s\n' % str(data))
1259 id, ps = data
1259 id, ps = data
1260
1260
1261 files = []
1261 files = []
1262 fctxs = {}
1262 fctxs = {}
1263
1263
1264 p2 = None
1264 p2 = None
1265 if mergeable_file:
1265 if mergeable_file:
1266 fn = "mf"
1266 fn = "mf"
1267 p1 = repo[ps[0]]
1267 p1 = repo[ps[0]]
1268 if len(ps) > 1:
1268 if len(ps) > 1:
1269 p2 = repo[ps[1]]
1269 p2 = repo[ps[1]]
1270 pa = p1.ancestor(p2)
1270 pa = p1.ancestor(p2)
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1272 m3 = simplemerge.Merge3Text(base, local, other)
1272 m3 = simplemerge.Merge3Text(base, local, other)
1273 ml = [l.strip() for l in m3.merge_lines()]
1273 ml = [l.strip() for l in m3.merge_lines()]
1274 ml.append("")
1274 ml.append("")
1275 elif at > 0:
1275 elif at > 0:
1276 ml = p1[fn].data().split("\n")
1276 ml = p1[fn].data().split("\n")
1277 else:
1277 else:
1278 ml = initialmergedlines
1278 ml = initialmergedlines
1279 ml[id * linesperrev] += " r%i" % id
1279 ml[id * linesperrev] += " r%i" % id
1280 mergedtext = "\n".join(ml)
1280 mergedtext = "\n".join(ml)
1281 files.append(fn)
1281 files.append(fn)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1283
1283
1284 if overwritten_file:
1284 if overwritten_file:
1285 fn = "of"
1285 fn = "of"
1286 files.append(fn)
1286 files.append(fn)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1288
1288
1289 if new_file:
1289 if new_file:
1290 fn = "nf%i" % id
1290 fn = "nf%i" % id
1291 files.append(fn)
1291 files.append(fn)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1293 if len(ps) > 1:
1293 if len(ps) > 1:
1294 if not p2:
1294 if not p2:
1295 p2 = repo[ps[1]]
1295 p2 = repo[ps[1]]
1296 for fn in p2:
1296 for fn in p2:
1297 if fn.startswith("nf"):
1297 if fn.startswith("nf"):
1298 files.append(fn)
1298 files.append(fn)
1299 fctxs[fn] = p2[fn]
1299 fctxs[fn] = p2[fn]
1300
1300
1301 def fctxfn(repo, cx, path):
1301 def fctxfn(repo, cx, path):
1302 return fctxs.get(path)
1302 return fctxs.get(path)
1303
1303
1304 if len(ps) == 0 or ps[0] < 0:
1304 if len(ps) == 0 or ps[0] < 0:
1305 pars = [None, None]
1305 pars = [None, None]
1306 elif len(ps) == 1:
1306 elif len(ps) == 1:
1307 pars = [nodeids[ps[0]], None]
1307 pars = [nodeids[ps[0]], None]
1308 else:
1308 else:
1309 pars = [nodeids[p] for p in ps]
1309 pars = [nodeids[p] for p in ps]
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1311 date=(id, 0),
1311 date=(id, 0),
1312 user="debugbuilddag",
1312 user="debugbuilddag",
1313 extra={'branch': atbranch})
1313 extra={'branch': atbranch})
1314 nodeid = repo.commitctx(cx)
1314 nodeid = repo.commitctx(cx)
1315 nodeids.append(nodeid)
1315 nodeids.append(nodeid)
1316 at = id
1316 at = id
1317 elif type == 'l':
1317 elif type == 'l':
1318 id, name = data
1318 id, name = data
1319 ui.note('tag %s\n' % name)
1319 ui.note('tag %s\n' % name)
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1321 elif type == 'a':
1321 elif type == 'a':
1322 ui.note('branch %s\n' % data)
1322 ui.note('branch %s\n' % data)
1323 atbranch = data
1323 atbranch = data
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1325 tr.close()
1325 tr.close()
1326 finally:
1326 finally:
1327 ui.progress(_('building'), None)
1327 ui.progress(_('building'), None)
1328 tr.release()
1328 tr.release()
1329
1329
1330 if tags:
1330 if tags:
1331 repo.opener.write("localtags", "".join(tags))
1331 repo.opener.write("localtags", "".join(tags))
1332
1332
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1335 """lists the contents of a bundle"""
1335 """lists the contents of a bundle"""
1336 f = url.open(ui, bundlepath)
1336 f = url.open(ui, bundlepath)
1337 try:
1337 try:
1338 gen = changegroup.readbundle(f, bundlepath)
1338 gen = changegroup.readbundle(f, bundlepath)
1339 if all:
1339 if all:
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1341
1341
1342 def showchunks(named):
1342 def showchunks(named):
1343 ui.write("\n%s\n" % named)
1343 ui.write("\n%s\n" % named)
1344 chain = None
1344 chain = None
1345 while True:
1345 while True:
1346 chunkdata = gen.deltachunk(chain)
1346 chunkdata = gen.deltachunk(chain)
1347 if not chunkdata:
1347 if not chunkdata:
1348 break
1348 break
1349 node = chunkdata['node']
1349 node = chunkdata['node']
1350 p1 = chunkdata['p1']
1350 p1 = chunkdata['p1']
1351 p2 = chunkdata['p2']
1351 p2 = chunkdata['p2']
1352 cs = chunkdata['cs']
1352 cs = chunkdata['cs']
1353 deltabase = chunkdata['deltabase']
1353 deltabase = chunkdata['deltabase']
1354 delta = chunkdata['delta']
1354 delta = chunkdata['delta']
1355 ui.write("%s %s %s %s %s %s\n" %
1355 ui.write("%s %s %s %s %s %s\n" %
1356 (hex(node), hex(p1), hex(p2),
1356 (hex(node), hex(p1), hex(p2),
1357 hex(cs), hex(deltabase), len(delta)))
1357 hex(cs), hex(deltabase), len(delta)))
1358 chain = node
1358 chain = node
1359
1359
1360 chunkdata = gen.changelogheader()
1360 chunkdata = gen.changelogheader()
1361 showchunks("changelog")
1361 showchunks("changelog")
1362 chunkdata = gen.manifestheader()
1362 chunkdata = gen.manifestheader()
1363 showchunks("manifest")
1363 showchunks("manifest")
1364 while True:
1364 while True:
1365 chunkdata = gen.filelogheader()
1365 chunkdata = gen.filelogheader()
1366 if not chunkdata:
1366 if not chunkdata:
1367 break
1367 break
1368 fname = chunkdata['filename']
1368 fname = chunkdata['filename']
1369 showchunks(fname)
1369 showchunks(fname)
1370 else:
1370 else:
1371 chunkdata = gen.changelogheader()
1371 chunkdata = gen.changelogheader()
1372 chain = None
1372 chain = None
1373 while True:
1373 while True:
1374 chunkdata = gen.deltachunk(chain)
1374 chunkdata = gen.deltachunk(chain)
1375 if not chunkdata:
1375 if not chunkdata:
1376 break
1376 break
1377 node = chunkdata['node']
1377 node = chunkdata['node']
1378 ui.write("%s\n" % hex(node))
1378 ui.write("%s\n" % hex(node))
1379 chain = node
1379 chain = node
1380 finally:
1380 finally:
1381 f.close()
1381 f.close()
1382
1382
1383 @command('debugcheckstate', [], '')
1383 @command('debugcheckstate', [], '')
1384 def debugcheckstate(ui, repo):
1384 def debugcheckstate(ui, repo):
1385 """validate the correctness of the current dirstate"""
1385 """validate the correctness of the current dirstate"""
1386 parent1, parent2 = repo.dirstate.parents()
1386 parent1, parent2 = repo.dirstate.parents()
1387 m1 = repo[parent1].manifest()
1387 m1 = repo[parent1].manifest()
1388 m2 = repo[parent2].manifest()
1388 m2 = repo[parent2].manifest()
1389 errors = 0
1389 errors = 0
1390 for f in repo.dirstate:
1390 for f in repo.dirstate:
1391 state = repo.dirstate[f]
1391 state = repo.dirstate[f]
1392 if state in "nr" and f not in m1:
1392 if state in "nr" and f not in m1:
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1394 errors += 1
1394 errors += 1
1395 if state in "a" and f in m1:
1395 if state in "a" and f in m1:
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1397 errors += 1
1397 errors += 1
1398 if state in "m" and f not in m1 and f not in m2:
1398 if state in "m" and f not in m1 and f not in m2:
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1400 (f, state))
1400 (f, state))
1401 errors += 1
1401 errors += 1
1402 for f in m1:
1402 for f in m1:
1403 state = repo.dirstate[f]
1403 state = repo.dirstate[f]
1404 if state not in "nrm":
1404 if state not in "nrm":
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1406 errors += 1
1406 errors += 1
1407 if errors:
1407 if errors:
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1409 raise util.Abort(error)
1409 raise util.Abort(error)
1410
1410
1411 @command('debugcommands', [], _('[COMMAND]'))
1411 @command('debugcommands', [], _('[COMMAND]'))
1412 def debugcommands(ui, cmd='', *args):
1412 def debugcommands(ui, cmd='', *args):
1413 """list all available commands and options"""
1413 """list all available commands and options"""
1414 for cmd, vals in sorted(table.iteritems()):
1414 for cmd, vals in sorted(table.iteritems()):
1415 cmd = cmd.split('|')[0].strip('^')
1415 cmd = cmd.split('|')[0].strip('^')
1416 opts = ', '.join([i[1] for i in vals[1]])
1416 opts = ', '.join([i[1] for i in vals[1]])
1417 ui.write('%s: %s\n' % (cmd, opts))
1417 ui.write('%s: %s\n' % (cmd, opts))
1418
1418
1419 @command('debugcomplete',
1419 @command('debugcomplete',
1420 [('o', 'options', None, _('show the command options'))],
1420 [('o', 'options', None, _('show the command options'))],
1421 _('[-o] CMD'))
1421 _('[-o] CMD'))
1422 def debugcomplete(ui, cmd='', **opts):
1422 def debugcomplete(ui, cmd='', **opts):
1423 """returns the completion list associated with the given command"""
1423 """returns the completion list associated with the given command"""
1424
1424
1425 if opts.get('options'):
1425 if opts.get('options'):
1426 options = []
1426 options = []
1427 otables = [globalopts]
1427 otables = [globalopts]
1428 if cmd:
1428 if cmd:
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1430 otables.append(entry[1])
1430 otables.append(entry[1])
1431 for t in otables:
1431 for t in otables:
1432 for o in t:
1432 for o in t:
1433 if "(DEPRECATED)" in o[3]:
1433 if "(DEPRECATED)" in o[3]:
1434 continue
1434 continue
1435 if o[0]:
1435 if o[0]:
1436 options.append('-%s' % o[0])
1436 options.append('-%s' % o[0])
1437 options.append('--%s' % o[1])
1437 options.append('--%s' % o[1])
1438 ui.write("%s\n" % "\n".join(options))
1438 ui.write("%s\n" % "\n".join(options))
1439 return
1439 return
1440
1440
1441 cmdlist = cmdutil.findpossible(cmd, table)
1441 cmdlist = cmdutil.findpossible(cmd, table)
1442 if ui.verbose:
1442 if ui.verbose:
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1445
1445
1446 @command('debugdag',
1446 @command('debugdag',
1447 [('t', 'tags', None, _('use tags as labels')),
1447 [('t', 'tags', None, _('use tags as labels')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1449 ('', 'dots', None, _('use dots for runs')),
1449 ('', 'dots', None, _('use dots for runs')),
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1451 _('[OPTION]... [FILE [REV]...]'))
1451 _('[OPTION]... [FILE [REV]...]'))
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1453 """format the changelog or an index DAG as a concise textual description
1453 """format the changelog or an index DAG as a concise textual description
1454
1454
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1456 revision numbers, they get labelled in the output as rN.
1456 revision numbers, they get labelled in the output as rN.
1457
1457
1458 Otherwise, the changelog DAG of the current repo is emitted.
1458 Otherwise, the changelog DAG of the current repo is emitted.
1459 """
1459 """
1460 spaces = opts.get('spaces')
1460 spaces = opts.get('spaces')
1461 dots = opts.get('dots')
1461 dots = opts.get('dots')
1462 if file_:
1462 if file_:
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1464 revs = set((int(r) for r in revs))
1464 revs = set((int(r) for r in revs))
1465 def events():
1465 def events():
1466 for r in rlog:
1466 for r in rlog:
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1468 if r in revs:
1468 if r in revs:
1469 yield 'l', (r, "r%i" % r)
1469 yield 'l', (r, "r%i" % r)
1470 elif repo:
1470 elif repo:
1471 cl = repo.changelog
1471 cl = repo.changelog
1472 tags = opts.get('tags')
1472 tags = opts.get('tags')
1473 branches = opts.get('branches')
1473 branches = opts.get('branches')
1474 if tags:
1474 if tags:
1475 labels = {}
1475 labels = {}
1476 for l, n in repo.tags().items():
1476 for l, n in repo.tags().items():
1477 labels.setdefault(cl.rev(n), []).append(l)
1477 labels.setdefault(cl.rev(n), []).append(l)
1478 def events():
1478 def events():
1479 b = "default"
1479 b = "default"
1480 for r in cl:
1480 for r in cl:
1481 if branches:
1481 if branches:
1482 newb = cl.read(cl.node(r))[5]['branch']
1482 newb = cl.read(cl.node(r))[5]['branch']
1483 if newb != b:
1483 if newb != b:
1484 yield 'a', newb
1484 yield 'a', newb
1485 b = newb
1485 b = newb
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1487 if tags:
1487 if tags:
1488 ls = labels.get(r)
1488 ls = labels.get(r)
1489 if ls:
1489 if ls:
1490 for l in ls:
1490 for l in ls:
1491 yield 'l', (r, l)
1491 yield 'l', (r, l)
1492 else:
1492 else:
1493 raise util.Abort(_('need repo for changelog dag'))
1493 raise util.Abort(_('need repo for changelog dag'))
1494
1494
1495 for line in dagparser.dagtextlines(events(),
1495 for line in dagparser.dagtextlines(events(),
1496 addspaces=spaces,
1496 addspaces=spaces,
1497 wraplabels=True,
1497 wraplabels=True,
1498 wrapannotations=True,
1498 wrapannotations=True,
1499 wrapnonlinear=dots,
1499 wrapnonlinear=dots,
1500 usedots=dots,
1500 usedots=dots,
1501 maxlinewidth=70):
1501 maxlinewidth=70):
1502 ui.write(line)
1502 ui.write(line)
1503 ui.write("\n")
1503 ui.write("\n")
1504
1504
1505 @command('debugdata',
1505 @command('debugdata',
1506 [('c', 'changelog', False, _('open changelog')),
1506 [('c', 'changelog', False, _('open changelog')),
1507 ('m', 'manifest', False, _('open manifest'))],
1507 ('m', 'manifest', False, _('open manifest'))],
1508 _('-c|-m|FILE REV'))
1508 _('-c|-m|FILE REV'))
1509 def debugdata(ui, repo, file_, rev = None, **opts):
1509 def debugdata(ui, repo, file_, rev = None, **opts):
1510 """dump the contents of a data file revision"""
1510 """dump the contents of a data file revision"""
1511 if opts.get('changelog') or opts.get('manifest'):
1511 if opts.get('changelog') or opts.get('manifest'):
1512 file_, rev = None, file_
1512 file_, rev = None, file_
1513 elif rev is None:
1513 elif rev is None:
1514 raise error.CommandError('debugdata', _('invalid arguments'))
1514 raise error.CommandError('debugdata', _('invalid arguments'))
1515 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1515 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1516 try:
1516 try:
1517 ui.write(r.revision(r.lookup(rev)))
1517 ui.write(r.revision(r.lookup(rev)))
1518 except KeyError:
1518 except KeyError:
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1520
1520
1521 @command('debugdate',
1521 @command('debugdate',
1522 [('e', 'extended', None, _('try extended date formats'))],
1522 [('e', 'extended', None, _('try extended date formats'))],
1523 _('[-e] DATE [RANGE]'))
1523 _('[-e] DATE [RANGE]'))
1524 def debugdate(ui, date, range=None, **opts):
1524 def debugdate(ui, date, range=None, **opts):
1525 """parse and display a date"""
1525 """parse and display a date"""
1526 if opts["extended"]:
1526 if opts["extended"]:
1527 d = util.parsedate(date, util.extendeddateformats)
1527 d = util.parsedate(date, util.extendeddateformats)
1528 else:
1528 else:
1529 d = util.parsedate(date)
1529 d = util.parsedate(date)
1530 ui.write("internal: %s %s\n" % d)
1530 ui.write("internal: %s %s\n" % d)
1531 ui.write("standard: %s\n" % util.datestr(d))
1531 ui.write("standard: %s\n" % util.datestr(d))
1532 if range:
1532 if range:
1533 m = util.matchdate(range)
1533 m = util.matchdate(range)
1534 ui.write("match: %s\n" % m(d[0]))
1534 ui.write("match: %s\n" % m(d[0]))
1535
1535
1536 @command('debugdiscovery',
1536 @command('debugdiscovery',
1537 [('', 'old', None, _('use old-style discovery')),
1537 [('', 'old', None, _('use old-style discovery')),
1538 ('', 'nonheads', None,
1538 ('', 'nonheads', None,
1539 _('use old-style discovery with non-heads included')),
1539 _('use old-style discovery with non-heads included')),
1540 ] + remoteopts,
1540 ] + remoteopts,
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1543 """runs the changeset discovery protocol in isolation"""
1543 """runs the changeset discovery protocol in isolation"""
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1545 remote = hg.peer(repo, opts, remoteurl)
1545 remote = hg.peer(repo, opts, remoteurl)
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1547
1547
1548 # make sure tests are repeatable
1548 # make sure tests are repeatable
1549 random.seed(12323)
1549 random.seed(12323)
1550
1550
1551 def doit(localheads, remoteheads):
1551 def doit(localheads, remoteheads):
1552 if opts.get('old'):
1552 if opts.get('old'):
1553 if localheads:
1553 if localheads:
1554 raise util.Abort('cannot use localheads with old style discovery')
1554 raise util.Abort('cannot use localheads with old style discovery')
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1556 force=True)
1556 force=True)
1557 common = set(common)
1557 common = set(common)
1558 if not opts.get('nonheads'):
1558 if not opts.get('nonheads'):
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1560 for n in common]))
1560 for n in common]))
1561 dag = dagutil.revlogdag(repo.changelog)
1561 dag = dagutil.revlogdag(repo.changelog)
1562 all = dag.ancestorset(dag.internalizeall(common))
1562 all = dag.ancestorset(dag.internalizeall(common))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1564 else:
1564 else:
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1566 common = set(common)
1566 common = set(common)
1567 rheads = set(hds)
1567 rheads = set(hds)
1568 lheads = set(repo.heads())
1568 lheads = set(repo.heads())
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1570 if lheads <= common:
1570 if lheads <= common:
1571 ui.write("local is subset\n")
1571 ui.write("local is subset\n")
1572 elif rheads <= common:
1572 elif rheads <= common:
1573 ui.write("remote is subset\n")
1573 ui.write("remote is subset\n")
1574
1574
1575 serverlogs = opts.get('serverlog')
1575 serverlogs = opts.get('serverlog')
1576 if serverlogs:
1576 if serverlogs:
1577 for filename in serverlogs:
1577 for filename in serverlogs:
1578 logfile = open(filename, 'r')
1578 logfile = open(filename, 'r')
1579 try:
1579 try:
1580 line = logfile.readline()
1580 line = logfile.readline()
1581 while line:
1581 while line:
1582 parts = line.strip().split(';')
1582 parts = line.strip().split(';')
1583 op = parts[1]
1583 op = parts[1]
1584 if op == 'cg':
1584 if op == 'cg':
1585 pass
1585 pass
1586 elif op == 'cgss':
1586 elif op == 'cgss':
1587 doit(parts[2].split(' '), parts[3].split(' '))
1587 doit(parts[2].split(' '), parts[3].split(' '))
1588 elif op == 'unb':
1588 elif op == 'unb':
1589 doit(parts[3].split(' '), parts[2].split(' '))
1589 doit(parts[3].split(' '), parts[2].split(' '))
1590 line = logfile.readline()
1590 line = logfile.readline()
1591 finally:
1591 finally:
1592 logfile.close()
1592 logfile.close()
1593
1593
1594 else:
1594 else:
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1596 opts.get('remote_head'))
1596 opts.get('remote_head'))
1597 localrevs = opts.get('local_head')
1597 localrevs = opts.get('local_head')
1598 doit(localrevs, remoterevs)
1598 doit(localrevs, remoterevs)
1599
1599
1600 @command('debugfileset', [], ('REVSPEC'))
1600 @command('debugfileset', [], ('REVSPEC'))
1601 def debugfileset(ui, repo, expr):
1601 def debugfileset(ui, repo, expr):
1602 '''parse and apply a fileset specification'''
1602 '''parse and apply a fileset specification'''
1603 if ui.verbose:
1603 if ui.verbose:
1604 tree = fileset.parse(expr)[0]
1604 tree = fileset.parse(expr)[0]
1605 ui.note(tree, "\n")
1605 ui.note(tree, "\n")
1606 matcher = lambda x: scmutil.match(repo, x, default='glob')
1606 matcher = lambda x: scmutil.match(repo, x, default='glob')
1607
1607
1608 for f in fileset.getfileset(repo[None], matcher, expr):
1608 for f in fileset.getfileset(repo[None], matcher, expr):
1609 ui.write("%s\n" % f)
1609 ui.write("%s\n" % f)
1610
1610
1611 @command('debugfsinfo', [], _('[PATH]'))
1611 @command('debugfsinfo', [], _('[PATH]'))
1612 def debugfsinfo(ui, path = "."):
1612 def debugfsinfo(ui, path = "."):
1613 """show information detected about current filesystem"""
1613 """show information detected about current filesystem"""
1614 util.writefile('.debugfsinfo', '')
1614 util.writefile('.debugfsinfo', '')
1615 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1615 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1616 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1616 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1617 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1617 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1618 and 'yes' or 'no'))
1618 and 'yes' or 'no'))
1619 os.unlink('.debugfsinfo')
1619 os.unlink('.debugfsinfo')
1620
1620
1621 @command('debuggetbundle',
1621 @command('debuggetbundle',
1622 [('H', 'head', [], _('id of head node'), _('ID')),
1622 [('H', 'head', [], _('id of head node'), _('ID')),
1623 ('C', 'common', [], _('id of common node'), _('ID')),
1623 ('C', 'common', [], _('id of common node'), _('ID')),
1624 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1624 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1625 _('REPO FILE [-H|-C ID]...'))
1625 _('REPO FILE [-H|-C ID]...'))
1626 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1626 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1627 """retrieves a bundle from a repo
1627 """retrieves a bundle from a repo
1628
1628
1629 Every ID must be a full-length hex node id string. Saves the bundle to the
1629 Every ID must be a full-length hex node id string. Saves the bundle to the
1630 given file.
1630 given file.
1631 """
1631 """
1632 repo = hg.peer(ui, opts, repopath)
1632 repo = hg.peer(ui, opts, repopath)
1633 if not repo.capable('getbundle'):
1633 if not repo.capable('getbundle'):
1634 raise util.Abort("getbundle() not supported by target repository")
1634 raise util.Abort("getbundle() not supported by target repository")
1635 args = {}
1635 args = {}
1636 if common:
1636 if common:
1637 args['common'] = [bin(s) for s in common]
1637 args['common'] = [bin(s) for s in common]
1638 if head:
1638 if head:
1639 args['heads'] = [bin(s) for s in head]
1639 args['heads'] = [bin(s) for s in head]
1640 bundle = repo.getbundle('debug', **args)
1640 bundle = repo.getbundle('debug', **args)
1641
1641
1642 bundletype = opts.get('type', 'bzip2').lower()
1642 bundletype = opts.get('type', 'bzip2').lower()
1643 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1643 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1644 bundletype = btypes.get(bundletype)
1644 bundletype = btypes.get(bundletype)
1645 if bundletype not in changegroup.bundletypes:
1645 if bundletype not in changegroup.bundletypes:
1646 raise util.Abort(_('unknown bundle type specified with --type'))
1646 raise util.Abort(_('unknown bundle type specified with --type'))
1647 changegroup.writebundle(bundle, bundlepath, bundletype)
1647 changegroup.writebundle(bundle, bundlepath, bundletype)
1648
1648
1649 @command('debugignore', [], '')
1649 @command('debugignore', [], '')
1650 def debugignore(ui, repo, *values, **opts):
1650 def debugignore(ui, repo, *values, **opts):
1651 """display the combined ignore pattern"""
1651 """display the combined ignore pattern"""
1652 ignore = repo.dirstate._ignore
1652 ignore = repo.dirstate._ignore
1653 if hasattr(ignore, 'includepat'):
1653 if hasattr(ignore, 'includepat'):
1654 ui.write("%s\n" % ignore.includepat)
1654 ui.write("%s\n" % ignore.includepat)
1655 else:
1655 else:
1656 raise util.Abort(_("no ignore patterns found"))
1656 raise util.Abort(_("no ignore patterns found"))
1657
1657
1658 @command('debugindex',
1658 @command('debugindex',
1659 [('c', 'changelog', False, _('open changelog')),
1659 [('c', 'changelog', False, _('open changelog')),
1660 ('m', 'manifest', False, _('open manifest')),
1660 ('m', 'manifest', False, _('open manifest')),
1661 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1661 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1662 _('[-f FORMAT] -c|-m|FILE'))
1662 _('[-f FORMAT] -c|-m|FILE'))
1663 def debugindex(ui, repo, file_ = None, **opts):
1663 def debugindex(ui, repo, file_ = None, **opts):
1664 """dump the contents of an index file"""
1664 """dump the contents of an index file"""
1665 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1665 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1666 format = opts.get('format', 0)
1666 format = opts.get('format', 0)
1667 if format not in (0, 1):
1667 if format not in (0, 1):
1668 raise util.Abort(_("unknown format %d") % format)
1668 raise util.Abort(_("unknown format %d") % format)
1669
1669
1670 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1670 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1671 if generaldelta:
1671 if generaldelta:
1672 basehdr = ' delta'
1672 basehdr = ' delta'
1673 else:
1673 else:
1674 basehdr = ' base'
1674 basehdr = ' base'
1675
1675
1676 if format == 0:
1676 if format == 0:
1677 ui.write(" rev offset length " + basehdr + " linkrev"
1677 ui.write(" rev offset length " + basehdr + " linkrev"
1678 " nodeid p1 p2\n")
1678 " nodeid p1 p2\n")
1679 elif format == 1:
1679 elif format == 1:
1680 ui.write(" rev flag offset length"
1680 ui.write(" rev flag offset length"
1681 " size " + basehdr + " link p1 p2 nodeid\n")
1681 " size " + basehdr + " link p1 p2 nodeid\n")
1682
1682
1683 for i in r:
1683 for i in r:
1684 node = r.node(i)
1684 node = r.node(i)
1685 if generaldelta:
1685 if generaldelta:
1686 base = r.deltaparent(i)
1686 base = r.deltaparent(i)
1687 else:
1687 else:
1688 base = r.chainbase(i)
1688 base = r.chainbase(i)
1689 if format == 0:
1689 if format == 0:
1690 try:
1690 try:
1691 pp = r.parents(node)
1691 pp = r.parents(node)
1692 except:
1692 except:
1693 pp = [nullid, nullid]
1693 pp = [nullid, nullid]
1694 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1694 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1695 i, r.start(i), r.length(i), base, r.linkrev(i),
1695 i, r.start(i), r.length(i), base, r.linkrev(i),
1696 short(node), short(pp[0]), short(pp[1])))
1696 short(node), short(pp[0]), short(pp[1])))
1697 elif format == 1:
1697 elif format == 1:
1698 pr = r.parentrevs(i)
1698 pr = r.parentrevs(i)
1699 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1699 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1700 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1700 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1701 base, r.linkrev(i), pr[0], pr[1], short(node)))
1701 base, r.linkrev(i), pr[0], pr[1], short(node)))
1702
1702
1703 @command('debugindexdot', [], _('FILE'))
1703 @command('debugindexdot', [], _('FILE'))
1704 def debugindexdot(ui, repo, file_):
1704 def debugindexdot(ui, repo, file_):
1705 """dump an index DAG as a graphviz dot file"""
1705 """dump an index DAG as a graphviz dot file"""
1706 r = None
1706 r = None
1707 if repo:
1707 if repo:
1708 filelog = repo.file(file_)
1708 filelog = repo.file(file_)
1709 if len(filelog):
1709 if len(filelog):
1710 r = filelog
1710 r = filelog
1711 if not r:
1711 if not r:
1712 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1712 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1713 ui.write("digraph G {\n")
1713 ui.write("digraph G {\n")
1714 for i in r:
1714 for i in r:
1715 node = r.node(i)
1715 node = r.node(i)
1716 pp = r.parents(node)
1716 pp = r.parents(node)
1717 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1717 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1718 if pp[1] != nullid:
1718 if pp[1] != nullid:
1719 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1719 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1720 ui.write("}\n")
1720 ui.write("}\n")
1721
1721
1722 @command('debuginstall', [], '')
1722 @command('debuginstall', [], '')
1723 def debuginstall(ui):
1723 def debuginstall(ui):
1724 '''test Mercurial installation
1724 '''test Mercurial installation
1725
1725
1726 Returns 0 on success.
1726 Returns 0 on success.
1727 '''
1727 '''
1728
1728
1729 def writetemp(contents):
1729 def writetemp(contents):
1730 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1730 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1731 f = os.fdopen(fd, "wb")
1731 f = os.fdopen(fd, "wb")
1732 f.write(contents)
1732 f.write(contents)
1733 f.close()
1733 f.close()
1734 return name
1734 return name
1735
1735
1736 problems = 0
1736 problems = 0
1737
1737
1738 # encoding
1738 # encoding
1739 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1739 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1740 try:
1740 try:
1741 encoding.fromlocal("test")
1741 encoding.fromlocal("test")
1742 except util.Abort, inst:
1742 except util.Abort, inst:
1743 ui.write(" %s\n" % inst)
1743 ui.write(" %s\n" % inst)
1744 ui.write(_(" (check that your locale is properly set)\n"))
1744 ui.write(_(" (check that your locale is properly set)\n"))
1745 problems += 1
1745 problems += 1
1746
1746
1747 # compiled modules
1747 # compiled modules
1748 ui.status(_("Checking installed modules (%s)...\n")
1748 ui.status(_("Checking installed modules (%s)...\n")
1749 % os.path.dirname(__file__))
1749 % os.path.dirname(__file__))
1750 try:
1750 try:
1751 import bdiff, mpatch, base85, osutil
1751 import bdiff, mpatch, base85, osutil
1752 except Exception, inst:
1752 except Exception, inst:
1753 ui.write(" %s\n" % inst)
1753 ui.write(" %s\n" % inst)
1754 ui.write(_(" One or more extensions could not be found"))
1754 ui.write(_(" One or more extensions could not be found"))
1755 ui.write(_(" (check that you compiled the extensions)\n"))
1755 ui.write(_(" (check that you compiled the extensions)\n"))
1756 problems += 1
1756 problems += 1
1757
1757
1758 # templates
1758 # templates
1759 ui.status(_("Checking templates...\n"))
1759 ui.status(_("Checking templates...\n"))
1760 try:
1760 try:
1761 import templater
1761 import templater
1762 templater.templater(templater.templatepath("map-cmdline.default"))
1762 templater.templater(templater.templatepath("map-cmdline.default"))
1763 except Exception, inst:
1763 except Exception, inst:
1764 ui.write(" %s\n" % inst)
1764 ui.write(" %s\n" % inst)
1765 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1765 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1766 problems += 1
1766 problems += 1
1767
1767
1768 # editor
1768 # editor
1769 ui.status(_("Checking commit editor...\n"))
1769 ui.status(_("Checking commit editor...\n"))
1770 editor = ui.geteditor()
1770 editor = ui.geteditor()
1771 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1771 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1772 if not cmdpath:
1772 if not cmdpath:
1773 if editor == 'vi':
1773 if editor == 'vi':
1774 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1774 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1775 ui.write(_(" (specify a commit editor in your configuration"
1775 ui.write(_(" (specify a commit editor in your configuration"
1776 " file)\n"))
1776 " file)\n"))
1777 else:
1777 else:
1778 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1778 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1779 ui.write(_(" (specify a commit editor in your configuration"
1779 ui.write(_(" (specify a commit editor in your configuration"
1780 " file)\n"))
1780 " file)\n"))
1781 problems += 1
1781 problems += 1
1782
1782
1783 # check username
1783 # check username
1784 ui.status(_("Checking username...\n"))
1784 ui.status(_("Checking username...\n"))
1785 try:
1785 try:
1786 ui.username()
1786 ui.username()
1787 except util.Abort, e:
1787 except util.Abort, e:
1788 ui.write(" %s\n" % e)
1788 ui.write(" %s\n" % e)
1789 ui.write(_(" (specify a username in your configuration file)\n"))
1789 ui.write(_(" (specify a username in your configuration file)\n"))
1790 problems += 1
1790 problems += 1
1791
1791
1792 if not problems:
1792 if not problems:
1793 ui.status(_("No problems detected\n"))
1793 ui.status(_("No problems detected\n"))
1794 else:
1794 else:
1795 ui.write(_("%s problems detected,"
1795 ui.write(_("%s problems detected,"
1796 " please check your install!\n") % problems)
1796 " please check your install!\n") % problems)
1797
1797
1798 return problems
1798 return problems
1799
1799
1800 @command('debugknown', [], _('REPO ID...'))
1800 @command('debugknown', [], _('REPO ID...'))
1801 def debugknown(ui, repopath, *ids, **opts):
1801 def debugknown(ui, repopath, *ids, **opts):
1802 """test whether node ids are known to a repo
1802 """test whether node ids are known to a repo
1803
1803
1804 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1804 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1805 indicating unknown/known.
1805 indicating unknown/known.
1806 """
1806 """
1807 repo = hg.peer(ui, opts, repopath)
1807 repo = hg.peer(ui, opts, repopath)
1808 if not repo.capable('known'):
1808 if not repo.capable('known'):
1809 raise util.Abort("known() not supported by target repository")
1809 raise util.Abort("known() not supported by target repository")
1810 flags = repo.known([bin(s) for s in ids])
1810 flags = repo.known([bin(s) for s in ids])
1811 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1811 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1812
1812
1813 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1813 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1814 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1814 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1815 '''access the pushkey key/value protocol
1815 '''access the pushkey key/value protocol
1816
1816
1817 With two args, list the keys in the given namespace.
1817 With two args, list the keys in the given namespace.
1818
1818
1819 With five args, set a key to new if it currently is set to old.
1819 With five args, set a key to new if it currently is set to old.
1820 Reports success or failure.
1820 Reports success or failure.
1821 '''
1821 '''
1822
1822
1823 target = hg.peer(ui, {}, repopath)
1823 target = hg.peer(ui, {}, repopath)
1824 if keyinfo:
1824 if keyinfo:
1825 key, old, new = keyinfo
1825 key, old, new = keyinfo
1826 r = target.pushkey(namespace, key, old, new)
1826 r = target.pushkey(namespace, key, old, new)
1827 ui.status(str(r) + '\n')
1827 ui.status(str(r) + '\n')
1828 return not r
1828 return not r
1829 else:
1829 else:
1830 for k, v in target.listkeys(namespace).iteritems():
1830 for k, v in target.listkeys(namespace).iteritems():
1831 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1831 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1832 v.encode('string-escape')))
1832 v.encode('string-escape')))
1833
1833
1834 @command('debugrebuildstate',
1834 @command('debugrebuildstate',
1835 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1835 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1836 _('[-r REV] [REV]'))
1836 _('[-r REV] [REV]'))
1837 def debugrebuildstate(ui, repo, rev="tip"):
1837 def debugrebuildstate(ui, repo, rev="tip"):
1838 """rebuild the dirstate as it would look like for the given revision"""
1838 """rebuild the dirstate as it would look like for the given revision"""
1839 ctx = scmutil.revsingle(repo, rev)
1839 ctx = scmutil.revsingle(repo, rev)
1840 wlock = repo.wlock()
1840 wlock = repo.wlock()
1841 try:
1841 try:
1842 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1842 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1843 finally:
1843 finally:
1844 wlock.release()
1844 wlock.release()
1845
1845
1846 @command('debugrename',
1846 @command('debugrename',
1847 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1847 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1848 _('[-r REV] FILE'))
1848 _('[-r REV] FILE'))
1849 def debugrename(ui, repo, file1, *pats, **opts):
1849 def debugrename(ui, repo, file1, *pats, **opts):
1850 """dump rename information"""
1850 """dump rename information"""
1851
1851
1852 ctx = scmutil.revsingle(repo, opts.get('rev'))
1852 ctx = scmutil.revsingle(repo, opts.get('rev'))
1853 m = scmutil.match(repo, (file1,) + pats, opts)
1853 m = scmutil.match(repo, (file1,) + pats, opts)
1854 for abs in ctx.walk(m):
1854 for abs in ctx.walk(m):
1855 fctx = ctx[abs]
1855 fctx = ctx[abs]
1856 o = fctx.filelog().renamed(fctx.filenode())
1856 o = fctx.filelog().renamed(fctx.filenode())
1857 rel = m.rel(abs)
1857 rel = m.rel(abs)
1858 if o:
1858 if o:
1859 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1859 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1860 else:
1860 else:
1861 ui.write(_("%s not renamed\n") % rel)
1861 ui.write(_("%s not renamed\n") % rel)
1862
1862
1863 @command('debugrevlog',
1863 @command('debugrevlog',
1864 [('c', 'changelog', False, _('open changelog')),
1864 [('c', 'changelog', False, _('open changelog')),
1865 ('m', 'manifest', False, _('open manifest')),
1865 ('m', 'manifest', False, _('open manifest')),
1866 ('d', 'dump', False, _('dump index data'))],
1866 ('d', 'dump', False, _('dump index data'))],
1867 _('-c|-m|FILE'))
1867 _('-c|-m|FILE'))
1868 def debugrevlog(ui, repo, file_ = None, **opts):
1868 def debugrevlog(ui, repo, file_ = None, **opts):
1869 """show data and statistics about a revlog"""
1869 """show data and statistics about a revlog"""
1870 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1870 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1871
1871
1872 if opts.get("dump"):
1872 if opts.get("dump"):
1873 numrevs = len(r)
1873 numrevs = len(r)
1874 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1874 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1875 " rawsize totalsize compression heads\n")
1875 " rawsize totalsize compression heads\n")
1876 ts = 0
1876 ts = 0
1877 heads = set()
1877 heads = set()
1878 for rev in xrange(numrevs):
1878 for rev in xrange(numrevs):
1879 dbase = r.deltaparent(rev)
1879 dbase = r.deltaparent(rev)
1880 if dbase == -1:
1880 if dbase == -1:
1881 dbase = rev
1881 dbase = rev
1882 cbase = r.chainbase(rev)
1882 cbase = r.chainbase(rev)
1883 p1, p2 = r.parentrevs(rev)
1883 p1, p2 = r.parentrevs(rev)
1884 rs = r.rawsize(rev)
1884 rs = r.rawsize(rev)
1885 ts = ts + rs
1885 ts = ts + rs
1886 heads -= set(r.parentrevs(rev))
1886 heads -= set(r.parentrevs(rev))
1887 heads.add(rev)
1887 heads.add(rev)
1888 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1888 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1889 (rev, p1, p2, r.start(rev), r.end(rev),
1889 (rev, p1, p2, r.start(rev), r.end(rev),
1890 r.start(dbase), r.start(cbase),
1890 r.start(dbase), r.start(cbase),
1891 r.start(p1), r.start(p2),
1891 r.start(p1), r.start(p2),
1892 rs, ts, ts / r.end(rev), len(heads)))
1892 rs, ts, ts / r.end(rev), len(heads)))
1893 return 0
1893 return 0
1894
1894
1895 v = r.version
1895 v = r.version
1896 format = v & 0xFFFF
1896 format = v & 0xFFFF
1897 flags = []
1897 flags = []
1898 gdelta = False
1898 gdelta = False
1899 if v & revlog.REVLOGNGINLINEDATA:
1899 if v & revlog.REVLOGNGINLINEDATA:
1900 flags.append('inline')
1900 flags.append('inline')
1901 if v & revlog.REVLOGGENERALDELTA:
1901 if v & revlog.REVLOGGENERALDELTA:
1902 gdelta = True
1902 gdelta = True
1903 flags.append('generaldelta')
1903 flags.append('generaldelta')
1904 if not flags:
1904 if not flags:
1905 flags = ['(none)']
1905 flags = ['(none)']
1906
1906
1907 nummerges = 0
1907 nummerges = 0
1908 numfull = 0
1908 numfull = 0
1909 numprev = 0
1909 numprev = 0
1910 nump1 = 0
1910 nump1 = 0
1911 nump2 = 0
1911 nump2 = 0
1912 numother = 0
1912 numother = 0
1913 nump1prev = 0
1913 nump1prev = 0
1914 nump2prev = 0
1914 nump2prev = 0
1915 chainlengths = []
1915 chainlengths = []
1916
1916
1917 datasize = [None, 0, 0L]
1917 datasize = [None, 0, 0L]
1918 fullsize = [None, 0, 0L]
1918 fullsize = [None, 0, 0L]
1919 deltasize = [None, 0, 0L]
1919 deltasize = [None, 0, 0L]
1920
1920
1921 def addsize(size, l):
1921 def addsize(size, l):
1922 if l[0] is None or size < l[0]:
1922 if l[0] is None or size < l[0]:
1923 l[0] = size
1923 l[0] = size
1924 if size > l[1]:
1924 if size > l[1]:
1925 l[1] = size
1925 l[1] = size
1926 l[2] += size
1926 l[2] += size
1927
1927
1928 numrevs = len(r)
1928 numrevs = len(r)
1929 for rev in xrange(numrevs):
1929 for rev in xrange(numrevs):
1930 p1, p2 = r.parentrevs(rev)
1930 p1, p2 = r.parentrevs(rev)
1931 delta = r.deltaparent(rev)
1931 delta = r.deltaparent(rev)
1932 if format > 0:
1932 if format > 0:
1933 addsize(r.rawsize(rev), datasize)
1933 addsize(r.rawsize(rev), datasize)
1934 if p2 != nullrev:
1934 if p2 != nullrev:
1935 nummerges += 1
1935 nummerges += 1
1936 size = r.length(rev)
1936 size = r.length(rev)
1937 if delta == nullrev:
1937 if delta == nullrev:
1938 chainlengths.append(0)
1938 chainlengths.append(0)
1939 numfull += 1
1939 numfull += 1
1940 addsize(size, fullsize)
1940 addsize(size, fullsize)
1941 else:
1941 else:
1942 chainlengths.append(chainlengths[delta] + 1)
1942 chainlengths.append(chainlengths[delta] + 1)
1943 addsize(size, deltasize)
1943 addsize(size, deltasize)
1944 if delta == rev - 1:
1944 if delta == rev - 1:
1945 numprev += 1
1945 numprev += 1
1946 if delta == p1:
1946 if delta == p1:
1947 nump1prev += 1
1947 nump1prev += 1
1948 elif delta == p2:
1948 elif delta == p2:
1949 nump2prev += 1
1949 nump2prev += 1
1950 elif delta == p1:
1950 elif delta == p1:
1951 nump1 += 1
1951 nump1 += 1
1952 elif delta == p2:
1952 elif delta == p2:
1953 nump2 += 1
1953 nump2 += 1
1954 elif delta != nullrev:
1954 elif delta != nullrev:
1955 numother += 1
1955 numother += 1
1956
1956
1957 numdeltas = numrevs - numfull
1957 numdeltas = numrevs - numfull
1958 numoprev = numprev - nump1prev - nump2prev
1958 numoprev = numprev - nump1prev - nump2prev
1959 totalrawsize = datasize[2]
1959 totalrawsize = datasize[2]
1960 datasize[2] /= numrevs
1960 datasize[2] /= numrevs
1961 fulltotal = fullsize[2]
1961 fulltotal = fullsize[2]
1962 fullsize[2] /= numfull
1962 fullsize[2] /= numfull
1963 deltatotal = deltasize[2]
1963 deltatotal = deltasize[2]
1964 deltasize[2] /= numrevs - numfull
1964 deltasize[2] /= numrevs - numfull
1965 totalsize = fulltotal + deltatotal
1965 totalsize = fulltotal + deltatotal
1966 avgchainlen = sum(chainlengths) / numrevs
1966 avgchainlen = sum(chainlengths) / numrevs
1967 compratio = totalrawsize / totalsize
1967 compratio = totalrawsize / totalsize
1968
1968
1969 basedfmtstr = '%%%dd\n'
1969 basedfmtstr = '%%%dd\n'
1970 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1970 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1971
1971
1972 def dfmtstr(max):
1972 def dfmtstr(max):
1973 return basedfmtstr % len(str(max))
1973 return basedfmtstr % len(str(max))
1974 def pcfmtstr(max, padding=0):
1974 def pcfmtstr(max, padding=0):
1975 return basepcfmtstr % (len(str(max)), ' ' * padding)
1975 return basepcfmtstr % (len(str(max)), ' ' * padding)
1976
1976
1977 def pcfmt(value, total):
1977 def pcfmt(value, total):
1978 return (value, 100 * float(value) / total)
1978 return (value, 100 * float(value) / total)
1979
1979
1980 ui.write('format : %d\n' % format)
1980 ui.write('format : %d\n' % format)
1981 ui.write('flags : %s\n' % ', '.join(flags))
1981 ui.write('flags : %s\n' % ', '.join(flags))
1982
1982
1983 ui.write('\n')
1983 ui.write('\n')
1984 fmt = pcfmtstr(totalsize)
1984 fmt = pcfmtstr(totalsize)
1985 fmt2 = dfmtstr(totalsize)
1985 fmt2 = dfmtstr(totalsize)
1986 ui.write('revisions : ' + fmt2 % numrevs)
1986 ui.write('revisions : ' + fmt2 % numrevs)
1987 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1987 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1988 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1988 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1989 ui.write('revisions : ' + fmt2 % numrevs)
1989 ui.write('revisions : ' + fmt2 % numrevs)
1990 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1990 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1991 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1991 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1992 ui.write('revision size : ' + fmt2 % totalsize)
1992 ui.write('revision size : ' + fmt2 % totalsize)
1993 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1993 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1994 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1994 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1995
1995
1996 ui.write('\n')
1996 ui.write('\n')
1997 fmt = dfmtstr(max(avgchainlen, compratio))
1997 fmt = dfmtstr(max(avgchainlen, compratio))
1998 ui.write('avg chain length : ' + fmt % avgchainlen)
1998 ui.write('avg chain length : ' + fmt % avgchainlen)
1999 ui.write('compression ratio : ' + fmt % compratio)
1999 ui.write('compression ratio : ' + fmt % compratio)
2000
2000
2001 if format > 0:
2001 if format > 0:
2002 ui.write('\n')
2002 ui.write('\n')
2003 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2003 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2004 % tuple(datasize))
2004 % tuple(datasize))
2005 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2005 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2006 % tuple(fullsize))
2006 % tuple(fullsize))
2007 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2007 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2008 % tuple(deltasize))
2008 % tuple(deltasize))
2009
2009
2010 if numdeltas > 0:
2010 if numdeltas > 0:
2011 ui.write('\n')
2011 ui.write('\n')
2012 fmt = pcfmtstr(numdeltas)
2012 fmt = pcfmtstr(numdeltas)
2013 fmt2 = pcfmtstr(numdeltas, 4)
2013 fmt2 = pcfmtstr(numdeltas, 4)
2014 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2014 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2015 if numprev > 0:
2015 if numprev > 0:
2016 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2016 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2017 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2017 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2018 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2018 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2019 if gdelta:
2019 if gdelta:
2020 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2020 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2021 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2021 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2022 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2022 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2023
2023
2024 @command('debugrevspec', [], ('REVSPEC'))
2024 @command('debugrevspec', [], ('REVSPEC'))
2025 def debugrevspec(ui, repo, expr):
2025 def debugrevspec(ui, repo, expr):
2026 '''parse and apply a revision specification'''
2026 '''parse and apply a revision specification'''
2027 if ui.verbose:
2027 if ui.verbose:
2028 tree = revset.parse(expr)[0]
2028 tree = revset.parse(expr)[0]
2029 ui.note(tree, "\n")
2029 ui.note(tree, "\n")
2030 newtree = revset.findaliases(ui, tree)
2030 newtree = revset.findaliases(ui, tree)
2031 if newtree != tree:
2031 if newtree != tree:
2032 ui.note(newtree, "\n")
2032 ui.note(newtree, "\n")
2033 func = revset.match(ui, expr)
2033 func = revset.match(ui, expr)
2034 for c in func(repo, range(len(repo))):
2034 for c in func(repo, range(len(repo))):
2035 ui.write("%s\n" % c)
2035 ui.write("%s\n" % c)
2036
2036
2037 @command('debugsetparents', [], _('REV1 [REV2]'))
2037 @command('debugsetparents', [], _('REV1 [REV2]'))
2038 def debugsetparents(ui, repo, rev1, rev2=None):
2038 def debugsetparents(ui, repo, rev1, rev2=None):
2039 """manually set the parents of the current working directory
2039 """manually set the parents of the current working directory
2040
2040
2041 This is useful for writing repository conversion tools, but should
2041 This is useful for writing repository conversion tools, but should
2042 be used with care.
2042 be used with care.
2043
2043
2044 Returns 0 on success.
2044 Returns 0 on success.
2045 """
2045 """
2046
2046
2047 r1 = scmutil.revsingle(repo, rev1).node()
2047 r1 = scmutil.revsingle(repo, rev1).node()
2048 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2048 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2049
2049
2050 wlock = repo.wlock()
2050 wlock = repo.wlock()
2051 try:
2051 try:
2052 repo.dirstate.setparents(r1, r2)
2052 repo.dirstate.setparents(r1, r2)
2053 finally:
2053 finally:
2054 wlock.release()
2054 wlock.release()
2055
2055
2056 @command('debugstate',
2056 @command('debugstate',
2057 [('', 'nodates', None, _('do not display the saved mtime')),
2057 [('', 'nodates', None, _('do not display the saved mtime')),
2058 ('', 'datesort', None, _('sort by saved mtime'))],
2058 ('', 'datesort', None, _('sort by saved mtime'))],
2059 _('[OPTION]...'))
2059 _('[OPTION]...'))
2060 def debugstate(ui, repo, nodates=None, datesort=None):
2060 def debugstate(ui, repo, nodates=None, datesort=None):
2061 """show the contents of the current dirstate"""
2061 """show the contents of the current dirstate"""
2062 timestr = ""
2062 timestr = ""
2063 showdate = not nodates
2063 showdate = not nodates
2064 if datesort:
2064 if datesort:
2065 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2065 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2066 else:
2066 else:
2067 keyfunc = None # sort by filename
2067 keyfunc = None # sort by filename
2068 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2068 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2069 if showdate:
2069 if showdate:
2070 if ent[3] == -1:
2070 if ent[3] == -1:
2071 # Pad or slice to locale representation
2071 # Pad or slice to locale representation
2072 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2072 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2073 time.localtime(0)))
2073 time.localtime(0)))
2074 timestr = 'unset'
2074 timestr = 'unset'
2075 timestr = (timestr[:locale_len] +
2075 timestr = (timestr[:locale_len] +
2076 ' ' * (locale_len - len(timestr)))
2076 ' ' * (locale_len - len(timestr)))
2077 else:
2077 else:
2078 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2078 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2079 time.localtime(ent[3]))
2079 time.localtime(ent[3]))
2080 if ent[1] & 020000:
2080 if ent[1] & 020000:
2081 mode = 'lnk'
2081 mode = 'lnk'
2082 else:
2082 else:
2083 mode = '%3o' % (ent[1] & 0777)
2083 mode = '%3o' % (ent[1] & 0777)
2084 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2084 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2085 for f in repo.dirstate.copies():
2085 for f in repo.dirstate.copies():
2086 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2086 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2087
2087
2088 @command('debugsub',
2088 @command('debugsub',
2089 [('r', 'rev', '',
2089 [('r', 'rev', '',
2090 _('revision to check'), _('REV'))],
2090 _('revision to check'), _('REV'))],
2091 _('[-r REV] [REV]'))
2091 _('[-r REV] [REV]'))
2092 def debugsub(ui, repo, rev=None):
2092 def debugsub(ui, repo, rev=None):
2093 ctx = scmutil.revsingle(repo, rev, None)
2093 ctx = scmutil.revsingle(repo, rev, None)
2094 for k, v in sorted(ctx.substate.items()):
2094 for k, v in sorted(ctx.substate.items()):
2095 ui.write('path %s\n' % k)
2095 ui.write('path %s\n' % k)
2096 ui.write(' source %s\n' % v[0])
2096 ui.write(' source %s\n' % v[0])
2097 ui.write(' revision %s\n' % v[1])
2097 ui.write(' revision %s\n' % v[1])
2098
2098
2099 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2099 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2100 def debugwalk(ui, repo, *pats, **opts):
2100 def debugwalk(ui, repo, *pats, **opts):
2101 """show how files match on given patterns"""
2101 """show how files match on given patterns"""
2102 m = scmutil.match(repo, pats, opts)
2102 m = scmutil.match(repo, pats, opts)
2103 items = list(repo.walk(m))
2103 items = list(repo.walk(m))
2104 if not items:
2104 if not items:
2105 return
2105 return
2106 fmt = 'f %%-%ds %%-%ds %%s' % (
2106 fmt = 'f %%-%ds %%-%ds %%s' % (
2107 max([len(abs) for abs in items]),
2107 max([len(abs) for abs in items]),
2108 max([len(m.rel(abs)) for abs in items]))
2108 max([len(m.rel(abs)) for abs in items]))
2109 for abs in items:
2109 for abs in items:
2110 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2110 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2111 ui.write("%s\n" % line.rstrip())
2111 ui.write("%s\n" % line.rstrip())
2112
2112
2113 @command('debugwireargs',
2113 @command('debugwireargs',
2114 [('', 'three', '', 'three'),
2114 [('', 'three', '', 'three'),
2115 ('', 'four', '', 'four'),
2115 ('', 'four', '', 'four'),
2116 ('', 'five', '', 'five'),
2116 ('', 'five', '', 'five'),
2117 ] + remoteopts,
2117 ] + remoteopts,
2118 _('REPO [OPTIONS]... [ONE [TWO]]'))
2118 _('REPO [OPTIONS]... [ONE [TWO]]'))
2119 def debugwireargs(ui, repopath, *vals, **opts):
2119 def debugwireargs(ui, repopath, *vals, **opts):
2120 repo = hg.peer(ui, opts, repopath)
2120 repo = hg.peer(ui, opts, repopath)
2121 for opt in remoteopts:
2121 for opt in remoteopts:
2122 del opts[opt[1]]
2122 del opts[opt[1]]
2123 args = {}
2123 args = {}
2124 for k, v in opts.iteritems():
2124 for k, v in opts.iteritems():
2125 if v:
2125 if v:
2126 args[k] = v
2126 args[k] = v
2127 # run twice to check that we don't mess up the stream for the next command
2127 # run twice to check that we don't mess up the stream for the next command
2128 res1 = repo.debugwireargs(*vals, **args)
2128 res1 = repo.debugwireargs(*vals, **args)
2129 res2 = repo.debugwireargs(*vals, **args)
2129 res2 = repo.debugwireargs(*vals, **args)
2130 ui.write("%s\n" % res1)
2130 ui.write("%s\n" % res1)
2131 if res1 != res2:
2131 if res1 != res2:
2132 ui.warn("%s\n" % res2)
2132 ui.warn("%s\n" % res2)
2133
2133
2134 @command('^diff',
2134 @command('^diff',
2135 [('r', 'rev', [], _('revision'), _('REV')),
2135 [('r', 'rev', [], _('revision'), _('REV')),
2136 ('c', 'change', '', _('change made by revision'), _('REV'))
2136 ('c', 'change', '', _('change made by revision'), _('REV'))
2137 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2137 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2138 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2138 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2139 def diff(ui, repo, *pats, **opts):
2139 def diff(ui, repo, *pats, **opts):
2140 """diff repository (or selected files)
2140 """diff repository (or selected files)
2141
2141
2142 Show differences between revisions for the specified files.
2142 Show differences between revisions for the specified files.
2143
2143
2144 Differences between files are shown using the unified diff format.
2144 Differences between files are shown using the unified diff format.
2145
2145
2146 .. note::
2146 .. note::
2147 diff may generate unexpected results for merges, as it will
2147 diff may generate unexpected results for merges, as it will
2148 default to comparing against the working directory's first
2148 default to comparing against the working directory's first
2149 parent changeset if no revisions are specified.
2149 parent changeset if no revisions are specified.
2150
2150
2151 When two revision arguments are given, then changes are shown
2151 When two revision arguments are given, then changes are shown
2152 between those revisions. If only one revision is specified then
2152 between those revisions. If only one revision is specified then
2153 that revision is compared to the working directory, and, when no
2153 that revision is compared to the working directory, and, when no
2154 revisions are specified, the working directory files are compared
2154 revisions are specified, the working directory files are compared
2155 to its parent.
2155 to its parent.
2156
2156
2157 Alternatively you can specify -c/--change with a revision to see
2157 Alternatively you can specify -c/--change with a revision to see
2158 the changes in that changeset relative to its first parent.
2158 the changes in that changeset relative to its first parent.
2159
2159
2160 Without the -a/--text option, diff will avoid generating diffs of
2160 Without the -a/--text option, diff will avoid generating diffs of
2161 files it detects as binary. With -a, diff will generate a diff
2161 files it detects as binary. With -a, diff will generate a diff
2162 anyway, probably with undesirable results.
2162 anyway, probably with undesirable results.
2163
2163
2164 Use the -g/--git option to generate diffs in the git extended diff
2164 Use the -g/--git option to generate diffs in the git extended diff
2165 format. For more information, read :hg:`help diffs`.
2165 format. For more information, read :hg:`help diffs`.
2166
2166
2167 Returns 0 on success.
2167 Returns 0 on success.
2168 """
2168 """
2169
2169
2170 revs = opts.get('rev')
2170 revs = opts.get('rev')
2171 change = opts.get('change')
2171 change = opts.get('change')
2172 stat = opts.get('stat')
2172 stat = opts.get('stat')
2173 reverse = opts.get('reverse')
2173 reverse = opts.get('reverse')
2174
2174
2175 if revs and change:
2175 if revs and change:
2176 msg = _('cannot specify --rev and --change at the same time')
2176 msg = _('cannot specify --rev and --change at the same time')
2177 raise util.Abort(msg)
2177 raise util.Abort(msg)
2178 elif change:
2178 elif change:
2179 node2 = scmutil.revsingle(repo, change, None).node()
2179 node2 = scmutil.revsingle(repo, change, None).node()
2180 node1 = repo[node2].p1().node()
2180 node1 = repo[node2].p1().node()
2181 else:
2181 else:
2182 node1, node2 = scmutil.revpair(repo, revs)
2182 node1, node2 = scmutil.revpair(repo, revs)
2183
2183
2184 if reverse:
2184 if reverse:
2185 node1, node2 = node2, node1
2185 node1, node2 = node2, node1
2186
2186
2187 diffopts = patch.diffopts(ui, opts)
2187 diffopts = patch.diffopts(ui, opts)
2188 m = scmutil.match(repo, pats, opts)
2188 m = scmutil.match(repo, pats, opts)
2189 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2189 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2190 listsubrepos=opts.get('subrepos'))
2190 listsubrepos=opts.get('subrepos'))
2191
2191
2192 @command('^export',
2192 @command('^export',
2193 [('o', 'output', '',
2193 [('o', 'output', '',
2194 _('print output to file with formatted name'), _('FORMAT')),
2194 _('print output to file with formatted name'), _('FORMAT')),
2195 ('', 'switch-parent', None, _('diff against the second parent')),
2195 ('', 'switch-parent', None, _('diff against the second parent')),
2196 ('r', 'rev', [], _('revisions to export'), _('REV')),
2196 ('r', 'rev', [], _('revisions to export'), _('REV')),
2197 ] + diffopts,
2197 ] + diffopts,
2198 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2198 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2199 def export(ui, repo, *changesets, **opts):
2199 def export(ui, repo, *changesets, **opts):
2200 """dump the header and diffs for one or more changesets
2200 """dump the header and diffs for one or more changesets
2201
2201
2202 Print the changeset header and diffs for one or more revisions.
2202 Print the changeset header and diffs for one or more revisions.
2203
2203
2204 The information shown in the changeset header is: author, date,
2204 The information shown in the changeset header is: author, date,
2205 branch name (if non-default), changeset hash, parent(s) and commit
2205 branch name (if non-default), changeset hash, parent(s) and commit
2206 comment.
2206 comment.
2207
2207
2208 .. note::
2208 .. note::
2209 export may generate unexpected diff output for merge
2209 export may generate unexpected diff output for merge
2210 changesets, as it will compare the merge changeset against its
2210 changesets, as it will compare the merge changeset against its
2211 first parent only.
2211 first parent only.
2212
2212
2213 Output may be to a file, in which case the name of the file is
2213 Output may be to a file, in which case the name of the file is
2214 given using a format string. The formatting rules are as follows:
2214 given using a format string. The formatting rules are as follows:
2215
2215
2216 :``%%``: literal "%" character
2216 :``%%``: literal "%" character
2217 :``%H``: changeset hash (40 hexadecimal digits)
2217 :``%H``: changeset hash (40 hexadecimal digits)
2218 :``%N``: number of patches being generated
2218 :``%N``: number of patches being generated
2219 :``%R``: changeset revision number
2219 :``%R``: changeset revision number
2220 :``%b``: basename of the exporting repository
2220 :``%b``: basename of the exporting repository
2221 :``%h``: short-form changeset hash (12 hexadecimal digits)
2221 :``%h``: short-form changeset hash (12 hexadecimal digits)
2222 :``%n``: zero-padded sequence number, starting at 1
2222 :``%n``: zero-padded sequence number, starting at 1
2223 :``%r``: zero-padded changeset revision number
2223 :``%r``: zero-padded changeset revision number
2224
2224
2225 Without the -a/--text option, export will avoid generating diffs
2225 Without the -a/--text option, export will avoid generating diffs
2226 of files it detects as binary. With -a, export will generate a
2226 of files it detects as binary. With -a, export will generate a
2227 diff anyway, probably with undesirable results.
2227 diff anyway, probably with undesirable results.
2228
2228
2229 Use the -g/--git option to generate diffs in the git extended diff
2229 Use the -g/--git option to generate diffs in the git extended diff
2230 format. See :hg:`help diffs` for more information.
2230 format. See :hg:`help diffs` for more information.
2231
2231
2232 With the --switch-parent option, the diff will be against the
2232 With the --switch-parent option, the diff will be against the
2233 second parent. It can be useful to review a merge.
2233 second parent. It can be useful to review a merge.
2234
2234
2235 Returns 0 on success.
2235 Returns 0 on success.
2236 """
2236 """
2237 changesets += tuple(opts.get('rev', []))
2237 changesets += tuple(opts.get('rev', []))
2238 if not changesets:
2238 if not changesets:
2239 raise util.Abort(_("export requires at least one changeset"))
2239 raise util.Abort(_("export requires at least one changeset"))
2240 revs = scmutil.revrange(repo, changesets)
2240 revs = scmutil.revrange(repo, changesets)
2241 if len(revs) > 1:
2241 if len(revs) > 1:
2242 ui.note(_('exporting patches:\n'))
2242 ui.note(_('exporting patches:\n'))
2243 else:
2243 else:
2244 ui.note(_('exporting patch:\n'))
2244 ui.note(_('exporting patch:\n'))
2245 cmdutil.export(repo, revs, template=opts.get('output'),
2245 cmdutil.export(repo, revs, template=opts.get('output'),
2246 switch_parent=opts.get('switch_parent'),
2246 switch_parent=opts.get('switch_parent'),
2247 opts=patch.diffopts(ui, opts))
2247 opts=patch.diffopts(ui, opts))
2248
2248
2249 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2249 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2250 def forget(ui, repo, *pats, **opts):
2250 def forget(ui, repo, *pats, **opts):
2251 """forget the specified files on the next commit
2251 """forget the specified files on the next commit
2252
2252
2253 Mark the specified files so they will no longer be tracked
2253 Mark the specified files so they will no longer be tracked
2254 after the next commit.
2254 after the next commit.
2255
2255
2256 This only removes files from the current branch, not from the
2256 This only removes files from the current branch, not from the
2257 entire project history, and it does not delete them from the
2257 entire project history, and it does not delete them from the
2258 working directory.
2258 working directory.
2259
2259
2260 To undo a forget before the next commit, see :hg:`add`.
2260 To undo a forget before the next commit, see :hg:`add`.
2261
2261
2262 Returns 0 on success.
2262 Returns 0 on success.
2263 """
2263 """
2264
2264
2265 if not pats:
2265 if not pats:
2266 raise util.Abort(_('no files specified'))
2266 raise util.Abort(_('no files specified'))
2267
2267
2268 m = scmutil.match(repo, pats, opts)
2268 m = scmutil.match(repo, pats, opts)
2269 s = repo.status(match=m, clean=True)
2269 s = repo.status(match=m, clean=True)
2270 forget = sorted(s[0] + s[1] + s[3] + s[6])
2270 forget = sorted(s[0] + s[1] + s[3] + s[6])
2271 errs = 0
2271 errs = 0
2272
2272
2273 for f in m.files():
2273 for f in m.files():
2274 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2274 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2275 ui.warn(_('not removing %s: file is already untracked\n')
2275 ui.warn(_('not removing %s: file is already untracked\n')
2276 % m.rel(f))
2276 % m.rel(f))
2277 errs = 1
2277 errs = 1
2278
2278
2279 for f in forget:
2279 for f in forget:
2280 if ui.verbose or not m.exact(f):
2280 if ui.verbose or not m.exact(f):
2281 ui.status(_('removing %s\n') % m.rel(f))
2281 ui.status(_('removing %s\n') % m.rel(f))
2282
2282
2283 repo[None].forget(forget)
2283 repo[None].forget(forget)
2284 return errs
2284 return errs
2285
2285
2286 @command('grep',
2286 @command('grep',
2287 [('0', 'print0', None, _('end fields with NUL')),
2287 [('0', 'print0', None, _('end fields with NUL')),
2288 ('', 'all', None, _('print all revisions that match')),
2288 ('', 'all', None, _('print all revisions that match')),
2289 ('a', 'text', None, _('treat all files as text')),
2289 ('a', 'text', None, _('treat all files as text')),
2290 ('f', 'follow', None,
2290 ('f', 'follow', None,
2291 _('follow changeset history,'
2291 _('follow changeset history,'
2292 ' or file history across copies and renames')),
2292 ' or file history across copies and renames')),
2293 ('i', 'ignore-case', None, _('ignore case when matching')),
2293 ('i', 'ignore-case', None, _('ignore case when matching')),
2294 ('l', 'files-with-matches', None,
2294 ('l', 'files-with-matches', None,
2295 _('print only filenames and revisions that match')),
2295 _('print only filenames and revisions that match')),
2296 ('n', 'line-number', None, _('print matching line numbers')),
2296 ('n', 'line-number', None, _('print matching line numbers')),
2297 ('r', 'rev', [],
2297 ('r', 'rev', [],
2298 _('only search files changed within revision range'), _('REV')),
2298 _('only search files changed within revision range'), _('REV')),
2299 ('u', 'user', None, _('list the author (long with -v)')),
2299 ('u', 'user', None, _('list the author (long with -v)')),
2300 ('d', 'date', None, _('list the date (short with -q)')),
2300 ('d', 'date', None, _('list the date (short with -q)')),
2301 ] + walkopts,
2301 ] + walkopts,
2302 _('[OPTION]... PATTERN [FILE]...'))
2302 _('[OPTION]... PATTERN [FILE]...'))
2303 def grep(ui, repo, pattern, *pats, **opts):
2303 def grep(ui, repo, pattern, *pats, **opts):
2304 """search for a pattern in specified files and revisions
2304 """search for a pattern in specified files and revisions
2305
2305
2306 Search revisions of files for a regular expression.
2306 Search revisions of files for a regular expression.
2307
2307
2308 This command behaves differently than Unix grep. It only accepts
2308 This command behaves differently than Unix grep. It only accepts
2309 Python/Perl regexps. It searches repository history, not the
2309 Python/Perl regexps. It searches repository history, not the
2310 working directory. It always prints the revision number in which a
2310 working directory. It always prints the revision number in which a
2311 match appears.
2311 match appears.
2312
2312
2313 By default, grep only prints output for the first revision of a
2313 By default, grep only prints output for the first revision of a
2314 file in which it finds a match. To get it to print every revision
2314 file in which it finds a match. To get it to print every revision
2315 that contains a change in match status ("-" for a match that
2315 that contains a change in match status ("-" for a match that
2316 becomes a non-match, or "+" for a non-match that becomes a match),
2316 becomes a non-match, or "+" for a non-match that becomes a match),
2317 use the --all flag.
2317 use the --all flag.
2318
2318
2319 Returns 0 if a match is found, 1 otherwise.
2319 Returns 0 if a match is found, 1 otherwise.
2320 """
2320 """
2321 reflags = 0
2321 reflags = 0
2322 if opts.get('ignore_case'):
2322 if opts.get('ignore_case'):
2323 reflags |= re.I
2323 reflags |= re.I
2324 try:
2324 try:
2325 regexp = re.compile(pattern, reflags)
2325 regexp = re.compile(pattern, reflags)
2326 except re.error, inst:
2326 except re.error, inst:
2327 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2327 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2328 return 1
2328 return 1
2329 sep, eol = ':', '\n'
2329 sep, eol = ':', '\n'
2330 if opts.get('print0'):
2330 if opts.get('print0'):
2331 sep = eol = '\0'
2331 sep = eol = '\0'
2332
2332
2333 getfile = util.lrucachefunc(repo.file)
2333 getfile = util.lrucachefunc(repo.file)
2334
2334
2335 def matchlines(body):
2335 def matchlines(body):
2336 begin = 0
2336 begin = 0
2337 linenum = 0
2337 linenum = 0
2338 while True:
2338 while True:
2339 match = regexp.search(body, begin)
2339 match = regexp.search(body, begin)
2340 if not match:
2340 if not match:
2341 break
2341 break
2342 mstart, mend = match.span()
2342 mstart, mend = match.span()
2343 linenum += body.count('\n', begin, mstart) + 1
2343 linenum += body.count('\n', begin, mstart) + 1
2344 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2344 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2345 begin = body.find('\n', mend) + 1 or len(body)
2345 begin = body.find('\n', mend) + 1 or len(body)
2346 lend = begin - 1
2346 lend = begin - 1
2347 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2347 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2348
2348
2349 class linestate(object):
2349 class linestate(object):
2350 def __init__(self, line, linenum, colstart, colend):
2350 def __init__(self, line, linenum, colstart, colend):
2351 self.line = line
2351 self.line = line
2352 self.linenum = linenum
2352 self.linenum = linenum
2353 self.colstart = colstart
2353 self.colstart = colstart
2354 self.colend = colend
2354 self.colend = colend
2355
2355
2356 def __hash__(self):
2356 def __hash__(self):
2357 return hash((self.linenum, self.line))
2357 return hash((self.linenum, self.line))
2358
2358
2359 def __eq__(self, other):
2359 def __eq__(self, other):
2360 return self.line == other.line
2360 return self.line == other.line
2361
2361
2362 matches = {}
2362 matches = {}
2363 copies = {}
2363 copies = {}
2364 def grepbody(fn, rev, body):
2364 def grepbody(fn, rev, body):
2365 matches[rev].setdefault(fn, [])
2365 matches[rev].setdefault(fn, [])
2366 m = matches[rev][fn]
2366 m = matches[rev][fn]
2367 for lnum, cstart, cend, line in matchlines(body):
2367 for lnum, cstart, cend, line in matchlines(body):
2368 s = linestate(line, lnum, cstart, cend)
2368 s = linestate(line, lnum, cstart, cend)
2369 m.append(s)
2369 m.append(s)
2370
2370
2371 def difflinestates(a, b):
2371 def difflinestates(a, b):
2372 sm = difflib.SequenceMatcher(None, a, b)
2372 sm = difflib.SequenceMatcher(None, a, b)
2373 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2373 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2374 if tag == 'insert':
2374 if tag == 'insert':
2375 for i in xrange(blo, bhi):
2375 for i in xrange(blo, bhi):
2376 yield ('+', b[i])
2376 yield ('+', b[i])
2377 elif tag == 'delete':
2377 elif tag == 'delete':
2378 for i in xrange(alo, ahi):
2378 for i in xrange(alo, ahi):
2379 yield ('-', a[i])
2379 yield ('-', a[i])
2380 elif tag == 'replace':
2380 elif tag == 'replace':
2381 for i in xrange(alo, ahi):
2381 for i in xrange(alo, ahi):
2382 yield ('-', a[i])
2382 yield ('-', a[i])
2383 for i in xrange(blo, bhi):
2383 for i in xrange(blo, bhi):
2384 yield ('+', b[i])
2384 yield ('+', b[i])
2385
2385
2386 def display(fn, ctx, pstates, states):
2386 def display(fn, ctx, pstates, states):
2387 rev = ctx.rev()
2387 rev = ctx.rev()
2388 datefunc = ui.quiet and util.shortdate or util.datestr
2388 datefunc = ui.quiet and util.shortdate or util.datestr
2389 found = False
2389 found = False
2390 filerevmatches = {}
2390 filerevmatches = {}
2391 def binary():
2391 def binary():
2392 flog = getfile(fn)
2392 flog = getfile(fn)
2393 return util.binary(flog.read(ctx.filenode(fn)))
2393 return util.binary(flog.read(ctx.filenode(fn)))
2394
2394
2395 if opts.get('all'):
2395 if opts.get('all'):
2396 iter = difflinestates(pstates, states)
2396 iter = difflinestates(pstates, states)
2397 else:
2397 else:
2398 iter = [('', l) for l in states]
2398 iter = [('', l) for l in states]
2399 for change, l in iter:
2399 for change, l in iter:
2400 cols = [fn, str(rev)]
2400 cols = [fn, str(rev)]
2401 before, match, after = None, None, None
2401 before, match, after = None, None, None
2402 if opts.get('line_number'):
2402 if opts.get('line_number'):
2403 cols.append(str(l.linenum))
2403 cols.append(str(l.linenum))
2404 if opts.get('all'):
2404 if opts.get('all'):
2405 cols.append(change)
2405 cols.append(change)
2406 if opts.get('user'):
2406 if opts.get('user'):
2407 cols.append(ui.shortuser(ctx.user()))
2407 cols.append(ui.shortuser(ctx.user()))
2408 if opts.get('date'):
2408 if opts.get('date'):
2409 cols.append(datefunc(ctx.date()))
2409 cols.append(datefunc(ctx.date()))
2410 if opts.get('files_with_matches'):
2410 if opts.get('files_with_matches'):
2411 c = (fn, rev)
2411 c = (fn, rev)
2412 if c in filerevmatches:
2412 if c in filerevmatches:
2413 continue
2413 continue
2414 filerevmatches[c] = 1
2414 filerevmatches[c] = 1
2415 else:
2415 else:
2416 before = l.line[:l.colstart]
2416 before = l.line[:l.colstart]
2417 match = l.line[l.colstart:l.colend]
2417 match = l.line[l.colstart:l.colend]
2418 after = l.line[l.colend:]
2418 after = l.line[l.colend:]
2419 ui.write(sep.join(cols))
2419 ui.write(sep.join(cols))
2420 if before is not None:
2420 if before is not None:
2421 if not opts.get('text') and binary():
2421 if not opts.get('text') and binary():
2422 ui.write(sep + " Binary file matches")
2422 ui.write(sep + " Binary file matches")
2423 else:
2423 else:
2424 ui.write(sep + before)
2424 ui.write(sep + before)
2425 ui.write(match, label='grep.match')
2425 ui.write(match, label='grep.match')
2426 ui.write(after)
2426 ui.write(after)
2427 ui.write(eol)
2427 ui.write(eol)
2428 found = True
2428 found = True
2429 return found
2429 return found
2430
2430
2431 skip = {}
2431 skip = {}
2432 revfiles = {}
2432 revfiles = {}
2433 matchfn = scmutil.match(repo, pats, opts)
2433 matchfn = scmutil.match(repo, pats, opts)
2434 found = False
2434 found = False
2435 follow = opts.get('follow')
2435 follow = opts.get('follow')
2436
2436
2437 def prep(ctx, fns):
2437 def prep(ctx, fns):
2438 rev = ctx.rev()
2438 rev = ctx.rev()
2439 pctx = ctx.p1()
2439 pctx = ctx.p1()
2440 parent = pctx.rev()
2440 parent = pctx.rev()
2441 matches.setdefault(rev, {})
2441 matches.setdefault(rev, {})
2442 matches.setdefault(parent, {})
2442 matches.setdefault(parent, {})
2443 files = revfiles.setdefault(rev, [])
2443 files = revfiles.setdefault(rev, [])
2444 for fn in fns:
2444 for fn in fns:
2445 flog = getfile(fn)
2445 flog = getfile(fn)
2446 try:
2446 try:
2447 fnode = ctx.filenode(fn)
2447 fnode = ctx.filenode(fn)
2448 except error.LookupError:
2448 except error.LookupError:
2449 continue
2449 continue
2450
2450
2451 copied = flog.renamed(fnode)
2451 copied = flog.renamed(fnode)
2452 copy = follow and copied and copied[0]
2452 copy = follow and copied and copied[0]
2453 if copy:
2453 if copy:
2454 copies.setdefault(rev, {})[fn] = copy
2454 copies.setdefault(rev, {})[fn] = copy
2455 if fn in skip:
2455 if fn in skip:
2456 if copy:
2456 if copy:
2457 skip[copy] = True
2457 skip[copy] = True
2458 continue
2458 continue
2459 files.append(fn)
2459 files.append(fn)
2460
2460
2461 if fn not in matches[rev]:
2461 if fn not in matches[rev]:
2462 grepbody(fn, rev, flog.read(fnode))
2462 grepbody(fn, rev, flog.read(fnode))
2463
2463
2464 pfn = copy or fn
2464 pfn = copy or fn
2465 if pfn not in matches[parent]:
2465 if pfn not in matches[parent]:
2466 try:
2466 try:
2467 fnode = pctx.filenode(pfn)
2467 fnode = pctx.filenode(pfn)
2468 grepbody(pfn, parent, flog.read(fnode))
2468 grepbody(pfn, parent, flog.read(fnode))
2469 except error.LookupError:
2469 except error.LookupError:
2470 pass
2470 pass
2471
2471
2472 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2472 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2473 rev = ctx.rev()
2473 rev = ctx.rev()
2474 parent = ctx.p1().rev()
2474 parent = ctx.p1().rev()
2475 for fn in sorted(revfiles.get(rev, [])):
2475 for fn in sorted(revfiles.get(rev, [])):
2476 states = matches[rev][fn]
2476 states = matches[rev][fn]
2477 copy = copies.get(rev, {}).get(fn)
2477 copy = copies.get(rev, {}).get(fn)
2478 if fn in skip:
2478 if fn in skip:
2479 if copy:
2479 if copy:
2480 skip[copy] = True
2480 skip[copy] = True
2481 continue
2481 continue
2482 pstates = matches.get(parent, {}).get(copy or fn, [])
2482 pstates = matches.get(parent, {}).get(copy or fn, [])
2483 if pstates or states:
2483 if pstates or states:
2484 r = display(fn, ctx, pstates, states)
2484 r = display(fn, ctx, pstates, states)
2485 found = found or r
2485 found = found or r
2486 if r and not opts.get('all'):
2486 if r and not opts.get('all'):
2487 skip[fn] = True
2487 skip[fn] = True
2488 if copy:
2488 if copy:
2489 skip[copy] = True
2489 skip[copy] = True
2490 del matches[rev]
2490 del matches[rev]
2491 del revfiles[rev]
2491 del revfiles[rev]
2492
2492
2493 return not found
2493 return not found
2494
2494
2495 @command('heads',
2495 @command('heads',
2496 [('r', 'rev', '',
2496 [('r', 'rev', '',
2497 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2497 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2498 ('t', 'topo', False, _('show topological heads only')),
2498 ('t', 'topo', False, _('show topological heads only')),
2499 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2499 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2500 ('c', 'closed', False, _('show normal and closed branch heads')),
2500 ('c', 'closed', False, _('show normal and closed branch heads')),
2501 ] + templateopts,
2501 ] + templateopts,
2502 _('[-ac] [-r STARTREV] [REV]...'))
2502 _('[-ac] [-r STARTREV] [REV]...'))
2503 def heads(ui, repo, *branchrevs, **opts):
2503 def heads(ui, repo, *branchrevs, **opts):
2504 """show current repository heads or show branch heads
2504 """show current repository heads or show branch heads
2505
2505
2506 With no arguments, show all repository branch heads.
2506 With no arguments, show all repository branch heads.
2507
2507
2508 Repository "heads" are changesets with no child changesets. They are
2508 Repository "heads" are changesets with no child changesets. They are
2509 where development generally takes place and are the usual targets
2509 where development generally takes place and are the usual targets
2510 for update and merge operations. Branch heads are changesets that have
2510 for update and merge operations. Branch heads are changesets that have
2511 no child changeset on the same branch.
2511 no child changeset on the same branch.
2512
2512
2513 If one or more REVs are given, only branch heads on the branches
2513 If one or more REVs are given, only branch heads on the branches
2514 associated with the specified changesets are shown.
2514 associated with the specified changesets are shown.
2515
2515
2516 If -c/--closed is specified, also show branch heads marked closed
2516 If -c/--closed is specified, also show branch heads marked closed
2517 (see :hg:`commit --close-branch`).
2517 (see :hg:`commit --close-branch`).
2518
2518
2519 If STARTREV is specified, only those heads that are descendants of
2519 If STARTREV is specified, only those heads that are descendants of
2520 STARTREV will be displayed.
2520 STARTREV will be displayed.
2521
2521
2522 If -t/--topo is specified, named branch mechanics will be ignored and only
2522 If -t/--topo is specified, named branch mechanics will be ignored and only
2523 changesets without children will be shown.
2523 changesets without children will be shown.
2524
2524
2525 Returns 0 if matching heads are found, 1 if not.
2525 Returns 0 if matching heads are found, 1 if not.
2526 """
2526 """
2527
2527
2528 start = None
2528 start = None
2529 if 'rev' in opts:
2529 if 'rev' in opts:
2530 start = scmutil.revsingle(repo, opts['rev'], None).node()
2530 start = scmutil.revsingle(repo, opts['rev'], None).node()
2531
2531
2532 if opts.get('topo'):
2532 if opts.get('topo'):
2533 heads = [repo[h] for h in repo.heads(start)]
2533 heads = [repo[h] for h in repo.heads(start)]
2534 else:
2534 else:
2535 heads = []
2535 heads = []
2536 for branch in repo.branchmap():
2536 for branch in repo.branchmap():
2537 heads += repo.branchheads(branch, start, opts.get('closed'))
2537 heads += repo.branchheads(branch, start, opts.get('closed'))
2538 heads = [repo[h] for h in heads]
2538 heads = [repo[h] for h in heads]
2539
2539
2540 if branchrevs:
2540 if branchrevs:
2541 branches = set(repo[br].branch() for br in branchrevs)
2541 branches = set(repo[br].branch() for br in branchrevs)
2542 heads = [h for h in heads if h.branch() in branches]
2542 heads = [h for h in heads if h.branch() in branches]
2543
2543
2544 if opts.get('active') and branchrevs:
2544 if opts.get('active') and branchrevs:
2545 dagheads = repo.heads(start)
2545 dagheads = repo.heads(start)
2546 heads = [h for h in heads if h.node() in dagheads]
2546 heads = [h for h in heads if h.node() in dagheads]
2547
2547
2548 if branchrevs:
2548 if branchrevs:
2549 haveheads = set(h.branch() for h in heads)
2549 haveheads = set(h.branch() for h in heads)
2550 if branches - haveheads:
2550 if branches - haveheads:
2551 headless = ', '.join(b for b in branches - haveheads)
2551 headless = ', '.join(b for b in branches - haveheads)
2552 msg = _('no open branch heads found on branches %s')
2552 msg = _('no open branch heads found on branches %s')
2553 if opts.get('rev'):
2553 if opts.get('rev'):
2554 msg += _(' (started at %s)' % opts['rev'])
2554 msg += _(' (started at %s)' % opts['rev'])
2555 ui.warn((msg + '\n') % headless)
2555 ui.warn((msg + '\n') % headless)
2556
2556
2557 if not heads:
2557 if not heads:
2558 return 1
2558 return 1
2559
2559
2560 heads = sorted(heads, key=lambda x: -x.rev())
2560 heads = sorted(heads, key=lambda x: -x.rev())
2561 displayer = cmdutil.show_changeset(ui, repo, opts)
2561 displayer = cmdutil.show_changeset(ui, repo, opts)
2562 for ctx in heads:
2562 for ctx in heads:
2563 displayer.show(ctx)
2563 displayer.show(ctx)
2564 displayer.close()
2564 displayer.close()
2565
2565
2566 @command('help',
2566 @command('help',
2567 [('e', 'extension', None, _('show only help for extensions')),
2567 [('e', 'extension', None, _('show only help for extensions')),
2568 ('c', 'command', None, _('show only help for commands'))],
2568 ('c', 'command', None, _('show only help for commands'))],
2569 _('[-ec] [TOPIC]'))
2569 _('[-ec] [TOPIC]'))
2570 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2570 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2571 """show help for a given topic or a help overview
2571 """show help for a given topic or a help overview
2572
2572
2573 With no arguments, print a list of commands with short help messages.
2573 With no arguments, print a list of commands with short help messages.
2574
2574
2575 Given a topic, extension, or command name, print help for that
2575 Given a topic, extension, or command name, print help for that
2576 topic.
2576 topic.
2577
2577
2578 Returns 0 if successful.
2578 Returns 0 if successful.
2579 """
2579 """
2580 option_lists = []
2580 option_lists = []
2581 textwidth = min(ui.termwidth(), 80) - 2
2581 textwidth = min(ui.termwidth(), 80) - 2
2582
2582
2583 def addglobalopts(aliases):
2583 def addglobalopts(aliases):
2584 if ui.verbose:
2584 if ui.verbose:
2585 option_lists.append((_("global options:"), globalopts))
2585 option_lists.append((_("global options:"), globalopts))
2586 if name == 'shortlist':
2586 if name == 'shortlist':
2587 option_lists.append((_('use "hg help" for the full list '
2587 option_lists.append((_('use "hg help" for the full list '
2588 'of commands'), ()))
2588 'of commands'), ()))
2589 else:
2589 else:
2590 if name == 'shortlist':
2590 if name == 'shortlist':
2591 msg = _('use "hg help" for the full list of commands '
2591 msg = _('use "hg help" for the full list of commands '
2592 'or "hg -v" for details')
2592 'or "hg -v" for details')
2593 elif name and not full:
2593 elif name and not full:
2594 msg = _('use "hg help %s" to show the full help text' % name)
2594 msg = _('use "hg help %s" to show the full help text' % name)
2595 elif aliases:
2595 elif aliases:
2596 msg = _('use "hg -v help%s" to show builtin aliases and '
2596 msg = _('use "hg -v help%s" to show builtin aliases and '
2597 'global options') % (name and " " + name or "")
2597 'global options') % (name and " " + name or "")
2598 else:
2598 else:
2599 msg = _('use "hg -v help %s" to show global options') % name
2599 msg = _('use "hg -v help %s" to show global options') % name
2600 option_lists.append((msg, ()))
2600 option_lists.append((msg, ()))
2601
2601
2602 def helpcmd(name):
2602 def helpcmd(name):
2603 if with_version:
2603 if with_version:
2604 version_(ui)
2604 version_(ui)
2605 ui.write('\n')
2605 ui.write('\n')
2606
2606
2607 try:
2607 try:
2608 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2608 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2609 except error.AmbiguousCommand, inst:
2609 except error.AmbiguousCommand, inst:
2610 # py3k fix: except vars can't be used outside the scope of the
2610 # py3k fix: except vars can't be used outside the scope of the
2611 # except block, nor can be used inside a lambda. python issue4617
2611 # except block, nor can be used inside a lambda. python issue4617
2612 prefix = inst.args[0]
2612 prefix = inst.args[0]
2613 select = lambda c: c.lstrip('^').startswith(prefix)
2613 select = lambda c: c.lstrip('^').startswith(prefix)
2614 helplist(_('list of commands:\n\n'), select)
2614 helplist(_('list of commands:\n\n'), select)
2615 return
2615 return
2616
2616
2617 # check if it's an invalid alias and display its error if it is
2617 # check if it's an invalid alias and display its error if it is
2618 if getattr(entry[0], 'badalias', False):
2618 if getattr(entry[0], 'badalias', False):
2619 if not unknowncmd:
2619 if not unknowncmd:
2620 entry[0](ui)
2620 entry[0](ui)
2621 return
2621 return
2622
2622
2623 # synopsis
2623 # synopsis
2624 if len(entry) > 2:
2624 if len(entry) > 2:
2625 if entry[2].startswith('hg'):
2625 if entry[2].startswith('hg'):
2626 ui.write("%s\n" % entry[2])
2626 ui.write("%s\n" % entry[2])
2627 else:
2627 else:
2628 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2628 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2629 else:
2629 else:
2630 ui.write('hg %s\n' % aliases[0])
2630 ui.write('hg %s\n' % aliases[0])
2631
2631
2632 # aliases
2632 # aliases
2633 if full and not ui.quiet and len(aliases) > 1:
2633 if full and not ui.quiet and len(aliases) > 1:
2634 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2634 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2635
2635
2636 # description
2636 # description
2637 doc = gettext(entry[0].__doc__)
2637 doc = gettext(entry[0].__doc__)
2638 if not doc:
2638 if not doc:
2639 doc = _("(no help text available)")
2639 doc = _("(no help text available)")
2640 if hasattr(entry[0], 'definition'): # aliased command
2640 if hasattr(entry[0], 'definition'): # aliased command
2641 if entry[0].definition.startswith('!'): # shell alias
2641 if entry[0].definition.startswith('!'): # shell alias
2642 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2642 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2643 else:
2643 else:
2644 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2644 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2645 if ui.quiet or not full:
2645 if ui.quiet or not full:
2646 doc = doc.splitlines()[0]
2646 doc = doc.splitlines()[0]
2647 keep = ui.verbose and ['verbose'] or []
2647 keep = ui.verbose and ['verbose'] or []
2648 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2648 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2649 ui.write("\n%s\n" % formatted)
2649 ui.write("\n%s\n" % formatted)
2650 if pruned:
2650 if pruned:
2651 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2651 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2652
2652
2653 if not ui.quiet:
2653 if not ui.quiet:
2654 # options
2654 # options
2655 if entry[1]:
2655 if entry[1]:
2656 option_lists.append((_("options:\n"), entry[1]))
2656 option_lists.append((_("options:\n"), entry[1]))
2657
2657
2658 addglobalopts(False)
2658 addglobalopts(False)
2659
2659
2660 # check if this command shadows a non-trivial (multi-line)
2660 # check if this command shadows a non-trivial (multi-line)
2661 # extension help text
2661 # extension help text
2662 try:
2662 try:
2663 mod = extensions.find(name)
2663 mod = extensions.find(name)
2664 doc = gettext(mod.__doc__) or ''
2664 doc = gettext(mod.__doc__) or ''
2665 if '\n' in doc.strip():
2665 if '\n' in doc.strip():
2666 msg = _('use "hg help -e %s" to show help for '
2666 msg = _('use "hg help -e %s" to show help for '
2667 'the %s extension') % (name, name)
2667 'the %s extension') % (name, name)
2668 ui.write('\n%s\n' % msg)
2668 ui.write('\n%s\n' % msg)
2669 except KeyError:
2669 except KeyError:
2670 pass
2670 pass
2671
2671
2672 def helplist(header, select=None):
2672 def helplist(header, select=None):
2673 h = {}
2673 h = {}
2674 cmds = {}
2674 cmds = {}
2675 for c, e in table.iteritems():
2675 for c, e in table.iteritems():
2676 f = c.split("|", 1)[0]
2676 f = c.split("|", 1)[0]
2677 if select and not select(f):
2677 if select and not select(f):
2678 continue
2678 continue
2679 if (not select and name != 'shortlist' and
2679 if (not select and name != 'shortlist' and
2680 e[0].__module__ != __name__):
2680 e[0].__module__ != __name__):
2681 continue
2681 continue
2682 if name == "shortlist" and not f.startswith("^"):
2682 if name == "shortlist" and not f.startswith("^"):
2683 continue
2683 continue
2684 f = f.lstrip("^")
2684 f = f.lstrip("^")
2685 if not ui.debugflag and f.startswith("debug"):
2685 if not ui.debugflag and f.startswith("debug"):
2686 continue
2686 continue
2687 doc = e[0].__doc__
2687 doc = e[0].__doc__
2688 if doc and 'DEPRECATED' in doc and not ui.verbose:
2688 if doc and 'DEPRECATED' in doc and not ui.verbose:
2689 continue
2689 continue
2690 doc = gettext(doc)
2690 doc = gettext(doc)
2691 if not doc:
2691 if not doc:
2692 doc = _("(no help text available)")
2692 doc = _("(no help text available)")
2693 h[f] = doc.splitlines()[0].rstrip()
2693 h[f] = doc.splitlines()[0].rstrip()
2694 cmds[f] = c.lstrip("^")
2694 cmds[f] = c.lstrip("^")
2695
2695
2696 if not h:
2696 if not h:
2697 ui.status(_('no commands defined\n'))
2697 ui.status(_('no commands defined\n'))
2698 return
2698 return
2699
2699
2700 ui.status(header)
2700 ui.status(header)
2701 fns = sorted(h)
2701 fns = sorted(h)
2702 m = max(map(len, fns))
2702 m = max(map(len, fns))
2703 for f in fns:
2703 for f in fns:
2704 if ui.verbose:
2704 if ui.verbose:
2705 commands = cmds[f].replace("|",", ")
2705 commands = cmds[f].replace("|",", ")
2706 ui.write(" %s:\n %s\n"%(commands, h[f]))
2706 ui.write(" %s:\n %s\n"%(commands, h[f]))
2707 else:
2707 else:
2708 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2708 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2709 initindent=' %-*s ' % (m, f),
2709 initindent=' %-*s ' % (m, f),
2710 hangindent=' ' * (m + 4))))
2710 hangindent=' ' * (m + 4))))
2711
2711
2712 if not ui.quiet:
2712 if not ui.quiet:
2713 addglobalopts(True)
2713 addglobalopts(True)
2714
2714
2715 def helptopic(name):
2715 def helptopic(name):
2716 for names, header, doc in help.helptable:
2716 for names, header, doc in help.helptable:
2717 if name in names:
2717 if name in names:
2718 break
2718 break
2719 else:
2719 else:
2720 raise error.UnknownCommand(name)
2720 raise error.UnknownCommand(name)
2721
2721
2722 # description
2722 # description
2723 if not doc:
2723 if not doc:
2724 doc = _("(no help text available)")
2724 doc = _("(no help text available)")
2725 if hasattr(doc, '__call__'):
2725 if hasattr(doc, '__call__'):
2726 doc = doc()
2726 doc = doc()
2727
2727
2728 ui.write("%s\n\n" % header)
2728 ui.write("%s\n\n" % header)
2729 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2729 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2730 try:
2730 try:
2731 cmdutil.findcmd(name, table)
2731 cmdutil.findcmd(name, table)
2732 ui.write(_('\nuse "hg help -c %s" to see help for '
2732 ui.write(_('\nuse "hg help -c %s" to see help for '
2733 'the %s command\n') % (name, name))
2733 'the %s command\n') % (name, name))
2734 except error.UnknownCommand:
2734 except error.UnknownCommand:
2735 pass
2735 pass
2736
2736
2737 def helpext(name):
2737 def helpext(name):
2738 try:
2738 try:
2739 mod = extensions.find(name)
2739 mod = extensions.find(name)
2740 doc = gettext(mod.__doc__) or _('no help text available')
2740 doc = gettext(mod.__doc__) or _('no help text available')
2741 except KeyError:
2741 except KeyError:
2742 mod = None
2742 mod = None
2743 doc = extensions.disabledext(name)
2743 doc = extensions.disabledext(name)
2744 if not doc:
2744 if not doc:
2745 raise error.UnknownCommand(name)
2745 raise error.UnknownCommand(name)
2746
2746
2747 if '\n' not in doc:
2747 if '\n' not in doc:
2748 head, tail = doc, ""
2748 head, tail = doc, ""
2749 else:
2749 else:
2750 head, tail = doc.split('\n', 1)
2750 head, tail = doc.split('\n', 1)
2751 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2751 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2752 if tail:
2752 if tail:
2753 ui.write(minirst.format(tail, textwidth))
2753 ui.write(minirst.format(tail, textwidth))
2754 ui.status('\n\n')
2754 ui.status('\n\n')
2755
2755
2756 if mod:
2756 if mod:
2757 try:
2757 try:
2758 ct = mod.cmdtable
2758 ct = mod.cmdtable
2759 except AttributeError:
2759 except AttributeError:
2760 ct = {}
2760 ct = {}
2761 modcmds = set([c.split('|', 1)[0] for c in ct])
2761 modcmds = set([c.split('|', 1)[0] for c in ct])
2762 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2762 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2763 else:
2763 else:
2764 ui.write(_('use "hg help extensions" for information on enabling '
2764 ui.write(_('use "hg help extensions" for information on enabling '
2765 'extensions\n'))
2765 'extensions\n'))
2766
2766
2767 def helpextcmd(name):
2767 def helpextcmd(name):
2768 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2768 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2769 doc = gettext(mod.__doc__).splitlines()[0]
2769 doc = gettext(mod.__doc__).splitlines()[0]
2770
2770
2771 msg = help.listexts(_("'%s' is provided by the following "
2771 msg = help.listexts(_("'%s' is provided by the following "
2772 "extension:") % cmd, {ext: doc}, indent=4)
2772 "extension:") % cmd, {ext: doc}, indent=4)
2773 ui.write(minirst.format(msg, textwidth))
2773 ui.write(minirst.format(msg, textwidth))
2774 ui.write('\n\n')
2774 ui.write('\n\n')
2775 ui.write(_('use "hg help extensions" for information on enabling '
2775 ui.write(_('use "hg help extensions" for information on enabling '
2776 'extensions\n'))
2776 'extensions\n'))
2777
2777
2778 if name and name != 'shortlist':
2778 if name and name != 'shortlist':
2779 i = None
2779 i = None
2780 if unknowncmd:
2780 if unknowncmd:
2781 queries = (helpextcmd,)
2781 queries = (helpextcmd,)
2782 elif opts.get('extension'):
2782 elif opts.get('extension'):
2783 queries = (helpext,)
2783 queries = (helpext,)
2784 elif opts.get('command'):
2784 elif opts.get('command'):
2785 queries = (helpcmd,)
2785 queries = (helpcmd,)
2786 else:
2786 else:
2787 queries = (helptopic, helpcmd, helpext, helpextcmd)
2787 queries = (helptopic, helpcmd, helpext, helpextcmd)
2788 for f in queries:
2788 for f in queries:
2789 try:
2789 try:
2790 f(name)
2790 f(name)
2791 i = None
2791 i = None
2792 break
2792 break
2793 except error.UnknownCommand, inst:
2793 except error.UnknownCommand, inst:
2794 i = inst
2794 i = inst
2795 if i:
2795 if i:
2796 raise i
2796 raise i
2797
2797
2798 else:
2798 else:
2799 # program name
2799 # program name
2800 if ui.verbose or with_version:
2800 if ui.verbose or with_version:
2801 version_(ui)
2801 version_(ui)
2802 else:
2802 else:
2803 ui.status(_("Mercurial Distributed SCM\n"))
2803 ui.status(_("Mercurial Distributed SCM\n"))
2804 ui.status('\n')
2804 ui.status('\n')
2805
2805
2806 # list of commands
2806 # list of commands
2807 if name == "shortlist":
2807 if name == "shortlist":
2808 header = _('basic commands:\n\n')
2808 header = _('basic commands:\n\n')
2809 else:
2809 else:
2810 header = _('list of commands:\n\n')
2810 header = _('list of commands:\n\n')
2811
2811
2812 helplist(header)
2812 helplist(header)
2813 if name != 'shortlist':
2813 if name != 'shortlist':
2814 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2814 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2815 if text:
2815 if text:
2816 ui.write("\n%s\n" % minirst.format(text, textwidth))
2816 ui.write("\n%s\n" % minirst.format(text, textwidth))
2817
2817
2818 # list all option lists
2818 # list all option lists
2819 opt_output = []
2819 opt_output = []
2820 multioccur = False
2820 multioccur = False
2821 for title, options in option_lists:
2821 for title, options in option_lists:
2822 opt_output.append(("\n%s" % title, None))
2822 opt_output.append(("\n%s" % title, None))
2823 for option in options:
2823 for option in options:
2824 if len(option) == 5:
2824 if len(option) == 5:
2825 shortopt, longopt, default, desc, optlabel = option
2825 shortopt, longopt, default, desc, optlabel = option
2826 else:
2826 else:
2827 shortopt, longopt, default, desc = option
2827 shortopt, longopt, default, desc = option
2828 optlabel = _("VALUE") # default label
2828 optlabel = _("VALUE") # default label
2829
2829
2830 if _("DEPRECATED") in desc and not ui.verbose:
2830 if _("DEPRECATED") in desc and not ui.verbose:
2831 continue
2831 continue
2832 if isinstance(default, list):
2832 if isinstance(default, list):
2833 numqualifier = " %s [+]" % optlabel
2833 numqualifier = " %s [+]" % optlabel
2834 multioccur = True
2834 multioccur = True
2835 elif (default is not None) and not isinstance(default, bool):
2835 elif (default is not None) and not isinstance(default, bool):
2836 numqualifier = " %s" % optlabel
2836 numqualifier = " %s" % optlabel
2837 else:
2837 else:
2838 numqualifier = ""
2838 numqualifier = ""
2839 opt_output.append(("%2s%s" %
2839 opt_output.append(("%2s%s" %
2840 (shortopt and "-%s" % shortopt,
2840 (shortopt and "-%s" % shortopt,
2841 longopt and " --%s%s" %
2841 longopt and " --%s%s" %
2842 (longopt, numqualifier)),
2842 (longopt, numqualifier)),
2843 "%s%s" % (desc,
2843 "%s%s" % (desc,
2844 default
2844 default
2845 and _(" (default: %s)") % default
2845 and _(" (default: %s)") % default
2846 or "")))
2846 or "")))
2847 if multioccur:
2847 if multioccur:
2848 msg = _("\n[+] marked option can be specified multiple times")
2848 msg = _("\n[+] marked option can be specified multiple times")
2849 if ui.verbose and name != 'shortlist':
2849 if ui.verbose and name != 'shortlist':
2850 opt_output.append((msg, None))
2850 opt_output.append((msg, None))
2851 else:
2851 else:
2852 opt_output.insert(-1, (msg, None))
2852 opt_output.insert(-1, (msg, None))
2853
2853
2854 if not name:
2854 if not name:
2855 ui.write(_("\nadditional help topics:\n\n"))
2855 ui.write(_("\nadditional help topics:\n\n"))
2856 topics = []
2856 topics = []
2857 for names, header, doc in help.helptable:
2857 for names, header, doc in help.helptable:
2858 topics.append((sorted(names, key=len, reverse=True)[0], header))
2858 topics.append((sorted(names, key=len, reverse=True)[0], header))
2859 topics_len = max([len(s[0]) for s in topics])
2859 topics_len = max([len(s[0]) for s in topics])
2860 for t, desc in topics:
2860 for t, desc in topics:
2861 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2861 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2862
2862
2863 if opt_output:
2863 if opt_output:
2864 colwidth = encoding.colwidth
2864 colwidth = encoding.colwidth
2865 # normalize: (opt or message, desc or None, width of opt)
2865 # normalize: (opt or message, desc or None, width of opt)
2866 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2866 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2867 for opt, desc in opt_output]
2867 for opt, desc in opt_output]
2868 hanging = max([e[2] for e in entries])
2868 hanging = max([e[2] for e in entries])
2869 for opt, desc, width in entries:
2869 for opt, desc, width in entries:
2870 if desc:
2870 if desc:
2871 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2871 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2872 hangindent = ' ' * (hanging + 3)
2872 hangindent = ' ' * (hanging + 3)
2873 ui.write('%s\n' % (util.wrap(desc, textwidth,
2873 ui.write('%s\n' % (util.wrap(desc, textwidth,
2874 initindent=initindent,
2874 initindent=initindent,
2875 hangindent=hangindent)))
2875 hangindent=hangindent)))
2876 else:
2876 else:
2877 ui.write("%s\n" % opt)
2877 ui.write("%s\n" % opt)
2878
2878
2879 @command('identify|id',
2879 @command('identify|id',
2880 [('r', 'rev', '',
2880 [('r', 'rev', '',
2881 _('identify the specified revision'), _('REV')),
2881 _('identify the specified revision'), _('REV')),
2882 ('n', 'num', None, _('show local revision number')),
2882 ('n', 'num', None, _('show local revision number')),
2883 ('i', 'id', None, _('show global revision id')),
2883 ('i', 'id', None, _('show global revision id')),
2884 ('b', 'branch', None, _('show branch')),
2884 ('b', 'branch', None, _('show branch')),
2885 ('t', 'tags', None, _('show tags')),
2885 ('t', 'tags', None, _('show tags')),
2886 ('B', 'bookmarks', None, _('show bookmarks'))],
2886 ('B', 'bookmarks', None, _('show bookmarks'))],
2887 _('[-nibtB] [-r REV] [SOURCE]'))
2887 _('[-nibtB] [-r REV] [SOURCE]'))
2888 def identify(ui, repo, source=None, rev=None,
2888 def identify(ui, repo, source=None, rev=None,
2889 num=None, id=None, branch=None, tags=None, bookmarks=None):
2889 num=None, id=None, branch=None, tags=None, bookmarks=None):
2890 """identify the working copy or specified revision
2890 """identify the working copy or specified revision
2891
2891
2892 Print a summary identifying the repository state at REV using one or
2892 Print a summary identifying the repository state at REV using one or
2893 two parent hash identifiers, followed by a "+" if the working
2893 two parent hash identifiers, followed by a "+" if the working
2894 directory has uncommitted changes, the branch name (if not default),
2894 directory has uncommitted changes, the branch name (if not default),
2895 a list of tags, and a list of bookmarks.
2895 a list of tags, and a list of bookmarks.
2896
2896
2897 When REV is not given, print a summary of the current state of the
2897 When REV is not given, print a summary of the current state of the
2898 repository.
2898 repository.
2899
2899
2900 Specifying a path to a repository root or Mercurial bundle will
2900 Specifying a path to a repository root or Mercurial bundle will
2901 cause lookup to operate on that repository/bundle.
2901 cause lookup to operate on that repository/bundle.
2902
2902
2903 Returns 0 if successful.
2903 Returns 0 if successful.
2904 """
2904 """
2905
2905
2906 if not repo and not source:
2906 if not repo and not source:
2907 raise util.Abort(_("there is no Mercurial repository here "
2907 raise util.Abort(_("there is no Mercurial repository here "
2908 "(.hg not found)"))
2908 "(.hg not found)"))
2909
2909
2910 hexfunc = ui.debugflag and hex or short
2910 hexfunc = ui.debugflag and hex or short
2911 default = not (num or id or branch or tags or bookmarks)
2911 default = not (num or id or branch or tags or bookmarks)
2912 output = []
2912 output = []
2913 revs = []
2913 revs = []
2914
2914
2915 if source:
2915 if source:
2916 source, branches = hg.parseurl(ui.expandpath(source))
2916 source, branches = hg.parseurl(ui.expandpath(source))
2917 repo = hg.peer(ui, {}, source)
2917 repo = hg.peer(ui, {}, source)
2918 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2918 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2919
2919
2920 if not repo.local():
2920 if not repo.local():
2921 if num or branch or tags:
2921 if num or branch or tags:
2922 raise util.Abort(
2922 raise util.Abort(
2923 _("can't query remote revision number, branch, or tags"))
2923 _("can't query remote revision number, branch, or tags"))
2924 if not rev and revs:
2924 if not rev and revs:
2925 rev = revs[0]
2925 rev = revs[0]
2926 if not rev:
2926 if not rev:
2927 rev = "tip"
2927 rev = "tip"
2928
2928
2929 remoterev = repo.lookup(rev)
2929 remoterev = repo.lookup(rev)
2930 if default or id:
2930 if default or id:
2931 output = [hexfunc(remoterev)]
2931 output = [hexfunc(remoterev)]
2932
2932
2933 def getbms():
2933 def getbms():
2934 bms = []
2934 bms = []
2935
2935
2936 if 'bookmarks' in repo.listkeys('namespaces'):
2936 if 'bookmarks' in repo.listkeys('namespaces'):
2937 hexremoterev = hex(remoterev)
2937 hexremoterev = hex(remoterev)
2938 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2938 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2939 if bmr == hexremoterev]
2939 if bmr == hexremoterev]
2940
2940
2941 return bms
2941 return bms
2942
2942
2943 if bookmarks:
2943 if bookmarks:
2944 output.extend(getbms())
2944 output.extend(getbms())
2945 elif default and not ui.quiet:
2945 elif default and not ui.quiet:
2946 # multiple bookmarks for a single parent separated by '/'
2946 # multiple bookmarks for a single parent separated by '/'
2947 bm = '/'.join(getbms())
2947 bm = '/'.join(getbms())
2948 if bm:
2948 if bm:
2949 output.append(bm)
2949 output.append(bm)
2950 else:
2950 else:
2951 if not rev:
2951 if not rev:
2952 ctx = repo[None]
2952 ctx = repo[None]
2953 parents = ctx.parents()
2953 parents = ctx.parents()
2954 changed = ""
2954 changed = ""
2955 if default or id or num:
2955 if default or id or num:
2956 changed = util.any(repo.status()) and "+" or ""
2956 changed = util.any(repo.status()) and "+" or ""
2957 if default or id:
2957 if default or id:
2958 output = ["%s%s" %
2958 output = ["%s%s" %
2959 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2959 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2960 if num:
2960 if num:
2961 output.append("%s%s" %
2961 output.append("%s%s" %
2962 ('+'.join([str(p.rev()) for p in parents]), changed))
2962 ('+'.join([str(p.rev()) for p in parents]), changed))
2963 else:
2963 else:
2964 ctx = scmutil.revsingle(repo, rev)
2964 ctx = scmutil.revsingle(repo, rev)
2965 if default or id:
2965 if default or id:
2966 output = [hexfunc(ctx.node())]
2966 output = [hexfunc(ctx.node())]
2967 if num:
2967 if num:
2968 output.append(str(ctx.rev()))
2968 output.append(str(ctx.rev()))
2969
2969
2970 if default and not ui.quiet:
2970 if default and not ui.quiet:
2971 b = ctx.branch()
2971 b = ctx.branch()
2972 if b != 'default':
2972 if b != 'default':
2973 output.append("(%s)" % b)
2973 output.append("(%s)" % b)
2974
2974
2975 # multiple tags for a single parent separated by '/'
2975 # multiple tags for a single parent separated by '/'
2976 t = '/'.join(ctx.tags())
2976 t = '/'.join(ctx.tags())
2977 if t:
2977 if t:
2978 output.append(t)
2978 output.append(t)
2979
2979
2980 # multiple bookmarks for a single parent separated by '/'
2980 # multiple bookmarks for a single parent separated by '/'
2981 bm = '/'.join(ctx.bookmarks())
2981 bm = '/'.join(ctx.bookmarks())
2982 if bm:
2982 if bm:
2983 output.append(bm)
2983 output.append(bm)
2984 else:
2984 else:
2985 if branch:
2985 if branch:
2986 output.append(ctx.branch())
2986 output.append(ctx.branch())
2987
2987
2988 if tags:
2988 if tags:
2989 output.extend(ctx.tags())
2989 output.extend(ctx.tags())
2990
2990
2991 if bookmarks:
2991 if bookmarks:
2992 output.extend(ctx.bookmarks())
2992 output.extend(ctx.bookmarks())
2993
2993
2994 ui.write("%s\n" % ' '.join(output))
2994 ui.write("%s\n" % ' '.join(output))
2995
2995
2996 @command('import|patch',
2996 @command('import|patch',
2997 [('p', 'strip', 1,
2997 [('p', 'strip', 1,
2998 _('directory strip option for patch. This has the same '
2998 _('directory strip option for patch. This has the same '
2999 'meaning as the corresponding patch option'), _('NUM')),
2999 'meaning as the corresponding patch option'), _('NUM')),
3000 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3000 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3001 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3001 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3002 ('', 'no-commit', None,
3002 ('', 'no-commit', None,
3003 _("don't commit, just update the working directory")),
3003 _("don't commit, just update the working directory")),
3004 ('', 'exact', None,
3004 ('', 'exact', None,
3005 _('apply patch to the nodes from which it was generated')),
3005 _('apply patch to the nodes from which it was generated')),
3006 ('', 'import-branch', None,
3006 ('', 'import-branch', None,
3007 _('use any branch information in patch (implied by --exact)'))] +
3007 _('use any branch information in patch (implied by --exact)'))] +
3008 commitopts + commitopts2 + similarityopts,
3008 commitopts + commitopts2 + similarityopts,
3009 _('[OPTION]... PATCH...'))
3009 _('[OPTION]... PATCH...'))
3010 def import_(ui, repo, patch1, *patches, **opts):
3010 def import_(ui, repo, patch1, *patches, **opts):
3011 """import an ordered set of patches
3011 """import an ordered set of patches
3012
3012
3013 Import a list of patches and commit them individually (unless
3013 Import a list of patches and commit them individually (unless
3014 --no-commit is specified).
3014 --no-commit is specified).
3015
3015
3016 If there are outstanding changes in the working directory, import
3016 If there are outstanding changes in the working directory, import
3017 will abort unless given the -f/--force flag.
3017 will abort unless given the -f/--force flag.
3018
3018
3019 You can import a patch straight from a mail message. Even patches
3019 You can import a patch straight from a mail message. Even patches
3020 as attachments work (to use the body part, it must have type
3020 as attachments work (to use the body part, it must have type
3021 text/plain or text/x-patch). From and Subject headers of email
3021 text/plain or text/x-patch). From and Subject headers of email
3022 message are used as default committer and commit message. All
3022 message are used as default committer and commit message. All
3023 text/plain body parts before first diff are added to commit
3023 text/plain body parts before first diff are added to commit
3024 message.
3024 message.
3025
3025
3026 If the imported patch was generated by :hg:`export`, user and
3026 If the imported patch was generated by :hg:`export`, user and
3027 description from patch override values from message headers and
3027 description from patch override values from message headers and
3028 body. Values given on command line with -m/--message and -u/--user
3028 body. Values given on command line with -m/--message and -u/--user
3029 override these.
3029 override these.
3030
3030
3031 If --exact is specified, import will set the working directory to
3031 If --exact is specified, import will set the working directory to
3032 the parent of each patch before applying it, and will abort if the
3032 the parent of each patch before applying it, and will abort if the
3033 resulting changeset has a different ID than the one recorded in
3033 resulting changeset has a different ID than the one recorded in
3034 the patch. This may happen due to character set problems or other
3034 the patch. This may happen due to character set problems or other
3035 deficiencies in the text patch format.
3035 deficiencies in the text patch format.
3036
3036
3037 With -s/--similarity, hg will attempt to discover renames and
3037 With -s/--similarity, hg will attempt to discover renames and
3038 copies in the patch in the same way as 'addremove'.
3038 copies in the patch in the same way as 'addremove'.
3039
3039
3040 To read a patch from standard input, use "-" as the patch name. If
3040 To read a patch from standard input, use "-" as the patch name. If
3041 a URL is specified, the patch will be downloaded from it.
3041 a URL is specified, the patch will be downloaded from it.
3042 See :hg:`help dates` for a list of formats valid for -d/--date.
3042 See :hg:`help dates` for a list of formats valid for -d/--date.
3043
3043
3044 Returns 0 on success.
3044 Returns 0 on success.
3045 """
3045 """
3046 patches = (patch1,) + patches
3046 patches = (patch1,) + patches
3047
3047
3048 date = opts.get('date')
3048 date = opts.get('date')
3049 if date:
3049 if date:
3050 opts['date'] = util.parsedate(date)
3050 opts['date'] = util.parsedate(date)
3051
3051
3052 try:
3052 try:
3053 sim = float(opts.get('similarity') or 0)
3053 sim = float(opts.get('similarity') or 0)
3054 except ValueError:
3054 except ValueError:
3055 raise util.Abort(_('similarity must be a number'))
3055 raise util.Abort(_('similarity must be a number'))
3056 if sim < 0 or sim > 100:
3056 if sim < 0 or sim > 100:
3057 raise util.Abort(_('similarity must be between 0 and 100'))
3057 raise util.Abort(_('similarity must be between 0 and 100'))
3058
3058
3059 if opts.get('exact') or not opts.get('force'):
3059 if opts.get('exact') or not opts.get('force'):
3060 cmdutil.bailifchanged(repo)
3060 cmdutil.bailifchanged(repo)
3061
3061
3062 d = opts["base"]
3062 d = opts["base"]
3063 strip = opts["strip"]
3063 strip = opts["strip"]
3064 wlock = lock = None
3064 wlock = lock = None
3065 msgs = []
3065 msgs = []
3066
3066
3067 def tryone(ui, hunk):
3067 def tryone(ui, hunk):
3068 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3068 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3069 patch.extract(ui, hunk)
3069 patch.extract(ui, hunk)
3070
3070
3071 if not tmpname:
3071 if not tmpname:
3072 return None
3072 return None
3073 commitid = _('to working directory')
3073 commitid = _('to working directory')
3074
3074
3075 try:
3075 try:
3076 cmdline_message = cmdutil.logmessage(opts)
3076 cmdline_message = cmdutil.logmessage(opts)
3077 if cmdline_message:
3077 if cmdline_message:
3078 # pickup the cmdline msg
3078 # pickup the cmdline msg
3079 message = cmdline_message
3079 message = cmdline_message
3080 elif message:
3080 elif message:
3081 # pickup the patch msg
3081 # pickup the patch msg
3082 message = message.strip()
3082 message = message.strip()
3083 else:
3083 else:
3084 # launch the editor
3084 # launch the editor
3085 message = None
3085 message = None
3086 ui.debug('message:\n%s\n' % message)
3086 ui.debug('message:\n%s\n' % message)
3087
3087
3088 wp = repo.parents()
3088 wp = repo.parents()
3089 if opts.get('exact'):
3089 if opts.get('exact'):
3090 if not nodeid or not p1:
3090 if not nodeid or not p1:
3091 raise util.Abort(_('not a Mercurial patch'))
3091 raise util.Abort(_('not a Mercurial patch'))
3092 p1 = repo.lookup(p1)
3092 p1 = repo.lookup(p1)
3093 p2 = repo.lookup(p2 or hex(nullid))
3093 p2 = repo.lookup(p2 or hex(nullid))
3094
3094
3095 if p1 != wp[0].node():
3095 if p1 != wp[0].node():
3096 hg.clean(repo, p1)
3096 hg.clean(repo, p1)
3097 repo.dirstate.setparents(p1, p2)
3097 repo.dirstate.setparents(p1, p2)
3098 elif p2:
3098 elif p2:
3099 try:
3099 try:
3100 p1 = repo.lookup(p1)
3100 p1 = repo.lookup(p1)
3101 p2 = repo.lookup(p2)
3101 p2 = repo.lookup(p2)
3102 if p1 == wp[0].node():
3102 if p1 == wp[0].node():
3103 repo.dirstate.setparents(p1, p2)
3103 repo.dirstate.setparents(p1, p2)
3104 except error.RepoError:
3104 except error.RepoError:
3105 pass
3105 pass
3106 if opts.get('exact') or opts.get('import_branch'):
3106 if opts.get('exact') or opts.get('import_branch'):
3107 repo.dirstate.setbranch(branch or 'default')
3107 repo.dirstate.setbranch(branch or 'default')
3108
3108
3109 files = {}
3109 files = set()
3110 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3110 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3111 eolmode=None, similarity=sim / 100.0)
3111 eolmode=None, similarity=sim / 100.0)
3112 files = list(files)
3112 files = list(files)
3113 if opts.get('no_commit'):
3113 if opts.get('no_commit'):
3114 if message:
3114 if message:
3115 msgs.append(message)
3115 msgs.append(message)
3116 else:
3116 else:
3117 if opts.get('exact'):
3117 if opts.get('exact'):
3118 m = None
3118 m = None
3119 else:
3119 else:
3120 m = scmutil.matchfiles(repo, files or [])
3120 m = scmutil.matchfiles(repo, files or [])
3121 n = repo.commit(message, opts.get('user') or user,
3121 n = repo.commit(message, opts.get('user') or user,
3122 opts.get('date') or date, match=m,
3122 opts.get('date') or date, match=m,
3123 editor=cmdutil.commiteditor)
3123 editor=cmdutil.commiteditor)
3124 if opts.get('exact'):
3124 if opts.get('exact'):
3125 if hex(n) != nodeid:
3125 if hex(n) != nodeid:
3126 repo.rollback()
3126 repo.rollback()
3127 raise util.Abort(_('patch is damaged'
3127 raise util.Abort(_('patch is damaged'
3128 ' or loses information'))
3128 ' or loses information'))
3129 # Force a dirstate write so that the next transaction
3129 # Force a dirstate write so that the next transaction
3130 # backups an up-do-date file.
3130 # backups an up-do-date file.
3131 repo.dirstate.write()
3131 repo.dirstate.write()
3132 if n:
3132 if n:
3133 commitid = short(n)
3133 commitid = short(n)
3134
3134
3135 return commitid
3135 return commitid
3136 finally:
3136 finally:
3137 os.unlink(tmpname)
3137 os.unlink(tmpname)
3138
3138
3139 try:
3139 try:
3140 wlock = repo.wlock()
3140 wlock = repo.wlock()
3141 lock = repo.lock()
3141 lock = repo.lock()
3142 lastcommit = None
3142 lastcommit = None
3143 for p in patches:
3143 for p in patches:
3144 pf = os.path.join(d, p)
3144 pf = os.path.join(d, p)
3145
3145
3146 if pf == '-':
3146 if pf == '-':
3147 ui.status(_("applying patch from stdin\n"))
3147 ui.status(_("applying patch from stdin\n"))
3148 pf = sys.stdin
3148 pf = sys.stdin
3149 else:
3149 else:
3150 ui.status(_("applying %s\n") % p)
3150 ui.status(_("applying %s\n") % p)
3151 pf = url.open(ui, pf)
3151 pf = url.open(ui, pf)
3152
3152
3153 haspatch = False
3153 haspatch = False
3154 for hunk in patch.split(pf):
3154 for hunk in patch.split(pf):
3155 commitid = tryone(ui, hunk)
3155 commitid = tryone(ui, hunk)
3156 if commitid:
3156 if commitid:
3157 haspatch = True
3157 haspatch = True
3158 if lastcommit:
3158 if lastcommit:
3159 ui.status(_('applied %s\n') % lastcommit)
3159 ui.status(_('applied %s\n') % lastcommit)
3160 lastcommit = commitid
3160 lastcommit = commitid
3161
3161
3162 if not haspatch:
3162 if not haspatch:
3163 raise util.Abort(_('no diffs found'))
3163 raise util.Abort(_('no diffs found'))
3164
3164
3165 if msgs:
3165 if msgs:
3166 repo.savecommitmessage('\n* * *\n'.join(msgs))
3166 repo.savecommitmessage('\n* * *\n'.join(msgs))
3167 finally:
3167 finally:
3168 release(lock, wlock)
3168 release(lock, wlock)
3169
3169
3170 @command('incoming|in',
3170 @command('incoming|in',
3171 [('f', 'force', None,
3171 [('f', 'force', None,
3172 _('run even if remote repository is unrelated')),
3172 _('run even if remote repository is unrelated')),
3173 ('n', 'newest-first', None, _('show newest record first')),
3173 ('n', 'newest-first', None, _('show newest record first')),
3174 ('', 'bundle', '',
3174 ('', 'bundle', '',
3175 _('file to store the bundles into'), _('FILE')),
3175 _('file to store the bundles into'), _('FILE')),
3176 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3176 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3177 ('B', 'bookmarks', False, _("compare bookmarks")),
3177 ('B', 'bookmarks', False, _("compare bookmarks")),
3178 ('b', 'branch', [],
3178 ('b', 'branch', [],
3179 _('a specific branch you would like to pull'), _('BRANCH')),
3179 _('a specific branch you would like to pull'), _('BRANCH')),
3180 ] + logopts + remoteopts + subrepoopts,
3180 ] + logopts + remoteopts + subrepoopts,
3181 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3181 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3182 def incoming(ui, repo, source="default", **opts):
3182 def incoming(ui, repo, source="default", **opts):
3183 """show new changesets found in source
3183 """show new changesets found in source
3184
3184
3185 Show new changesets found in the specified path/URL or the default
3185 Show new changesets found in the specified path/URL or the default
3186 pull location. These are the changesets that would have been pulled
3186 pull location. These are the changesets that would have been pulled
3187 if a pull at the time you issued this command.
3187 if a pull at the time you issued this command.
3188
3188
3189 For remote repository, using --bundle avoids downloading the
3189 For remote repository, using --bundle avoids downloading the
3190 changesets twice if the incoming is followed by a pull.
3190 changesets twice if the incoming is followed by a pull.
3191
3191
3192 See pull for valid source format details.
3192 See pull for valid source format details.
3193
3193
3194 Returns 0 if there are incoming changes, 1 otherwise.
3194 Returns 0 if there are incoming changes, 1 otherwise.
3195 """
3195 """
3196 if opts.get('bundle') and opts.get('subrepos'):
3196 if opts.get('bundle') and opts.get('subrepos'):
3197 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3197 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3198
3198
3199 if opts.get('bookmarks'):
3199 if opts.get('bookmarks'):
3200 source, branches = hg.parseurl(ui.expandpath(source),
3200 source, branches = hg.parseurl(ui.expandpath(source),
3201 opts.get('branch'))
3201 opts.get('branch'))
3202 other = hg.peer(repo, opts, source)
3202 other = hg.peer(repo, opts, source)
3203 if 'bookmarks' not in other.listkeys('namespaces'):
3203 if 'bookmarks' not in other.listkeys('namespaces'):
3204 ui.warn(_("remote doesn't support bookmarks\n"))
3204 ui.warn(_("remote doesn't support bookmarks\n"))
3205 return 0
3205 return 0
3206 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3206 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3207 return bookmarks.diff(ui, repo, other)
3207 return bookmarks.diff(ui, repo, other)
3208
3208
3209 repo._subtoppath = ui.expandpath(source)
3209 repo._subtoppath = ui.expandpath(source)
3210 try:
3210 try:
3211 return hg.incoming(ui, repo, source, opts)
3211 return hg.incoming(ui, repo, source, opts)
3212 finally:
3212 finally:
3213 del repo._subtoppath
3213 del repo._subtoppath
3214
3214
3215
3215
3216 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3216 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3217 def init(ui, dest=".", **opts):
3217 def init(ui, dest=".", **opts):
3218 """create a new repository in the given directory
3218 """create a new repository in the given directory
3219
3219
3220 Initialize a new repository in the given directory. If the given
3220 Initialize a new repository in the given directory. If the given
3221 directory does not exist, it will be created.
3221 directory does not exist, it will be created.
3222
3222
3223 If no directory is given, the current directory is used.
3223 If no directory is given, the current directory is used.
3224
3224
3225 It is possible to specify an ``ssh://`` URL as the destination.
3225 It is possible to specify an ``ssh://`` URL as the destination.
3226 See :hg:`help urls` for more information.
3226 See :hg:`help urls` for more information.
3227
3227
3228 Returns 0 on success.
3228 Returns 0 on success.
3229 """
3229 """
3230 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3230 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3231
3231
3232 @command('locate',
3232 @command('locate',
3233 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3233 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3234 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3234 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3235 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3235 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3236 ] + walkopts,
3236 ] + walkopts,
3237 _('[OPTION]... [PATTERN]...'))
3237 _('[OPTION]... [PATTERN]...'))
3238 def locate(ui, repo, *pats, **opts):
3238 def locate(ui, repo, *pats, **opts):
3239 """locate files matching specific patterns
3239 """locate files matching specific patterns
3240
3240
3241 Print files under Mercurial control in the working directory whose
3241 Print files under Mercurial control in the working directory whose
3242 names match the given patterns.
3242 names match the given patterns.
3243
3243
3244 By default, this command searches all directories in the working
3244 By default, this command searches all directories in the working
3245 directory. To search just the current directory and its
3245 directory. To search just the current directory and its
3246 subdirectories, use "--include .".
3246 subdirectories, use "--include .".
3247
3247
3248 If no patterns are given to match, this command prints the names
3248 If no patterns are given to match, this command prints the names
3249 of all files under Mercurial control in the working directory.
3249 of all files under Mercurial control in the working directory.
3250
3250
3251 If you want to feed the output of this command into the "xargs"
3251 If you want to feed the output of this command into the "xargs"
3252 command, use the -0 option to both this command and "xargs". This
3252 command, use the -0 option to both this command and "xargs". This
3253 will avoid the problem of "xargs" treating single filenames that
3253 will avoid the problem of "xargs" treating single filenames that
3254 contain whitespace as multiple filenames.
3254 contain whitespace as multiple filenames.
3255
3255
3256 Returns 0 if a match is found, 1 otherwise.
3256 Returns 0 if a match is found, 1 otherwise.
3257 """
3257 """
3258 end = opts.get('print0') and '\0' or '\n'
3258 end = opts.get('print0') and '\0' or '\n'
3259 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3259 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3260
3260
3261 ret = 1
3261 ret = 1
3262 m = scmutil.match(repo, pats, opts, default='relglob')
3262 m = scmutil.match(repo, pats, opts, default='relglob')
3263 m.bad = lambda x, y: False
3263 m.bad = lambda x, y: False
3264 for abs in repo[rev].walk(m):
3264 for abs in repo[rev].walk(m):
3265 if not rev and abs not in repo.dirstate:
3265 if not rev and abs not in repo.dirstate:
3266 continue
3266 continue
3267 if opts.get('fullpath'):
3267 if opts.get('fullpath'):
3268 ui.write(repo.wjoin(abs), end)
3268 ui.write(repo.wjoin(abs), end)
3269 else:
3269 else:
3270 ui.write(((pats and m.rel(abs)) or abs), end)
3270 ui.write(((pats and m.rel(abs)) or abs), end)
3271 ret = 0
3271 ret = 0
3272
3272
3273 return ret
3273 return ret
3274
3274
3275 @command('^log|history',
3275 @command('^log|history',
3276 [('f', 'follow', None,
3276 [('f', 'follow', None,
3277 _('follow changeset history, or file history across copies and renames')),
3277 _('follow changeset history, or file history across copies and renames')),
3278 ('', 'follow-first', None,
3278 ('', 'follow-first', None,
3279 _('only follow the first parent of merge changesets')),
3279 _('only follow the first parent of merge changesets')),
3280 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3280 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3281 ('C', 'copies', None, _('show copied files')),
3281 ('C', 'copies', None, _('show copied files')),
3282 ('k', 'keyword', [],
3282 ('k', 'keyword', [],
3283 _('do case-insensitive search for a given text'), _('TEXT')),
3283 _('do case-insensitive search for a given text'), _('TEXT')),
3284 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3284 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3285 ('', 'removed', None, _('include revisions where files were removed')),
3285 ('', 'removed', None, _('include revisions where files were removed')),
3286 ('m', 'only-merges', None, _('show only merges')),
3286 ('m', 'only-merges', None, _('show only merges')),
3287 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3287 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3288 ('', 'only-branch', [],
3288 ('', 'only-branch', [],
3289 _('show only changesets within the given named branch (DEPRECATED)'),
3289 _('show only changesets within the given named branch (DEPRECATED)'),
3290 _('BRANCH')),
3290 _('BRANCH')),
3291 ('b', 'branch', [],
3291 ('b', 'branch', [],
3292 _('show changesets within the given named branch'), _('BRANCH')),
3292 _('show changesets within the given named branch'), _('BRANCH')),
3293 ('P', 'prune', [],
3293 ('P', 'prune', [],
3294 _('do not display revision or any of its ancestors'), _('REV')),
3294 _('do not display revision or any of its ancestors'), _('REV')),
3295 ] + logopts + walkopts,
3295 ] + logopts + walkopts,
3296 _('[OPTION]... [FILE]'))
3296 _('[OPTION]... [FILE]'))
3297 def log(ui, repo, *pats, **opts):
3297 def log(ui, repo, *pats, **opts):
3298 """show revision history of entire repository or files
3298 """show revision history of entire repository or files
3299
3299
3300 Print the revision history of the specified files or the entire
3300 Print the revision history of the specified files or the entire
3301 project.
3301 project.
3302
3302
3303 File history is shown without following rename or copy history of
3303 File history is shown without following rename or copy history of
3304 files. Use -f/--follow with a filename to follow history across
3304 files. Use -f/--follow with a filename to follow history across
3305 renames and copies. --follow without a filename will only show
3305 renames and copies. --follow without a filename will only show
3306 ancestors or descendants of the starting revision. --follow-first
3306 ancestors or descendants of the starting revision. --follow-first
3307 only follows the first parent of merge revisions.
3307 only follows the first parent of merge revisions.
3308
3308
3309 If no revision range is specified, the default is ``tip:0`` unless
3309 If no revision range is specified, the default is ``tip:0`` unless
3310 --follow is set, in which case the working directory parent is
3310 --follow is set, in which case the working directory parent is
3311 used as the starting revision. You can specify a revision set for
3311 used as the starting revision. You can specify a revision set for
3312 log, see :hg:`help revsets` for more information.
3312 log, see :hg:`help revsets` for more information.
3313
3313
3314 See :hg:`help dates` for a list of formats valid for -d/--date.
3314 See :hg:`help dates` for a list of formats valid for -d/--date.
3315
3315
3316 By default this command prints revision number and changeset id,
3316 By default this command prints revision number and changeset id,
3317 tags, non-trivial parents, user, date and time, and a summary for
3317 tags, non-trivial parents, user, date and time, and a summary for
3318 each commit. When the -v/--verbose switch is used, the list of
3318 each commit. When the -v/--verbose switch is used, the list of
3319 changed files and full commit message are shown.
3319 changed files and full commit message are shown.
3320
3320
3321 .. note::
3321 .. note::
3322 log -p/--patch may generate unexpected diff output for merge
3322 log -p/--patch may generate unexpected diff output for merge
3323 changesets, as it will only compare the merge changeset against
3323 changesets, as it will only compare the merge changeset against
3324 its first parent. Also, only files different from BOTH parents
3324 its first parent. Also, only files different from BOTH parents
3325 will appear in files:.
3325 will appear in files:.
3326
3326
3327 Returns 0 on success.
3327 Returns 0 on success.
3328 """
3328 """
3329
3329
3330 matchfn = scmutil.match(repo, pats, opts)
3330 matchfn = scmutil.match(repo, pats, opts)
3331 limit = cmdutil.loglimit(opts)
3331 limit = cmdutil.loglimit(opts)
3332 count = 0
3332 count = 0
3333
3333
3334 endrev = None
3334 endrev = None
3335 if opts.get('copies') and opts.get('rev'):
3335 if opts.get('copies') and opts.get('rev'):
3336 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3336 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3337
3337
3338 df = False
3338 df = False
3339 if opts["date"]:
3339 if opts["date"]:
3340 df = util.matchdate(opts["date"])
3340 df = util.matchdate(opts["date"])
3341
3341
3342 branches = opts.get('branch', []) + opts.get('only_branch', [])
3342 branches = opts.get('branch', []) + opts.get('only_branch', [])
3343 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3343 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3344
3344
3345 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3345 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3346 def prep(ctx, fns):
3346 def prep(ctx, fns):
3347 rev = ctx.rev()
3347 rev = ctx.rev()
3348 parents = [p for p in repo.changelog.parentrevs(rev)
3348 parents = [p for p in repo.changelog.parentrevs(rev)
3349 if p != nullrev]
3349 if p != nullrev]
3350 if opts.get('no_merges') and len(parents) == 2:
3350 if opts.get('no_merges') and len(parents) == 2:
3351 return
3351 return
3352 if opts.get('only_merges') and len(parents) != 2:
3352 if opts.get('only_merges') and len(parents) != 2:
3353 return
3353 return
3354 if opts.get('branch') and ctx.branch() not in opts['branch']:
3354 if opts.get('branch') and ctx.branch() not in opts['branch']:
3355 return
3355 return
3356 if df and not df(ctx.date()[0]):
3356 if df and not df(ctx.date()[0]):
3357 return
3357 return
3358 if opts['user'] and not [k for k in opts['user']
3358 if opts['user'] and not [k for k in opts['user']
3359 if k.lower() in ctx.user().lower()]:
3359 if k.lower() in ctx.user().lower()]:
3360 return
3360 return
3361 if opts.get('keyword'):
3361 if opts.get('keyword'):
3362 for k in [kw.lower() for kw in opts['keyword']]:
3362 for k in [kw.lower() for kw in opts['keyword']]:
3363 if (k in ctx.user().lower() or
3363 if (k in ctx.user().lower() or
3364 k in ctx.description().lower() or
3364 k in ctx.description().lower() or
3365 k in " ".join(ctx.files()).lower()):
3365 k in " ".join(ctx.files()).lower()):
3366 break
3366 break
3367 else:
3367 else:
3368 return
3368 return
3369
3369
3370 copies = None
3370 copies = None
3371 if opts.get('copies') and rev:
3371 if opts.get('copies') and rev:
3372 copies = []
3372 copies = []
3373 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3373 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3374 for fn in ctx.files():
3374 for fn in ctx.files():
3375 rename = getrenamed(fn, rev)
3375 rename = getrenamed(fn, rev)
3376 if rename:
3376 if rename:
3377 copies.append((fn, rename[0]))
3377 copies.append((fn, rename[0]))
3378
3378
3379 revmatchfn = None
3379 revmatchfn = None
3380 if opts.get('patch') or opts.get('stat'):
3380 if opts.get('patch') or opts.get('stat'):
3381 if opts.get('follow') or opts.get('follow_first'):
3381 if opts.get('follow') or opts.get('follow_first'):
3382 # note: this might be wrong when following through merges
3382 # note: this might be wrong when following through merges
3383 revmatchfn = scmutil.match(repo, fns, default='path')
3383 revmatchfn = scmutil.match(repo, fns, default='path')
3384 else:
3384 else:
3385 revmatchfn = matchfn
3385 revmatchfn = matchfn
3386
3386
3387 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3387 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3388
3388
3389 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3389 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3390 if count == limit:
3390 if count == limit:
3391 break
3391 break
3392 if displayer.flush(ctx.rev()):
3392 if displayer.flush(ctx.rev()):
3393 count += 1
3393 count += 1
3394 displayer.close()
3394 displayer.close()
3395
3395
3396 @command('manifest',
3396 @command('manifest',
3397 [('r', 'rev', '', _('revision to display'), _('REV')),
3397 [('r', 'rev', '', _('revision to display'), _('REV')),
3398 ('', 'all', False, _("list files from all revisions"))],
3398 ('', 'all', False, _("list files from all revisions"))],
3399 _('[-r REV]'))
3399 _('[-r REV]'))
3400 def manifest(ui, repo, node=None, rev=None, **opts):
3400 def manifest(ui, repo, node=None, rev=None, **opts):
3401 """output the current or given revision of the project manifest
3401 """output the current or given revision of the project manifest
3402
3402
3403 Print a list of version controlled files for the given revision.
3403 Print a list of version controlled files for the given revision.
3404 If no revision is given, the first parent of the working directory
3404 If no revision is given, the first parent of the working directory
3405 is used, or the null revision if no revision is checked out.
3405 is used, or the null revision if no revision is checked out.
3406
3406
3407 With -v, print file permissions, symlink and executable bits.
3407 With -v, print file permissions, symlink and executable bits.
3408 With --debug, print file revision hashes.
3408 With --debug, print file revision hashes.
3409
3409
3410 If option --all is specified, the list of all files from all revisions
3410 If option --all is specified, the list of all files from all revisions
3411 is printed. This includes deleted and renamed files.
3411 is printed. This includes deleted and renamed files.
3412
3412
3413 Returns 0 on success.
3413 Returns 0 on success.
3414 """
3414 """
3415 if opts.get('all'):
3415 if opts.get('all'):
3416 if rev or node:
3416 if rev or node:
3417 raise util.Abort(_("can't specify a revision with --all"))
3417 raise util.Abort(_("can't specify a revision with --all"))
3418
3418
3419 res = []
3419 res = []
3420 prefix = "data/"
3420 prefix = "data/"
3421 suffix = ".i"
3421 suffix = ".i"
3422 plen = len(prefix)
3422 plen = len(prefix)
3423 slen = len(suffix)
3423 slen = len(suffix)
3424 lock = repo.lock()
3424 lock = repo.lock()
3425 try:
3425 try:
3426 for fn, b, size in repo.store.datafiles():
3426 for fn, b, size in repo.store.datafiles():
3427 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3427 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3428 res.append(fn[plen:-slen])
3428 res.append(fn[plen:-slen])
3429 finally:
3429 finally:
3430 lock.release()
3430 lock.release()
3431 for f in sorted(res):
3431 for f in sorted(res):
3432 ui.write("%s\n" % f)
3432 ui.write("%s\n" % f)
3433 return
3433 return
3434
3434
3435 if rev and node:
3435 if rev and node:
3436 raise util.Abort(_("please specify just one revision"))
3436 raise util.Abort(_("please specify just one revision"))
3437
3437
3438 if not node:
3438 if not node:
3439 node = rev
3439 node = rev
3440
3440
3441 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3441 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3442 ctx = scmutil.revsingle(repo, node)
3442 ctx = scmutil.revsingle(repo, node)
3443 for f in ctx:
3443 for f in ctx:
3444 if ui.debugflag:
3444 if ui.debugflag:
3445 ui.write("%40s " % hex(ctx.manifest()[f]))
3445 ui.write("%40s " % hex(ctx.manifest()[f]))
3446 if ui.verbose:
3446 if ui.verbose:
3447 ui.write(decor[ctx.flags(f)])
3447 ui.write(decor[ctx.flags(f)])
3448 ui.write("%s\n" % f)
3448 ui.write("%s\n" % f)
3449
3449
3450 @command('^merge',
3450 @command('^merge',
3451 [('f', 'force', None, _('force a merge with outstanding changes')),
3451 [('f', 'force', None, _('force a merge with outstanding changes')),
3452 ('t', 'tool', '', _('specify merge tool')),
3452 ('t', 'tool', '', _('specify merge tool')),
3453 ('r', 'rev', '', _('revision to merge'), _('REV')),
3453 ('r', 'rev', '', _('revision to merge'), _('REV')),
3454 ('P', 'preview', None,
3454 ('P', 'preview', None,
3455 _('review revisions to merge (no merge is performed)'))],
3455 _('review revisions to merge (no merge is performed)'))],
3456 _('[-P] [-f] [[-r] REV]'))
3456 _('[-P] [-f] [[-r] REV]'))
3457 def merge(ui, repo, node=None, **opts):
3457 def merge(ui, repo, node=None, **opts):
3458 """merge working directory with another revision
3458 """merge working directory with another revision
3459
3459
3460 The current working directory is updated with all changes made in
3460 The current working directory is updated with all changes made in
3461 the requested revision since the last common predecessor revision.
3461 the requested revision since the last common predecessor revision.
3462
3462
3463 Files that changed between either parent are marked as changed for
3463 Files that changed between either parent are marked as changed for
3464 the next commit and a commit must be performed before any further
3464 the next commit and a commit must be performed before any further
3465 updates to the repository are allowed. The next commit will have
3465 updates to the repository are allowed. The next commit will have
3466 two parents.
3466 two parents.
3467
3467
3468 ``--tool`` can be used to specify the merge tool used for file
3468 ``--tool`` can be used to specify the merge tool used for file
3469 merges. It overrides the HGMERGE environment variable and your
3469 merges. It overrides the HGMERGE environment variable and your
3470 configuration files. See :hg:`help merge-tools` for options.
3470 configuration files. See :hg:`help merge-tools` for options.
3471
3471
3472 If no revision is specified, the working directory's parent is a
3472 If no revision is specified, the working directory's parent is a
3473 head revision, and the current branch contains exactly one other
3473 head revision, and the current branch contains exactly one other
3474 head, the other head is merged with by default. Otherwise, an
3474 head, the other head is merged with by default. Otherwise, an
3475 explicit revision with which to merge with must be provided.
3475 explicit revision with which to merge with must be provided.
3476
3476
3477 :hg:`resolve` must be used to resolve unresolved files.
3477 :hg:`resolve` must be used to resolve unresolved files.
3478
3478
3479 To undo an uncommitted merge, use :hg:`update --clean .` which
3479 To undo an uncommitted merge, use :hg:`update --clean .` which
3480 will check out a clean copy of the original merge parent, losing
3480 will check out a clean copy of the original merge parent, losing
3481 all changes.
3481 all changes.
3482
3482
3483 Returns 0 on success, 1 if there are unresolved files.
3483 Returns 0 on success, 1 if there are unresolved files.
3484 """
3484 """
3485
3485
3486 if opts.get('rev') and node:
3486 if opts.get('rev') and node:
3487 raise util.Abort(_("please specify just one revision"))
3487 raise util.Abort(_("please specify just one revision"))
3488 if not node:
3488 if not node:
3489 node = opts.get('rev')
3489 node = opts.get('rev')
3490
3490
3491 if not node:
3491 if not node:
3492 branch = repo[None].branch()
3492 branch = repo[None].branch()
3493 bheads = repo.branchheads(branch)
3493 bheads = repo.branchheads(branch)
3494 if len(bheads) > 2:
3494 if len(bheads) > 2:
3495 raise util.Abort(_("branch '%s' has %d heads - "
3495 raise util.Abort(_("branch '%s' has %d heads - "
3496 "please merge with an explicit rev")
3496 "please merge with an explicit rev")
3497 % (branch, len(bheads)),
3497 % (branch, len(bheads)),
3498 hint=_("run 'hg heads .' to see heads"))
3498 hint=_("run 'hg heads .' to see heads"))
3499
3499
3500 parent = repo.dirstate.p1()
3500 parent = repo.dirstate.p1()
3501 if len(bheads) == 1:
3501 if len(bheads) == 1:
3502 if len(repo.heads()) > 1:
3502 if len(repo.heads()) > 1:
3503 raise util.Abort(_("branch '%s' has one head - "
3503 raise util.Abort(_("branch '%s' has one head - "
3504 "please merge with an explicit rev")
3504 "please merge with an explicit rev")
3505 % branch,
3505 % branch,
3506 hint=_("run 'hg heads' to see all heads"))
3506 hint=_("run 'hg heads' to see all heads"))
3507 msg = _('there is nothing to merge')
3507 msg = _('there is nothing to merge')
3508 if parent != repo.lookup(repo[None].branch()):
3508 if parent != repo.lookup(repo[None].branch()):
3509 msg = _('%s - use "hg update" instead') % msg
3509 msg = _('%s - use "hg update" instead') % msg
3510 raise util.Abort(msg)
3510 raise util.Abort(msg)
3511
3511
3512 if parent not in bheads:
3512 if parent not in bheads:
3513 raise util.Abort(_('working directory not at a head revision'),
3513 raise util.Abort(_('working directory not at a head revision'),
3514 hint=_("use 'hg update' or merge with an "
3514 hint=_("use 'hg update' or merge with an "
3515 "explicit revision"))
3515 "explicit revision"))
3516 node = parent == bheads[0] and bheads[-1] or bheads[0]
3516 node = parent == bheads[0] and bheads[-1] or bheads[0]
3517 else:
3517 else:
3518 node = scmutil.revsingle(repo, node).node()
3518 node = scmutil.revsingle(repo, node).node()
3519
3519
3520 if opts.get('preview'):
3520 if opts.get('preview'):
3521 # find nodes that are ancestors of p2 but not of p1
3521 # find nodes that are ancestors of p2 but not of p1
3522 p1 = repo.lookup('.')
3522 p1 = repo.lookup('.')
3523 p2 = repo.lookup(node)
3523 p2 = repo.lookup(node)
3524 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3524 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3525
3525
3526 displayer = cmdutil.show_changeset(ui, repo, opts)
3526 displayer = cmdutil.show_changeset(ui, repo, opts)
3527 for node in nodes:
3527 for node in nodes:
3528 displayer.show(repo[node])
3528 displayer.show(repo[node])
3529 displayer.close()
3529 displayer.close()
3530 return 0
3530 return 0
3531
3531
3532 try:
3532 try:
3533 # ui.forcemerge is an internal variable, do not document
3533 # ui.forcemerge is an internal variable, do not document
3534 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3534 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3535 return hg.merge(repo, node, force=opts.get('force'))
3535 return hg.merge(repo, node, force=opts.get('force'))
3536 finally:
3536 finally:
3537 ui.setconfig('ui', 'forcemerge', '')
3537 ui.setconfig('ui', 'forcemerge', '')
3538
3538
3539 @command('outgoing|out',
3539 @command('outgoing|out',
3540 [('f', 'force', None, _('run even when the destination is unrelated')),
3540 [('f', 'force', None, _('run even when the destination is unrelated')),
3541 ('r', 'rev', [],
3541 ('r', 'rev', [],
3542 _('a changeset intended to be included in the destination'), _('REV')),
3542 _('a changeset intended to be included in the destination'), _('REV')),
3543 ('n', 'newest-first', None, _('show newest record first')),
3543 ('n', 'newest-first', None, _('show newest record first')),
3544 ('B', 'bookmarks', False, _('compare bookmarks')),
3544 ('B', 'bookmarks', False, _('compare bookmarks')),
3545 ('b', 'branch', [], _('a specific branch you would like to push'),
3545 ('b', 'branch', [], _('a specific branch you would like to push'),
3546 _('BRANCH')),
3546 _('BRANCH')),
3547 ] + logopts + remoteopts + subrepoopts,
3547 ] + logopts + remoteopts + subrepoopts,
3548 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3548 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3549 def outgoing(ui, repo, dest=None, **opts):
3549 def outgoing(ui, repo, dest=None, **opts):
3550 """show changesets not found in the destination
3550 """show changesets not found in the destination
3551
3551
3552 Show changesets not found in the specified destination repository
3552 Show changesets not found in the specified destination repository
3553 or the default push location. These are the changesets that would
3553 or the default push location. These are the changesets that would
3554 be pushed if a push was requested.
3554 be pushed if a push was requested.
3555
3555
3556 See pull for details of valid destination formats.
3556 See pull for details of valid destination formats.
3557
3557
3558 Returns 0 if there are outgoing changes, 1 otherwise.
3558 Returns 0 if there are outgoing changes, 1 otherwise.
3559 """
3559 """
3560
3560
3561 if opts.get('bookmarks'):
3561 if opts.get('bookmarks'):
3562 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3562 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3563 dest, branches = hg.parseurl(dest, opts.get('branch'))
3563 dest, branches = hg.parseurl(dest, opts.get('branch'))
3564 other = hg.peer(repo, opts, dest)
3564 other = hg.peer(repo, opts, dest)
3565 if 'bookmarks' not in other.listkeys('namespaces'):
3565 if 'bookmarks' not in other.listkeys('namespaces'):
3566 ui.warn(_("remote doesn't support bookmarks\n"))
3566 ui.warn(_("remote doesn't support bookmarks\n"))
3567 return 0
3567 return 0
3568 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3568 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3569 return bookmarks.diff(ui, other, repo)
3569 return bookmarks.diff(ui, other, repo)
3570
3570
3571 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3571 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3572 try:
3572 try:
3573 return hg.outgoing(ui, repo, dest, opts)
3573 return hg.outgoing(ui, repo, dest, opts)
3574 finally:
3574 finally:
3575 del repo._subtoppath
3575 del repo._subtoppath
3576
3576
3577 @command('parents',
3577 @command('parents',
3578 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3578 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3579 ] + templateopts,
3579 ] + templateopts,
3580 _('[-r REV] [FILE]'))
3580 _('[-r REV] [FILE]'))
3581 def parents(ui, repo, file_=None, **opts):
3581 def parents(ui, repo, file_=None, **opts):
3582 """show the parents of the working directory or revision
3582 """show the parents of the working directory or revision
3583
3583
3584 Print the working directory's parent revisions. If a revision is
3584 Print the working directory's parent revisions. If a revision is
3585 given via -r/--rev, the parent of that revision will be printed.
3585 given via -r/--rev, the parent of that revision will be printed.
3586 If a file argument is given, the revision in which the file was
3586 If a file argument is given, the revision in which the file was
3587 last changed (before the working directory revision or the
3587 last changed (before the working directory revision or the
3588 argument to --rev if given) is printed.
3588 argument to --rev if given) is printed.
3589
3589
3590 Returns 0 on success.
3590 Returns 0 on success.
3591 """
3591 """
3592
3592
3593 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3593 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3594
3594
3595 if file_:
3595 if file_:
3596 m = scmutil.match(repo, (file_,), opts)
3596 m = scmutil.match(repo, (file_,), opts)
3597 if m.anypats() or len(m.files()) != 1:
3597 if m.anypats() or len(m.files()) != 1:
3598 raise util.Abort(_('can only specify an explicit filename'))
3598 raise util.Abort(_('can only specify an explicit filename'))
3599 file_ = m.files()[0]
3599 file_ = m.files()[0]
3600 filenodes = []
3600 filenodes = []
3601 for cp in ctx.parents():
3601 for cp in ctx.parents():
3602 if not cp:
3602 if not cp:
3603 continue
3603 continue
3604 try:
3604 try:
3605 filenodes.append(cp.filenode(file_))
3605 filenodes.append(cp.filenode(file_))
3606 except error.LookupError:
3606 except error.LookupError:
3607 pass
3607 pass
3608 if not filenodes:
3608 if not filenodes:
3609 raise util.Abort(_("'%s' not found in manifest!") % file_)
3609 raise util.Abort(_("'%s' not found in manifest!") % file_)
3610 fl = repo.file(file_)
3610 fl = repo.file(file_)
3611 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3611 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3612 else:
3612 else:
3613 p = [cp.node() for cp in ctx.parents()]
3613 p = [cp.node() for cp in ctx.parents()]
3614
3614
3615 displayer = cmdutil.show_changeset(ui, repo, opts)
3615 displayer = cmdutil.show_changeset(ui, repo, opts)
3616 for n in p:
3616 for n in p:
3617 if n != nullid:
3617 if n != nullid:
3618 displayer.show(repo[n])
3618 displayer.show(repo[n])
3619 displayer.close()
3619 displayer.close()
3620
3620
3621 @command('paths', [], _('[NAME]'))
3621 @command('paths', [], _('[NAME]'))
3622 def paths(ui, repo, search=None):
3622 def paths(ui, repo, search=None):
3623 """show aliases for remote repositories
3623 """show aliases for remote repositories
3624
3624
3625 Show definition of symbolic path name NAME. If no name is given,
3625 Show definition of symbolic path name NAME. If no name is given,
3626 show definition of all available names.
3626 show definition of all available names.
3627
3627
3628 Option -q/--quiet suppresses all output when searching for NAME
3628 Option -q/--quiet suppresses all output when searching for NAME
3629 and shows only the path names when listing all definitions.
3629 and shows only the path names when listing all definitions.
3630
3630
3631 Path names are defined in the [paths] section of your
3631 Path names are defined in the [paths] section of your
3632 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3632 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3633 repository, ``.hg/hgrc`` is used, too.
3633 repository, ``.hg/hgrc`` is used, too.
3634
3634
3635 The path names ``default`` and ``default-push`` have a special
3635 The path names ``default`` and ``default-push`` have a special
3636 meaning. When performing a push or pull operation, they are used
3636 meaning. When performing a push or pull operation, they are used
3637 as fallbacks if no location is specified on the command-line.
3637 as fallbacks if no location is specified on the command-line.
3638 When ``default-push`` is set, it will be used for push and
3638 When ``default-push`` is set, it will be used for push and
3639 ``default`` will be used for pull; otherwise ``default`` is used
3639 ``default`` will be used for pull; otherwise ``default`` is used
3640 as the fallback for both. When cloning a repository, the clone
3640 as the fallback for both. When cloning a repository, the clone
3641 source is written as ``default`` in ``.hg/hgrc``. Note that
3641 source is written as ``default`` in ``.hg/hgrc``. Note that
3642 ``default`` and ``default-push`` apply to all inbound (e.g.
3642 ``default`` and ``default-push`` apply to all inbound (e.g.
3643 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3643 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3644 :hg:`bundle`) operations.
3644 :hg:`bundle`) operations.
3645
3645
3646 See :hg:`help urls` for more information.
3646 See :hg:`help urls` for more information.
3647
3647
3648 Returns 0 on success.
3648 Returns 0 on success.
3649 """
3649 """
3650 if search:
3650 if search:
3651 for name, path in ui.configitems("paths"):
3651 for name, path in ui.configitems("paths"):
3652 if name == search:
3652 if name == search:
3653 ui.status("%s\n" % util.hidepassword(path))
3653 ui.status("%s\n" % util.hidepassword(path))
3654 return
3654 return
3655 if not ui.quiet:
3655 if not ui.quiet:
3656 ui.warn(_("not found!\n"))
3656 ui.warn(_("not found!\n"))
3657 return 1
3657 return 1
3658 else:
3658 else:
3659 for name, path in ui.configitems("paths"):
3659 for name, path in ui.configitems("paths"):
3660 if ui.quiet:
3660 if ui.quiet:
3661 ui.write("%s\n" % name)
3661 ui.write("%s\n" % name)
3662 else:
3662 else:
3663 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3663 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3664
3664
3665 def postincoming(ui, repo, modheads, optupdate, checkout):
3665 def postincoming(ui, repo, modheads, optupdate, checkout):
3666 if modheads == 0:
3666 if modheads == 0:
3667 return
3667 return
3668 if optupdate:
3668 if optupdate:
3669 try:
3669 try:
3670 return hg.update(repo, checkout)
3670 return hg.update(repo, checkout)
3671 except util.Abort, inst:
3671 except util.Abort, inst:
3672 ui.warn(_("not updating: %s\n" % str(inst)))
3672 ui.warn(_("not updating: %s\n" % str(inst)))
3673 return 0
3673 return 0
3674 if modheads > 1:
3674 if modheads > 1:
3675 currentbranchheads = len(repo.branchheads())
3675 currentbranchheads = len(repo.branchheads())
3676 if currentbranchheads == modheads:
3676 if currentbranchheads == modheads:
3677 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3677 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3678 elif currentbranchheads > 1:
3678 elif currentbranchheads > 1:
3679 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3679 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3680 else:
3680 else:
3681 ui.status(_("(run 'hg heads' to see heads)\n"))
3681 ui.status(_("(run 'hg heads' to see heads)\n"))
3682 else:
3682 else:
3683 ui.status(_("(run 'hg update' to get a working copy)\n"))
3683 ui.status(_("(run 'hg update' to get a working copy)\n"))
3684
3684
3685 @command('^pull',
3685 @command('^pull',
3686 [('u', 'update', None,
3686 [('u', 'update', None,
3687 _('update to new branch head if changesets were pulled')),
3687 _('update to new branch head if changesets were pulled')),
3688 ('f', 'force', None, _('run even when remote repository is unrelated')),
3688 ('f', 'force', None, _('run even when remote repository is unrelated')),
3689 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3689 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3690 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3690 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3691 ('b', 'branch', [], _('a specific branch you would like to pull'),
3691 ('b', 'branch', [], _('a specific branch you would like to pull'),
3692 _('BRANCH')),
3692 _('BRANCH')),
3693 ] + remoteopts,
3693 ] + remoteopts,
3694 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3694 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3695 def pull(ui, repo, source="default", **opts):
3695 def pull(ui, repo, source="default", **opts):
3696 """pull changes from the specified source
3696 """pull changes from the specified source
3697
3697
3698 Pull changes from a remote repository to a local one.
3698 Pull changes from a remote repository to a local one.
3699
3699
3700 This finds all changes from the repository at the specified path
3700 This finds all changes from the repository at the specified path
3701 or URL and adds them to a local repository (the current one unless
3701 or URL and adds them to a local repository (the current one unless
3702 -R is specified). By default, this does not update the copy of the
3702 -R is specified). By default, this does not update the copy of the
3703 project in the working directory.
3703 project in the working directory.
3704
3704
3705 Use :hg:`incoming` if you want to see what would have been added
3705 Use :hg:`incoming` if you want to see what would have been added
3706 by a pull at the time you issued this command. If you then decide
3706 by a pull at the time you issued this command. If you then decide
3707 to add those changes to the repository, you should use :hg:`pull
3707 to add those changes to the repository, you should use :hg:`pull
3708 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3708 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3709
3709
3710 If SOURCE is omitted, the 'default' path will be used.
3710 If SOURCE is omitted, the 'default' path will be used.
3711 See :hg:`help urls` for more information.
3711 See :hg:`help urls` for more information.
3712
3712
3713 Returns 0 on success, 1 if an update had unresolved files.
3713 Returns 0 on success, 1 if an update had unresolved files.
3714 """
3714 """
3715 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3715 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3716 other = hg.peer(repo, opts, source)
3716 other = hg.peer(repo, opts, source)
3717 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3717 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3718 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3718 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3719
3719
3720 if opts.get('bookmark'):
3720 if opts.get('bookmark'):
3721 if not revs:
3721 if not revs:
3722 revs = []
3722 revs = []
3723 rb = other.listkeys('bookmarks')
3723 rb = other.listkeys('bookmarks')
3724 for b in opts['bookmark']:
3724 for b in opts['bookmark']:
3725 if b not in rb:
3725 if b not in rb:
3726 raise util.Abort(_('remote bookmark %s not found!') % b)
3726 raise util.Abort(_('remote bookmark %s not found!') % b)
3727 revs.append(rb[b])
3727 revs.append(rb[b])
3728
3728
3729 if revs:
3729 if revs:
3730 try:
3730 try:
3731 revs = [other.lookup(rev) for rev in revs]
3731 revs = [other.lookup(rev) for rev in revs]
3732 except error.CapabilityError:
3732 except error.CapabilityError:
3733 err = _("other repository doesn't support revision lookup, "
3733 err = _("other repository doesn't support revision lookup, "
3734 "so a rev cannot be specified.")
3734 "so a rev cannot be specified.")
3735 raise util.Abort(err)
3735 raise util.Abort(err)
3736
3736
3737 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3737 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3738 bookmarks.updatefromremote(ui, repo, other)
3738 bookmarks.updatefromremote(ui, repo, other)
3739 if checkout:
3739 if checkout:
3740 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3740 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3741 repo._subtoppath = source
3741 repo._subtoppath = source
3742 try:
3742 try:
3743 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3743 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3744
3744
3745 finally:
3745 finally:
3746 del repo._subtoppath
3746 del repo._subtoppath
3747
3747
3748 # update specified bookmarks
3748 # update specified bookmarks
3749 if opts.get('bookmark'):
3749 if opts.get('bookmark'):
3750 for b in opts['bookmark']:
3750 for b in opts['bookmark']:
3751 # explicit pull overrides local bookmark if any
3751 # explicit pull overrides local bookmark if any
3752 ui.status(_("importing bookmark %s\n") % b)
3752 ui.status(_("importing bookmark %s\n") % b)
3753 repo._bookmarks[b] = repo[rb[b]].node()
3753 repo._bookmarks[b] = repo[rb[b]].node()
3754 bookmarks.write(repo)
3754 bookmarks.write(repo)
3755
3755
3756 return ret
3756 return ret
3757
3757
3758 @command('^push',
3758 @command('^push',
3759 [('f', 'force', None, _('force push')),
3759 [('f', 'force', None, _('force push')),
3760 ('r', 'rev', [],
3760 ('r', 'rev', [],
3761 _('a changeset intended to be included in the destination'),
3761 _('a changeset intended to be included in the destination'),
3762 _('REV')),
3762 _('REV')),
3763 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3763 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3764 ('b', 'branch', [],
3764 ('b', 'branch', [],
3765 _('a specific branch you would like to push'), _('BRANCH')),
3765 _('a specific branch you would like to push'), _('BRANCH')),
3766 ('', 'new-branch', False, _('allow pushing a new branch')),
3766 ('', 'new-branch', False, _('allow pushing a new branch')),
3767 ] + remoteopts,
3767 ] + remoteopts,
3768 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3768 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3769 def push(ui, repo, dest=None, **opts):
3769 def push(ui, repo, dest=None, **opts):
3770 """push changes to the specified destination
3770 """push changes to the specified destination
3771
3771
3772 Push changesets from the local repository to the specified
3772 Push changesets from the local repository to the specified
3773 destination.
3773 destination.
3774
3774
3775 This operation is symmetrical to pull: it is identical to a pull
3775 This operation is symmetrical to pull: it is identical to a pull
3776 in the destination repository from the current one.
3776 in the destination repository from the current one.
3777
3777
3778 By default, push will not allow creation of new heads at the
3778 By default, push will not allow creation of new heads at the
3779 destination, since multiple heads would make it unclear which head
3779 destination, since multiple heads would make it unclear which head
3780 to use. In this situation, it is recommended to pull and merge
3780 to use. In this situation, it is recommended to pull and merge
3781 before pushing.
3781 before pushing.
3782
3782
3783 Use --new-branch if you want to allow push to create a new named
3783 Use --new-branch if you want to allow push to create a new named
3784 branch that is not present at the destination. This allows you to
3784 branch that is not present at the destination. This allows you to
3785 only create a new branch without forcing other changes.
3785 only create a new branch without forcing other changes.
3786
3786
3787 Use -f/--force to override the default behavior and push all
3787 Use -f/--force to override the default behavior and push all
3788 changesets on all branches.
3788 changesets on all branches.
3789
3789
3790 If -r/--rev is used, the specified revision and all its ancestors
3790 If -r/--rev is used, the specified revision and all its ancestors
3791 will be pushed to the remote repository.
3791 will be pushed to the remote repository.
3792
3792
3793 Please see :hg:`help urls` for important details about ``ssh://``
3793 Please see :hg:`help urls` for important details about ``ssh://``
3794 URLs. If DESTINATION is omitted, a default path will be used.
3794 URLs. If DESTINATION is omitted, a default path will be used.
3795
3795
3796 Returns 0 if push was successful, 1 if nothing to push.
3796 Returns 0 if push was successful, 1 if nothing to push.
3797 """
3797 """
3798
3798
3799 if opts.get('bookmark'):
3799 if opts.get('bookmark'):
3800 for b in opts['bookmark']:
3800 for b in opts['bookmark']:
3801 # translate -B options to -r so changesets get pushed
3801 # translate -B options to -r so changesets get pushed
3802 if b in repo._bookmarks:
3802 if b in repo._bookmarks:
3803 opts.setdefault('rev', []).append(b)
3803 opts.setdefault('rev', []).append(b)
3804 else:
3804 else:
3805 # if we try to push a deleted bookmark, translate it to null
3805 # if we try to push a deleted bookmark, translate it to null
3806 # this lets simultaneous -r, -b options continue working
3806 # this lets simultaneous -r, -b options continue working
3807 opts.setdefault('rev', []).append("null")
3807 opts.setdefault('rev', []).append("null")
3808
3808
3809 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3809 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3810 dest, branches = hg.parseurl(dest, opts.get('branch'))
3810 dest, branches = hg.parseurl(dest, opts.get('branch'))
3811 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3811 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3812 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3812 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3813 other = hg.peer(repo, opts, dest)
3813 other = hg.peer(repo, opts, dest)
3814 if revs:
3814 if revs:
3815 revs = [repo.lookup(rev) for rev in revs]
3815 revs = [repo.lookup(rev) for rev in revs]
3816
3816
3817 repo._subtoppath = dest
3817 repo._subtoppath = dest
3818 try:
3818 try:
3819 # push subrepos depth-first for coherent ordering
3819 # push subrepos depth-first for coherent ordering
3820 c = repo['']
3820 c = repo['']
3821 subs = c.substate # only repos that are committed
3821 subs = c.substate # only repos that are committed
3822 for s in sorted(subs):
3822 for s in sorted(subs):
3823 if not c.sub(s).push(opts.get('force')):
3823 if not c.sub(s).push(opts.get('force')):
3824 return False
3824 return False
3825 finally:
3825 finally:
3826 del repo._subtoppath
3826 del repo._subtoppath
3827 result = repo.push(other, opts.get('force'), revs=revs,
3827 result = repo.push(other, opts.get('force'), revs=revs,
3828 newbranch=opts.get('new_branch'))
3828 newbranch=opts.get('new_branch'))
3829
3829
3830 result = (result == 0)
3830 result = (result == 0)
3831
3831
3832 if opts.get('bookmark'):
3832 if opts.get('bookmark'):
3833 rb = other.listkeys('bookmarks')
3833 rb = other.listkeys('bookmarks')
3834 for b in opts['bookmark']:
3834 for b in opts['bookmark']:
3835 # explicit push overrides remote bookmark if any
3835 # explicit push overrides remote bookmark if any
3836 if b in repo._bookmarks:
3836 if b in repo._bookmarks:
3837 ui.status(_("exporting bookmark %s\n") % b)
3837 ui.status(_("exporting bookmark %s\n") % b)
3838 new = repo[b].hex()
3838 new = repo[b].hex()
3839 elif b in rb:
3839 elif b in rb:
3840 ui.status(_("deleting remote bookmark %s\n") % b)
3840 ui.status(_("deleting remote bookmark %s\n") % b)
3841 new = '' # delete
3841 new = '' # delete
3842 else:
3842 else:
3843 ui.warn(_('bookmark %s does not exist on the local '
3843 ui.warn(_('bookmark %s does not exist on the local '
3844 'or remote repository!\n') % b)
3844 'or remote repository!\n') % b)
3845 return 2
3845 return 2
3846 old = rb.get(b, '')
3846 old = rb.get(b, '')
3847 r = other.pushkey('bookmarks', b, old, new)
3847 r = other.pushkey('bookmarks', b, old, new)
3848 if not r:
3848 if not r:
3849 ui.warn(_('updating bookmark %s failed!\n') % b)
3849 ui.warn(_('updating bookmark %s failed!\n') % b)
3850 if not result:
3850 if not result:
3851 result = 2
3851 result = 2
3852
3852
3853 return result
3853 return result
3854
3854
3855 @command('recover', [])
3855 @command('recover', [])
3856 def recover(ui, repo):
3856 def recover(ui, repo):
3857 """roll back an interrupted transaction
3857 """roll back an interrupted transaction
3858
3858
3859 Recover from an interrupted commit or pull.
3859 Recover from an interrupted commit or pull.
3860
3860
3861 This command tries to fix the repository status after an
3861 This command tries to fix the repository status after an
3862 interrupted operation. It should only be necessary when Mercurial
3862 interrupted operation. It should only be necessary when Mercurial
3863 suggests it.
3863 suggests it.
3864
3864
3865 Returns 0 if successful, 1 if nothing to recover or verify fails.
3865 Returns 0 if successful, 1 if nothing to recover or verify fails.
3866 """
3866 """
3867 if repo.recover():
3867 if repo.recover():
3868 return hg.verify(repo)
3868 return hg.verify(repo)
3869 return 1
3869 return 1
3870
3870
3871 @command('^remove|rm',
3871 @command('^remove|rm',
3872 [('A', 'after', None, _('record delete for missing files')),
3872 [('A', 'after', None, _('record delete for missing files')),
3873 ('f', 'force', None,
3873 ('f', 'force', None,
3874 _('remove (and delete) file even if added or modified')),
3874 _('remove (and delete) file even if added or modified')),
3875 ] + walkopts,
3875 ] + walkopts,
3876 _('[OPTION]... FILE...'))
3876 _('[OPTION]... FILE...'))
3877 def remove(ui, repo, *pats, **opts):
3877 def remove(ui, repo, *pats, **opts):
3878 """remove the specified files on the next commit
3878 """remove the specified files on the next commit
3879
3879
3880 Schedule the indicated files for removal from the repository.
3880 Schedule the indicated files for removal from the repository.
3881
3881
3882 This only removes files from the current branch, not from the
3882 This only removes files from the current branch, not from the
3883 entire project history. -A/--after can be used to remove only
3883 entire project history. -A/--after can be used to remove only
3884 files that have already been deleted, -f/--force can be used to
3884 files that have already been deleted, -f/--force can be used to
3885 force deletion, and -Af can be used to remove files from the next
3885 force deletion, and -Af can be used to remove files from the next
3886 revision without deleting them from the working directory.
3886 revision without deleting them from the working directory.
3887
3887
3888 The following table details the behavior of remove for different
3888 The following table details the behavior of remove for different
3889 file states (columns) and option combinations (rows). The file
3889 file states (columns) and option combinations (rows). The file
3890 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3890 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3891 reported by :hg:`status`). The actions are Warn, Remove (from
3891 reported by :hg:`status`). The actions are Warn, Remove (from
3892 branch) and Delete (from disk)::
3892 branch) and Delete (from disk)::
3893
3893
3894 A C M !
3894 A C M !
3895 none W RD W R
3895 none W RD W R
3896 -f R RD RD R
3896 -f R RD RD R
3897 -A W W W R
3897 -A W W W R
3898 -Af R R R R
3898 -Af R R R R
3899
3899
3900 Note that remove never deletes files in Added [A] state from the
3900 Note that remove never deletes files in Added [A] state from the
3901 working directory, not even if option --force is specified.
3901 working directory, not even if option --force is specified.
3902
3902
3903 This command schedules the files to be removed at the next commit.
3903 This command schedules the files to be removed at the next commit.
3904 To undo a remove before that, see :hg:`revert`.
3904 To undo a remove before that, see :hg:`revert`.
3905
3905
3906 Returns 0 on success, 1 if any warnings encountered.
3906 Returns 0 on success, 1 if any warnings encountered.
3907 """
3907 """
3908
3908
3909 ret = 0
3909 ret = 0
3910 after, force = opts.get('after'), opts.get('force')
3910 after, force = opts.get('after'), opts.get('force')
3911 if not pats and not after:
3911 if not pats and not after:
3912 raise util.Abort(_('no files specified'))
3912 raise util.Abort(_('no files specified'))
3913
3913
3914 m = scmutil.match(repo, pats, opts)
3914 m = scmutil.match(repo, pats, opts)
3915 s = repo.status(match=m, clean=True)
3915 s = repo.status(match=m, clean=True)
3916 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3916 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3917
3917
3918 for f in m.files():
3918 for f in m.files():
3919 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3919 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3920 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3920 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3921 ret = 1
3921 ret = 1
3922
3922
3923 if force:
3923 if force:
3924 list = modified + deleted + clean + added
3924 list = modified + deleted + clean + added
3925 elif after:
3925 elif after:
3926 list = deleted
3926 list = deleted
3927 for f in modified + added + clean:
3927 for f in modified + added + clean:
3928 ui.warn(_('not removing %s: file still exists (use -f'
3928 ui.warn(_('not removing %s: file still exists (use -f'
3929 ' to force removal)\n') % m.rel(f))
3929 ' to force removal)\n') % m.rel(f))
3930 ret = 1
3930 ret = 1
3931 else:
3931 else:
3932 list = deleted + clean
3932 list = deleted + clean
3933 for f in modified:
3933 for f in modified:
3934 ui.warn(_('not removing %s: file is modified (use -f'
3934 ui.warn(_('not removing %s: file is modified (use -f'
3935 ' to force removal)\n') % m.rel(f))
3935 ' to force removal)\n') % m.rel(f))
3936 ret = 1
3936 ret = 1
3937 for f in added:
3937 for f in added:
3938 ui.warn(_('not removing %s: file has been marked for add (use -f'
3938 ui.warn(_('not removing %s: file has been marked for add (use -f'
3939 ' to force removal)\n') % m.rel(f))
3939 ' to force removal)\n') % m.rel(f))
3940 ret = 1
3940 ret = 1
3941
3941
3942 for f in sorted(list):
3942 for f in sorted(list):
3943 if ui.verbose or not m.exact(f):
3943 if ui.verbose or not m.exact(f):
3944 ui.status(_('removing %s\n') % m.rel(f))
3944 ui.status(_('removing %s\n') % m.rel(f))
3945
3945
3946 wlock = repo.wlock()
3946 wlock = repo.wlock()
3947 try:
3947 try:
3948 if not after:
3948 if not after:
3949 for f in list:
3949 for f in list:
3950 if f in added:
3950 if f in added:
3951 continue # we never unlink added files on remove
3951 continue # we never unlink added files on remove
3952 try:
3952 try:
3953 util.unlinkpath(repo.wjoin(f))
3953 util.unlinkpath(repo.wjoin(f))
3954 except OSError, inst:
3954 except OSError, inst:
3955 if inst.errno != errno.ENOENT:
3955 if inst.errno != errno.ENOENT:
3956 raise
3956 raise
3957 repo[None].forget(list)
3957 repo[None].forget(list)
3958 finally:
3958 finally:
3959 wlock.release()
3959 wlock.release()
3960
3960
3961 return ret
3961 return ret
3962
3962
3963 @command('rename|move|mv',
3963 @command('rename|move|mv',
3964 [('A', 'after', None, _('record a rename that has already occurred')),
3964 [('A', 'after', None, _('record a rename that has already occurred')),
3965 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3965 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3966 ] + walkopts + dryrunopts,
3966 ] + walkopts + dryrunopts,
3967 _('[OPTION]... SOURCE... DEST'))
3967 _('[OPTION]... SOURCE... DEST'))
3968 def rename(ui, repo, *pats, **opts):
3968 def rename(ui, repo, *pats, **opts):
3969 """rename files; equivalent of copy + remove
3969 """rename files; equivalent of copy + remove
3970
3970
3971 Mark dest as copies of sources; mark sources for deletion. If dest
3971 Mark dest as copies of sources; mark sources for deletion. If dest
3972 is a directory, copies are put in that directory. If dest is a
3972 is a directory, copies are put in that directory. If dest is a
3973 file, there can only be one source.
3973 file, there can only be one source.
3974
3974
3975 By default, this command copies the contents of files as they
3975 By default, this command copies the contents of files as they
3976 exist in the working directory. If invoked with -A/--after, the
3976 exist in the working directory. If invoked with -A/--after, the
3977 operation is recorded, but no copying is performed.
3977 operation is recorded, but no copying is performed.
3978
3978
3979 This command takes effect at the next commit. To undo a rename
3979 This command takes effect at the next commit. To undo a rename
3980 before that, see :hg:`revert`.
3980 before that, see :hg:`revert`.
3981
3981
3982 Returns 0 on success, 1 if errors are encountered.
3982 Returns 0 on success, 1 if errors are encountered.
3983 """
3983 """
3984 wlock = repo.wlock(False)
3984 wlock = repo.wlock(False)
3985 try:
3985 try:
3986 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3986 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3987 finally:
3987 finally:
3988 wlock.release()
3988 wlock.release()
3989
3989
3990 @command('resolve',
3990 @command('resolve',
3991 [('a', 'all', None, _('select all unresolved files')),
3991 [('a', 'all', None, _('select all unresolved files')),
3992 ('l', 'list', None, _('list state of files needing merge')),
3992 ('l', 'list', None, _('list state of files needing merge')),
3993 ('m', 'mark', None, _('mark files as resolved')),
3993 ('m', 'mark', None, _('mark files as resolved')),
3994 ('u', 'unmark', None, _('mark files as unresolved')),
3994 ('u', 'unmark', None, _('mark files as unresolved')),
3995 ('t', 'tool', '', _('specify merge tool')),
3995 ('t', 'tool', '', _('specify merge tool')),
3996 ('n', 'no-status', None, _('hide status prefix'))]
3996 ('n', 'no-status', None, _('hide status prefix'))]
3997 + walkopts,
3997 + walkopts,
3998 _('[OPTION]... [FILE]...'))
3998 _('[OPTION]... [FILE]...'))
3999 def resolve(ui, repo, *pats, **opts):
3999 def resolve(ui, repo, *pats, **opts):
4000 """redo merges or set/view the merge status of files
4000 """redo merges or set/view the merge status of files
4001
4001
4002 Merges with unresolved conflicts are often the result of
4002 Merges with unresolved conflicts are often the result of
4003 non-interactive merging using the ``internal:merge`` configuration
4003 non-interactive merging using the ``internal:merge`` configuration
4004 setting, or a command-line merge tool like ``diff3``. The resolve
4004 setting, or a command-line merge tool like ``diff3``. The resolve
4005 command is used to manage the files involved in a merge, after
4005 command is used to manage the files involved in a merge, after
4006 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4006 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4007 working directory must have two parents).
4007 working directory must have two parents).
4008
4008
4009 The resolve command can be used in the following ways:
4009 The resolve command can be used in the following ways:
4010
4010
4011 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4011 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4012 files, discarding any previous merge attempts. Re-merging is not
4012 files, discarding any previous merge attempts. Re-merging is not
4013 performed for files already marked as resolved. Use ``--all/-a``
4013 performed for files already marked as resolved. Use ``--all/-a``
4014 to selects all unresolved files. ``--tool`` can be used to specify
4014 to selects all unresolved files. ``--tool`` can be used to specify
4015 the merge tool used for the given files. It overrides the HGMERGE
4015 the merge tool used for the given files. It overrides the HGMERGE
4016 environment variable and your configuration files.
4016 environment variable and your configuration files.
4017
4017
4018 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4018 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4019 (e.g. after having manually fixed-up the files). The default is
4019 (e.g. after having manually fixed-up the files). The default is
4020 to mark all unresolved files.
4020 to mark all unresolved files.
4021
4021
4022 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4022 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4023 default is to mark all resolved files.
4023 default is to mark all resolved files.
4024
4024
4025 - :hg:`resolve -l`: list files which had or still have conflicts.
4025 - :hg:`resolve -l`: list files which had or still have conflicts.
4026 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4026 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4027
4027
4028 Note that Mercurial will not let you commit files with unresolved
4028 Note that Mercurial will not let you commit files with unresolved
4029 merge conflicts. You must use :hg:`resolve -m ...` before you can
4029 merge conflicts. You must use :hg:`resolve -m ...` before you can
4030 commit after a conflicting merge.
4030 commit after a conflicting merge.
4031
4031
4032 Returns 0 on success, 1 if any files fail a resolve attempt.
4032 Returns 0 on success, 1 if any files fail a resolve attempt.
4033 """
4033 """
4034
4034
4035 all, mark, unmark, show, nostatus = \
4035 all, mark, unmark, show, nostatus = \
4036 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4036 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4037
4037
4038 if (show and (mark or unmark)) or (mark and unmark):
4038 if (show and (mark or unmark)) or (mark and unmark):
4039 raise util.Abort(_("too many options specified"))
4039 raise util.Abort(_("too many options specified"))
4040 if pats and all:
4040 if pats and all:
4041 raise util.Abort(_("can't specify --all and patterns"))
4041 raise util.Abort(_("can't specify --all and patterns"))
4042 if not (all or pats or show or mark or unmark):
4042 if not (all or pats or show or mark or unmark):
4043 raise util.Abort(_('no files or directories specified; '
4043 raise util.Abort(_('no files or directories specified; '
4044 'use --all to remerge all files'))
4044 'use --all to remerge all files'))
4045
4045
4046 ms = mergemod.mergestate(repo)
4046 ms = mergemod.mergestate(repo)
4047 m = scmutil.match(repo, pats, opts)
4047 m = scmutil.match(repo, pats, opts)
4048 ret = 0
4048 ret = 0
4049
4049
4050 for f in ms:
4050 for f in ms:
4051 if m(f):
4051 if m(f):
4052 if show:
4052 if show:
4053 if nostatus:
4053 if nostatus:
4054 ui.write("%s\n" % f)
4054 ui.write("%s\n" % f)
4055 else:
4055 else:
4056 ui.write("%s %s\n" % (ms[f].upper(), f),
4056 ui.write("%s %s\n" % (ms[f].upper(), f),
4057 label='resolve.' +
4057 label='resolve.' +
4058 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4058 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4059 elif mark:
4059 elif mark:
4060 ms.mark(f, "r")
4060 ms.mark(f, "r")
4061 elif unmark:
4061 elif unmark:
4062 ms.mark(f, "u")
4062 ms.mark(f, "u")
4063 else:
4063 else:
4064 wctx = repo[None]
4064 wctx = repo[None]
4065 mctx = wctx.parents()[-1]
4065 mctx = wctx.parents()[-1]
4066
4066
4067 # backup pre-resolve (merge uses .orig for its own purposes)
4067 # backup pre-resolve (merge uses .orig for its own purposes)
4068 a = repo.wjoin(f)
4068 a = repo.wjoin(f)
4069 util.copyfile(a, a + ".resolve")
4069 util.copyfile(a, a + ".resolve")
4070
4070
4071 try:
4071 try:
4072 # resolve file
4072 # resolve file
4073 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4073 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4074 if ms.resolve(f, wctx, mctx):
4074 if ms.resolve(f, wctx, mctx):
4075 ret = 1
4075 ret = 1
4076 finally:
4076 finally:
4077 ui.setconfig('ui', 'forcemerge', '')
4077 ui.setconfig('ui', 'forcemerge', '')
4078
4078
4079 # replace filemerge's .orig file with our resolve file
4079 # replace filemerge's .orig file with our resolve file
4080 util.rename(a + ".resolve", a + ".orig")
4080 util.rename(a + ".resolve", a + ".orig")
4081
4081
4082 ms.commit()
4082 ms.commit()
4083 return ret
4083 return ret
4084
4084
4085 @command('revert',
4085 @command('revert',
4086 [('a', 'all', None, _('revert all changes when no arguments given')),
4086 [('a', 'all', None, _('revert all changes when no arguments given')),
4087 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4087 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4088 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4088 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4089 ('', 'no-backup', None, _('do not save backup copies of files')),
4089 ('', 'no-backup', None, _('do not save backup copies of files')),
4090 ] + walkopts + dryrunopts,
4090 ] + walkopts + dryrunopts,
4091 _('[OPTION]... [-r REV] [NAME]...'))
4091 _('[OPTION]... [-r REV] [NAME]...'))
4092 def revert(ui, repo, *pats, **opts):
4092 def revert(ui, repo, *pats, **opts):
4093 """restore files to their checkout state
4093 """restore files to their checkout state
4094
4094
4095 .. note::
4095 .. note::
4096 To check out earlier revisions, you should use :hg:`update REV`.
4096 To check out earlier revisions, you should use :hg:`update REV`.
4097 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4097 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4098
4098
4099 With no revision specified, revert the specified files or directories
4099 With no revision specified, revert the specified files or directories
4100 to the state they had in the first parent of the working directory.
4100 to the state they had in the first parent of the working directory.
4101 This restores the contents of files to an unmodified
4101 This restores the contents of files to an unmodified
4102 state and unschedules adds, removes, copies, and renames.
4102 state and unschedules adds, removes, copies, and renames.
4103
4103
4104 Using the -r/--rev or -d/--date options, revert the given files or
4104 Using the -r/--rev or -d/--date options, revert the given files or
4105 directories to their states as of a specific revision. Because
4105 directories to their states as of a specific revision. Because
4106 revert does not change the working directory parents, this will
4106 revert does not change the working directory parents, this will
4107 cause these files to appear modified. This can be helpful to "back
4107 cause these files to appear modified. This can be helpful to "back
4108 out" some or all of an earlier change. See :hg:`backout` for a
4108 out" some or all of an earlier change. See :hg:`backout` for a
4109 related method.
4109 related method.
4110
4110
4111 Modified files are saved with a .orig suffix before reverting.
4111 Modified files are saved with a .orig suffix before reverting.
4112 To disable these backups, use --no-backup.
4112 To disable these backups, use --no-backup.
4113
4113
4114 See :hg:`help dates` for a list of formats valid for -d/--date.
4114 See :hg:`help dates` for a list of formats valid for -d/--date.
4115
4115
4116 Returns 0 on success.
4116 Returns 0 on success.
4117 """
4117 """
4118
4118
4119 if opts.get("date"):
4119 if opts.get("date"):
4120 if opts.get("rev"):
4120 if opts.get("rev"):
4121 raise util.Abort(_("you can't specify a revision and a date"))
4121 raise util.Abort(_("you can't specify a revision and a date"))
4122 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4122 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4123
4123
4124 parent, p2 = repo.dirstate.parents()
4124 parent, p2 = repo.dirstate.parents()
4125
4125
4126 if not pats and not opts.get('all'):
4126 if not pats and not opts.get('all'):
4127 raise util.Abort(_('no files or directories specified'),
4127 raise util.Abort(_('no files or directories specified'),
4128 hint=_('use --all to revert all files'))
4128 hint=_('use --all to revert all files'))
4129
4129
4130 ctx = scmutil.revsingle(repo, opts.get('rev'))
4130 ctx = scmutil.revsingle(repo, opts.get('rev'))
4131 node = ctx.node()
4131 node = ctx.node()
4132 mf = ctx.manifest()
4132 mf = ctx.manifest()
4133 if node == parent:
4133 if node == parent:
4134 pmf = mf
4134 pmf = mf
4135 else:
4135 else:
4136 pmf = None
4136 pmf = None
4137
4137
4138 # need all matching names in dirstate and manifest of target rev,
4138 # need all matching names in dirstate and manifest of target rev,
4139 # so have to walk both. do not print errors if files exist in one
4139 # so have to walk both. do not print errors if files exist in one
4140 # but not other.
4140 # but not other.
4141
4141
4142 names = {}
4142 names = {}
4143
4143
4144 wlock = repo.wlock()
4144 wlock = repo.wlock()
4145 try:
4145 try:
4146 # walk dirstate.
4146 # walk dirstate.
4147
4147
4148 m = scmutil.match(repo, pats, opts)
4148 m = scmutil.match(repo, pats, opts)
4149 m.bad = lambda x, y: False
4149 m.bad = lambda x, y: False
4150 for abs in repo.walk(m):
4150 for abs in repo.walk(m):
4151 names[abs] = m.rel(abs), m.exact(abs)
4151 names[abs] = m.rel(abs), m.exact(abs)
4152
4152
4153 # walk target manifest.
4153 # walk target manifest.
4154
4154
4155 def badfn(path, msg):
4155 def badfn(path, msg):
4156 if path in names:
4156 if path in names:
4157 return
4157 return
4158 path_ = path + '/'
4158 path_ = path + '/'
4159 for f in names:
4159 for f in names:
4160 if f.startswith(path_):
4160 if f.startswith(path_):
4161 return
4161 return
4162 ui.warn("%s: %s\n" % (m.rel(path), msg))
4162 ui.warn("%s: %s\n" % (m.rel(path), msg))
4163
4163
4164 m = scmutil.match(repo, pats, opts)
4164 m = scmutil.match(repo, pats, opts)
4165 m.bad = badfn
4165 m.bad = badfn
4166 for abs in repo[node].walk(m):
4166 for abs in repo[node].walk(m):
4167 if abs not in names:
4167 if abs not in names:
4168 names[abs] = m.rel(abs), m.exact(abs)
4168 names[abs] = m.rel(abs), m.exact(abs)
4169
4169
4170 m = scmutil.matchfiles(repo, names)
4170 m = scmutil.matchfiles(repo, names)
4171 changes = repo.status(match=m)[:4]
4171 changes = repo.status(match=m)[:4]
4172 modified, added, removed, deleted = map(set, changes)
4172 modified, added, removed, deleted = map(set, changes)
4173
4173
4174 # if f is a rename, also revert the source
4174 # if f is a rename, also revert the source
4175 cwd = repo.getcwd()
4175 cwd = repo.getcwd()
4176 for f in added:
4176 for f in added:
4177 src = repo.dirstate.copied(f)
4177 src = repo.dirstate.copied(f)
4178 if src and src not in names and repo.dirstate[src] == 'r':
4178 if src and src not in names and repo.dirstate[src] == 'r':
4179 removed.add(src)
4179 removed.add(src)
4180 names[src] = (repo.pathto(src, cwd), True)
4180 names[src] = (repo.pathto(src, cwd), True)
4181
4181
4182 def removeforget(abs):
4182 def removeforget(abs):
4183 if repo.dirstate[abs] == 'a':
4183 if repo.dirstate[abs] == 'a':
4184 return _('forgetting %s\n')
4184 return _('forgetting %s\n')
4185 return _('removing %s\n')
4185 return _('removing %s\n')
4186
4186
4187 revert = ([], _('reverting %s\n'))
4187 revert = ([], _('reverting %s\n'))
4188 add = ([], _('adding %s\n'))
4188 add = ([], _('adding %s\n'))
4189 remove = ([], removeforget)
4189 remove = ([], removeforget)
4190 undelete = ([], _('undeleting %s\n'))
4190 undelete = ([], _('undeleting %s\n'))
4191
4191
4192 disptable = (
4192 disptable = (
4193 # dispatch table:
4193 # dispatch table:
4194 # file state
4194 # file state
4195 # action if in target manifest
4195 # action if in target manifest
4196 # action if not in target manifest
4196 # action if not in target manifest
4197 # make backup if in target manifest
4197 # make backup if in target manifest
4198 # make backup if not in target manifest
4198 # make backup if not in target manifest
4199 (modified, revert, remove, True, True),
4199 (modified, revert, remove, True, True),
4200 (added, revert, remove, True, False),
4200 (added, revert, remove, True, False),
4201 (removed, undelete, None, False, False),
4201 (removed, undelete, None, False, False),
4202 (deleted, revert, remove, False, False),
4202 (deleted, revert, remove, False, False),
4203 )
4203 )
4204
4204
4205 for abs, (rel, exact) in sorted(names.items()):
4205 for abs, (rel, exact) in sorted(names.items()):
4206 mfentry = mf.get(abs)
4206 mfentry = mf.get(abs)
4207 target = repo.wjoin(abs)
4207 target = repo.wjoin(abs)
4208 def handle(xlist, dobackup):
4208 def handle(xlist, dobackup):
4209 xlist[0].append(abs)
4209 xlist[0].append(abs)
4210 if (dobackup and not opts.get('no_backup') and
4210 if (dobackup and not opts.get('no_backup') and
4211 os.path.lexists(target)):
4211 os.path.lexists(target)):
4212 bakname = "%s.orig" % rel
4212 bakname = "%s.orig" % rel
4213 ui.note(_('saving current version of %s as %s\n') %
4213 ui.note(_('saving current version of %s as %s\n') %
4214 (rel, bakname))
4214 (rel, bakname))
4215 if not opts.get('dry_run'):
4215 if not opts.get('dry_run'):
4216 util.rename(target, bakname)
4216 util.rename(target, bakname)
4217 if ui.verbose or not exact:
4217 if ui.verbose or not exact:
4218 msg = xlist[1]
4218 msg = xlist[1]
4219 if not isinstance(msg, basestring):
4219 if not isinstance(msg, basestring):
4220 msg = msg(abs)
4220 msg = msg(abs)
4221 ui.status(msg % rel)
4221 ui.status(msg % rel)
4222 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4222 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4223 if abs not in table:
4223 if abs not in table:
4224 continue
4224 continue
4225 # file has changed in dirstate
4225 # file has changed in dirstate
4226 if mfentry:
4226 if mfentry:
4227 handle(hitlist, backuphit)
4227 handle(hitlist, backuphit)
4228 elif misslist is not None:
4228 elif misslist is not None:
4229 handle(misslist, backupmiss)
4229 handle(misslist, backupmiss)
4230 break
4230 break
4231 else:
4231 else:
4232 if abs not in repo.dirstate:
4232 if abs not in repo.dirstate:
4233 if mfentry:
4233 if mfentry:
4234 handle(add, True)
4234 handle(add, True)
4235 elif exact:
4235 elif exact:
4236 ui.warn(_('file not managed: %s\n') % rel)
4236 ui.warn(_('file not managed: %s\n') % rel)
4237 continue
4237 continue
4238 # file has not changed in dirstate
4238 # file has not changed in dirstate
4239 if node == parent:
4239 if node == parent:
4240 if exact:
4240 if exact:
4241 ui.warn(_('no changes needed to %s\n') % rel)
4241 ui.warn(_('no changes needed to %s\n') % rel)
4242 continue
4242 continue
4243 if pmf is None:
4243 if pmf is None:
4244 # only need parent manifest in this unlikely case,
4244 # only need parent manifest in this unlikely case,
4245 # so do not read by default
4245 # so do not read by default
4246 pmf = repo[parent].manifest()
4246 pmf = repo[parent].manifest()
4247 if abs in pmf:
4247 if abs in pmf:
4248 if mfentry:
4248 if mfentry:
4249 # if version of file is same in parent and target
4249 # if version of file is same in parent and target
4250 # manifests, do nothing
4250 # manifests, do nothing
4251 if (pmf[abs] != mfentry or
4251 if (pmf[abs] != mfentry or
4252 pmf.flags(abs) != mf.flags(abs)):
4252 pmf.flags(abs) != mf.flags(abs)):
4253 handle(revert, False)
4253 handle(revert, False)
4254 else:
4254 else:
4255 handle(remove, False)
4255 handle(remove, False)
4256
4256
4257 if not opts.get('dry_run'):
4257 if not opts.get('dry_run'):
4258 def checkout(f):
4258 def checkout(f):
4259 fc = ctx[f]
4259 fc = ctx[f]
4260 repo.wwrite(f, fc.data(), fc.flags())
4260 repo.wwrite(f, fc.data(), fc.flags())
4261
4261
4262 audit_path = scmutil.pathauditor(repo.root)
4262 audit_path = scmutil.pathauditor(repo.root)
4263 for f in remove[0]:
4263 for f in remove[0]:
4264 if repo.dirstate[f] == 'a':
4264 if repo.dirstate[f] == 'a':
4265 repo.dirstate.drop(f)
4265 repo.dirstate.drop(f)
4266 continue
4266 continue
4267 audit_path(f)
4267 audit_path(f)
4268 try:
4268 try:
4269 util.unlinkpath(repo.wjoin(f))
4269 util.unlinkpath(repo.wjoin(f))
4270 except OSError:
4270 except OSError:
4271 pass
4271 pass
4272 repo.dirstate.remove(f)
4272 repo.dirstate.remove(f)
4273
4273
4274 normal = None
4274 normal = None
4275 if node == parent:
4275 if node == parent:
4276 # We're reverting to our parent. If possible, we'd like status
4276 # We're reverting to our parent. If possible, we'd like status
4277 # to report the file as clean. We have to use normallookup for
4277 # to report the file as clean. We have to use normallookup for
4278 # merges to avoid losing information about merged/dirty files.
4278 # merges to avoid losing information about merged/dirty files.
4279 if p2 != nullid:
4279 if p2 != nullid:
4280 normal = repo.dirstate.normallookup
4280 normal = repo.dirstate.normallookup
4281 else:
4281 else:
4282 normal = repo.dirstate.normal
4282 normal = repo.dirstate.normal
4283 for f in revert[0]:
4283 for f in revert[0]:
4284 checkout(f)
4284 checkout(f)
4285 if normal:
4285 if normal:
4286 normal(f)
4286 normal(f)
4287
4287
4288 for f in add[0]:
4288 for f in add[0]:
4289 checkout(f)
4289 checkout(f)
4290 repo.dirstate.add(f)
4290 repo.dirstate.add(f)
4291
4291
4292 normal = repo.dirstate.normallookup
4292 normal = repo.dirstate.normallookup
4293 if node == parent and p2 == nullid:
4293 if node == parent and p2 == nullid:
4294 normal = repo.dirstate.normal
4294 normal = repo.dirstate.normal
4295 for f in undelete[0]:
4295 for f in undelete[0]:
4296 checkout(f)
4296 checkout(f)
4297 normal(f)
4297 normal(f)
4298
4298
4299 finally:
4299 finally:
4300 wlock.release()
4300 wlock.release()
4301
4301
4302 @command('rollback', dryrunopts)
4302 @command('rollback', dryrunopts)
4303 def rollback(ui, repo, **opts):
4303 def rollback(ui, repo, **opts):
4304 """roll back the last transaction (dangerous)
4304 """roll back the last transaction (dangerous)
4305
4305
4306 This command should be used with care. There is only one level of
4306 This command should be used with care. There is only one level of
4307 rollback, and there is no way to undo a rollback. It will also
4307 rollback, and there is no way to undo a rollback. It will also
4308 restore the dirstate at the time of the last transaction, losing
4308 restore the dirstate at the time of the last transaction, losing
4309 any dirstate changes since that time. This command does not alter
4309 any dirstate changes since that time. This command does not alter
4310 the working directory.
4310 the working directory.
4311
4311
4312 Transactions are used to encapsulate the effects of all commands
4312 Transactions are used to encapsulate the effects of all commands
4313 that create new changesets or propagate existing changesets into a
4313 that create new changesets or propagate existing changesets into a
4314 repository. For example, the following commands are transactional,
4314 repository. For example, the following commands are transactional,
4315 and their effects can be rolled back:
4315 and their effects can be rolled back:
4316
4316
4317 - commit
4317 - commit
4318 - import
4318 - import
4319 - pull
4319 - pull
4320 - push (with this repository as the destination)
4320 - push (with this repository as the destination)
4321 - unbundle
4321 - unbundle
4322
4322
4323 This command is not intended for use on public repositories. Once
4323 This command is not intended for use on public repositories. Once
4324 changes are visible for pull by other users, rolling a transaction
4324 changes are visible for pull by other users, rolling a transaction
4325 back locally is ineffective (someone else may already have pulled
4325 back locally is ineffective (someone else may already have pulled
4326 the changes). Furthermore, a race is possible with readers of the
4326 the changes). Furthermore, a race is possible with readers of the
4327 repository; for example an in-progress pull from the repository
4327 repository; for example an in-progress pull from the repository
4328 may fail if a rollback is performed.
4328 may fail if a rollback is performed.
4329
4329
4330 Returns 0 on success, 1 if no rollback data is available.
4330 Returns 0 on success, 1 if no rollback data is available.
4331 """
4331 """
4332 return repo.rollback(opts.get('dry_run'))
4332 return repo.rollback(opts.get('dry_run'))
4333
4333
4334 @command('root', [])
4334 @command('root', [])
4335 def root(ui, repo):
4335 def root(ui, repo):
4336 """print the root (top) of the current working directory
4336 """print the root (top) of the current working directory
4337
4337
4338 Print the root directory of the current repository.
4338 Print the root directory of the current repository.
4339
4339
4340 Returns 0 on success.
4340 Returns 0 on success.
4341 """
4341 """
4342 ui.write(repo.root + "\n")
4342 ui.write(repo.root + "\n")
4343
4343
4344 @command('^serve',
4344 @command('^serve',
4345 [('A', 'accesslog', '', _('name of access log file to write to'),
4345 [('A', 'accesslog', '', _('name of access log file to write to'),
4346 _('FILE')),
4346 _('FILE')),
4347 ('d', 'daemon', None, _('run server in background')),
4347 ('d', 'daemon', None, _('run server in background')),
4348 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4348 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4349 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4349 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4350 # use string type, then we can check if something was passed
4350 # use string type, then we can check if something was passed
4351 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4351 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4352 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4352 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4353 _('ADDR')),
4353 _('ADDR')),
4354 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4354 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4355 _('PREFIX')),
4355 _('PREFIX')),
4356 ('n', 'name', '',
4356 ('n', 'name', '',
4357 _('name to show in web pages (default: working directory)'), _('NAME')),
4357 _('name to show in web pages (default: working directory)'), _('NAME')),
4358 ('', 'web-conf', '',
4358 ('', 'web-conf', '',
4359 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4359 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4360 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4360 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4361 _('FILE')),
4361 _('FILE')),
4362 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4362 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4363 ('', 'stdio', None, _('for remote clients')),
4363 ('', 'stdio', None, _('for remote clients')),
4364 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4364 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4365 ('', 'style', '', _('template style to use'), _('STYLE')),
4365 ('', 'style', '', _('template style to use'), _('STYLE')),
4366 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4366 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4367 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4367 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4368 _('[OPTION]...'))
4368 _('[OPTION]...'))
4369 def serve(ui, repo, **opts):
4369 def serve(ui, repo, **opts):
4370 """start stand-alone webserver
4370 """start stand-alone webserver
4371
4371
4372 Start a local HTTP repository browser and pull server. You can use
4372 Start a local HTTP repository browser and pull server. You can use
4373 this for ad-hoc sharing and browsing of repositories. It is
4373 this for ad-hoc sharing and browsing of repositories. It is
4374 recommended to use a real web server to serve a repository for
4374 recommended to use a real web server to serve a repository for
4375 longer periods of time.
4375 longer periods of time.
4376
4376
4377 Please note that the server does not implement access control.
4377 Please note that the server does not implement access control.
4378 This means that, by default, anybody can read from the server and
4378 This means that, by default, anybody can read from the server and
4379 nobody can write to it by default. Set the ``web.allow_push``
4379 nobody can write to it by default. Set the ``web.allow_push``
4380 option to ``*`` to allow everybody to push to the server. You
4380 option to ``*`` to allow everybody to push to the server. You
4381 should use a real web server if you need to authenticate users.
4381 should use a real web server if you need to authenticate users.
4382
4382
4383 By default, the server logs accesses to stdout and errors to
4383 By default, the server logs accesses to stdout and errors to
4384 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4384 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4385 files.
4385 files.
4386
4386
4387 To have the server choose a free port number to listen on, specify
4387 To have the server choose a free port number to listen on, specify
4388 a port number of 0; in this case, the server will print the port
4388 a port number of 0; in this case, the server will print the port
4389 number it uses.
4389 number it uses.
4390
4390
4391 Returns 0 on success.
4391 Returns 0 on success.
4392 """
4392 """
4393
4393
4394 if opts["stdio"]:
4394 if opts["stdio"]:
4395 if repo is None:
4395 if repo is None:
4396 raise error.RepoError(_("There is no Mercurial repository here"
4396 raise error.RepoError(_("There is no Mercurial repository here"
4397 " (.hg not found)"))
4397 " (.hg not found)"))
4398 s = sshserver.sshserver(ui, repo)
4398 s = sshserver.sshserver(ui, repo)
4399 s.serve_forever()
4399 s.serve_forever()
4400
4400
4401 # this way we can check if something was given in the command-line
4401 # this way we can check if something was given in the command-line
4402 if opts.get('port'):
4402 if opts.get('port'):
4403 opts['port'] = util.getport(opts.get('port'))
4403 opts['port'] = util.getport(opts.get('port'))
4404
4404
4405 baseui = repo and repo.baseui or ui
4405 baseui = repo and repo.baseui or ui
4406 optlist = ("name templates style address port prefix ipv6"
4406 optlist = ("name templates style address port prefix ipv6"
4407 " accesslog errorlog certificate encoding")
4407 " accesslog errorlog certificate encoding")
4408 for o in optlist.split():
4408 for o in optlist.split():
4409 val = opts.get(o, '')
4409 val = opts.get(o, '')
4410 if val in (None, ''): # should check against default options instead
4410 if val in (None, ''): # should check against default options instead
4411 continue
4411 continue
4412 baseui.setconfig("web", o, val)
4412 baseui.setconfig("web", o, val)
4413 if repo and repo.ui != baseui:
4413 if repo and repo.ui != baseui:
4414 repo.ui.setconfig("web", o, val)
4414 repo.ui.setconfig("web", o, val)
4415
4415
4416 o = opts.get('web_conf') or opts.get('webdir_conf')
4416 o = opts.get('web_conf') or opts.get('webdir_conf')
4417 if not o:
4417 if not o:
4418 if not repo:
4418 if not repo:
4419 raise error.RepoError(_("There is no Mercurial repository"
4419 raise error.RepoError(_("There is no Mercurial repository"
4420 " here (.hg not found)"))
4420 " here (.hg not found)"))
4421 o = repo.root
4421 o = repo.root
4422
4422
4423 app = hgweb.hgweb(o, baseui=ui)
4423 app = hgweb.hgweb(o, baseui=ui)
4424
4424
4425 class service(object):
4425 class service(object):
4426 def init(self):
4426 def init(self):
4427 util.setsignalhandler()
4427 util.setsignalhandler()
4428 self.httpd = hgweb.server.create_server(ui, app)
4428 self.httpd = hgweb.server.create_server(ui, app)
4429
4429
4430 if opts['port'] and not ui.verbose:
4430 if opts['port'] and not ui.verbose:
4431 return
4431 return
4432
4432
4433 if self.httpd.prefix:
4433 if self.httpd.prefix:
4434 prefix = self.httpd.prefix.strip('/') + '/'
4434 prefix = self.httpd.prefix.strip('/') + '/'
4435 else:
4435 else:
4436 prefix = ''
4436 prefix = ''
4437
4437
4438 port = ':%d' % self.httpd.port
4438 port = ':%d' % self.httpd.port
4439 if port == ':80':
4439 if port == ':80':
4440 port = ''
4440 port = ''
4441
4441
4442 bindaddr = self.httpd.addr
4442 bindaddr = self.httpd.addr
4443 if bindaddr == '0.0.0.0':
4443 if bindaddr == '0.0.0.0':
4444 bindaddr = '*'
4444 bindaddr = '*'
4445 elif ':' in bindaddr: # IPv6
4445 elif ':' in bindaddr: # IPv6
4446 bindaddr = '[%s]' % bindaddr
4446 bindaddr = '[%s]' % bindaddr
4447
4447
4448 fqaddr = self.httpd.fqaddr
4448 fqaddr = self.httpd.fqaddr
4449 if ':' in fqaddr:
4449 if ':' in fqaddr:
4450 fqaddr = '[%s]' % fqaddr
4450 fqaddr = '[%s]' % fqaddr
4451 if opts['port']:
4451 if opts['port']:
4452 write = ui.status
4452 write = ui.status
4453 else:
4453 else:
4454 write = ui.write
4454 write = ui.write
4455 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4455 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4456 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4456 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4457
4457
4458 def run(self):
4458 def run(self):
4459 self.httpd.serve_forever()
4459 self.httpd.serve_forever()
4460
4460
4461 service = service()
4461 service = service()
4462
4462
4463 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4463 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4464
4464
4465 @command('showconfig|debugconfig',
4465 @command('showconfig|debugconfig',
4466 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4466 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4467 _('[-u] [NAME]...'))
4467 _('[-u] [NAME]...'))
4468 def showconfig(ui, repo, *values, **opts):
4468 def showconfig(ui, repo, *values, **opts):
4469 """show combined config settings from all hgrc files
4469 """show combined config settings from all hgrc files
4470
4470
4471 With no arguments, print names and values of all config items.
4471 With no arguments, print names and values of all config items.
4472
4472
4473 With one argument of the form section.name, print just the value
4473 With one argument of the form section.name, print just the value
4474 of that config item.
4474 of that config item.
4475
4475
4476 With multiple arguments, print names and values of all config
4476 With multiple arguments, print names and values of all config
4477 items with matching section names.
4477 items with matching section names.
4478
4478
4479 With --debug, the source (filename and line number) is printed
4479 With --debug, the source (filename and line number) is printed
4480 for each config item.
4480 for each config item.
4481
4481
4482 Returns 0 on success.
4482 Returns 0 on success.
4483 """
4483 """
4484
4484
4485 for f in scmutil.rcpath():
4485 for f in scmutil.rcpath():
4486 ui.debug(_('read config from: %s\n') % f)
4486 ui.debug(_('read config from: %s\n') % f)
4487 untrusted = bool(opts.get('untrusted'))
4487 untrusted = bool(opts.get('untrusted'))
4488 if values:
4488 if values:
4489 sections = [v for v in values if '.' not in v]
4489 sections = [v for v in values if '.' not in v]
4490 items = [v for v in values if '.' in v]
4490 items = [v for v in values if '.' in v]
4491 if len(items) > 1 or items and sections:
4491 if len(items) > 1 or items and sections:
4492 raise util.Abort(_('only one config item permitted'))
4492 raise util.Abort(_('only one config item permitted'))
4493 for section, name, value in ui.walkconfig(untrusted=untrusted):
4493 for section, name, value in ui.walkconfig(untrusted=untrusted):
4494 value = str(value).replace('\n', '\\n')
4494 value = str(value).replace('\n', '\\n')
4495 sectname = section + '.' + name
4495 sectname = section + '.' + name
4496 if values:
4496 if values:
4497 for v in values:
4497 for v in values:
4498 if v == section:
4498 if v == section:
4499 ui.debug('%s: ' %
4499 ui.debug('%s: ' %
4500 ui.configsource(section, name, untrusted))
4500 ui.configsource(section, name, untrusted))
4501 ui.write('%s=%s\n' % (sectname, value))
4501 ui.write('%s=%s\n' % (sectname, value))
4502 elif v == sectname:
4502 elif v == sectname:
4503 ui.debug('%s: ' %
4503 ui.debug('%s: ' %
4504 ui.configsource(section, name, untrusted))
4504 ui.configsource(section, name, untrusted))
4505 ui.write(value, '\n')
4505 ui.write(value, '\n')
4506 else:
4506 else:
4507 ui.debug('%s: ' %
4507 ui.debug('%s: ' %
4508 ui.configsource(section, name, untrusted))
4508 ui.configsource(section, name, untrusted))
4509 ui.write('%s=%s\n' % (sectname, value))
4509 ui.write('%s=%s\n' % (sectname, value))
4510
4510
4511 @command('^status|st',
4511 @command('^status|st',
4512 [('A', 'all', None, _('show status of all files')),
4512 [('A', 'all', None, _('show status of all files')),
4513 ('m', 'modified', None, _('show only modified files')),
4513 ('m', 'modified', None, _('show only modified files')),
4514 ('a', 'added', None, _('show only added files')),
4514 ('a', 'added', None, _('show only added files')),
4515 ('r', 'removed', None, _('show only removed files')),
4515 ('r', 'removed', None, _('show only removed files')),
4516 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4516 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4517 ('c', 'clean', None, _('show only files without changes')),
4517 ('c', 'clean', None, _('show only files without changes')),
4518 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4518 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4519 ('i', 'ignored', None, _('show only ignored files')),
4519 ('i', 'ignored', None, _('show only ignored files')),
4520 ('n', 'no-status', None, _('hide status prefix')),
4520 ('n', 'no-status', None, _('hide status prefix')),
4521 ('C', 'copies', None, _('show source of copied files')),
4521 ('C', 'copies', None, _('show source of copied files')),
4522 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4522 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4523 ('', 'rev', [], _('show difference from revision'), _('REV')),
4523 ('', 'rev', [], _('show difference from revision'), _('REV')),
4524 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4524 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4525 ] + walkopts + subrepoopts,
4525 ] + walkopts + subrepoopts,
4526 _('[OPTION]... [FILE]...'))
4526 _('[OPTION]... [FILE]...'))
4527 def status(ui, repo, *pats, **opts):
4527 def status(ui, repo, *pats, **opts):
4528 """show changed files in the working directory
4528 """show changed files in the working directory
4529
4529
4530 Show status of files in the repository. If names are given, only
4530 Show status of files in the repository. If names are given, only
4531 files that match are shown. Files that are clean or ignored or
4531 files that match are shown. Files that are clean or ignored or
4532 the source of a copy/move operation, are not listed unless
4532 the source of a copy/move operation, are not listed unless
4533 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4533 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4534 Unless options described with "show only ..." are given, the
4534 Unless options described with "show only ..." are given, the
4535 options -mardu are used.
4535 options -mardu are used.
4536
4536
4537 Option -q/--quiet hides untracked (unknown and ignored) files
4537 Option -q/--quiet hides untracked (unknown and ignored) files
4538 unless explicitly requested with -u/--unknown or -i/--ignored.
4538 unless explicitly requested with -u/--unknown or -i/--ignored.
4539
4539
4540 .. note::
4540 .. note::
4541 status may appear to disagree with diff if permissions have
4541 status may appear to disagree with diff if permissions have
4542 changed or a merge has occurred. The standard diff format does
4542 changed or a merge has occurred. The standard diff format does
4543 not report permission changes and diff only reports changes
4543 not report permission changes and diff only reports changes
4544 relative to one merge parent.
4544 relative to one merge parent.
4545
4545
4546 If one revision is given, it is used as the base revision.
4546 If one revision is given, it is used as the base revision.
4547 If two revisions are given, the differences between them are
4547 If two revisions are given, the differences between them are
4548 shown. The --change option can also be used as a shortcut to list
4548 shown. The --change option can also be used as a shortcut to list
4549 the changed files of a revision from its first parent.
4549 the changed files of a revision from its first parent.
4550
4550
4551 The codes used to show the status of files are::
4551 The codes used to show the status of files are::
4552
4552
4553 M = modified
4553 M = modified
4554 A = added
4554 A = added
4555 R = removed
4555 R = removed
4556 C = clean
4556 C = clean
4557 ! = missing (deleted by non-hg command, but still tracked)
4557 ! = missing (deleted by non-hg command, but still tracked)
4558 ? = not tracked
4558 ? = not tracked
4559 I = ignored
4559 I = ignored
4560 = origin of the previous file listed as A (added)
4560 = origin of the previous file listed as A (added)
4561
4561
4562 Returns 0 on success.
4562 Returns 0 on success.
4563 """
4563 """
4564
4564
4565 revs = opts.get('rev')
4565 revs = opts.get('rev')
4566 change = opts.get('change')
4566 change = opts.get('change')
4567
4567
4568 if revs and change:
4568 if revs and change:
4569 msg = _('cannot specify --rev and --change at the same time')
4569 msg = _('cannot specify --rev and --change at the same time')
4570 raise util.Abort(msg)
4570 raise util.Abort(msg)
4571 elif change:
4571 elif change:
4572 node2 = repo.lookup(change)
4572 node2 = repo.lookup(change)
4573 node1 = repo[node2].p1().node()
4573 node1 = repo[node2].p1().node()
4574 else:
4574 else:
4575 node1, node2 = scmutil.revpair(repo, revs)
4575 node1, node2 = scmutil.revpair(repo, revs)
4576
4576
4577 cwd = (pats and repo.getcwd()) or ''
4577 cwd = (pats and repo.getcwd()) or ''
4578 end = opts.get('print0') and '\0' or '\n'
4578 end = opts.get('print0') and '\0' or '\n'
4579 copy = {}
4579 copy = {}
4580 states = 'modified added removed deleted unknown ignored clean'.split()
4580 states = 'modified added removed deleted unknown ignored clean'.split()
4581 show = [k for k in states if opts.get(k)]
4581 show = [k for k in states if opts.get(k)]
4582 if opts.get('all'):
4582 if opts.get('all'):
4583 show += ui.quiet and (states[:4] + ['clean']) or states
4583 show += ui.quiet and (states[:4] + ['clean']) or states
4584 if not show:
4584 if not show:
4585 show = ui.quiet and states[:4] or states[:5]
4585 show = ui.quiet and states[:4] or states[:5]
4586
4586
4587 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4587 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4588 'ignored' in show, 'clean' in show, 'unknown' in show,
4588 'ignored' in show, 'clean' in show, 'unknown' in show,
4589 opts.get('subrepos'))
4589 opts.get('subrepos'))
4590 changestates = zip(states, 'MAR!?IC', stat)
4590 changestates = zip(states, 'MAR!?IC', stat)
4591
4591
4592 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4592 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4593 ctxn = repo[nullid]
4593 ctxn = repo[nullid]
4594 ctx1 = repo[node1]
4594 ctx1 = repo[node1]
4595 ctx2 = repo[node2]
4595 ctx2 = repo[node2]
4596 added = stat[1]
4596 added = stat[1]
4597 if node2 is None:
4597 if node2 is None:
4598 added = stat[0] + stat[1] # merged?
4598 added = stat[0] + stat[1] # merged?
4599
4599
4600 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4600 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4601 if k in added:
4601 if k in added:
4602 copy[k] = v
4602 copy[k] = v
4603 elif v in added:
4603 elif v in added:
4604 copy[v] = k
4604 copy[v] = k
4605
4605
4606 for state, char, files in changestates:
4606 for state, char, files in changestates:
4607 if state in show:
4607 if state in show:
4608 format = "%s %%s%s" % (char, end)
4608 format = "%s %%s%s" % (char, end)
4609 if opts.get('no_status'):
4609 if opts.get('no_status'):
4610 format = "%%s%s" % end
4610 format = "%%s%s" % end
4611
4611
4612 for f in files:
4612 for f in files:
4613 ui.write(format % repo.pathto(f, cwd),
4613 ui.write(format % repo.pathto(f, cwd),
4614 label='status.' + state)
4614 label='status.' + state)
4615 if f in copy:
4615 if f in copy:
4616 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4616 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4617 label='status.copied')
4617 label='status.copied')
4618
4618
4619 @command('^summary|sum',
4619 @command('^summary|sum',
4620 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4620 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4621 def summary(ui, repo, **opts):
4621 def summary(ui, repo, **opts):
4622 """summarize working directory state
4622 """summarize working directory state
4623
4623
4624 This generates a brief summary of the working directory state,
4624 This generates a brief summary of the working directory state,
4625 including parents, branch, commit status, and available updates.
4625 including parents, branch, commit status, and available updates.
4626
4626
4627 With the --remote option, this will check the default paths for
4627 With the --remote option, this will check the default paths for
4628 incoming and outgoing changes. This can be time-consuming.
4628 incoming and outgoing changes. This can be time-consuming.
4629
4629
4630 Returns 0 on success.
4630 Returns 0 on success.
4631 """
4631 """
4632
4632
4633 ctx = repo[None]
4633 ctx = repo[None]
4634 parents = ctx.parents()
4634 parents = ctx.parents()
4635 pnode = parents[0].node()
4635 pnode = parents[0].node()
4636
4636
4637 for p in parents:
4637 for p in parents:
4638 # label with log.changeset (instead of log.parent) since this
4638 # label with log.changeset (instead of log.parent) since this
4639 # shows a working directory parent *changeset*:
4639 # shows a working directory parent *changeset*:
4640 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4640 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4641 label='log.changeset')
4641 label='log.changeset')
4642 ui.write(' '.join(p.tags()), label='log.tag')
4642 ui.write(' '.join(p.tags()), label='log.tag')
4643 if p.bookmarks():
4643 if p.bookmarks():
4644 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4644 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4645 if p.rev() == -1:
4645 if p.rev() == -1:
4646 if not len(repo):
4646 if not len(repo):
4647 ui.write(_(' (empty repository)'))
4647 ui.write(_(' (empty repository)'))
4648 else:
4648 else:
4649 ui.write(_(' (no revision checked out)'))
4649 ui.write(_(' (no revision checked out)'))
4650 ui.write('\n')
4650 ui.write('\n')
4651 if p.description():
4651 if p.description():
4652 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4652 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4653 label='log.summary')
4653 label='log.summary')
4654
4654
4655 branch = ctx.branch()
4655 branch = ctx.branch()
4656 bheads = repo.branchheads(branch)
4656 bheads = repo.branchheads(branch)
4657 m = _('branch: %s\n') % branch
4657 m = _('branch: %s\n') % branch
4658 if branch != 'default':
4658 if branch != 'default':
4659 ui.write(m, label='log.branch')
4659 ui.write(m, label='log.branch')
4660 else:
4660 else:
4661 ui.status(m, label='log.branch')
4661 ui.status(m, label='log.branch')
4662
4662
4663 st = list(repo.status(unknown=True))[:6]
4663 st = list(repo.status(unknown=True))[:6]
4664
4664
4665 c = repo.dirstate.copies()
4665 c = repo.dirstate.copies()
4666 copied, renamed = [], []
4666 copied, renamed = [], []
4667 for d, s in c.iteritems():
4667 for d, s in c.iteritems():
4668 if s in st[2]:
4668 if s in st[2]:
4669 st[2].remove(s)
4669 st[2].remove(s)
4670 renamed.append(d)
4670 renamed.append(d)
4671 else:
4671 else:
4672 copied.append(d)
4672 copied.append(d)
4673 if d in st[1]:
4673 if d in st[1]:
4674 st[1].remove(d)
4674 st[1].remove(d)
4675 st.insert(3, renamed)
4675 st.insert(3, renamed)
4676 st.insert(4, copied)
4676 st.insert(4, copied)
4677
4677
4678 ms = mergemod.mergestate(repo)
4678 ms = mergemod.mergestate(repo)
4679 st.append([f for f in ms if ms[f] == 'u'])
4679 st.append([f for f in ms if ms[f] == 'u'])
4680
4680
4681 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4681 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4682 st.append(subs)
4682 st.append(subs)
4683
4683
4684 labels = [ui.label(_('%d modified'), 'status.modified'),
4684 labels = [ui.label(_('%d modified'), 'status.modified'),
4685 ui.label(_('%d added'), 'status.added'),
4685 ui.label(_('%d added'), 'status.added'),
4686 ui.label(_('%d removed'), 'status.removed'),
4686 ui.label(_('%d removed'), 'status.removed'),
4687 ui.label(_('%d renamed'), 'status.copied'),
4687 ui.label(_('%d renamed'), 'status.copied'),
4688 ui.label(_('%d copied'), 'status.copied'),
4688 ui.label(_('%d copied'), 'status.copied'),
4689 ui.label(_('%d deleted'), 'status.deleted'),
4689 ui.label(_('%d deleted'), 'status.deleted'),
4690 ui.label(_('%d unknown'), 'status.unknown'),
4690 ui.label(_('%d unknown'), 'status.unknown'),
4691 ui.label(_('%d ignored'), 'status.ignored'),
4691 ui.label(_('%d ignored'), 'status.ignored'),
4692 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4692 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4693 ui.label(_('%d subrepos'), 'status.modified')]
4693 ui.label(_('%d subrepos'), 'status.modified')]
4694 t = []
4694 t = []
4695 for s, l in zip(st, labels):
4695 for s, l in zip(st, labels):
4696 if s:
4696 if s:
4697 t.append(l % len(s))
4697 t.append(l % len(s))
4698
4698
4699 t = ', '.join(t)
4699 t = ', '.join(t)
4700 cleanworkdir = False
4700 cleanworkdir = False
4701
4701
4702 if len(parents) > 1:
4702 if len(parents) > 1:
4703 t += _(' (merge)')
4703 t += _(' (merge)')
4704 elif branch != parents[0].branch():
4704 elif branch != parents[0].branch():
4705 t += _(' (new branch)')
4705 t += _(' (new branch)')
4706 elif (parents[0].extra().get('close') and
4706 elif (parents[0].extra().get('close') and
4707 pnode in repo.branchheads(branch, closed=True)):
4707 pnode in repo.branchheads(branch, closed=True)):
4708 t += _(' (head closed)')
4708 t += _(' (head closed)')
4709 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4709 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4710 t += _(' (clean)')
4710 t += _(' (clean)')
4711 cleanworkdir = True
4711 cleanworkdir = True
4712 elif pnode not in bheads:
4712 elif pnode not in bheads:
4713 t += _(' (new branch head)')
4713 t += _(' (new branch head)')
4714
4714
4715 if cleanworkdir:
4715 if cleanworkdir:
4716 ui.status(_('commit: %s\n') % t.strip())
4716 ui.status(_('commit: %s\n') % t.strip())
4717 else:
4717 else:
4718 ui.write(_('commit: %s\n') % t.strip())
4718 ui.write(_('commit: %s\n') % t.strip())
4719
4719
4720 # all ancestors of branch heads - all ancestors of parent = new csets
4720 # all ancestors of branch heads - all ancestors of parent = new csets
4721 new = [0] * len(repo)
4721 new = [0] * len(repo)
4722 cl = repo.changelog
4722 cl = repo.changelog
4723 for a in [cl.rev(n) for n in bheads]:
4723 for a in [cl.rev(n) for n in bheads]:
4724 new[a] = 1
4724 new[a] = 1
4725 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4725 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4726 new[a] = 1
4726 new[a] = 1
4727 for a in [p.rev() for p in parents]:
4727 for a in [p.rev() for p in parents]:
4728 if a >= 0:
4728 if a >= 0:
4729 new[a] = 0
4729 new[a] = 0
4730 for a in cl.ancestors(*[p.rev() for p in parents]):
4730 for a in cl.ancestors(*[p.rev() for p in parents]):
4731 new[a] = 0
4731 new[a] = 0
4732 new = sum(new)
4732 new = sum(new)
4733
4733
4734 if new == 0:
4734 if new == 0:
4735 ui.status(_('update: (current)\n'))
4735 ui.status(_('update: (current)\n'))
4736 elif pnode not in bheads:
4736 elif pnode not in bheads:
4737 ui.write(_('update: %d new changesets (update)\n') % new)
4737 ui.write(_('update: %d new changesets (update)\n') % new)
4738 else:
4738 else:
4739 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4739 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4740 (new, len(bheads)))
4740 (new, len(bheads)))
4741
4741
4742 if opts.get('remote'):
4742 if opts.get('remote'):
4743 t = []
4743 t = []
4744 source, branches = hg.parseurl(ui.expandpath('default'))
4744 source, branches = hg.parseurl(ui.expandpath('default'))
4745 other = hg.peer(repo, {}, source)
4745 other = hg.peer(repo, {}, source)
4746 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4746 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4747 ui.debug('comparing with %s\n' % util.hidepassword(source))
4747 ui.debug('comparing with %s\n' % util.hidepassword(source))
4748 repo.ui.pushbuffer()
4748 repo.ui.pushbuffer()
4749 commoninc = discovery.findcommonincoming(repo, other)
4749 commoninc = discovery.findcommonincoming(repo, other)
4750 _common, incoming, _rheads = commoninc
4750 _common, incoming, _rheads = commoninc
4751 repo.ui.popbuffer()
4751 repo.ui.popbuffer()
4752 if incoming:
4752 if incoming:
4753 t.append(_('1 or more incoming'))
4753 t.append(_('1 or more incoming'))
4754
4754
4755 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4755 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4756 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4756 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4757 if source != dest:
4757 if source != dest:
4758 other = hg.peer(repo, {}, dest)
4758 other = hg.peer(repo, {}, dest)
4759 commoninc = None
4759 commoninc = None
4760 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4760 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4761 repo.ui.pushbuffer()
4761 repo.ui.pushbuffer()
4762 common, outheads = discovery.findcommonoutgoing(repo, other,
4762 common, outheads = discovery.findcommonoutgoing(repo, other,
4763 commoninc=commoninc)
4763 commoninc=commoninc)
4764 repo.ui.popbuffer()
4764 repo.ui.popbuffer()
4765 o = repo.changelog.findmissing(common=common, heads=outheads)
4765 o = repo.changelog.findmissing(common=common, heads=outheads)
4766 if o:
4766 if o:
4767 t.append(_('%d outgoing') % len(o))
4767 t.append(_('%d outgoing') % len(o))
4768 if 'bookmarks' in other.listkeys('namespaces'):
4768 if 'bookmarks' in other.listkeys('namespaces'):
4769 lmarks = repo.listkeys('bookmarks')
4769 lmarks = repo.listkeys('bookmarks')
4770 rmarks = other.listkeys('bookmarks')
4770 rmarks = other.listkeys('bookmarks')
4771 diff = set(rmarks) - set(lmarks)
4771 diff = set(rmarks) - set(lmarks)
4772 if len(diff) > 0:
4772 if len(diff) > 0:
4773 t.append(_('%d incoming bookmarks') % len(diff))
4773 t.append(_('%d incoming bookmarks') % len(diff))
4774 diff = set(lmarks) - set(rmarks)
4774 diff = set(lmarks) - set(rmarks)
4775 if len(diff) > 0:
4775 if len(diff) > 0:
4776 t.append(_('%d outgoing bookmarks') % len(diff))
4776 t.append(_('%d outgoing bookmarks') % len(diff))
4777
4777
4778 if t:
4778 if t:
4779 ui.write(_('remote: %s\n') % (', '.join(t)))
4779 ui.write(_('remote: %s\n') % (', '.join(t)))
4780 else:
4780 else:
4781 ui.status(_('remote: (synced)\n'))
4781 ui.status(_('remote: (synced)\n'))
4782
4782
4783 @command('tag',
4783 @command('tag',
4784 [('f', 'force', None, _('force tag')),
4784 [('f', 'force', None, _('force tag')),
4785 ('l', 'local', None, _('make the tag local')),
4785 ('l', 'local', None, _('make the tag local')),
4786 ('r', 'rev', '', _('revision to tag'), _('REV')),
4786 ('r', 'rev', '', _('revision to tag'), _('REV')),
4787 ('', 'remove', None, _('remove a tag')),
4787 ('', 'remove', None, _('remove a tag')),
4788 # -l/--local is already there, commitopts cannot be used
4788 # -l/--local is already there, commitopts cannot be used
4789 ('e', 'edit', None, _('edit commit message')),
4789 ('e', 'edit', None, _('edit commit message')),
4790 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4790 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4791 ] + commitopts2,
4791 ] + commitopts2,
4792 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4792 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4793 def tag(ui, repo, name1, *names, **opts):
4793 def tag(ui, repo, name1, *names, **opts):
4794 """add one or more tags for the current or given revision
4794 """add one or more tags for the current or given revision
4795
4795
4796 Name a particular revision using <name>.
4796 Name a particular revision using <name>.
4797
4797
4798 Tags are used to name particular revisions of the repository and are
4798 Tags are used to name particular revisions of the repository and are
4799 very useful to compare different revisions, to go back to significant
4799 very useful to compare different revisions, to go back to significant
4800 earlier versions or to mark branch points as releases, etc. Changing
4800 earlier versions or to mark branch points as releases, etc. Changing
4801 an existing tag is normally disallowed; use -f/--force to override.
4801 an existing tag is normally disallowed; use -f/--force to override.
4802
4802
4803 If no revision is given, the parent of the working directory is
4803 If no revision is given, the parent of the working directory is
4804 used, or tip if no revision is checked out.
4804 used, or tip if no revision is checked out.
4805
4805
4806 To facilitate version control, distribution, and merging of tags,
4806 To facilitate version control, distribution, and merging of tags,
4807 they are stored as a file named ".hgtags" which is managed similarly
4807 they are stored as a file named ".hgtags" which is managed similarly
4808 to other project files and can be hand-edited if necessary. This
4808 to other project files and can be hand-edited if necessary. This
4809 also means that tagging creates a new commit. The file
4809 also means that tagging creates a new commit. The file
4810 ".hg/localtags" is used for local tags (not shared among
4810 ".hg/localtags" is used for local tags (not shared among
4811 repositories).
4811 repositories).
4812
4812
4813 Tag commits are usually made at the head of a branch. If the parent
4813 Tag commits are usually made at the head of a branch. If the parent
4814 of the working directory is not a branch head, :hg:`tag` aborts; use
4814 of the working directory is not a branch head, :hg:`tag` aborts; use
4815 -f/--force to force the tag commit to be based on a non-head
4815 -f/--force to force the tag commit to be based on a non-head
4816 changeset.
4816 changeset.
4817
4817
4818 See :hg:`help dates` for a list of formats valid for -d/--date.
4818 See :hg:`help dates` for a list of formats valid for -d/--date.
4819
4819
4820 Since tag names have priority over branch names during revision
4820 Since tag names have priority over branch names during revision
4821 lookup, using an existing branch name as a tag name is discouraged.
4821 lookup, using an existing branch name as a tag name is discouraged.
4822
4822
4823 Returns 0 on success.
4823 Returns 0 on success.
4824 """
4824 """
4825
4825
4826 rev_ = "."
4826 rev_ = "."
4827 names = [t.strip() for t in (name1,) + names]
4827 names = [t.strip() for t in (name1,) + names]
4828 if len(names) != len(set(names)):
4828 if len(names) != len(set(names)):
4829 raise util.Abort(_('tag names must be unique'))
4829 raise util.Abort(_('tag names must be unique'))
4830 for n in names:
4830 for n in names:
4831 if n in ['tip', '.', 'null']:
4831 if n in ['tip', '.', 'null']:
4832 raise util.Abort(_("the name '%s' is reserved") % n)
4832 raise util.Abort(_("the name '%s' is reserved") % n)
4833 if not n:
4833 if not n:
4834 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4834 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4835 if opts.get('rev') and opts.get('remove'):
4835 if opts.get('rev') and opts.get('remove'):
4836 raise util.Abort(_("--rev and --remove are incompatible"))
4836 raise util.Abort(_("--rev and --remove are incompatible"))
4837 if opts.get('rev'):
4837 if opts.get('rev'):
4838 rev_ = opts['rev']
4838 rev_ = opts['rev']
4839 message = opts.get('message')
4839 message = opts.get('message')
4840 if opts.get('remove'):
4840 if opts.get('remove'):
4841 expectedtype = opts.get('local') and 'local' or 'global'
4841 expectedtype = opts.get('local') and 'local' or 'global'
4842 for n in names:
4842 for n in names:
4843 if not repo.tagtype(n):
4843 if not repo.tagtype(n):
4844 raise util.Abort(_("tag '%s' does not exist") % n)
4844 raise util.Abort(_("tag '%s' does not exist") % n)
4845 if repo.tagtype(n) != expectedtype:
4845 if repo.tagtype(n) != expectedtype:
4846 if expectedtype == 'global':
4846 if expectedtype == 'global':
4847 raise util.Abort(_("tag '%s' is not a global tag") % n)
4847 raise util.Abort(_("tag '%s' is not a global tag") % n)
4848 else:
4848 else:
4849 raise util.Abort(_("tag '%s' is not a local tag") % n)
4849 raise util.Abort(_("tag '%s' is not a local tag") % n)
4850 rev_ = nullid
4850 rev_ = nullid
4851 if not message:
4851 if not message:
4852 # we don't translate commit messages
4852 # we don't translate commit messages
4853 message = 'Removed tag %s' % ', '.join(names)
4853 message = 'Removed tag %s' % ', '.join(names)
4854 elif not opts.get('force'):
4854 elif not opts.get('force'):
4855 for n in names:
4855 for n in names:
4856 if n in repo.tags():
4856 if n in repo.tags():
4857 raise util.Abort(_("tag '%s' already exists "
4857 raise util.Abort(_("tag '%s' already exists "
4858 "(use -f to force)") % n)
4858 "(use -f to force)") % n)
4859 if not opts.get('local'):
4859 if not opts.get('local'):
4860 p1, p2 = repo.dirstate.parents()
4860 p1, p2 = repo.dirstate.parents()
4861 if p2 != nullid:
4861 if p2 != nullid:
4862 raise util.Abort(_('uncommitted merge'))
4862 raise util.Abort(_('uncommitted merge'))
4863 bheads = repo.branchheads()
4863 bheads = repo.branchheads()
4864 if not opts.get('force') and bheads and p1 not in bheads:
4864 if not opts.get('force') and bheads and p1 not in bheads:
4865 raise util.Abort(_('not at a branch head (use -f to force)'))
4865 raise util.Abort(_('not at a branch head (use -f to force)'))
4866 r = scmutil.revsingle(repo, rev_).node()
4866 r = scmutil.revsingle(repo, rev_).node()
4867
4867
4868 if not message:
4868 if not message:
4869 # we don't translate commit messages
4869 # we don't translate commit messages
4870 message = ('Added tag %s for changeset %s' %
4870 message = ('Added tag %s for changeset %s' %
4871 (', '.join(names), short(r)))
4871 (', '.join(names), short(r)))
4872
4872
4873 date = opts.get('date')
4873 date = opts.get('date')
4874 if date:
4874 if date:
4875 date = util.parsedate(date)
4875 date = util.parsedate(date)
4876
4876
4877 if opts.get('edit'):
4877 if opts.get('edit'):
4878 message = ui.edit(message, ui.username())
4878 message = ui.edit(message, ui.username())
4879
4879
4880 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4880 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4881
4881
4882 @command('tags', [], '')
4882 @command('tags', [], '')
4883 def tags(ui, repo):
4883 def tags(ui, repo):
4884 """list repository tags
4884 """list repository tags
4885
4885
4886 This lists both regular and local tags. When the -v/--verbose
4886 This lists both regular and local tags. When the -v/--verbose
4887 switch is used, a third column "local" is printed for local tags.
4887 switch is used, a third column "local" is printed for local tags.
4888
4888
4889 Returns 0 on success.
4889 Returns 0 on success.
4890 """
4890 """
4891
4891
4892 hexfunc = ui.debugflag and hex or short
4892 hexfunc = ui.debugflag and hex or short
4893 tagtype = ""
4893 tagtype = ""
4894
4894
4895 for t, n in reversed(repo.tagslist()):
4895 for t, n in reversed(repo.tagslist()):
4896 if ui.quiet:
4896 if ui.quiet:
4897 ui.write("%s\n" % t)
4897 ui.write("%s\n" % t)
4898 continue
4898 continue
4899
4899
4900 hn = hexfunc(n)
4900 hn = hexfunc(n)
4901 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4901 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4902 spaces = " " * (30 - encoding.colwidth(t))
4902 spaces = " " * (30 - encoding.colwidth(t))
4903
4903
4904 if ui.verbose:
4904 if ui.verbose:
4905 if repo.tagtype(t) == 'local':
4905 if repo.tagtype(t) == 'local':
4906 tagtype = " local"
4906 tagtype = " local"
4907 else:
4907 else:
4908 tagtype = ""
4908 tagtype = ""
4909 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4909 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4910
4910
4911 @command('tip',
4911 @command('tip',
4912 [('p', 'patch', None, _('show patch')),
4912 [('p', 'patch', None, _('show patch')),
4913 ('g', 'git', None, _('use git extended diff format')),
4913 ('g', 'git', None, _('use git extended diff format')),
4914 ] + templateopts,
4914 ] + templateopts,
4915 _('[-p] [-g]'))
4915 _('[-p] [-g]'))
4916 def tip(ui, repo, **opts):
4916 def tip(ui, repo, **opts):
4917 """show the tip revision
4917 """show the tip revision
4918
4918
4919 The tip revision (usually just called the tip) is the changeset
4919 The tip revision (usually just called the tip) is the changeset
4920 most recently added to the repository (and therefore the most
4920 most recently added to the repository (and therefore the most
4921 recently changed head).
4921 recently changed head).
4922
4922
4923 If you have just made a commit, that commit will be the tip. If
4923 If you have just made a commit, that commit will be the tip. If
4924 you have just pulled changes from another repository, the tip of
4924 you have just pulled changes from another repository, the tip of
4925 that repository becomes the current tip. The "tip" tag is special
4925 that repository becomes the current tip. The "tip" tag is special
4926 and cannot be renamed or assigned to a different changeset.
4926 and cannot be renamed or assigned to a different changeset.
4927
4927
4928 Returns 0 on success.
4928 Returns 0 on success.
4929 """
4929 """
4930 displayer = cmdutil.show_changeset(ui, repo, opts)
4930 displayer = cmdutil.show_changeset(ui, repo, opts)
4931 displayer.show(repo[len(repo) - 1])
4931 displayer.show(repo[len(repo) - 1])
4932 displayer.close()
4932 displayer.close()
4933
4933
4934 @command('unbundle',
4934 @command('unbundle',
4935 [('u', 'update', None,
4935 [('u', 'update', None,
4936 _('update to new branch head if changesets were unbundled'))],
4936 _('update to new branch head if changesets were unbundled'))],
4937 _('[-u] FILE...'))
4937 _('[-u] FILE...'))
4938 def unbundle(ui, repo, fname1, *fnames, **opts):
4938 def unbundle(ui, repo, fname1, *fnames, **opts):
4939 """apply one or more changegroup files
4939 """apply one or more changegroup files
4940
4940
4941 Apply one or more compressed changegroup files generated by the
4941 Apply one or more compressed changegroup files generated by the
4942 bundle command.
4942 bundle command.
4943
4943
4944 Returns 0 on success, 1 if an update has unresolved files.
4944 Returns 0 on success, 1 if an update has unresolved files.
4945 """
4945 """
4946 fnames = (fname1,) + fnames
4946 fnames = (fname1,) + fnames
4947
4947
4948 lock = repo.lock()
4948 lock = repo.lock()
4949 wc = repo['.']
4949 wc = repo['.']
4950 try:
4950 try:
4951 for fname in fnames:
4951 for fname in fnames:
4952 f = url.open(ui, fname)
4952 f = url.open(ui, fname)
4953 gen = changegroup.readbundle(f, fname)
4953 gen = changegroup.readbundle(f, fname)
4954 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4954 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4955 lock=lock)
4955 lock=lock)
4956 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4956 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4957 finally:
4957 finally:
4958 lock.release()
4958 lock.release()
4959 return postincoming(ui, repo, modheads, opts.get('update'), None)
4959 return postincoming(ui, repo, modheads, opts.get('update'), None)
4960
4960
4961 @command('^update|up|checkout|co',
4961 @command('^update|up|checkout|co',
4962 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4962 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4963 ('c', 'check', None,
4963 ('c', 'check', None,
4964 _('update across branches if no uncommitted changes')),
4964 _('update across branches if no uncommitted changes')),
4965 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4965 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4966 ('r', 'rev', '', _('revision'), _('REV'))],
4966 ('r', 'rev', '', _('revision'), _('REV'))],
4967 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4967 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4968 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4968 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4969 """update working directory (or switch revisions)
4969 """update working directory (or switch revisions)
4970
4970
4971 Update the repository's working directory to the specified
4971 Update the repository's working directory to the specified
4972 changeset. If no changeset is specified, update to the tip of the
4972 changeset. If no changeset is specified, update to the tip of the
4973 current named branch.
4973 current named branch.
4974
4974
4975 If the changeset is not a descendant of the working directory's
4975 If the changeset is not a descendant of the working directory's
4976 parent, the update is aborted. With the -c/--check option, the
4976 parent, the update is aborted. With the -c/--check option, the
4977 working directory is checked for uncommitted changes; if none are
4977 working directory is checked for uncommitted changes; if none are
4978 found, the working directory is updated to the specified
4978 found, the working directory is updated to the specified
4979 changeset.
4979 changeset.
4980
4980
4981 The following rules apply when the working directory contains
4981 The following rules apply when the working directory contains
4982 uncommitted changes:
4982 uncommitted changes:
4983
4983
4984 1. If neither -c/--check nor -C/--clean is specified, and if
4984 1. If neither -c/--check nor -C/--clean is specified, and if
4985 the requested changeset is an ancestor or descendant of
4985 the requested changeset is an ancestor or descendant of
4986 the working directory's parent, the uncommitted changes
4986 the working directory's parent, the uncommitted changes
4987 are merged into the requested changeset and the merged
4987 are merged into the requested changeset and the merged
4988 result is left uncommitted. If the requested changeset is
4988 result is left uncommitted. If the requested changeset is
4989 not an ancestor or descendant (that is, it is on another
4989 not an ancestor or descendant (that is, it is on another
4990 branch), the update is aborted and the uncommitted changes
4990 branch), the update is aborted and the uncommitted changes
4991 are preserved.
4991 are preserved.
4992
4992
4993 2. With the -c/--check option, the update is aborted and the
4993 2. With the -c/--check option, the update is aborted and the
4994 uncommitted changes are preserved.
4994 uncommitted changes are preserved.
4995
4995
4996 3. With the -C/--clean option, uncommitted changes are discarded and
4996 3. With the -C/--clean option, uncommitted changes are discarded and
4997 the working directory is updated to the requested changeset.
4997 the working directory is updated to the requested changeset.
4998
4998
4999 Use null as the changeset to remove the working directory (like
4999 Use null as the changeset to remove the working directory (like
5000 :hg:`clone -U`).
5000 :hg:`clone -U`).
5001
5001
5002 If you want to update just one file to an older changeset, use
5002 If you want to update just one file to an older changeset, use
5003 :hg:`revert`.
5003 :hg:`revert`.
5004
5004
5005 See :hg:`help dates` for a list of formats valid for -d/--date.
5005 See :hg:`help dates` for a list of formats valid for -d/--date.
5006
5006
5007 Returns 0 on success, 1 if there are unresolved files.
5007 Returns 0 on success, 1 if there are unresolved files.
5008 """
5008 """
5009 if rev and node:
5009 if rev and node:
5010 raise util.Abort(_("please specify just one revision"))
5010 raise util.Abort(_("please specify just one revision"))
5011
5011
5012 if rev is None or rev == '':
5012 if rev is None or rev == '':
5013 rev = node
5013 rev = node
5014
5014
5015 # if we defined a bookmark, we have to remember the original bookmark name
5015 # if we defined a bookmark, we have to remember the original bookmark name
5016 brev = rev
5016 brev = rev
5017 rev = scmutil.revsingle(repo, rev, rev).rev()
5017 rev = scmutil.revsingle(repo, rev, rev).rev()
5018
5018
5019 if check and clean:
5019 if check and clean:
5020 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5020 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5021
5021
5022 if check:
5022 if check:
5023 # we could use dirty() but we can ignore merge and branch trivia
5023 # we could use dirty() but we can ignore merge and branch trivia
5024 c = repo[None]
5024 c = repo[None]
5025 if c.modified() or c.added() or c.removed():
5025 if c.modified() or c.added() or c.removed():
5026 raise util.Abort(_("uncommitted local changes"))
5026 raise util.Abort(_("uncommitted local changes"))
5027
5027
5028 if date:
5028 if date:
5029 if rev is not None:
5029 if rev is not None:
5030 raise util.Abort(_("you can't specify a revision and a date"))
5030 raise util.Abort(_("you can't specify a revision and a date"))
5031 rev = cmdutil.finddate(ui, repo, date)
5031 rev = cmdutil.finddate(ui, repo, date)
5032
5032
5033 if clean or check:
5033 if clean or check:
5034 ret = hg.clean(repo, rev)
5034 ret = hg.clean(repo, rev)
5035 else:
5035 else:
5036 ret = hg.update(repo, rev)
5036 ret = hg.update(repo, rev)
5037
5037
5038 if brev in repo._bookmarks:
5038 if brev in repo._bookmarks:
5039 bookmarks.setcurrent(repo, brev)
5039 bookmarks.setcurrent(repo, brev)
5040
5040
5041 return ret
5041 return ret
5042
5042
5043 @command('verify', [])
5043 @command('verify', [])
5044 def verify(ui, repo):
5044 def verify(ui, repo):
5045 """verify the integrity of the repository
5045 """verify the integrity of the repository
5046
5046
5047 Verify the integrity of the current repository.
5047 Verify the integrity of the current repository.
5048
5048
5049 This will perform an extensive check of the repository's
5049 This will perform an extensive check of the repository's
5050 integrity, validating the hashes and checksums of each entry in
5050 integrity, validating the hashes and checksums of each entry in
5051 the changelog, manifest, and tracked files, as well as the
5051 the changelog, manifest, and tracked files, as well as the
5052 integrity of their crosslinks and indices.
5052 integrity of their crosslinks and indices.
5053
5053
5054 Returns 0 on success, 1 if errors are encountered.
5054 Returns 0 on success, 1 if errors are encountered.
5055 """
5055 """
5056 return hg.verify(repo)
5056 return hg.verify(repo)
5057
5057
5058 @command('version', [])
5058 @command('version', [])
5059 def version_(ui):
5059 def version_(ui):
5060 """output version and copyright information"""
5060 """output version and copyright information"""
5061 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5061 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5062 % util.version())
5062 % util.version())
5063 ui.status(_(
5063 ui.status(_(
5064 "(see http://mercurial.selenic.com for more information)\n"
5064 "(see http://mercurial.selenic.com for more information)\n"
5065 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5065 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5066 "This is free software; see the source for copying conditions. "
5066 "This is free software; see the source for copying conditions. "
5067 "There is NO\nwarranty; "
5067 "There is NO\nwarranty; "
5068 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5068 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5069 ))
5069 ))
5070
5070
5071 norepo = ("clone init version help debugcommands debugcomplete"
5071 norepo = ("clone init version help debugcommands debugcomplete"
5072 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5072 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5073 " debugknown debuggetbundle debugbundle")
5073 " debugknown debuggetbundle debugbundle")
5074 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5074 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5075 " debugdata debugindex debugindexdot debugrevlog")
5075 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1785 +1,1785 b''
1 # patch.py - patch file parsing routines
1 # patch.py - patch file parsing routines
2 #
2 #
3 # Copyright 2006 Brendan Cully <brendan@kublai.com>
3 # Copyright 2006 Brendan Cully <brendan@kublai.com>
4 # Copyright 2007 Chris Mason <chris.mason@oracle.com>
4 # Copyright 2007 Chris Mason <chris.mason@oracle.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 import cStringIO, email.Parser, os, errno, re
9 import cStringIO, email.Parser, os, errno, re
10 import tempfile, zlib, shutil
10 import tempfile, zlib, shutil
11
11
12 from i18n import _
12 from i18n import _
13 from node import hex, nullid, short
13 from node import hex, nullid, short
14 import base85, mdiff, scmutil, util, diffhelpers, copies, encoding
14 import base85, mdiff, scmutil, util, diffhelpers, copies, encoding
15
15
16 gitre = re.compile('diff --git a/(.*) b/(.*)')
16 gitre = re.compile('diff --git a/(.*) b/(.*)')
17
17
18 class PatchError(Exception):
18 class PatchError(Exception):
19 pass
19 pass
20
20
21
21
22 # public functions
22 # public functions
23
23
24 def split(stream):
24 def split(stream):
25 '''return an iterator of individual patches from a stream'''
25 '''return an iterator of individual patches from a stream'''
26 def isheader(line, inheader):
26 def isheader(line, inheader):
27 if inheader and line[0] in (' ', '\t'):
27 if inheader and line[0] in (' ', '\t'):
28 # continuation
28 # continuation
29 return True
29 return True
30 if line[0] in (' ', '-', '+'):
30 if line[0] in (' ', '-', '+'):
31 # diff line - don't check for header pattern in there
31 # diff line - don't check for header pattern in there
32 return False
32 return False
33 l = line.split(': ', 1)
33 l = line.split(': ', 1)
34 return len(l) == 2 and ' ' not in l[0]
34 return len(l) == 2 and ' ' not in l[0]
35
35
36 def chunk(lines):
36 def chunk(lines):
37 return cStringIO.StringIO(''.join(lines))
37 return cStringIO.StringIO(''.join(lines))
38
38
39 def hgsplit(stream, cur):
39 def hgsplit(stream, cur):
40 inheader = True
40 inheader = True
41
41
42 for line in stream:
42 for line in stream:
43 if not line.strip():
43 if not line.strip():
44 inheader = False
44 inheader = False
45 if not inheader and line.startswith('# HG changeset patch'):
45 if not inheader and line.startswith('# HG changeset patch'):
46 yield chunk(cur)
46 yield chunk(cur)
47 cur = []
47 cur = []
48 inheader = True
48 inheader = True
49
49
50 cur.append(line)
50 cur.append(line)
51
51
52 if cur:
52 if cur:
53 yield chunk(cur)
53 yield chunk(cur)
54
54
55 def mboxsplit(stream, cur):
55 def mboxsplit(stream, cur):
56 for line in stream:
56 for line in stream:
57 if line.startswith('From '):
57 if line.startswith('From '):
58 for c in split(chunk(cur[1:])):
58 for c in split(chunk(cur[1:])):
59 yield c
59 yield c
60 cur = []
60 cur = []
61
61
62 cur.append(line)
62 cur.append(line)
63
63
64 if cur:
64 if cur:
65 for c in split(chunk(cur[1:])):
65 for c in split(chunk(cur[1:])):
66 yield c
66 yield c
67
67
68 def mimesplit(stream, cur):
68 def mimesplit(stream, cur):
69 def msgfp(m):
69 def msgfp(m):
70 fp = cStringIO.StringIO()
70 fp = cStringIO.StringIO()
71 g = email.Generator.Generator(fp, mangle_from_=False)
71 g = email.Generator.Generator(fp, mangle_from_=False)
72 g.flatten(m)
72 g.flatten(m)
73 fp.seek(0)
73 fp.seek(0)
74 return fp
74 return fp
75
75
76 for line in stream:
76 for line in stream:
77 cur.append(line)
77 cur.append(line)
78 c = chunk(cur)
78 c = chunk(cur)
79
79
80 m = email.Parser.Parser().parse(c)
80 m = email.Parser.Parser().parse(c)
81 if not m.is_multipart():
81 if not m.is_multipart():
82 yield msgfp(m)
82 yield msgfp(m)
83 else:
83 else:
84 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
84 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
85 for part in m.walk():
85 for part in m.walk():
86 ct = part.get_content_type()
86 ct = part.get_content_type()
87 if ct not in ok_types:
87 if ct not in ok_types:
88 continue
88 continue
89 yield msgfp(part)
89 yield msgfp(part)
90
90
91 def headersplit(stream, cur):
91 def headersplit(stream, cur):
92 inheader = False
92 inheader = False
93
93
94 for line in stream:
94 for line in stream:
95 if not inheader and isheader(line, inheader):
95 if not inheader and isheader(line, inheader):
96 yield chunk(cur)
96 yield chunk(cur)
97 cur = []
97 cur = []
98 inheader = True
98 inheader = True
99 if inheader and not isheader(line, inheader):
99 if inheader and not isheader(line, inheader):
100 inheader = False
100 inheader = False
101
101
102 cur.append(line)
102 cur.append(line)
103
103
104 if cur:
104 if cur:
105 yield chunk(cur)
105 yield chunk(cur)
106
106
107 def remainder(cur):
107 def remainder(cur):
108 yield chunk(cur)
108 yield chunk(cur)
109
109
110 class fiter(object):
110 class fiter(object):
111 def __init__(self, fp):
111 def __init__(self, fp):
112 self.fp = fp
112 self.fp = fp
113
113
114 def __iter__(self):
114 def __iter__(self):
115 return self
115 return self
116
116
117 def next(self):
117 def next(self):
118 l = self.fp.readline()
118 l = self.fp.readline()
119 if not l:
119 if not l:
120 raise StopIteration
120 raise StopIteration
121 return l
121 return l
122
122
123 inheader = False
123 inheader = False
124 cur = []
124 cur = []
125
125
126 mimeheaders = ['content-type']
126 mimeheaders = ['content-type']
127
127
128 if not hasattr(stream, 'next'):
128 if not hasattr(stream, 'next'):
129 # http responses, for example, have readline but not next
129 # http responses, for example, have readline but not next
130 stream = fiter(stream)
130 stream = fiter(stream)
131
131
132 for line in stream:
132 for line in stream:
133 cur.append(line)
133 cur.append(line)
134 if line.startswith('# HG changeset patch'):
134 if line.startswith('# HG changeset patch'):
135 return hgsplit(stream, cur)
135 return hgsplit(stream, cur)
136 elif line.startswith('From '):
136 elif line.startswith('From '):
137 return mboxsplit(stream, cur)
137 return mboxsplit(stream, cur)
138 elif isheader(line, inheader):
138 elif isheader(line, inheader):
139 inheader = True
139 inheader = True
140 if line.split(':', 1)[0].lower() in mimeheaders:
140 if line.split(':', 1)[0].lower() in mimeheaders:
141 # let email parser handle this
141 # let email parser handle this
142 return mimesplit(stream, cur)
142 return mimesplit(stream, cur)
143 elif line.startswith('--- ') and inheader:
143 elif line.startswith('--- ') and inheader:
144 # No evil headers seen by diff start, split by hand
144 # No evil headers seen by diff start, split by hand
145 return headersplit(stream, cur)
145 return headersplit(stream, cur)
146 # Not enough info, keep reading
146 # Not enough info, keep reading
147
147
148 # if we are here, we have a very plain patch
148 # if we are here, we have a very plain patch
149 return remainder(cur)
149 return remainder(cur)
150
150
151 def extract(ui, fileobj):
151 def extract(ui, fileobj):
152 '''extract patch from data read from fileobj.
152 '''extract patch from data read from fileobj.
153
153
154 patch can be a normal patch or contained in an email message.
154 patch can be a normal patch or contained in an email message.
155
155
156 return tuple (filename, message, user, date, branch, node, p1, p2).
156 return tuple (filename, message, user, date, branch, node, p1, p2).
157 Any item in the returned tuple can be None. If filename is None,
157 Any item in the returned tuple can be None. If filename is None,
158 fileobj did not contain a patch. Caller must unlink filename when done.'''
158 fileobj did not contain a patch. Caller must unlink filename when done.'''
159
159
160 # attempt to detect the start of a patch
160 # attempt to detect the start of a patch
161 # (this heuristic is borrowed from quilt)
161 # (this heuristic is borrowed from quilt)
162 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |'
162 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |'
163 r'retrieving revision [0-9]+(\.[0-9]+)*$|'
163 r'retrieving revision [0-9]+(\.[0-9]+)*$|'
164 r'---[ \t].*?^\+\+\+[ \t]|'
164 r'---[ \t].*?^\+\+\+[ \t]|'
165 r'\*\*\*[ \t].*?^---[ \t])', re.MULTILINE|re.DOTALL)
165 r'\*\*\*[ \t].*?^---[ \t])', re.MULTILINE|re.DOTALL)
166
166
167 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
167 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
168 tmpfp = os.fdopen(fd, 'w')
168 tmpfp = os.fdopen(fd, 'w')
169 try:
169 try:
170 msg = email.Parser.Parser().parse(fileobj)
170 msg = email.Parser.Parser().parse(fileobj)
171
171
172 subject = msg['Subject']
172 subject = msg['Subject']
173 user = msg['From']
173 user = msg['From']
174 if not subject and not user:
174 if not subject and not user:
175 # Not an email, restore parsed headers if any
175 # Not an email, restore parsed headers if any
176 subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n'
176 subject = '\n'.join(': '.join(h) for h in msg.items()) + '\n'
177
177
178 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
178 gitsendmail = 'git-send-email' in msg.get('X-Mailer', '')
179 # should try to parse msg['Date']
179 # should try to parse msg['Date']
180 date = None
180 date = None
181 nodeid = None
181 nodeid = None
182 branch = None
182 branch = None
183 parents = []
183 parents = []
184
184
185 if subject:
185 if subject:
186 if subject.startswith('[PATCH'):
186 if subject.startswith('[PATCH'):
187 pend = subject.find(']')
187 pend = subject.find(']')
188 if pend >= 0:
188 if pend >= 0:
189 subject = subject[pend + 1:].lstrip()
189 subject = subject[pend + 1:].lstrip()
190 subject = subject.replace('\n\t', ' ')
190 subject = subject.replace('\n\t', ' ')
191 ui.debug('Subject: %s\n' % subject)
191 ui.debug('Subject: %s\n' % subject)
192 if user:
192 if user:
193 ui.debug('From: %s\n' % user)
193 ui.debug('From: %s\n' % user)
194 diffs_seen = 0
194 diffs_seen = 0
195 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
195 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
196 message = ''
196 message = ''
197 for part in msg.walk():
197 for part in msg.walk():
198 content_type = part.get_content_type()
198 content_type = part.get_content_type()
199 ui.debug('Content-Type: %s\n' % content_type)
199 ui.debug('Content-Type: %s\n' % content_type)
200 if content_type not in ok_types:
200 if content_type not in ok_types:
201 continue
201 continue
202 payload = part.get_payload(decode=True)
202 payload = part.get_payload(decode=True)
203 m = diffre.search(payload)
203 m = diffre.search(payload)
204 if m:
204 if m:
205 hgpatch = False
205 hgpatch = False
206 hgpatchheader = False
206 hgpatchheader = False
207 ignoretext = False
207 ignoretext = False
208
208
209 ui.debug('found patch at byte %d\n' % m.start(0))
209 ui.debug('found patch at byte %d\n' % m.start(0))
210 diffs_seen += 1
210 diffs_seen += 1
211 cfp = cStringIO.StringIO()
211 cfp = cStringIO.StringIO()
212 for line in payload[:m.start(0)].splitlines():
212 for line in payload[:m.start(0)].splitlines():
213 if line.startswith('# HG changeset patch') and not hgpatch:
213 if line.startswith('# HG changeset patch') and not hgpatch:
214 ui.debug('patch generated by hg export\n')
214 ui.debug('patch generated by hg export\n')
215 hgpatch = True
215 hgpatch = True
216 hgpatchheader = True
216 hgpatchheader = True
217 # drop earlier commit message content
217 # drop earlier commit message content
218 cfp.seek(0)
218 cfp.seek(0)
219 cfp.truncate()
219 cfp.truncate()
220 subject = None
220 subject = None
221 elif hgpatchheader:
221 elif hgpatchheader:
222 if line.startswith('# User '):
222 if line.startswith('# User '):
223 user = line[7:]
223 user = line[7:]
224 ui.debug('From: %s\n' % user)
224 ui.debug('From: %s\n' % user)
225 elif line.startswith("# Date "):
225 elif line.startswith("# Date "):
226 date = line[7:]
226 date = line[7:]
227 elif line.startswith("# Branch "):
227 elif line.startswith("# Branch "):
228 branch = line[9:]
228 branch = line[9:]
229 elif line.startswith("# Node ID "):
229 elif line.startswith("# Node ID "):
230 nodeid = line[10:]
230 nodeid = line[10:]
231 elif line.startswith("# Parent "):
231 elif line.startswith("# Parent "):
232 parents.append(line[10:])
232 parents.append(line[10:])
233 elif not line.startswith("# "):
233 elif not line.startswith("# "):
234 hgpatchheader = False
234 hgpatchheader = False
235 elif line == '---' and gitsendmail:
235 elif line == '---' and gitsendmail:
236 ignoretext = True
236 ignoretext = True
237 if not hgpatchheader and not ignoretext:
237 if not hgpatchheader and not ignoretext:
238 cfp.write(line)
238 cfp.write(line)
239 cfp.write('\n')
239 cfp.write('\n')
240 message = cfp.getvalue()
240 message = cfp.getvalue()
241 if tmpfp:
241 if tmpfp:
242 tmpfp.write(payload)
242 tmpfp.write(payload)
243 if not payload.endswith('\n'):
243 if not payload.endswith('\n'):
244 tmpfp.write('\n')
244 tmpfp.write('\n')
245 elif not diffs_seen and message and content_type == 'text/plain':
245 elif not diffs_seen and message and content_type == 'text/plain':
246 message += '\n' + payload
246 message += '\n' + payload
247 except:
247 except:
248 tmpfp.close()
248 tmpfp.close()
249 os.unlink(tmpname)
249 os.unlink(tmpname)
250 raise
250 raise
251
251
252 if subject and not message.startswith(subject):
252 if subject and not message.startswith(subject):
253 message = '%s\n%s' % (subject, message)
253 message = '%s\n%s' % (subject, message)
254 tmpfp.close()
254 tmpfp.close()
255 if not diffs_seen:
255 if not diffs_seen:
256 os.unlink(tmpname)
256 os.unlink(tmpname)
257 return None, message, user, date, branch, None, None, None
257 return None, message, user, date, branch, None, None, None
258 p1 = parents and parents.pop(0) or None
258 p1 = parents and parents.pop(0) or None
259 p2 = parents and parents.pop(0) or None
259 p2 = parents and parents.pop(0) or None
260 return tmpname, message, user, date, branch, nodeid, p1, p2
260 return tmpname, message, user, date, branch, nodeid, p1, p2
261
261
262 class patchmeta(object):
262 class patchmeta(object):
263 """Patched file metadata
263 """Patched file metadata
264
264
265 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY
265 'op' is the performed operation within ADD, DELETE, RENAME, MODIFY
266 or COPY. 'path' is patched file path. 'oldpath' is set to the
266 or COPY. 'path' is patched file path. 'oldpath' is set to the
267 origin file when 'op' is either COPY or RENAME, None otherwise. If
267 origin file when 'op' is either COPY or RENAME, None otherwise. If
268 file mode is changed, 'mode' is a tuple (islink, isexec) where
268 file mode is changed, 'mode' is a tuple (islink, isexec) where
269 'islink' is True if the file is a symlink and 'isexec' is True if
269 'islink' is True if the file is a symlink and 'isexec' is True if
270 the file is executable. Otherwise, 'mode' is None.
270 the file is executable. Otherwise, 'mode' is None.
271 """
271 """
272 def __init__(self, path):
272 def __init__(self, path):
273 self.path = path
273 self.path = path
274 self.oldpath = None
274 self.oldpath = None
275 self.mode = None
275 self.mode = None
276 self.op = 'MODIFY'
276 self.op = 'MODIFY'
277 self.binary = False
277 self.binary = False
278
278
279 def setmode(self, mode):
279 def setmode(self, mode):
280 islink = mode & 020000
280 islink = mode & 020000
281 isexec = mode & 0100
281 isexec = mode & 0100
282 self.mode = (islink, isexec)
282 self.mode = (islink, isexec)
283
283
284 def __repr__(self):
284 def __repr__(self):
285 return "<patchmeta %s %r>" % (self.op, self.path)
285 return "<patchmeta %s %r>" % (self.op, self.path)
286
286
287 def readgitpatch(lr):
287 def readgitpatch(lr):
288 """extract git-style metadata about patches from <patchname>"""
288 """extract git-style metadata about patches from <patchname>"""
289
289
290 # Filter patch for git information
290 # Filter patch for git information
291 gp = None
291 gp = None
292 gitpatches = []
292 gitpatches = []
293 for line in lr:
293 for line in lr:
294 line = line.rstrip(' \r\n')
294 line = line.rstrip(' \r\n')
295 if line.startswith('diff --git'):
295 if line.startswith('diff --git'):
296 m = gitre.match(line)
296 m = gitre.match(line)
297 if m:
297 if m:
298 if gp:
298 if gp:
299 gitpatches.append(gp)
299 gitpatches.append(gp)
300 dst = m.group(2)
300 dst = m.group(2)
301 gp = patchmeta(dst)
301 gp = patchmeta(dst)
302 elif gp:
302 elif gp:
303 if line.startswith('--- '):
303 if line.startswith('--- '):
304 gitpatches.append(gp)
304 gitpatches.append(gp)
305 gp = None
305 gp = None
306 continue
306 continue
307 if line.startswith('rename from '):
307 if line.startswith('rename from '):
308 gp.op = 'RENAME'
308 gp.op = 'RENAME'
309 gp.oldpath = line[12:]
309 gp.oldpath = line[12:]
310 elif line.startswith('rename to '):
310 elif line.startswith('rename to '):
311 gp.path = line[10:]
311 gp.path = line[10:]
312 elif line.startswith('copy from '):
312 elif line.startswith('copy from '):
313 gp.op = 'COPY'
313 gp.op = 'COPY'
314 gp.oldpath = line[10:]
314 gp.oldpath = line[10:]
315 elif line.startswith('copy to '):
315 elif line.startswith('copy to '):
316 gp.path = line[8:]
316 gp.path = line[8:]
317 elif line.startswith('deleted file'):
317 elif line.startswith('deleted file'):
318 gp.op = 'DELETE'
318 gp.op = 'DELETE'
319 elif line.startswith('new file mode '):
319 elif line.startswith('new file mode '):
320 gp.op = 'ADD'
320 gp.op = 'ADD'
321 gp.setmode(int(line[-6:], 8))
321 gp.setmode(int(line[-6:], 8))
322 elif line.startswith('new mode '):
322 elif line.startswith('new mode '):
323 gp.setmode(int(line[-6:], 8))
323 gp.setmode(int(line[-6:], 8))
324 elif line.startswith('GIT binary patch'):
324 elif line.startswith('GIT binary patch'):
325 gp.binary = True
325 gp.binary = True
326 if gp:
326 if gp:
327 gitpatches.append(gp)
327 gitpatches.append(gp)
328
328
329 return gitpatches
329 return gitpatches
330
330
331 class linereader(object):
331 class linereader(object):
332 # simple class to allow pushing lines back into the input stream
332 # simple class to allow pushing lines back into the input stream
333 def __init__(self, fp):
333 def __init__(self, fp):
334 self.fp = fp
334 self.fp = fp
335 self.buf = []
335 self.buf = []
336
336
337 def push(self, line):
337 def push(self, line):
338 if line is not None:
338 if line is not None:
339 self.buf.append(line)
339 self.buf.append(line)
340
340
341 def readline(self):
341 def readline(self):
342 if self.buf:
342 if self.buf:
343 l = self.buf[0]
343 l = self.buf[0]
344 del self.buf[0]
344 del self.buf[0]
345 return l
345 return l
346 return self.fp.readline()
346 return self.fp.readline()
347
347
348 def __iter__(self):
348 def __iter__(self):
349 while True:
349 while True:
350 l = self.readline()
350 l = self.readline()
351 if not l:
351 if not l:
352 break
352 break
353 yield l
353 yield l
354
354
355 class abstractbackend(object):
355 class abstractbackend(object):
356 def __init__(self, ui):
356 def __init__(self, ui):
357 self.ui = ui
357 self.ui = ui
358
358
359 def getfile(self, fname):
359 def getfile(self, fname):
360 """Return target file data and flags as a (data, (islink,
360 """Return target file data and flags as a (data, (islink,
361 isexec)) tuple.
361 isexec)) tuple.
362 """
362 """
363 raise NotImplementedError
363 raise NotImplementedError
364
364
365 def setfile(self, fname, data, mode, copysource):
365 def setfile(self, fname, data, mode, copysource):
366 """Write data to target file fname and set its mode. mode is a
366 """Write data to target file fname and set its mode. mode is a
367 (islink, isexec) tuple. If data is None, the file content should
367 (islink, isexec) tuple. If data is None, the file content should
368 be left unchanged. If the file is modified after being copied,
368 be left unchanged. If the file is modified after being copied,
369 copysource is set to the original file name.
369 copysource is set to the original file name.
370 """
370 """
371 raise NotImplementedError
371 raise NotImplementedError
372
372
373 def unlink(self, fname):
373 def unlink(self, fname):
374 """Unlink target file."""
374 """Unlink target file."""
375 raise NotImplementedError
375 raise NotImplementedError
376
376
377 def writerej(self, fname, failed, total, lines):
377 def writerej(self, fname, failed, total, lines):
378 """Write rejected lines for fname. total is the number of hunks
378 """Write rejected lines for fname. total is the number of hunks
379 which failed to apply and total the total number of hunks for this
379 which failed to apply and total the total number of hunks for this
380 files.
380 files.
381 """
381 """
382 pass
382 pass
383
383
384 def exists(self, fname):
384 def exists(self, fname):
385 raise NotImplementedError
385 raise NotImplementedError
386
386
387 class fsbackend(abstractbackend):
387 class fsbackend(abstractbackend):
388 def __init__(self, ui, basedir):
388 def __init__(self, ui, basedir):
389 super(fsbackend, self).__init__(ui)
389 super(fsbackend, self).__init__(ui)
390 self.opener = scmutil.opener(basedir)
390 self.opener = scmutil.opener(basedir)
391
391
392 def _join(self, f):
392 def _join(self, f):
393 return os.path.join(self.opener.base, f)
393 return os.path.join(self.opener.base, f)
394
394
395 def getfile(self, fname):
395 def getfile(self, fname):
396 path = self._join(fname)
396 path = self._join(fname)
397 if os.path.islink(path):
397 if os.path.islink(path):
398 return (os.readlink(path), (True, False))
398 return (os.readlink(path), (True, False))
399 isexec = False
399 isexec = False
400 try:
400 try:
401 isexec = os.lstat(path).st_mode & 0100 != 0
401 isexec = os.lstat(path).st_mode & 0100 != 0
402 except OSError, e:
402 except OSError, e:
403 if e.errno != errno.ENOENT:
403 if e.errno != errno.ENOENT:
404 raise
404 raise
405 return (self.opener.read(fname), (False, isexec))
405 return (self.opener.read(fname), (False, isexec))
406
406
407 def setfile(self, fname, data, mode, copysource):
407 def setfile(self, fname, data, mode, copysource):
408 islink, isexec = mode
408 islink, isexec = mode
409 if data is None:
409 if data is None:
410 util.setflags(self._join(fname), islink, isexec)
410 util.setflags(self._join(fname), islink, isexec)
411 return
411 return
412 if islink:
412 if islink:
413 self.opener.symlink(data, fname)
413 self.opener.symlink(data, fname)
414 else:
414 else:
415 self.opener.write(fname, data)
415 self.opener.write(fname, data)
416 if isexec:
416 if isexec:
417 util.setflags(self._join(fname), False, True)
417 util.setflags(self._join(fname), False, True)
418
418
419 def unlink(self, fname):
419 def unlink(self, fname):
420 try:
420 try:
421 util.unlinkpath(self._join(fname))
421 util.unlinkpath(self._join(fname))
422 except OSError, inst:
422 except OSError, inst:
423 if inst.errno != errno.ENOENT:
423 if inst.errno != errno.ENOENT:
424 raise
424 raise
425
425
426 def writerej(self, fname, failed, total, lines):
426 def writerej(self, fname, failed, total, lines):
427 fname = fname + ".rej"
427 fname = fname + ".rej"
428 self.ui.warn(
428 self.ui.warn(
429 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
429 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
430 (failed, total, fname))
430 (failed, total, fname))
431 fp = self.opener(fname, 'w')
431 fp = self.opener(fname, 'w')
432 fp.writelines(lines)
432 fp.writelines(lines)
433 fp.close()
433 fp.close()
434
434
435 def exists(self, fname):
435 def exists(self, fname):
436 return os.path.lexists(self._join(fname))
436 return os.path.lexists(self._join(fname))
437
437
438 class workingbackend(fsbackend):
438 class workingbackend(fsbackend):
439 def __init__(self, ui, repo, similarity):
439 def __init__(self, ui, repo, similarity):
440 super(workingbackend, self).__init__(ui, repo.root)
440 super(workingbackend, self).__init__(ui, repo.root)
441 self.repo = repo
441 self.repo = repo
442 self.similarity = similarity
442 self.similarity = similarity
443 self.removed = set()
443 self.removed = set()
444 self.changed = set()
444 self.changed = set()
445 self.copied = []
445 self.copied = []
446
446
447 def _checkknown(self, fname):
447 def _checkknown(self, fname):
448 if self.repo.dirstate[fname] == '?' and self.exists(fname):
448 if self.repo.dirstate[fname] == '?' and self.exists(fname):
449 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
449 raise PatchError(_('cannot patch %s: file is not tracked') % fname)
450
450
451 def setfile(self, fname, data, mode, copysource):
451 def setfile(self, fname, data, mode, copysource):
452 self._checkknown(fname)
452 self._checkknown(fname)
453 super(workingbackend, self).setfile(fname, data, mode, copysource)
453 super(workingbackend, self).setfile(fname, data, mode, copysource)
454 if copysource is not None:
454 if copysource is not None:
455 self.copied.append((copysource, fname))
455 self.copied.append((copysource, fname))
456 self.changed.add(fname)
456 self.changed.add(fname)
457
457
458 def unlink(self, fname):
458 def unlink(self, fname):
459 self._checkknown(fname)
459 self._checkknown(fname)
460 super(workingbackend, self).unlink(fname)
460 super(workingbackend, self).unlink(fname)
461 self.removed.add(fname)
461 self.removed.add(fname)
462 self.changed.add(fname)
462 self.changed.add(fname)
463
463
464 def close(self):
464 def close(self):
465 wctx = self.repo[None]
465 wctx = self.repo[None]
466 addremoved = set(self.changed)
466 addremoved = set(self.changed)
467 for src, dst in self.copied:
467 for src, dst in self.copied:
468 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
468 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
469 addremoved.discard(src)
469 addremoved.discard(src)
470 if (not self.similarity) and self.removed:
470 if (not self.similarity) and self.removed:
471 wctx.forget(sorted(self.removed))
471 wctx.forget(sorted(self.removed))
472 if addremoved:
472 if addremoved:
473 cwd = self.repo.getcwd()
473 cwd = self.repo.getcwd()
474 if cwd:
474 if cwd:
475 addremoved = [util.pathto(self.repo.root, cwd, f)
475 addremoved = [util.pathto(self.repo.root, cwd, f)
476 for f in addremoved]
476 for f in addremoved]
477 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
477 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
478 return sorted(self.changed)
478 return sorted(self.changed)
479
479
480 class filestore(object):
480 class filestore(object):
481 def __init__(self):
481 def __init__(self):
482 self.opener = None
482 self.opener = None
483 self.files = {}
483 self.files = {}
484 self.created = 0
484 self.created = 0
485
485
486 def setfile(self, fname, data, mode):
486 def setfile(self, fname, data, mode):
487 if self.opener is None:
487 if self.opener is None:
488 root = tempfile.mkdtemp(prefix='hg-patch-')
488 root = tempfile.mkdtemp(prefix='hg-patch-')
489 self.opener = scmutil.opener(root)
489 self.opener = scmutil.opener(root)
490 # Avoid filename issues with these simple names
490 # Avoid filename issues with these simple names
491 fn = str(self.created)
491 fn = str(self.created)
492 self.opener.write(fn, data)
492 self.opener.write(fn, data)
493 self.created += 1
493 self.created += 1
494 self.files[fname] = (fn, mode)
494 self.files[fname] = (fn, mode)
495
495
496 def getfile(self, fname):
496 def getfile(self, fname):
497 if fname not in self.files:
497 if fname not in self.files:
498 raise IOError()
498 raise IOError()
499 fn, mode = self.files[fname]
499 fn, mode = self.files[fname]
500 return self.opener.read(fn), mode
500 return self.opener.read(fn), mode
501
501
502 def close(self):
502 def close(self):
503 if self.opener:
503 if self.opener:
504 shutil.rmtree(self.opener.base)
504 shutil.rmtree(self.opener.base)
505
505
506 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
506 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
507 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
507 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
508 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
508 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
509 eolmodes = ['strict', 'crlf', 'lf', 'auto']
509 eolmodes = ['strict', 'crlf', 'lf', 'auto']
510
510
511 class patchfile(object):
511 class patchfile(object):
512 def __init__(self, ui, fname, backend, store, mode, create, remove,
512 def __init__(self, ui, fname, backend, store, mode, create, remove,
513 eolmode='strict', copysource=None):
513 eolmode='strict', copysource=None):
514 self.fname = fname
514 self.fname = fname
515 self.eolmode = eolmode
515 self.eolmode = eolmode
516 self.eol = None
516 self.eol = None
517 self.backend = backend
517 self.backend = backend
518 self.ui = ui
518 self.ui = ui
519 self.lines = []
519 self.lines = []
520 self.exists = False
520 self.exists = False
521 self.missing = True
521 self.missing = True
522 self.mode = mode
522 self.mode = mode
523 self.copysource = copysource
523 self.copysource = copysource
524 self.create = create
524 self.create = create
525 self.remove = remove
525 self.remove = remove
526 try:
526 try:
527 if copysource is None:
527 if copysource is None:
528 data, mode = backend.getfile(fname)
528 data, mode = backend.getfile(fname)
529 self.exists = True
529 self.exists = True
530 else:
530 else:
531 data, mode = store.getfile(copysource)
531 data, mode = store.getfile(copysource)
532 self.exists = backend.exists(fname)
532 self.exists = backend.exists(fname)
533 self.missing = False
533 self.missing = False
534 if data:
534 if data:
535 self.lines = data.splitlines(True)
535 self.lines = data.splitlines(True)
536 if self.mode is None:
536 if self.mode is None:
537 self.mode = mode
537 self.mode = mode
538 if self.lines:
538 if self.lines:
539 # Normalize line endings
539 # Normalize line endings
540 if self.lines[0].endswith('\r\n'):
540 if self.lines[0].endswith('\r\n'):
541 self.eol = '\r\n'
541 self.eol = '\r\n'
542 elif self.lines[0].endswith('\n'):
542 elif self.lines[0].endswith('\n'):
543 self.eol = '\n'
543 self.eol = '\n'
544 if eolmode != 'strict':
544 if eolmode != 'strict':
545 nlines = []
545 nlines = []
546 for l in self.lines:
546 for l in self.lines:
547 if l.endswith('\r\n'):
547 if l.endswith('\r\n'):
548 l = l[:-2] + '\n'
548 l = l[:-2] + '\n'
549 nlines.append(l)
549 nlines.append(l)
550 self.lines = nlines
550 self.lines = nlines
551 except IOError:
551 except IOError:
552 if create:
552 if create:
553 self.missing = False
553 self.missing = False
554 if self.mode is None:
554 if self.mode is None:
555 self.mode = (False, False)
555 self.mode = (False, False)
556 if self.missing:
556 if self.missing:
557 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
557 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
558
558
559 self.hash = {}
559 self.hash = {}
560 self.dirty = 0
560 self.dirty = 0
561 self.offset = 0
561 self.offset = 0
562 self.skew = 0
562 self.skew = 0
563 self.rej = []
563 self.rej = []
564 self.fileprinted = False
564 self.fileprinted = False
565 self.printfile(False)
565 self.printfile(False)
566 self.hunks = 0
566 self.hunks = 0
567
567
568 def writelines(self, fname, lines, mode):
568 def writelines(self, fname, lines, mode):
569 if self.eolmode == 'auto':
569 if self.eolmode == 'auto':
570 eol = self.eol
570 eol = self.eol
571 elif self.eolmode == 'crlf':
571 elif self.eolmode == 'crlf':
572 eol = '\r\n'
572 eol = '\r\n'
573 else:
573 else:
574 eol = '\n'
574 eol = '\n'
575
575
576 if self.eolmode != 'strict' and eol and eol != '\n':
576 if self.eolmode != 'strict' and eol and eol != '\n':
577 rawlines = []
577 rawlines = []
578 for l in lines:
578 for l in lines:
579 if l and l[-1] == '\n':
579 if l and l[-1] == '\n':
580 l = l[:-1] + eol
580 l = l[:-1] + eol
581 rawlines.append(l)
581 rawlines.append(l)
582 lines = rawlines
582 lines = rawlines
583
583
584 self.backend.setfile(fname, ''.join(lines), mode, self.copysource)
584 self.backend.setfile(fname, ''.join(lines), mode, self.copysource)
585
585
586 def printfile(self, warn):
586 def printfile(self, warn):
587 if self.fileprinted:
587 if self.fileprinted:
588 return
588 return
589 if warn or self.ui.verbose:
589 if warn or self.ui.verbose:
590 self.fileprinted = True
590 self.fileprinted = True
591 s = _("patching file %s\n") % self.fname
591 s = _("patching file %s\n") % self.fname
592 if warn:
592 if warn:
593 self.ui.warn(s)
593 self.ui.warn(s)
594 else:
594 else:
595 self.ui.note(s)
595 self.ui.note(s)
596
596
597
597
598 def findlines(self, l, linenum):
598 def findlines(self, l, linenum):
599 # looks through the hash and finds candidate lines. The
599 # looks through the hash and finds candidate lines. The
600 # result is a list of line numbers sorted based on distance
600 # result is a list of line numbers sorted based on distance
601 # from linenum
601 # from linenum
602
602
603 cand = self.hash.get(l, [])
603 cand = self.hash.get(l, [])
604 if len(cand) > 1:
604 if len(cand) > 1:
605 # resort our list of potentials forward then back.
605 # resort our list of potentials forward then back.
606 cand.sort(key=lambda x: abs(x - linenum))
606 cand.sort(key=lambda x: abs(x - linenum))
607 return cand
607 return cand
608
608
609 def write_rej(self):
609 def write_rej(self):
610 # our rejects are a little different from patch(1). This always
610 # our rejects are a little different from patch(1). This always
611 # creates rejects in the same form as the original patch. A file
611 # creates rejects in the same form as the original patch. A file
612 # header is inserted so that you can run the reject through patch again
612 # header is inserted so that you can run the reject through patch again
613 # without having to type the filename.
613 # without having to type the filename.
614 if not self.rej:
614 if not self.rej:
615 return
615 return
616 base = os.path.basename(self.fname)
616 base = os.path.basename(self.fname)
617 lines = ["--- %s\n+++ %s\n" % (base, base)]
617 lines = ["--- %s\n+++ %s\n" % (base, base)]
618 for x in self.rej:
618 for x in self.rej:
619 for l in x.hunk:
619 for l in x.hunk:
620 lines.append(l)
620 lines.append(l)
621 if l[-1] != '\n':
621 if l[-1] != '\n':
622 lines.append("\n\ No newline at end of file\n")
622 lines.append("\n\ No newline at end of file\n")
623 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
623 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
624
624
625 def apply(self, h):
625 def apply(self, h):
626 if not h.complete():
626 if not h.complete():
627 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
627 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
628 (h.number, h.desc, len(h.a), h.lena, len(h.b),
628 (h.number, h.desc, len(h.a), h.lena, len(h.b),
629 h.lenb))
629 h.lenb))
630
630
631 self.hunks += 1
631 self.hunks += 1
632
632
633 if self.missing:
633 if self.missing:
634 self.rej.append(h)
634 self.rej.append(h)
635 return -1
635 return -1
636
636
637 if self.exists and self.create:
637 if self.exists and self.create:
638 if self.copysource:
638 if self.copysource:
639 self.ui.warn(_("cannot create %s: destination already "
639 self.ui.warn(_("cannot create %s: destination already "
640 "exists\n" % self.fname))
640 "exists\n" % self.fname))
641 else:
641 else:
642 self.ui.warn(_("file %s already exists\n") % self.fname)
642 self.ui.warn(_("file %s already exists\n") % self.fname)
643 self.rej.append(h)
643 self.rej.append(h)
644 return -1
644 return -1
645
645
646 if isinstance(h, binhunk):
646 if isinstance(h, binhunk):
647 if self.remove:
647 if self.remove:
648 self.backend.unlink(self.fname)
648 self.backend.unlink(self.fname)
649 else:
649 else:
650 self.lines[:] = h.new()
650 self.lines[:] = h.new()
651 self.offset += len(h.new())
651 self.offset += len(h.new())
652 self.dirty = True
652 self.dirty = True
653 return 0
653 return 0
654
654
655 horig = h
655 horig = h
656 if (self.eolmode in ('crlf', 'lf')
656 if (self.eolmode in ('crlf', 'lf')
657 or self.eolmode == 'auto' and self.eol):
657 or self.eolmode == 'auto' and self.eol):
658 # If new eols are going to be normalized, then normalize
658 # If new eols are going to be normalized, then normalize
659 # hunk data before patching. Otherwise, preserve input
659 # hunk data before patching. Otherwise, preserve input
660 # line-endings.
660 # line-endings.
661 h = h.getnormalized()
661 h = h.getnormalized()
662
662
663 # fast case first, no offsets, no fuzz
663 # fast case first, no offsets, no fuzz
664 old = h.old()
664 old = h.old()
665 # patch starts counting at 1 unless we are adding the file
665 # patch starts counting at 1 unless we are adding the file
666 if h.starta == 0:
666 if h.starta == 0:
667 start = 0
667 start = 0
668 else:
668 else:
669 start = h.starta + self.offset - 1
669 start = h.starta + self.offset - 1
670 orig_start = start
670 orig_start = start
671 # if there's skew we want to emit the "(offset %d lines)" even
671 # if there's skew we want to emit the "(offset %d lines)" even
672 # when the hunk cleanly applies at start + skew, so skip the
672 # when the hunk cleanly applies at start + skew, so skip the
673 # fast case code
673 # fast case code
674 if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0:
674 if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0:
675 if self.remove:
675 if self.remove:
676 self.backend.unlink(self.fname)
676 self.backend.unlink(self.fname)
677 else:
677 else:
678 self.lines[start : start + h.lena] = h.new()
678 self.lines[start : start + h.lena] = h.new()
679 self.offset += h.lenb - h.lena
679 self.offset += h.lenb - h.lena
680 self.dirty = True
680 self.dirty = True
681 return 0
681 return 0
682
682
683 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
683 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
684 self.hash = {}
684 self.hash = {}
685 for x, s in enumerate(self.lines):
685 for x, s in enumerate(self.lines):
686 self.hash.setdefault(s, []).append(x)
686 self.hash.setdefault(s, []).append(x)
687 if h.hunk[-1][0] != ' ':
687 if h.hunk[-1][0] != ' ':
688 # if the hunk tried to put something at the bottom of the file
688 # if the hunk tried to put something at the bottom of the file
689 # override the start line and use eof here
689 # override the start line and use eof here
690 search_start = len(self.lines)
690 search_start = len(self.lines)
691 else:
691 else:
692 search_start = orig_start + self.skew
692 search_start = orig_start + self.skew
693
693
694 for fuzzlen in xrange(3):
694 for fuzzlen in xrange(3):
695 for toponly in [True, False]:
695 for toponly in [True, False]:
696 old = h.old(fuzzlen, toponly)
696 old = h.old(fuzzlen, toponly)
697
697
698 cand = self.findlines(old[0][1:], search_start)
698 cand = self.findlines(old[0][1:], search_start)
699 for l in cand:
699 for l in cand:
700 if diffhelpers.testhunk(old, self.lines, l) == 0:
700 if diffhelpers.testhunk(old, self.lines, l) == 0:
701 newlines = h.new(fuzzlen, toponly)
701 newlines = h.new(fuzzlen, toponly)
702 self.lines[l : l + len(old)] = newlines
702 self.lines[l : l + len(old)] = newlines
703 self.offset += len(newlines) - len(old)
703 self.offset += len(newlines) - len(old)
704 self.skew = l - orig_start
704 self.skew = l - orig_start
705 self.dirty = True
705 self.dirty = True
706 offset = l - orig_start - fuzzlen
706 offset = l - orig_start - fuzzlen
707 if fuzzlen:
707 if fuzzlen:
708 msg = _("Hunk #%d succeeded at %d "
708 msg = _("Hunk #%d succeeded at %d "
709 "with fuzz %d "
709 "with fuzz %d "
710 "(offset %d lines).\n")
710 "(offset %d lines).\n")
711 self.printfile(True)
711 self.printfile(True)
712 self.ui.warn(msg %
712 self.ui.warn(msg %
713 (h.number, l + 1, fuzzlen, offset))
713 (h.number, l + 1, fuzzlen, offset))
714 else:
714 else:
715 msg = _("Hunk #%d succeeded at %d "
715 msg = _("Hunk #%d succeeded at %d "
716 "(offset %d lines).\n")
716 "(offset %d lines).\n")
717 self.ui.note(msg % (h.number, l + 1, offset))
717 self.ui.note(msg % (h.number, l + 1, offset))
718 return fuzzlen
718 return fuzzlen
719 self.printfile(True)
719 self.printfile(True)
720 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
720 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
721 self.rej.append(horig)
721 self.rej.append(horig)
722 return -1
722 return -1
723
723
724 def close(self):
724 def close(self):
725 if self.dirty:
725 if self.dirty:
726 self.writelines(self.fname, self.lines, self.mode)
726 self.writelines(self.fname, self.lines, self.mode)
727 self.write_rej()
727 self.write_rej()
728 return len(self.rej)
728 return len(self.rej)
729
729
730 class hunk(object):
730 class hunk(object):
731 def __init__(self, desc, num, lr, context):
731 def __init__(self, desc, num, lr, context):
732 self.number = num
732 self.number = num
733 self.desc = desc
733 self.desc = desc
734 self.hunk = [desc]
734 self.hunk = [desc]
735 self.a = []
735 self.a = []
736 self.b = []
736 self.b = []
737 self.starta = self.lena = None
737 self.starta = self.lena = None
738 self.startb = self.lenb = None
738 self.startb = self.lenb = None
739 if lr is not None:
739 if lr is not None:
740 if context:
740 if context:
741 self.read_context_hunk(lr)
741 self.read_context_hunk(lr)
742 else:
742 else:
743 self.read_unified_hunk(lr)
743 self.read_unified_hunk(lr)
744
744
745 def getnormalized(self):
745 def getnormalized(self):
746 """Return a copy with line endings normalized to LF."""
746 """Return a copy with line endings normalized to LF."""
747
747
748 def normalize(lines):
748 def normalize(lines):
749 nlines = []
749 nlines = []
750 for line in lines:
750 for line in lines:
751 if line.endswith('\r\n'):
751 if line.endswith('\r\n'):
752 line = line[:-2] + '\n'
752 line = line[:-2] + '\n'
753 nlines.append(line)
753 nlines.append(line)
754 return nlines
754 return nlines
755
755
756 # Dummy object, it is rebuilt manually
756 # Dummy object, it is rebuilt manually
757 nh = hunk(self.desc, self.number, None, None)
757 nh = hunk(self.desc, self.number, None, None)
758 nh.number = self.number
758 nh.number = self.number
759 nh.desc = self.desc
759 nh.desc = self.desc
760 nh.hunk = self.hunk
760 nh.hunk = self.hunk
761 nh.a = normalize(self.a)
761 nh.a = normalize(self.a)
762 nh.b = normalize(self.b)
762 nh.b = normalize(self.b)
763 nh.starta = self.starta
763 nh.starta = self.starta
764 nh.startb = self.startb
764 nh.startb = self.startb
765 nh.lena = self.lena
765 nh.lena = self.lena
766 nh.lenb = self.lenb
766 nh.lenb = self.lenb
767 return nh
767 return nh
768
768
769 def read_unified_hunk(self, lr):
769 def read_unified_hunk(self, lr):
770 m = unidesc.match(self.desc)
770 m = unidesc.match(self.desc)
771 if not m:
771 if not m:
772 raise PatchError(_("bad hunk #%d") % self.number)
772 raise PatchError(_("bad hunk #%d") % self.number)
773 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
773 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
774 if self.lena is None:
774 if self.lena is None:
775 self.lena = 1
775 self.lena = 1
776 else:
776 else:
777 self.lena = int(self.lena)
777 self.lena = int(self.lena)
778 if self.lenb is None:
778 if self.lenb is None:
779 self.lenb = 1
779 self.lenb = 1
780 else:
780 else:
781 self.lenb = int(self.lenb)
781 self.lenb = int(self.lenb)
782 self.starta = int(self.starta)
782 self.starta = int(self.starta)
783 self.startb = int(self.startb)
783 self.startb = int(self.startb)
784 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
784 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
785 # if we hit eof before finishing out the hunk, the last line will
785 # if we hit eof before finishing out the hunk, the last line will
786 # be zero length. Lets try to fix it up.
786 # be zero length. Lets try to fix it up.
787 while len(self.hunk[-1]) == 0:
787 while len(self.hunk[-1]) == 0:
788 del self.hunk[-1]
788 del self.hunk[-1]
789 del self.a[-1]
789 del self.a[-1]
790 del self.b[-1]
790 del self.b[-1]
791 self.lena -= 1
791 self.lena -= 1
792 self.lenb -= 1
792 self.lenb -= 1
793 self._fixnewline(lr)
793 self._fixnewline(lr)
794
794
795 def read_context_hunk(self, lr):
795 def read_context_hunk(self, lr):
796 self.desc = lr.readline()
796 self.desc = lr.readline()
797 m = contextdesc.match(self.desc)
797 m = contextdesc.match(self.desc)
798 if not m:
798 if not m:
799 raise PatchError(_("bad hunk #%d") % self.number)
799 raise PatchError(_("bad hunk #%d") % self.number)
800 foo, self.starta, foo2, aend, foo3 = m.groups()
800 foo, self.starta, foo2, aend, foo3 = m.groups()
801 self.starta = int(self.starta)
801 self.starta = int(self.starta)
802 if aend is None:
802 if aend is None:
803 aend = self.starta
803 aend = self.starta
804 self.lena = int(aend) - self.starta
804 self.lena = int(aend) - self.starta
805 if self.starta:
805 if self.starta:
806 self.lena += 1
806 self.lena += 1
807 for x in xrange(self.lena):
807 for x in xrange(self.lena):
808 l = lr.readline()
808 l = lr.readline()
809 if l.startswith('---'):
809 if l.startswith('---'):
810 # lines addition, old block is empty
810 # lines addition, old block is empty
811 lr.push(l)
811 lr.push(l)
812 break
812 break
813 s = l[2:]
813 s = l[2:]
814 if l.startswith('- ') or l.startswith('! '):
814 if l.startswith('- ') or l.startswith('! '):
815 u = '-' + s
815 u = '-' + s
816 elif l.startswith(' '):
816 elif l.startswith(' '):
817 u = ' ' + s
817 u = ' ' + s
818 else:
818 else:
819 raise PatchError(_("bad hunk #%d old text line %d") %
819 raise PatchError(_("bad hunk #%d old text line %d") %
820 (self.number, x))
820 (self.number, x))
821 self.a.append(u)
821 self.a.append(u)
822 self.hunk.append(u)
822 self.hunk.append(u)
823
823
824 l = lr.readline()
824 l = lr.readline()
825 if l.startswith('\ '):
825 if l.startswith('\ '):
826 s = self.a[-1][:-1]
826 s = self.a[-1][:-1]
827 self.a[-1] = s
827 self.a[-1] = s
828 self.hunk[-1] = s
828 self.hunk[-1] = s
829 l = lr.readline()
829 l = lr.readline()
830 m = contextdesc.match(l)
830 m = contextdesc.match(l)
831 if not m:
831 if not m:
832 raise PatchError(_("bad hunk #%d") % self.number)
832 raise PatchError(_("bad hunk #%d") % self.number)
833 foo, self.startb, foo2, bend, foo3 = m.groups()
833 foo, self.startb, foo2, bend, foo3 = m.groups()
834 self.startb = int(self.startb)
834 self.startb = int(self.startb)
835 if bend is None:
835 if bend is None:
836 bend = self.startb
836 bend = self.startb
837 self.lenb = int(bend) - self.startb
837 self.lenb = int(bend) - self.startb
838 if self.startb:
838 if self.startb:
839 self.lenb += 1
839 self.lenb += 1
840 hunki = 1
840 hunki = 1
841 for x in xrange(self.lenb):
841 for x in xrange(self.lenb):
842 l = lr.readline()
842 l = lr.readline()
843 if l.startswith('\ '):
843 if l.startswith('\ '):
844 # XXX: the only way to hit this is with an invalid line range.
844 # XXX: the only way to hit this is with an invalid line range.
845 # The no-eol marker is not counted in the line range, but I
845 # The no-eol marker is not counted in the line range, but I
846 # guess there are diff(1) out there which behave differently.
846 # guess there are diff(1) out there which behave differently.
847 s = self.b[-1][:-1]
847 s = self.b[-1][:-1]
848 self.b[-1] = s
848 self.b[-1] = s
849 self.hunk[hunki - 1] = s
849 self.hunk[hunki - 1] = s
850 continue
850 continue
851 if not l:
851 if not l:
852 # line deletions, new block is empty and we hit EOF
852 # line deletions, new block is empty and we hit EOF
853 lr.push(l)
853 lr.push(l)
854 break
854 break
855 s = l[2:]
855 s = l[2:]
856 if l.startswith('+ ') or l.startswith('! '):
856 if l.startswith('+ ') or l.startswith('! '):
857 u = '+' + s
857 u = '+' + s
858 elif l.startswith(' '):
858 elif l.startswith(' '):
859 u = ' ' + s
859 u = ' ' + s
860 elif len(self.b) == 0:
860 elif len(self.b) == 0:
861 # line deletions, new block is empty
861 # line deletions, new block is empty
862 lr.push(l)
862 lr.push(l)
863 break
863 break
864 else:
864 else:
865 raise PatchError(_("bad hunk #%d old text line %d") %
865 raise PatchError(_("bad hunk #%d old text line %d") %
866 (self.number, x))
866 (self.number, x))
867 self.b.append(s)
867 self.b.append(s)
868 while True:
868 while True:
869 if hunki >= len(self.hunk):
869 if hunki >= len(self.hunk):
870 h = ""
870 h = ""
871 else:
871 else:
872 h = self.hunk[hunki]
872 h = self.hunk[hunki]
873 hunki += 1
873 hunki += 1
874 if h == u:
874 if h == u:
875 break
875 break
876 elif h.startswith('-'):
876 elif h.startswith('-'):
877 continue
877 continue
878 else:
878 else:
879 self.hunk.insert(hunki - 1, u)
879 self.hunk.insert(hunki - 1, u)
880 break
880 break
881
881
882 if not self.a:
882 if not self.a:
883 # this happens when lines were only added to the hunk
883 # this happens when lines were only added to the hunk
884 for x in self.hunk:
884 for x in self.hunk:
885 if x.startswith('-') or x.startswith(' '):
885 if x.startswith('-') or x.startswith(' '):
886 self.a.append(x)
886 self.a.append(x)
887 if not self.b:
887 if not self.b:
888 # this happens when lines were only deleted from the hunk
888 # this happens when lines were only deleted from the hunk
889 for x in self.hunk:
889 for x in self.hunk:
890 if x.startswith('+') or x.startswith(' '):
890 if x.startswith('+') or x.startswith(' '):
891 self.b.append(x[1:])
891 self.b.append(x[1:])
892 # @@ -start,len +start,len @@
892 # @@ -start,len +start,len @@
893 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
893 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
894 self.startb, self.lenb)
894 self.startb, self.lenb)
895 self.hunk[0] = self.desc
895 self.hunk[0] = self.desc
896 self._fixnewline(lr)
896 self._fixnewline(lr)
897
897
898 def _fixnewline(self, lr):
898 def _fixnewline(self, lr):
899 l = lr.readline()
899 l = lr.readline()
900 if l.startswith('\ '):
900 if l.startswith('\ '):
901 diffhelpers.fix_newline(self.hunk, self.a, self.b)
901 diffhelpers.fix_newline(self.hunk, self.a, self.b)
902 else:
902 else:
903 lr.push(l)
903 lr.push(l)
904
904
905 def complete(self):
905 def complete(self):
906 return len(self.a) == self.lena and len(self.b) == self.lenb
906 return len(self.a) == self.lena and len(self.b) == self.lenb
907
907
908 def fuzzit(self, l, fuzz, toponly):
908 def fuzzit(self, l, fuzz, toponly):
909 # this removes context lines from the top and bottom of list 'l'. It
909 # this removes context lines from the top and bottom of list 'l'. It
910 # checks the hunk to make sure only context lines are removed, and then
910 # checks the hunk to make sure only context lines are removed, and then
911 # returns a new shortened list of lines.
911 # returns a new shortened list of lines.
912 fuzz = min(fuzz, len(l)-1)
912 fuzz = min(fuzz, len(l)-1)
913 if fuzz:
913 if fuzz:
914 top = 0
914 top = 0
915 bot = 0
915 bot = 0
916 hlen = len(self.hunk)
916 hlen = len(self.hunk)
917 for x in xrange(hlen - 1):
917 for x in xrange(hlen - 1):
918 # the hunk starts with the @@ line, so use x+1
918 # the hunk starts with the @@ line, so use x+1
919 if self.hunk[x + 1][0] == ' ':
919 if self.hunk[x + 1][0] == ' ':
920 top += 1
920 top += 1
921 else:
921 else:
922 break
922 break
923 if not toponly:
923 if not toponly:
924 for x in xrange(hlen - 1):
924 for x in xrange(hlen - 1):
925 if self.hunk[hlen - bot - 1][0] == ' ':
925 if self.hunk[hlen - bot - 1][0] == ' ':
926 bot += 1
926 bot += 1
927 else:
927 else:
928 break
928 break
929
929
930 # top and bot now count context in the hunk
930 # top and bot now count context in the hunk
931 # adjust them if either one is short
931 # adjust them if either one is short
932 context = max(top, bot, 3)
932 context = max(top, bot, 3)
933 if bot < context:
933 if bot < context:
934 bot = max(0, fuzz - (context - bot))
934 bot = max(0, fuzz - (context - bot))
935 else:
935 else:
936 bot = min(fuzz, bot)
936 bot = min(fuzz, bot)
937 if top < context:
937 if top < context:
938 top = max(0, fuzz - (context - top))
938 top = max(0, fuzz - (context - top))
939 else:
939 else:
940 top = min(fuzz, top)
940 top = min(fuzz, top)
941
941
942 return l[top:len(l)-bot]
942 return l[top:len(l)-bot]
943 return l
943 return l
944
944
945 def old(self, fuzz=0, toponly=False):
945 def old(self, fuzz=0, toponly=False):
946 return self.fuzzit(self.a, fuzz, toponly)
946 return self.fuzzit(self.a, fuzz, toponly)
947
947
948 def new(self, fuzz=0, toponly=False):
948 def new(self, fuzz=0, toponly=False):
949 return self.fuzzit(self.b, fuzz, toponly)
949 return self.fuzzit(self.b, fuzz, toponly)
950
950
951 class binhunk:
951 class binhunk:
952 'A binary patch file. Only understands literals so far.'
952 'A binary patch file. Only understands literals so far.'
953 def __init__(self, lr):
953 def __init__(self, lr):
954 self.text = None
954 self.text = None
955 self.hunk = ['GIT binary patch\n']
955 self.hunk = ['GIT binary patch\n']
956 self._read(lr)
956 self._read(lr)
957
957
958 def complete(self):
958 def complete(self):
959 return self.text is not None
959 return self.text is not None
960
960
961 def new(self):
961 def new(self):
962 return [self.text]
962 return [self.text]
963
963
964 def _read(self, lr):
964 def _read(self, lr):
965 line = lr.readline()
965 line = lr.readline()
966 self.hunk.append(line)
966 self.hunk.append(line)
967 while line and not line.startswith('literal '):
967 while line and not line.startswith('literal '):
968 line = lr.readline()
968 line = lr.readline()
969 self.hunk.append(line)
969 self.hunk.append(line)
970 if not line:
970 if not line:
971 raise PatchError(_('could not extract binary patch'))
971 raise PatchError(_('could not extract binary patch'))
972 size = int(line[8:].rstrip())
972 size = int(line[8:].rstrip())
973 dec = []
973 dec = []
974 line = lr.readline()
974 line = lr.readline()
975 self.hunk.append(line)
975 self.hunk.append(line)
976 while len(line) > 1:
976 while len(line) > 1:
977 l = line[0]
977 l = line[0]
978 if l <= 'Z' and l >= 'A':
978 if l <= 'Z' and l >= 'A':
979 l = ord(l) - ord('A') + 1
979 l = ord(l) - ord('A') + 1
980 else:
980 else:
981 l = ord(l) - ord('a') + 27
981 l = ord(l) - ord('a') + 27
982 dec.append(base85.b85decode(line[1:-1])[:l])
982 dec.append(base85.b85decode(line[1:-1])[:l])
983 line = lr.readline()
983 line = lr.readline()
984 self.hunk.append(line)
984 self.hunk.append(line)
985 text = zlib.decompress(''.join(dec))
985 text = zlib.decompress(''.join(dec))
986 if len(text) != size:
986 if len(text) != size:
987 raise PatchError(_('binary patch is %d bytes, not %d') %
987 raise PatchError(_('binary patch is %d bytes, not %d') %
988 len(text), size)
988 len(text), size)
989 self.text = text
989 self.text = text
990
990
991 def parsefilename(str):
991 def parsefilename(str):
992 # --- filename \t|space stuff
992 # --- filename \t|space stuff
993 s = str[4:].rstrip('\r\n')
993 s = str[4:].rstrip('\r\n')
994 i = s.find('\t')
994 i = s.find('\t')
995 if i < 0:
995 if i < 0:
996 i = s.find(' ')
996 i = s.find(' ')
997 if i < 0:
997 if i < 0:
998 return s
998 return s
999 return s[:i]
999 return s[:i]
1000
1000
1001 def pathstrip(path, strip):
1001 def pathstrip(path, strip):
1002 pathlen = len(path)
1002 pathlen = len(path)
1003 i = 0
1003 i = 0
1004 if strip == 0:
1004 if strip == 0:
1005 return '', path.rstrip()
1005 return '', path.rstrip()
1006 count = strip
1006 count = strip
1007 while count > 0:
1007 while count > 0:
1008 i = path.find('/', i)
1008 i = path.find('/', i)
1009 if i == -1:
1009 if i == -1:
1010 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1010 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1011 (count, strip, path))
1011 (count, strip, path))
1012 i += 1
1012 i += 1
1013 # consume '//' in the path
1013 # consume '//' in the path
1014 while i < pathlen - 1 and path[i] == '/':
1014 while i < pathlen - 1 and path[i] == '/':
1015 i += 1
1015 i += 1
1016 count -= 1
1016 count -= 1
1017 return path[:i].lstrip(), path[i:].rstrip()
1017 return path[:i].lstrip(), path[i:].rstrip()
1018
1018
1019 def selectfile(backend, afile_orig, bfile_orig, hunk, strip, gp):
1019 def selectfile(backend, afile_orig, bfile_orig, hunk, strip, gp):
1020 if gp:
1020 if gp:
1021 # Git patches do not play games. Excluding copies from the
1021 # Git patches do not play games. Excluding copies from the
1022 # following heuristic avoids a lot of confusion
1022 # following heuristic avoids a lot of confusion
1023 fname = pathstrip(gp.path, strip - 1)[1]
1023 fname = pathstrip(gp.path, strip - 1)[1]
1024 create = gp.op in ('ADD', 'COPY', 'RENAME')
1024 create = gp.op in ('ADD', 'COPY', 'RENAME')
1025 remove = gp.op == 'DELETE'
1025 remove = gp.op == 'DELETE'
1026 return fname, create, remove
1026 return fname, create, remove
1027 nulla = afile_orig == "/dev/null"
1027 nulla = afile_orig == "/dev/null"
1028 nullb = bfile_orig == "/dev/null"
1028 nullb = bfile_orig == "/dev/null"
1029 create = nulla and hunk.starta == 0 and hunk.lena == 0
1029 create = nulla and hunk.starta == 0 and hunk.lena == 0
1030 remove = nullb and hunk.startb == 0 and hunk.lenb == 0
1030 remove = nullb and hunk.startb == 0 and hunk.lenb == 0
1031 abase, afile = pathstrip(afile_orig, strip)
1031 abase, afile = pathstrip(afile_orig, strip)
1032 gooda = not nulla and backend.exists(afile)
1032 gooda = not nulla and backend.exists(afile)
1033 bbase, bfile = pathstrip(bfile_orig, strip)
1033 bbase, bfile = pathstrip(bfile_orig, strip)
1034 if afile == bfile:
1034 if afile == bfile:
1035 goodb = gooda
1035 goodb = gooda
1036 else:
1036 else:
1037 goodb = not nullb and backend.exists(bfile)
1037 goodb = not nullb and backend.exists(bfile)
1038 missing = not goodb and not gooda and not create
1038 missing = not goodb and not gooda and not create
1039
1039
1040 # some diff programs apparently produce patches where the afile is
1040 # some diff programs apparently produce patches where the afile is
1041 # not /dev/null, but afile starts with bfile
1041 # not /dev/null, but afile starts with bfile
1042 abasedir = afile[:afile.rfind('/') + 1]
1042 abasedir = afile[:afile.rfind('/') + 1]
1043 bbasedir = bfile[:bfile.rfind('/') + 1]
1043 bbasedir = bfile[:bfile.rfind('/') + 1]
1044 if (missing and abasedir == bbasedir and afile.startswith(bfile)
1044 if (missing and abasedir == bbasedir and afile.startswith(bfile)
1045 and hunk.starta == 0 and hunk.lena == 0):
1045 and hunk.starta == 0 and hunk.lena == 0):
1046 create = True
1046 create = True
1047 missing = False
1047 missing = False
1048
1048
1049 # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the
1049 # If afile is "a/b/foo" and bfile is "a/b/foo.orig" we assume the
1050 # diff is between a file and its backup. In this case, the original
1050 # diff is between a file and its backup. In this case, the original
1051 # file should be patched (see original mpatch code).
1051 # file should be patched (see original mpatch code).
1052 isbackup = (abase == bbase and bfile.startswith(afile))
1052 isbackup = (abase == bbase and bfile.startswith(afile))
1053 fname = None
1053 fname = None
1054 if not missing:
1054 if not missing:
1055 if gooda and goodb:
1055 if gooda and goodb:
1056 fname = isbackup and afile or bfile
1056 fname = isbackup and afile or bfile
1057 elif gooda:
1057 elif gooda:
1058 fname = afile
1058 fname = afile
1059
1059
1060 if not fname:
1060 if not fname:
1061 if not nullb:
1061 if not nullb:
1062 fname = isbackup and afile or bfile
1062 fname = isbackup and afile or bfile
1063 elif not nulla:
1063 elif not nulla:
1064 fname = afile
1064 fname = afile
1065 else:
1065 else:
1066 raise PatchError(_("undefined source and destination files"))
1066 raise PatchError(_("undefined source and destination files"))
1067
1067
1068 return fname, create, remove
1068 return fname, create, remove
1069
1069
1070 def scangitpatch(lr, firstline):
1070 def scangitpatch(lr, firstline):
1071 """
1071 """
1072 Git patches can emit:
1072 Git patches can emit:
1073 - rename a to b
1073 - rename a to b
1074 - change b
1074 - change b
1075 - copy a to c
1075 - copy a to c
1076 - change c
1076 - change c
1077
1077
1078 We cannot apply this sequence as-is, the renamed 'a' could not be
1078 We cannot apply this sequence as-is, the renamed 'a' could not be
1079 found for it would have been renamed already. And we cannot copy
1079 found for it would have been renamed already. And we cannot copy
1080 from 'b' instead because 'b' would have been changed already. So
1080 from 'b' instead because 'b' would have been changed already. So
1081 we scan the git patch for copy and rename commands so we can
1081 we scan the git patch for copy and rename commands so we can
1082 perform the copies ahead of time.
1082 perform the copies ahead of time.
1083 """
1083 """
1084 pos = 0
1084 pos = 0
1085 try:
1085 try:
1086 pos = lr.fp.tell()
1086 pos = lr.fp.tell()
1087 fp = lr.fp
1087 fp = lr.fp
1088 except IOError:
1088 except IOError:
1089 fp = cStringIO.StringIO(lr.fp.read())
1089 fp = cStringIO.StringIO(lr.fp.read())
1090 gitlr = linereader(fp)
1090 gitlr = linereader(fp)
1091 gitlr.push(firstline)
1091 gitlr.push(firstline)
1092 gitpatches = readgitpatch(gitlr)
1092 gitpatches = readgitpatch(gitlr)
1093 fp.seek(pos)
1093 fp.seek(pos)
1094 return gitpatches
1094 return gitpatches
1095
1095
1096 def iterhunks(fp):
1096 def iterhunks(fp):
1097 """Read a patch and yield the following events:
1097 """Read a patch and yield the following events:
1098 - ("file", afile, bfile, firsthunk): select a new target file.
1098 - ("file", afile, bfile, firsthunk): select a new target file.
1099 - ("hunk", hunk): a new hunk is ready to be applied, follows a
1099 - ("hunk", hunk): a new hunk is ready to be applied, follows a
1100 "file" event.
1100 "file" event.
1101 - ("git", gitchanges): current diff is in git format, gitchanges
1101 - ("git", gitchanges): current diff is in git format, gitchanges
1102 maps filenames to gitpatch records. Unique event.
1102 maps filenames to gitpatch records. Unique event.
1103 """
1103 """
1104 afile = ""
1104 afile = ""
1105 bfile = ""
1105 bfile = ""
1106 state = None
1106 state = None
1107 hunknum = 0
1107 hunknum = 0
1108 emitfile = newfile = False
1108 emitfile = newfile = False
1109 gitpatches = None
1109 gitpatches = None
1110
1110
1111 # our states
1111 # our states
1112 BFILE = 1
1112 BFILE = 1
1113 context = None
1113 context = None
1114 lr = linereader(fp)
1114 lr = linereader(fp)
1115
1115
1116 while True:
1116 while True:
1117 x = lr.readline()
1117 x = lr.readline()
1118 if not x:
1118 if not x:
1119 break
1119 break
1120 if state == BFILE and (
1120 if state == BFILE and (
1121 (not context and x[0] == '@')
1121 (not context and x[0] == '@')
1122 or (context is not False and x.startswith('***************'))
1122 or (context is not False and x.startswith('***************'))
1123 or x.startswith('GIT binary patch')):
1123 or x.startswith('GIT binary patch')):
1124 gp = None
1124 gp = None
1125 if (gitpatches and
1125 if (gitpatches and
1126 (gitpatches[-1][0] == afile or gitpatches[-1][1] == bfile)):
1126 (gitpatches[-1][0] == afile or gitpatches[-1][1] == bfile)):
1127 gp = gitpatches.pop()[2]
1127 gp = gitpatches.pop()[2]
1128 if x.startswith('GIT binary patch'):
1128 if x.startswith('GIT binary patch'):
1129 h = binhunk(lr)
1129 h = binhunk(lr)
1130 else:
1130 else:
1131 if context is None and x.startswith('***************'):
1131 if context is None and x.startswith('***************'):
1132 context = True
1132 context = True
1133 h = hunk(x, hunknum + 1, lr, context)
1133 h = hunk(x, hunknum + 1, lr, context)
1134 hunknum += 1
1134 hunknum += 1
1135 if emitfile:
1135 if emitfile:
1136 emitfile = False
1136 emitfile = False
1137 yield 'file', (afile, bfile, h, gp)
1137 yield 'file', (afile, bfile, h, gp)
1138 yield 'hunk', h
1138 yield 'hunk', h
1139 elif x.startswith('diff --git'):
1139 elif x.startswith('diff --git'):
1140 m = gitre.match(x)
1140 m = gitre.match(x)
1141 if not m:
1141 if not m:
1142 continue
1142 continue
1143 if gitpatches is None:
1143 if gitpatches is None:
1144 # scan whole input for git metadata
1144 # scan whole input for git metadata
1145 gitpatches = [('a/' + gp.path, 'b/' + gp.path, gp) for gp
1145 gitpatches = [('a/' + gp.path, 'b/' + gp.path, gp) for gp
1146 in scangitpatch(lr, x)]
1146 in scangitpatch(lr, x)]
1147 yield 'git', [g[2] for g in gitpatches
1147 yield 'git', [g[2] for g in gitpatches
1148 if g[2].op in ('COPY', 'RENAME')]
1148 if g[2].op in ('COPY', 'RENAME')]
1149 gitpatches.reverse()
1149 gitpatches.reverse()
1150 afile = 'a/' + m.group(1)
1150 afile = 'a/' + m.group(1)
1151 bfile = 'b/' + m.group(2)
1151 bfile = 'b/' + m.group(2)
1152 while afile != gitpatches[-1][0] and bfile != gitpatches[-1][1]:
1152 while afile != gitpatches[-1][0] and bfile != gitpatches[-1][1]:
1153 gp = gitpatches.pop()[2]
1153 gp = gitpatches.pop()[2]
1154 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1154 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1155 gp = gitpatches[-1][2]
1155 gp = gitpatches[-1][2]
1156 # copy/rename + modify should modify target, not source
1156 # copy/rename + modify should modify target, not source
1157 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1157 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1158 afile = bfile
1158 afile = bfile
1159 newfile = True
1159 newfile = True
1160 elif x.startswith('---'):
1160 elif x.startswith('---'):
1161 # check for a unified diff
1161 # check for a unified diff
1162 l2 = lr.readline()
1162 l2 = lr.readline()
1163 if not l2.startswith('+++'):
1163 if not l2.startswith('+++'):
1164 lr.push(l2)
1164 lr.push(l2)
1165 continue
1165 continue
1166 newfile = True
1166 newfile = True
1167 context = False
1167 context = False
1168 afile = parsefilename(x)
1168 afile = parsefilename(x)
1169 bfile = parsefilename(l2)
1169 bfile = parsefilename(l2)
1170 elif x.startswith('***'):
1170 elif x.startswith('***'):
1171 # check for a context diff
1171 # check for a context diff
1172 l2 = lr.readline()
1172 l2 = lr.readline()
1173 if not l2.startswith('---'):
1173 if not l2.startswith('---'):
1174 lr.push(l2)
1174 lr.push(l2)
1175 continue
1175 continue
1176 l3 = lr.readline()
1176 l3 = lr.readline()
1177 lr.push(l3)
1177 lr.push(l3)
1178 if not l3.startswith("***************"):
1178 if not l3.startswith("***************"):
1179 lr.push(l2)
1179 lr.push(l2)
1180 continue
1180 continue
1181 newfile = True
1181 newfile = True
1182 context = True
1182 context = True
1183 afile = parsefilename(x)
1183 afile = parsefilename(x)
1184 bfile = parsefilename(l2)
1184 bfile = parsefilename(l2)
1185
1185
1186 if newfile:
1186 if newfile:
1187 newfile = False
1187 newfile = False
1188 emitfile = True
1188 emitfile = True
1189 state = BFILE
1189 state = BFILE
1190 hunknum = 0
1190 hunknum = 0
1191
1191
1192 while gitpatches:
1192 while gitpatches:
1193 gp = gitpatches.pop()[2]
1193 gp = gitpatches.pop()[2]
1194 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1194 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1195
1195
1196 def applydiff(ui, fp, changed, backend, store, strip=1, eolmode='strict'):
1196 def applydiff(ui, fp, changed, backend, store, strip=1, eolmode='strict'):
1197 """Reads a patch from fp and tries to apply it.
1197 """Reads a patch from fp and tries to apply it.
1198
1198
1199 The dict 'changed' is filled in with all of the filenames changed
1199 The dict 'changed' is filled in with all of the filenames changed
1200 by the patch. Returns 0 for a clean patch, -1 if any rejects were
1200 by the patch. Returns 0 for a clean patch, -1 if any rejects were
1201 found and 1 if there was any fuzz.
1201 found and 1 if there was any fuzz.
1202
1202
1203 If 'eolmode' is 'strict', the patch content and patched file are
1203 If 'eolmode' is 'strict', the patch content and patched file are
1204 read in binary mode. Otherwise, line endings are ignored when
1204 read in binary mode. Otherwise, line endings are ignored when
1205 patching then normalized according to 'eolmode'.
1205 patching then normalized according to 'eolmode'.
1206 """
1206 """
1207 return _applydiff(ui, fp, patchfile, backend, store, changed, strip=strip,
1207 return _applydiff(ui, fp, patchfile, backend, store, changed, strip=strip,
1208 eolmode=eolmode)
1208 eolmode=eolmode)
1209
1209
1210 def _applydiff(ui, fp, patcher, backend, store, changed, strip=1,
1210 def _applydiff(ui, fp, patcher, backend, store, changed, strip=1,
1211 eolmode='strict'):
1211 eolmode='strict'):
1212
1212
1213 def pstrip(p):
1213 def pstrip(p):
1214 return pathstrip(p, strip - 1)[1]
1214 return pathstrip(p, strip - 1)[1]
1215
1215
1216 rejects = 0
1216 rejects = 0
1217 err = 0
1217 err = 0
1218 current_file = None
1218 current_file = None
1219
1219
1220 for state, values in iterhunks(fp):
1220 for state, values in iterhunks(fp):
1221 if state == 'hunk':
1221 if state == 'hunk':
1222 if not current_file:
1222 if not current_file:
1223 continue
1223 continue
1224 ret = current_file.apply(values)
1224 ret = current_file.apply(values)
1225 if ret >= 0:
1225 if ret >= 0:
1226 changed.setdefault(current_file.fname, None)
1226 changed.add(current_file.fname)
1227 if ret > 0:
1227 if ret > 0:
1228 err = 1
1228 err = 1
1229 elif state == 'file':
1229 elif state == 'file':
1230 if current_file:
1230 if current_file:
1231 rejects += current_file.close()
1231 rejects += current_file.close()
1232 current_file = None
1232 current_file = None
1233 afile, bfile, first_hunk, gp = values
1233 afile, bfile, first_hunk, gp = values
1234 copysource = None
1234 copysource = None
1235 if gp:
1235 if gp:
1236 path = pstrip(gp.path)
1236 path = pstrip(gp.path)
1237 if gp.oldpath:
1237 if gp.oldpath:
1238 copysource = pstrip(gp.oldpath)
1238 copysource = pstrip(gp.oldpath)
1239 changed[path] = gp
1239 changed.add(path)
1240 if gp.op == 'RENAME':
1240 if gp.op == 'RENAME':
1241 backend.unlink(copysource)
1241 backend.unlink(copysource)
1242 if not first_hunk:
1242 if not first_hunk:
1243 if gp.op == 'DELETE':
1243 if gp.op == 'DELETE':
1244 backend.unlink(path)
1244 backend.unlink(path)
1245 continue
1245 continue
1246 data, mode = None, None
1246 data, mode = None, None
1247 if gp.op in ('RENAME', 'COPY'):
1247 if gp.op in ('RENAME', 'COPY'):
1248 data, mode = store.getfile(copysource)
1248 data, mode = store.getfile(copysource)
1249 if gp.mode:
1249 if gp.mode:
1250 mode = gp.mode
1250 mode = gp.mode
1251 if gp.op == 'ADD':
1251 if gp.op == 'ADD':
1252 # Added files without content have no hunk and
1252 # Added files without content have no hunk and
1253 # must be created
1253 # must be created
1254 data = ''
1254 data = ''
1255 if data or mode:
1255 if data or mode:
1256 if (gp.op in ('ADD', 'RENAME', 'COPY')
1256 if (gp.op in ('ADD', 'RENAME', 'COPY')
1257 and backend.exists(path)):
1257 and backend.exists(path)):
1258 raise PatchError(_("cannot create %s: destination "
1258 raise PatchError(_("cannot create %s: destination "
1259 "already exists") % path)
1259 "already exists") % path)
1260 backend.setfile(path, data, mode, copysource)
1260 backend.setfile(path, data, mode, copysource)
1261 if not first_hunk:
1261 if not first_hunk:
1262 continue
1262 continue
1263 try:
1263 try:
1264 mode = gp and gp.mode or None
1264 mode = gp and gp.mode or None
1265 current_file, create, remove = selectfile(
1265 current_file, create, remove = selectfile(
1266 backend, afile, bfile, first_hunk, strip, gp)
1266 backend, afile, bfile, first_hunk, strip, gp)
1267 current_file = patcher(ui, current_file, backend, store, mode,
1267 current_file = patcher(ui, current_file, backend, store, mode,
1268 create, remove, eolmode=eolmode,
1268 create, remove, eolmode=eolmode,
1269 copysource=copysource)
1269 copysource=copysource)
1270 except PatchError, inst:
1270 except PatchError, inst:
1271 ui.warn(str(inst) + '\n')
1271 ui.warn(str(inst) + '\n')
1272 current_file = None
1272 current_file = None
1273 rejects += 1
1273 rejects += 1
1274 continue
1274 continue
1275 elif state == 'git':
1275 elif state == 'git':
1276 for gp in values:
1276 for gp in values:
1277 path = pstrip(gp.oldpath)
1277 path = pstrip(gp.oldpath)
1278 data, mode = backend.getfile(path)
1278 data, mode = backend.getfile(path)
1279 store.setfile(path, data, mode)
1279 store.setfile(path, data, mode)
1280 else:
1280 else:
1281 raise util.Abort(_('unsupported parser state: %s') % state)
1281 raise util.Abort(_('unsupported parser state: %s') % state)
1282
1282
1283 if current_file:
1283 if current_file:
1284 rejects += current_file.close()
1284 rejects += current_file.close()
1285
1285
1286 if rejects:
1286 if rejects:
1287 return -1
1287 return -1
1288 return err
1288 return err
1289
1289
1290 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1290 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1291 similarity):
1291 similarity):
1292 """use <patcher> to apply <patchname> to the working directory.
1292 """use <patcher> to apply <patchname> to the working directory.
1293 returns whether patch was applied with fuzz factor."""
1293 returns whether patch was applied with fuzz factor."""
1294
1294
1295 fuzz = False
1295 fuzz = False
1296 args = []
1296 args = []
1297 cwd = repo.root
1297 cwd = repo.root
1298 if cwd:
1298 if cwd:
1299 args.append('-d %s' % util.shellquote(cwd))
1299 args.append('-d %s' % util.shellquote(cwd))
1300 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1300 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1301 util.shellquote(patchname)))
1301 util.shellquote(patchname)))
1302 try:
1302 try:
1303 for line in fp:
1303 for line in fp:
1304 line = line.rstrip()
1304 line = line.rstrip()
1305 ui.note(line + '\n')
1305 ui.note(line + '\n')
1306 if line.startswith('patching file '):
1306 if line.startswith('patching file '):
1307 pf = util.parsepatchoutput(line)
1307 pf = util.parsepatchoutput(line)
1308 printed_file = False
1308 printed_file = False
1309 files.setdefault(pf, None)
1309 files.add(pf)
1310 elif line.find('with fuzz') >= 0:
1310 elif line.find('with fuzz') >= 0:
1311 fuzz = True
1311 fuzz = True
1312 if not printed_file:
1312 if not printed_file:
1313 ui.warn(pf + '\n')
1313 ui.warn(pf + '\n')
1314 printed_file = True
1314 printed_file = True
1315 ui.warn(line + '\n')
1315 ui.warn(line + '\n')
1316 elif line.find('saving rejects to file') >= 0:
1316 elif line.find('saving rejects to file') >= 0:
1317 ui.warn(line + '\n')
1317 ui.warn(line + '\n')
1318 elif line.find('FAILED') >= 0:
1318 elif line.find('FAILED') >= 0:
1319 if not printed_file:
1319 if not printed_file:
1320 ui.warn(pf + '\n')
1320 ui.warn(pf + '\n')
1321 printed_file = True
1321 printed_file = True
1322 ui.warn(line + '\n')
1322 ui.warn(line + '\n')
1323 finally:
1323 finally:
1324 if files:
1324 if files:
1325 cfiles = list(files)
1325 cfiles = list(files)
1326 cwd = repo.getcwd()
1326 cwd = repo.getcwd()
1327 if cwd:
1327 if cwd:
1328 cfiles = [util.pathto(repo.root, cwd, f)
1328 cfiles = [util.pathto(repo.root, cwd, f)
1329 for f in cfile]
1329 for f in cfile]
1330 scmutil.addremove(repo, cfiles, similarity=similarity)
1330 scmutil.addremove(repo, cfiles, similarity=similarity)
1331 code = fp.close()
1331 code = fp.close()
1332 if code:
1332 if code:
1333 raise PatchError(_("patch command failed: %s") %
1333 raise PatchError(_("patch command failed: %s") %
1334 util.explainexit(code)[0])
1334 util.explainexit(code)[0])
1335 return fuzz
1335 return fuzz
1336
1336
1337 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1337 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1338 similarity=0):
1338 similarity=0):
1339 """use builtin patch to apply <patchobj> to the working directory.
1339 """use builtin patch to apply <patchobj> to the working directory.
1340 returns whether patch was applied with fuzz factor."""
1340 returns whether patch was applied with fuzz factor."""
1341
1341
1342 if files is None:
1342 if files is None:
1343 files = {}
1343 files = set()
1344 if eolmode is None:
1344 if eolmode is None:
1345 eolmode = ui.config('patch', 'eol', 'strict')
1345 eolmode = ui.config('patch', 'eol', 'strict')
1346 if eolmode.lower() not in eolmodes:
1346 if eolmode.lower() not in eolmodes:
1347 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1347 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1348 eolmode = eolmode.lower()
1348 eolmode = eolmode.lower()
1349
1349
1350 store = filestore()
1350 store = filestore()
1351 backend = workingbackend(ui, repo, similarity)
1351 backend = workingbackend(ui, repo, similarity)
1352 try:
1352 try:
1353 fp = open(patchobj, 'rb')
1353 fp = open(patchobj, 'rb')
1354 except TypeError:
1354 except TypeError:
1355 fp = patchobj
1355 fp = patchobj
1356 try:
1356 try:
1357 ret = applydiff(ui, fp, files, backend, store, strip=strip,
1357 ret = applydiff(ui, fp, files, backend, store, strip=strip,
1358 eolmode=eolmode)
1358 eolmode=eolmode)
1359 finally:
1359 finally:
1360 if fp != patchobj:
1360 if fp != patchobj:
1361 fp.close()
1361 fp.close()
1362 files.update(dict.fromkeys(backend.close()))
1362 files.update(backend.close())
1363 store.close()
1363 store.close()
1364 if ret < 0:
1364 if ret < 0:
1365 raise PatchError(_('patch failed to apply'))
1365 raise PatchError(_('patch failed to apply'))
1366 return ret > 0
1366 return ret > 0
1367
1367
1368 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1368 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1369 similarity=0):
1369 similarity=0):
1370 """Apply <patchname> to the working directory.
1370 """Apply <patchname> to the working directory.
1371
1371
1372 'eolmode' specifies how end of lines should be handled. It can be:
1372 'eolmode' specifies how end of lines should be handled. It can be:
1373 - 'strict': inputs are read in binary mode, EOLs are preserved
1373 - 'strict': inputs are read in binary mode, EOLs are preserved
1374 - 'crlf': EOLs are ignored when patching and reset to CRLF
1374 - 'crlf': EOLs are ignored when patching and reset to CRLF
1375 - 'lf': EOLs are ignored when patching and reset to LF
1375 - 'lf': EOLs are ignored when patching and reset to LF
1376 - None: get it from user settings, default to 'strict'
1376 - None: get it from user settings, default to 'strict'
1377 'eolmode' is ignored when using an external patcher program.
1377 'eolmode' is ignored when using an external patcher program.
1378
1378
1379 Returns whether patch was applied with fuzz factor.
1379 Returns whether patch was applied with fuzz factor.
1380 """
1380 """
1381 patcher = ui.config('ui', 'patch')
1381 patcher = ui.config('ui', 'patch')
1382 if files is None:
1382 if files is None:
1383 files = {}
1383 files = set()
1384 try:
1384 try:
1385 if patcher:
1385 if patcher:
1386 return _externalpatch(ui, repo, patcher, patchname, strip,
1386 return _externalpatch(ui, repo, patcher, patchname, strip,
1387 files, similarity)
1387 files, similarity)
1388 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1388 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1389 similarity)
1389 similarity)
1390 except PatchError, err:
1390 except PatchError, err:
1391 raise util.Abort(str(err))
1391 raise util.Abort(str(err))
1392
1392
1393 def changedfiles(ui, repo, patchpath, strip=1):
1393 def changedfiles(ui, repo, patchpath, strip=1):
1394 backend = fsbackend(ui, repo.root)
1394 backend = fsbackend(ui, repo.root)
1395 fp = open(patchpath, 'rb')
1395 fp = open(patchpath, 'rb')
1396 try:
1396 try:
1397 changed = set()
1397 changed = set()
1398 for state, values in iterhunks(fp):
1398 for state, values in iterhunks(fp):
1399 if state == 'file':
1399 if state == 'file':
1400 afile, bfile, first_hunk, gp = values
1400 afile, bfile, first_hunk, gp = values
1401 if gp:
1401 if gp:
1402 changed.add(pathstrip(gp.path, strip - 1)[1])
1402 changed.add(pathstrip(gp.path, strip - 1)[1])
1403 if gp.op == 'RENAME':
1403 if gp.op == 'RENAME':
1404 changed.add(pathstrip(gp.oldpath, strip - 1)[1])
1404 changed.add(pathstrip(gp.oldpath, strip - 1)[1])
1405 if not first_hunk:
1405 if not first_hunk:
1406 continue
1406 continue
1407 current_file, create, remove = selectfile(
1407 current_file, create, remove = selectfile(
1408 backend, afile, bfile, first_hunk, strip, gp)
1408 backend, afile, bfile, first_hunk, strip, gp)
1409 changed.add(current_file)
1409 changed.add(current_file)
1410 elif state not in ('hunk', 'git'):
1410 elif state not in ('hunk', 'git'):
1411 raise util.Abort(_('unsupported parser state: %s') % state)
1411 raise util.Abort(_('unsupported parser state: %s') % state)
1412 return changed
1412 return changed
1413 finally:
1413 finally:
1414 fp.close()
1414 fp.close()
1415
1415
1416 def b85diff(to, tn):
1416 def b85diff(to, tn):
1417 '''print base85-encoded binary diff'''
1417 '''print base85-encoded binary diff'''
1418 def gitindex(text):
1418 def gitindex(text):
1419 if not text:
1419 if not text:
1420 return hex(nullid)
1420 return hex(nullid)
1421 l = len(text)
1421 l = len(text)
1422 s = util.sha1('blob %d\0' % l)
1422 s = util.sha1('blob %d\0' % l)
1423 s.update(text)
1423 s.update(text)
1424 return s.hexdigest()
1424 return s.hexdigest()
1425
1425
1426 def fmtline(line):
1426 def fmtline(line):
1427 l = len(line)
1427 l = len(line)
1428 if l <= 26:
1428 if l <= 26:
1429 l = chr(ord('A') + l - 1)
1429 l = chr(ord('A') + l - 1)
1430 else:
1430 else:
1431 l = chr(l - 26 + ord('a') - 1)
1431 l = chr(l - 26 + ord('a') - 1)
1432 return '%c%s\n' % (l, base85.b85encode(line, True))
1432 return '%c%s\n' % (l, base85.b85encode(line, True))
1433
1433
1434 def chunk(text, csize=52):
1434 def chunk(text, csize=52):
1435 l = len(text)
1435 l = len(text)
1436 i = 0
1436 i = 0
1437 while i < l:
1437 while i < l:
1438 yield text[i:i + csize]
1438 yield text[i:i + csize]
1439 i += csize
1439 i += csize
1440
1440
1441 tohash = gitindex(to)
1441 tohash = gitindex(to)
1442 tnhash = gitindex(tn)
1442 tnhash = gitindex(tn)
1443 if tohash == tnhash:
1443 if tohash == tnhash:
1444 return ""
1444 return ""
1445
1445
1446 # TODO: deltas
1446 # TODO: deltas
1447 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1447 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1448 (tohash, tnhash, len(tn))]
1448 (tohash, tnhash, len(tn))]
1449 for l in chunk(zlib.compress(tn)):
1449 for l in chunk(zlib.compress(tn)):
1450 ret.append(fmtline(l))
1450 ret.append(fmtline(l))
1451 ret.append('\n')
1451 ret.append('\n')
1452 return ''.join(ret)
1452 return ''.join(ret)
1453
1453
1454 class GitDiffRequired(Exception):
1454 class GitDiffRequired(Exception):
1455 pass
1455 pass
1456
1456
1457 def diffopts(ui, opts=None, untrusted=False):
1457 def diffopts(ui, opts=None, untrusted=False):
1458 def get(key, name=None, getter=ui.configbool):
1458 def get(key, name=None, getter=ui.configbool):
1459 return ((opts and opts.get(key)) or
1459 return ((opts and opts.get(key)) or
1460 getter('diff', name or key, None, untrusted=untrusted))
1460 getter('diff', name or key, None, untrusted=untrusted))
1461 return mdiff.diffopts(
1461 return mdiff.diffopts(
1462 text=opts and opts.get('text'),
1462 text=opts and opts.get('text'),
1463 git=get('git'),
1463 git=get('git'),
1464 nodates=get('nodates'),
1464 nodates=get('nodates'),
1465 showfunc=get('show_function', 'showfunc'),
1465 showfunc=get('show_function', 'showfunc'),
1466 ignorews=get('ignore_all_space', 'ignorews'),
1466 ignorews=get('ignore_all_space', 'ignorews'),
1467 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1467 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1468 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1468 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1469 context=get('unified', getter=ui.config))
1469 context=get('unified', getter=ui.config))
1470
1470
1471 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1471 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1472 losedatafn=None, prefix=''):
1472 losedatafn=None, prefix=''):
1473 '''yields diff of changes to files between two nodes, or node and
1473 '''yields diff of changes to files between two nodes, or node and
1474 working directory.
1474 working directory.
1475
1475
1476 if node1 is None, use first dirstate parent instead.
1476 if node1 is None, use first dirstate parent instead.
1477 if node2 is None, compare node1 with working directory.
1477 if node2 is None, compare node1 with working directory.
1478
1478
1479 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1479 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1480 every time some change cannot be represented with the current
1480 every time some change cannot be represented with the current
1481 patch format. Return False to upgrade to git patch format, True to
1481 patch format. Return False to upgrade to git patch format, True to
1482 accept the loss or raise an exception to abort the diff. It is
1482 accept the loss or raise an exception to abort the diff. It is
1483 called with the name of current file being diffed as 'fn'. If set
1483 called with the name of current file being diffed as 'fn'. If set
1484 to None, patches will always be upgraded to git format when
1484 to None, patches will always be upgraded to git format when
1485 necessary.
1485 necessary.
1486
1486
1487 prefix is a filename prefix that is prepended to all filenames on
1487 prefix is a filename prefix that is prepended to all filenames on
1488 display (used for subrepos).
1488 display (used for subrepos).
1489 '''
1489 '''
1490
1490
1491 if opts is None:
1491 if opts is None:
1492 opts = mdiff.defaultopts
1492 opts = mdiff.defaultopts
1493
1493
1494 if not node1 and not node2:
1494 if not node1 and not node2:
1495 node1 = repo.dirstate.p1()
1495 node1 = repo.dirstate.p1()
1496
1496
1497 def lrugetfilectx():
1497 def lrugetfilectx():
1498 cache = {}
1498 cache = {}
1499 order = []
1499 order = []
1500 def getfilectx(f, ctx):
1500 def getfilectx(f, ctx):
1501 fctx = ctx.filectx(f, filelog=cache.get(f))
1501 fctx = ctx.filectx(f, filelog=cache.get(f))
1502 if f not in cache:
1502 if f not in cache:
1503 if len(cache) > 20:
1503 if len(cache) > 20:
1504 del cache[order.pop(0)]
1504 del cache[order.pop(0)]
1505 cache[f] = fctx.filelog()
1505 cache[f] = fctx.filelog()
1506 else:
1506 else:
1507 order.remove(f)
1507 order.remove(f)
1508 order.append(f)
1508 order.append(f)
1509 return fctx
1509 return fctx
1510 return getfilectx
1510 return getfilectx
1511 getfilectx = lrugetfilectx()
1511 getfilectx = lrugetfilectx()
1512
1512
1513 ctx1 = repo[node1]
1513 ctx1 = repo[node1]
1514 ctx2 = repo[node2]
1514 ctx2 = repo[node2]
1515
1515
1516 if not changes:
1516 if not changes:
1517 changes = repo.status(ctx1, ctx2, match=match)
1517 changes = repo.status(ctx1, ctx2, match=match)
1518 modified, added, removed = changes[:3]
1518 modified, added, removed = changes[:3]
1519
1519
1520 if not modified and not added and not removed:
1520 if not modified and not added and not removed:
1521 return []
1521 return []
1522
1522
1523 revs = None
1523 revs = None
1524 if not repo.ui.quiet:
1524 if not repo.ui.quiet:
1525 hexfunc = repo.ui.debugflag and hex or short
1525 hexfunc = repo.ui.debugflag and hex or short
1526 revs = [hexfunc(node) for node in [node1, node2] if node]
1526 revs = [hexfunc(node) for node in [node1, node2] if node]
1527
1527
1528 copy = {}
1528 copy = {}
1529 if opts.git or opts.upgrade:
1529 if opts.git or opts.upgrade:
1530 copy = copies.copies(repo, ctx1, ctx2, repo[nullid])[0]
1530 copy = copies.copies(repo, ctx1, ctx2, repo[nullid])[0]
1531
1531
1532 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1532 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1533 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1533 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1534 if opts.upgrade and not opts.git:
1534 if opts.upgrade and not opts.git:
1535 try:
1535 try:
1536 def losedata(fn):
1536 def losedata(fn):
1537 if not losedatafn or not losedatafn(fn=fn):
1537 if not losedatafn or not losedatafn(fn=fn):
1538 raise GitDiffRequired()
1538 raise GitDiffRequired()
1539 # Buffer the whole output until we are sure it can be generated
1539 # Buffer the whole output until we are sure it can be generated
1540 return list(difffn(opts.copy(git=False), losedata))
1540 return list(difffn(opts.copy(git=False), losedata))
1541 except GitDiffRequired:
1541 except GitDiffRequired:
1542 return difffn(opts.copy(git=True), None)
1542 return difffn(opts.copy(git=True), None)
1543 else:
1543 else:
1544 return difffn(opts, None)
1544 return difffn(opts, None)
1545
1545
1546 def difflabel(func, *args, **kw):
1546 def difflabel(func, *args, **kw):
1547 '''yields 2-tuples of (output, label) based on the output of func()'''
1547 '''yields 2-tuples of (output, label) based on the output of func()'''
1548 prefixes = [('diff', 'diff.diffline'),
1548 prefixes = [('diff', 'diff.diffline'),
1549 ('copy', 'diff.extended'),
1549 ('copy', 'diff.extended'),
1550 ('rename', 'diff.extended'),
1550 ('rename', 'diff.extended'),
1551 ('old', 'diff.extended'),
1551 ('old', 'diff.extended'),
1552 ('new', 'diff.extended'),
1552 ('new', 'diff.extended'),
1553 ('deleted', 'diff.extended'),
1553 ('deleted', 'diff.extended'),
1554 ('---', 'diff.file_a'),
1554 ('---', 'diff.file_a'),
1555 ('+++', 'diff.file_b'),
1555 ('+++', 'diff.file_b'),
1556 ('@@', 'diff.hunk'),
1556 ('@@', 'diff.hunk'),
1557 ('-', 'diff.deleted'),
1557 ('-', 'diff.deleted'),
1558 ('+', 'diff.inserted')]
1558 ('+', 'diff.inserted')]
1559
1559
1560 for chunk in func(*args, **kw):
1560 for chunk in func(*args, **kw):
1561 lines = chunk.split('\n')
1561 lines = chunk.split('\n')
1562 for i, line in enumerate(lines):
1562 for i, line in enumerate(lines):
1563 if i != 0:
1563 if i != 0:
1564 yield ('\n', '')
1564 yield ('\n', '')
1565 stripline = line
1565 stripline = line
1566 if line and line[0] in '+-':
1566 if line and line[0] in '+-':
1567 # highlight trailing whitespace, but only in changed lines
1567 # highlight trailing whitespace, but only in changed lines
1568 stripline = line.rstrip()
1568 stripline = line.rstrip()
1569 for prefix, label in prefixes:
1569 for prefix, label in prefixes:
1570 if stripline.startswith(prefix):
1570 if stripline.startswith(prefix):
1571 yield (stripline, label)
1571 yield (stripline, label)
1572 break
1572 break
1573 else:
1573 else:
1574 yield (line, '')
1574 yield (line, '')
1575 if line != stripline:
1575 if line != stripline:
1576 yield (line[len(stripline):], 'diff.trailingwhitespace')
1576 yield (line[len(stripline):], 'diff.trailingwhitespace')
1577
1577
1578 def diffui(*args, **kw):
1578 def diffui(*args, **kw):
1579 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1579 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1580 return difflabel(diff, *args, **kw)
1580 return difflabel(diff, *args, **kw)
1581
1581
1582
1582
1583 def _addmodehdr(header, omode, nmode):
1583 def _addmodehdr(header, omode, nmode):
1584 if omode != nmode:
1584 if omode != nmode:
1585 header.append('old mode %s\n' % omode)
1585 header.append('old mode %s\n' % omode)
1586 header.append('new mode %s\n' % nmode)
1586 header.append('new mode %s\n' % nmode)
1587
1587
1588 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1588 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1589 copy, getfilectx, opts, losedatafn, prefix):
1589 copy, getfilectx, opts, losedatafn, prefix):
1590
1590
1591 def join(f):
1591 def join(f):
1592 return os.path.join(prefix, f)
1592 return os.path.join(prefix, f)
1593
1593
1594 date1 = util.datestr(ctx1.date())
1594 date1 = util.datestr(ctx1.date())
1595 man1 = ctx1.manifest()
1595 man1 = ctx1.manifest()
1596
1596
1597 gone = set()
1597 gone = set()
1598 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1598 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1599
1599
1600 copyto = dict([(v, k) for k, v in copy.items()])
1600 copyto = dict([(v, k) for k, v in copy.items()])
1601
1601
1602 if opts.git:
1602 if opts.git:
1603 revs = None
1603 revs = None
1604
1604
1605 for f in sorted(modified + added + removed):
1605 for f in sorted(modified + added + removed):
1606 to = None
1606 to = None
1607 tn = None
1607 tn = None
1608 dodiff = True
1608 dodiff = True
1609 header = []
1609 header = []
1610 if f in man1:
1610 if f in man1:
1611 to = getfilectx(f, ctx1).data()
1611 to = getfilectx(f, ctx1).data()
1612 if f not in removed:
1612 if f not in removed:
1613 tn = getfilectx(f, ctx2).data()
1613 tn = getfilectx(f, ctx2).data()
1614 a, b = f, f
1614 a, b = f, f
1615 if opts.git or losedatafn:
1615 if opts.git or losedatafn:
1616 if f in added:
1616 if f in added:
1617 mode = gitmode[ctx2.flags(f)]
1617 mode = gitmode[ctx2.flags(f)]
1618 if f in copy or f in copyto:
1618 if f in copy or f in copyto:
1619 if opts.git:
1619 if opts.git:
1620 if f in copy:
1620 if f in copy:
1621 a = copy[f]
1621 a = copy[f]
1622 else:
1622 else:
1623 a = copyto[f]
1623 a = copyto[f]
1624 omode = gitmode[man1.flags(a)]
1624 omode = gitmode[man1.flags(a)]
1625 _addmodehdr(header, omode, mode)
1625 _addmodehdr(header, omode, mode)
1626 if a in removed and a not in gone:
1626 if a in removed and a not in gone:
1627 op = 'rename'
1627 op = 'rename'
1628 gone.add(a)
1628 gone.add(a)
1629 else:
1629 else:
1630 op = 'copy'
1630 op = 'copy'
1631 header.append('%s from %s\n' % (op, join(a)))
1631 header.append('%s from %s\n' % (op, join(a)))
1632 header.append('%s to %s\n' % (op, join(f)))
1632 header.append('%s to %s\n' % (op, join(f)))
1633 to = getfilectx(a, ctx1).data()
1633 to = getfilectx(a, ctx1).data()
1634 else:
1634 else:
1635 losedatafn(f)
1635 losedatafn(f)
1636 else:
1636 else:
1637 if opts.git:
1637 if opts.git:
1638 header.append('new file mode %s\n' % mode)
1638 header.append('new file mode %s\n' % mode)
1639 elif ctx2.flags(f):
1639 elif ctx2.flags(f):
1640 losedatafn(f)
1640 losedatafn(f)
1641 # In theory, if tn was copied or renamed we should check
1641 # In theory, if tn was copied or renamed we should check
1642 # if the source is binary too but the copy record already
1642 # if the source is binary too but the copy record already
1643 # forces git mode.
1643 # forces git mode.
1644 if util.binary(tn):
1644 if util.binary(tn):
1645 if opts.git:
1645 if opts.git:
1646 dodiff = 'binary'
1646 dodiff = 'binary'
1647 else:
1647 else:
1648 losedatafn(f)
1648 losedatafn(f)
1649 if not opts.git and not tn:
1649 if not opts.git and not tn:
1650 # regular diffs cannot represent new empty file
1650 # regular diffs cannot represent new empty file
1651 losedatafn(f)
1651 losedatafn(f)
1652 elif f in removed:
1652 elif f in removed:
1653 if opts.git:
1653 if opts.git:
1654 # have we already reported a copy above?
1654 # have we already reported a copy above?
1655 if ((f in copy and copy[f] in added
1655 if ((f in copy and copy[f] in added
1656 and copyto[copy[f]] == f) or
1656 and copyto[copy[f]] == f) or
1657 (f in copyto and copyto[f] in added
1657 (f in copyto and copyto[f] in added
1658 and copy[copyto[f]] == f)):
1658 and copy[copyto[f]] == f)):
1659 dodiff = False
1659 dodiff = False
1660 else:
1660 else:
1661 header.append('deleted file mode %s\n' %
1661 header.append('deleted file mode %s\n' %
1662 gitmode[man1.flags(f)])
1662 gitmode[man1.flags(f)])
1663 elif not to or util.binary(to):
1663 elif not to or util.binary(to):
1664 # regular diffs cannot represent empty file deletion
1664 # regular diffs cannot represent empty file deletion
1665 losedatafn(f)
1665 losedatafn(f)
1666 else:
1666 else:
1667 oflag = man1.flags(f)
1667 oflag = man1.flags(f)
1668 nflag = ctx2.flags(f)
1668 nflag = ctx2.flags(f)
1669 binary = util.binary(to) or util.binary(tn)
1669 binary = util.binary(to) or util.binary(tn)
1670 if opts.git:
1670 if opts.git:
1671 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1671 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1672 if binary:
1672 if binary:
1673 dodiff = 'binary'
1673 dodiff = 'binary'
1674 elif binary or nflag != oflag:
1674 elif binary or nflag != oflag:
1675 losedatafn(f)
1675 losedatafn(f)
1676 if opts.git:
1676 if opts.git:
1677 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1677 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1678
1678
1679 if dodiff:
1679 if dodiff:
1680 if dodiff == 'binary':
1680 if dodiff == 'binary':
1681 text = b85diff(to, tn)
1681 text = b85diff(to, tn)
1682 else:
1682 else:
1683 text = mdiff.unidiff(to, date1,
1683 text = mdiff.unidiff(to, date1,
1684 # ctx2 date may be dynamic
1684 # ctx2 date may be dynamic
1685 tn, util.datestr(ctx2.date()),
1685 tn, util.datestr(ctx2.date()),
1686 join(a), join(b), revs, opts=opts)
1686 join(a), join(b), revs, opts=opts)
1687 if header and (text or len(header) > 1):
1687 if header and (text or len(header) > 1):
1688 yield ''.join(header)
1688 yield ''.join(header)
1689 if text:
1689 if text:
1690 yield text
1690 yield text
1691
1691
1692 def diffstatsum(stats):
1692 def diffstatsum(stats):
1693 maxfile, maxtotal, addtotal, removetotal, binary = 0, 0, 0, 0, False
1693 maxfile, maxtotal, addtotal, removetotal, binary = 0, 0, 0, 0, False
1694 for f, a, r, b in stats:
1694 for f, a, r, b in stats:
1695 maxfile = max(maxfile, encoding.colwidth(f))
1695 maxfile = max(maxfile, encoding.colwidth(f))
1696 maxtotal = max(maxtotal, a + r)
1696 maxtotal = max(maxtotal, a + r)
1697 addtotal += a
1697 addtotal += a
1698 removetotal += r
1698 removetotal += r
1699 binary = binary or b
1699 binary = binary or b
1700
1700
1701 return maxfile, maxtotal, addtotal, removetotal, binary
1701 return maxfile, maxtotal, addtotal, removetotal, binary
1702
1702
1703 def diffstatdata(lines):
1703 def diffstatdata(lines):
1704 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1704 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1705
1705
1706 results = []
1706 results = []
1707 filename, adds, removes = None, 0, 0
1707 filename, adds, removes = None, 0, 0
1708
1708
1709 def addresult():
1709 def addresult():
1710 if filename:
1710 if filename:
1711 isbinary = adds == 0 and removes == 0
1711 isbinary = adds == 0 and removes == 0
1712 results.append((filename, adds, removes, isbinary))
1712 results.append((filename, adds, removes, isbinary))
1713
1713
1714 for line in lines:
1714 for line in lines:
1715 if line.startswith('diff'):
1715 if line.startswith('diff'):
1716 addresult()
1716 addresult()
1717 # set numbers to 0 anyway when starting new file
1717 # set numbers to 0 anyway when starting new file
1718 adds, removes = 0, 0
1718 adds, removes = 0, 0
1719 if line.startswith('diff --git'):
1719 if line.startswith('diff --git'):
1720 filename = gitre.search(line).group(1)
1720 filename = gitre.search(line).group(1)
1721 elif line.startswith('diff -r'):
1721 elif line.startswith('diff -r'):
1722 # format: "diff -r ... -r ... filename"
1722 # format: "diff -r ... -r ... filename"
1723 filename = diffre.search(line).group(1)
1723 filename = diffre.search(line).group(1)
1724 elif line.startswith('+') and not line.startswith('+++'):
1724 elif line.startswith('+') and not line.startswith('+++'):
1725 adds += 1
1725 adds += 1
1726 elif line.startswith('-') and not line.startswith('---'):
1726 elif line.startswith('-') and not line.startswith('---'):
1727 removes += 1
1727 removes += 1
1728 addresult()
1728 addresult()
1729 return results
1729 return results
1730
1730
1731 def diffstat(lines, width=80, git=False):
1731 def diffstat(lines, width=80, git=False):
1732 output = []
1732 output = []
1733 stats = diffstatdata(lines)
1733 stats = diffstatdata(lines)
1734 maxname, maxtotal, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1734 maxname, maxtotal, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1735
1735
1736 countwidth = len(str(maxtotal))
1736 countwidth = len(str(maxtotal))
1737 if hasbinary and countwidth < 3:
1737 if hasbinary and countwidth < 3:
1738 countwidth = 3
1738 countwidth = 3
1739 graphwidth = width - countwidth - maxname - 6
1739 graphwidth = width - countwidth - maxname - 6
1740 if graphwidth < 10:
1740 if graphwidth < 10:
1741 graphwidth = 10
1741 graphwidth = 10
1742
1742
1743 def scale(i):
1743 def scale(i):
1744 if maxtotal <= graphwidth:
1744 if maxtotal <= graphwidth:
1745 return i
1745 return i
1746 # If diffstat runs out of room it doesn't print anything,
1746 # If diffstat runs out of room it doesn't print anything,
1747 # which isn't very useful, so always print at least one + or -
1747 # which isn't very useful, so always print at least one + or -
1748 # if there were at least some changes.
1748 # if there were at least some changes.
1749 return max(i * graphwidth // maxtotal, int(bool(i)))
1749 return max(i * graphwidth // maxtotal, int(bool(i)))
1750
1750
1751 for filename, adds, removes, isbinary in stats:
1751 for filename, adds, removes, isbinary in stats:
1752 if git and isbinary:
1752 if git and isbinary:
1753 count = 'Bin'
1753 count = 'Bin'
1754 else:
1754 else:
1755 count = adds + removes
1755 count = adds + removes
1756 pluses = '+' * scale(adds)
1756 pluses = '+' * scale(adds)
1757 minuses = '-' * scale(removes)
1757 minuses = '-' * scale(removes)
1758 output.append(' %s%s | %*s %s%s\n' %
1758 output.append(' %s%s | %*s %s%s\n' %
1759 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1759 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1760 countwidth, count, pluses, minuses))
1760 countwidth, count, pluses, minuses))
1761
1761
1762 if stats:
1762 if stats:
1763 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1763 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1764 % (len(stats), totaladds, totalremoves))
1764 % (len(stats), totaladds, totalremoves))
1765
1765
1766 return ''.join(output)
1766 return ''.join(output)
1767
1767
1768 def diffstatui(*args, **kw):
1768 def diffstatui(*args, **kw):
1769 '''like diffstat(), but yields 2-tuples of (output, label) for
1769 '''like diffstat(), but yields 2-tuples of (output, label) for
1770 ui.write()
1770 ui.write()
1771 '''
1771 '''
1772
1772
1773 for line in diffstat(*args, **kw).splitlines():
1773 for line in diffstat(*args, **kw).splitlines():
1774 if line and line[-1] in '+-':
1774 if line and line[-1] in '+-':
1775 name, graph = line.rsplit(' ', 1)
1775 name, graph = line.rsplit(' ', 1)
1776 yield (name + ' ', '')
1776 yield (name + ' ', '')
1777 m = re.search(r'\++', graph)
1777 m = re.search(r'\++', graph)
1778 if m:
1778 if m:
1779 yield (m.group(0), 'diffstat.inserted')
1779 yield (m.group(0), 'diffstat.inserted')
1780 m = re.search(r'-+', graph)
1780 m = re.search(r'-+', graph)
1781 if m:
1781 if m:
1782 yield (m.group(0), 'diffstat.deleted')
1782 yield (m.group(0), 'diffstat.deleted')
1783 else:
1783 else:
1784 yield (line, '')
1784 yield (line, '')
1785 yield ('\n', '')
1785 yield ('\n', '')
General Comments 0
You need to be logged in to leave comments. Login now