##// END OF EJS Templates
context: make forget work like commands.forget...
Matt Mackall -
r14435:5f6090e5 default
parent child Browse files
Show More
@@ -1,3296 +1,3295 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, exactneg[0]
458 return False, 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, exactpos[0]
463 return True, exactpos[0]
464 return False, pos
464 return False, 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 %r\n') %
482 write(_('allowing %s - guarded by %r\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 %r\n') %
486 write(_('skipping %s - guarded by %r\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 = {}
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].remove(patches, True)
738 r[None].forget(patches)
739 else:
740 for p in patches:
739 for p in patches:
741 os.unlink(self.join(p))
740 os.unlink(self.join(p))
742
741
743 if numrevs:
742 if numrevs:
744 qfinished = self.applied[:numrevs]
743 qfinished = self.applied[:numrevs]
745 del self.applied[:numrevs]
744 del self.applied[:numrevs]
746 self.applied_dirty = 1
745 self.applied_dirty = 1
747
746
748 unknown = []
747 unknown = []
749
748
750 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],
751 reverse=True):
750 reverse=True):
752 if i is not None:
751 if i is not None:
753 del self.full_series[i]
752 del self.full_series[i]
754 else:
753 else:
755 unknown.append(p)
754 unknown.append(p)
756
755
757 if unknown:
756 if unknown:
758 if numrevs:
757 if numrevs:
759 rev = dict((entry.name, entry.node) for entry in qfinished)
758 rev = dict((entry.name, entry.node) for entry in qfinished)
760 for p in unknown:
759 for p in unknown:
761 msg = _('revision %s refers to unknown patches: %s\n')
760 msg = _('revision %s refers to unknown patches: %s\n')
762 self.ui.warn(msg % (short(rev[p]), p))
761 self.ui.warn(msg % (short(rev[p]), p))
763 else:
762 else:
764 msg = _('unknown patches: %s\n')
763 msg = _('unknown patches: %s\n')
765 raise util.Abort(''.join(msg % p for p in unknown))
764 raise util.Abort(''.join(msg % p for p in unknown))
766
765
767 self.parse_series()
766 self.parse_series()
768 self.series_dirty = 1
767 self.series_dirty = 1
769
768
770 def _revpatches(self, repo, revs):
769 def _revpatches(self, repo, revs):
771 firstrev = repo[self.applied[0].node].rev()
770 firstrev = repo[self.applied[0].node].rev()
772 patches = []
771 patches = []
773 for i, rev in enumerate(revs):
772 for i, rev in enumerate(revs):
774
773
775 if rev < firstrev:
774 if rev < firstrev:
776 raise util.Abort(_('revision %d is not managed') % rev)
775 raise util.Abort(_('revision %d is not managed') % rev)
777
776
778 ctx = repo[rev]
777 ctx = repo[rev]
779 base = self.applied[i].node
778 base = self.applied[i].node
780 if ctx.node() != base:
779 if ctx.node() != base:
781 msg = _('cannot delete revision %d above applied patches')
780 msg = _('cannot delete revision %d above applied patches')
782 raise util.Abort(msg % rev)
781 raise util.Abort(msg % rev)
783
782
784 patch = self.applied[i].name
783 patch = self.applied[i].name
785 for fmt in ('[mq]: %s', 'imported patch %s'):
784 for fmt in ('[mq]: %s', 'imported patch %s'):
786 if ctx.description() == fmt % patch:
785 if ctx.description() == fmt % patch:
787 msg = _('patch %s finalized without changeset message\n')
786 msg = _('patch %s finalized without changeset message\n')
788 repo.ui.status(msg % patch)
787 repo.ui.status(msg % patch)
789 break
788 break
790
789
791 patches.append(patch)
790 patches.append(patch)
792 return patches
791 return patches
793
792
794 def finish(self, repo, revs):
793 def finish(self, repo, revs):
795 patches = self._revpatches(repo, sorted(revs))
794 patches = self._revpatches(repo, sorted(revs))
796 self._cleanup(patches, len(patches))
795 self._cleanup(patches, len(patches))
797
796
798 def delete(self, repo, patches, opts):
797 def delete(self, repo, patches, opts):
799 if not patches and not opts.get('rev'):
798 if not patches and not opts.get('rev'):
800 raise util.Abort(_('qdelete requires at least one revision or '
799 raise util.Abort(_('qdelete requires at least one revision or '
801 'patch name'))
800 'patch name'))
802
801
803 realpatches = []
802 realpatches = []
804 for patch in patches:
803 for patch in patches:
805 patch = self.lookup(patch, strict=True)
804 patch = self.lookup(patch, strict=True)
806 info = self.isapplied(patch)
805 info = self.isapplied(patch)
807 if info:
806 if info:
808 raise util.Abort(_("cannot delete applied patch %s") % patch)
807 raise util.Abort(_("cannot delete applied patch %s") % patch)
809 if patch not in self.series:
808 if patch not in self.series:
810 raise util.Abort(_("patch %s not in series file") % patch)
809 raise util.Abort(_("patch %s not in series file") % patch)
811 if patch not in realpatches:
810 if patch not in realpatches:
812 realpatches.append(patch)
811 realpatches.append(patch)
813
812
814 numrevs = 0
813 numrevs = 0
815 if opts.get('rev'):
814 if opts.get('rev'):
816 if not self.applied:
815 if not self.applied:
817 raise util.Abort(_('no patches applied'))
816 raise util.Abort(_('no patches applied'))
818 revs = scmutil.revrange(repo, opts.get('rev'))
817 revs = scmutil.revrange(repo, opts.get('rev'))
819 if len(revs) > 1 and revs[0] > revs[1]:
818 if len(revs) > 1 and revs[0] > revs[1]:
820 revs.reverse()
819 revs.reverse()
821 revpatches = self._revpatches(repo, revs)
820 revpatches = self._revpatches(repo, revs)
822 realpatches += revpatches
821 realpatches += revpatches
823 numrevs = len(revpatches)
822 numrevs = len(revpatches)
824
823
825 self._cleanup(realpatches, numrevs, opts.get('keep'))
824 self._cleanup(realpatches, numrevs, opts.get('keep'))
826
825
827 def check_toppatch(self, repo):
826 def check_toppatch(self, repo):
828 if self.applied:
827 if self.applied:
829 top = self.applied[-1].node
828 top = self.applied[-1].node
830 patch = self.applied[-1].name
829 patch = self.applied[-1].name
831 pp = repo.dirstate.parents()
830 pp = repo.dirstate.parents()
832 if top not in pp:
831 if top not in pp:
833 raise util.Abort(_("working directory revision is not qtip"))
832 raise util.Abort(_("working directory revision is not qtip"))
834 return top, patch
833 return top, patch
835 return None, None
834 return None, None
836
835
837 def check_substate(self, repo):
836 def check_substate(self, repo):
838 '''return list of subrepos at a different revision than substate.
837 '''return list of subrepos at a different revision than substate.
839 Abort if any subrepos have uncommitted changes.'''
838 Abort if any subrepos have uncommitted changes.'''
840 inclsubs = []
839 inclsubs = []
841 wctx = repo[None]
840 wctx = repo[None]
842 for s in wctx.substate:
841 for s in wctx.substate:
843 if wctx.sub(s).dirty(True):
842 if wctx.sub(s).dirty(True):
844 raise util.Abort(
843 raise util.Abort(
845 _("uncommitted changes in subrepository %s") % s)
844 _("uncommitted changes in subrepository %s") % s)
846 elif wctx.sub(s).dirty():
845 elif wctx.sub(s).dirty():
847 inclsubs.append(s)
846 inclsubs.append(s)
848 return inclsubs
847 return inclsubs
849
848
850 def localchangesfound(self, refresh=True):
849 def localchangesfound(self, refresh=True):
851 if refresh:
850 if refresh:
852 raise util.Abort(_("local changes found, refresh first"))
851 raise util.Abort(_("local changes found, refresh first"))
853 else:
852 else:
854 raise util.Abort(_("local changes found"))
853 raise util.Abort(_("local changes found"))
855
854
856 def check_localchanges(self, repo, force=False, refresh=True):
855 def check_localchanges(self, repo, force=False, refresh=True):
857 m, a, r, d = repo.status()[:4]
856 m, a, r, d = repo.status()[:4]
858 if (m or a or r or d) and not force:
857 if (m or a or r or d) and not force:
859 self.localchangesfound(refresh)
858 self.localchangesfound(refresh)
860 return m, a, r, d
859 return m, a, r, d
861
860
862 _reserved = ('series', 'status', 'guards', '.', '..')
861 _reserved = ('series', 'status', 'guards', '.', '..')
863 def check_reserved_name(self, name):
862 def check_reserved_name(self, name):
864 if name in self._reserved:
863 if name in self._reserved:
865 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')
866 % name)
865 % name)
867 for prefix in ('.hg', '.mq'):
866 for prefix in ('.hg', '.mq'):
868 if name.startswith(prefix):
867 if name.startswith(prefix):
869 raise util.Abort(_('patch name cannot begin with "%s"')
868 raise util.Abort(_('patch name cannot begin with "%s"')
870 % prefix)
869 % prefix)
871 for c in ('#', ':'):
870 for c in ('#', ':'):
872 if c in name:
871 if c in name:
873 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')
874 % c)
873 % c)
875
874
876 def checkpatchname(self, name, force=False):
875 def checkpatchname(self, name, force=False):
877 self.check_reserved_name(name)
876 self.check_reserved_name(name)
878 if not force and os.path.exists(self.join(name)):
877 if not force and os.path.exists(self.join(name)):
879 if os.path.isdir(self.join(name)):
878 if os.path.isdir(self.join(name)):
880 raise util.Abort(_('"%s" already exists as a directory')
879 raise util.Abort(_('"%s" already exists as a directory')
881 % name)
880 % name)
882 else:
881 else:
883 raise util.Abort(_('patch "%s" already exists') % name)
882 raise util.Abort(_('patch "%s" already exists') % name)
884
883
885 def new(self, repo, patchfn, *pats, **opts):
884 def new(self, repo, patchfn, *pats, **opts):
886 """options:
885 """options:
887 msg: a string or a no-argument function returning a string
886 msg: a string or a no-argument function returning a string
888 """
887 """
889 msg = opts.get('msg')
888 msg = opts.get('msg')
890 user = opts.get('user')
889 user = opts.get('user')
891 date = opts.get('date')
890 date = opts.get('date')
892 if date:
891 if date:
893 date = util.parsedate(date)
892 date = util.parsedate(date)
894 diffopts = self.diffopts({'git': opts.get('git')})
893 diffopts = self.diffopts({'git': opts.get('git')})
895 if opts.get('checkname', True):
894 if opts.get('checkname', True):
896 self.checkpatchname(patchfn)
895 self.checkpatchname(patchfn)
897 inclsubs = self.check_substate(repo)
896 inclsubs = self.check_substate(repo)
898 if inclsubs:
897 if inclsubs:
899 inclsubs.append('.hgsubstate')
898 inclsubs.append('.hgsubstate')
900 if opts.get('include') or opts.get('exclude') or pats:
899 if opts.get('include') or opts.get('exclude') or pats:
901 if inclsubs:
900 if inclsubs:
902 pats = list(pats or []) + inclsubs
901 pats = list(pats or []) + inclsubs
903 match = scmutil.match(repo, pats, opts)
902 match = scmutil.match(repo, pats, opts)
904 # detect missing files in pats
903 # detect missing files in pats
905 def badfn(f, msg):
904 def badfn(f, msg):
906 if f != '.hgsubstate': # .hgsubstate is auto-created
905 if f != '.hgsubstate': # .hgsubstate is auto-created
907 raise util.Abort('%s: %s' % (f, msg))
906 raise util.Abort('%s: %s' % (f, msg))
908 match.bad = badfn
907 match.bad = badfn
909 m, a, r, d = repo.status(match=match)[:4]
908 m, a, r, d = repo.status(match=match)[:4]
910 else:
909 else:
911 m, a, r, d = self.check_localchanges(repo, force=True)
910 m, a, r, d = self.check_localchanges(repo, force=True)
912 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
913 if len(repo[None].parents()) > 1:
912 if len(repo[None].parents()) > 1:
914 raise util.Abort(_('cannot manage merge changesets'))
913 raise util.Abort(_('cannot manage merge changesets'))
915 commitfiles = m + a + r
914 commitfiles = m + a + r
916 self.check_toppatch(repo)
915 self.check_toppatch(repo)
917 insert = self.full_series_end()
916 insert = self.full_series_end()
918 wlock = repo.wlock()
917 wlock = repo.wlock()
919 try:
918 try:
920 try:
919 try:
921 # if patch file write fails, abort early
920 # if patch file write fails, abort early
922 p = self.opener(patchfn, "w")
921 p = self.opener(patchfn, "w")
923 except IOError, e:
922 except IOError, e:
924 raise util.Abort(_('cannot write patch "%s": %s')
923 raise util.Abort(_('cannot write patch "%s": %s')
925 % (patchfn, e.strerror))
924 % (patchfn, e.strerror))
926 try:
925 try:
927 if self.plainmode:
926 if self.plainmode:
928 if user:
927 if user:
929 p.write("From: " + user + "\n")
928 p.write("From: " + user + "\n")
930 if not date:
929 if not date:
931 p.write("\n")
930 p.write("\n")
932 if date:
931 if date:
933 p.write("Date: %d %d\n\n" % date)
932 p.write("Date: %d %d\n\n" % date)
934 else:
933 else:
935 p.write("# HG changeset patch\n")
934 p.write("# HG changeset patch\n")
936 p.write("# Parent "
935 p.write("# Parent "
937 + hex(repo[None].p1().node()) + "\n")
936 + hex(repo[None].p1().node()) + "\n")
938 if user:
937 if user:
939 p.write("# User " + user + "\n")
938 p.write("# User " + user + "\n")
940 if date:
939 if date:
941 p.write("# Date %s %s\n\n" % date)
940 p.write("# Date %s %s\n\n" % date)
942 if hasattr(msg, '__call__'):
941 if hasattr(msg, '__call__'):
943 msg = msg()
942 msg = msg()
944 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
945 n = repo.commit(commitmsg, user, date, match=match, force=True)
944 n = repo.commit(commitmsg, user, date, match=match, force=True)
946 if n is None:
945 if n is None:
947 raise util.Abort(_("repo commit failed"))
946 raise util.Abort(_("repo commit failed"))
948 try:
947 try:
949 self.full_series[insert:insert] = [patchfn]
948 self.full_series[insert:insert] = [patchfn]
950 self.applied.append(statusentry(n, patchfn))
949 self.applied.append(statusentry(n, patchfn))
951 self.parse_series()
950 self.parse_series()
952 self.series_dirty = 1
951 self.series_dirty = 1
953 self.applied_dirty = 1
952 self.applied_dirty = 1
954 if msg:
953 if msg:
955 msg = msg + "\n\n"
954 msg = msg + "\n\n"
956 p.write(msg)
955 p.write(msg)
957 if commitfiles:
956 if commitfiles:
958 parent = self.qparents(repo, n)
957 parent = self.qparents(repo, n)
959 chunks = patchmod.diff(repo, node1=parent, node2=n,
958 chunks = patchmod.diff(repo, node1=parent, node2=n,
960 match=match, opts=diffopts)
959 match=match, opts=diffopts)
961 for chunk in chunks:
960 for chunk in chunks:
962 p.write(chunk)
961 p.write(chunk)
963 p.close()
962 p.close()
964 wlock.release()
963 wlock.release()
965 wlock = None
964 wlock = None
966 r = self.qrepo()
965 r = self.qrepo()
967 if r:
966 if r:
968 r[None].add([patchfn])
967 r[None].add([patchfn])
969 except:
968 except:
970 repo.rollback()
969 repo.rollback()
971 raise
970 raise
972 except Exception:
971 except Exception:
973 patchpath = self.join(patchfn)
972 patchpath = self.join(patchfn)
974 try:
973 try:
975 os.unlink(patchpath)
974 os.unlink(patchpath)
976 except:
975 except:
977 self.ui.warn(_('error unlinking %s\n') % patchpath)
976 self.ui.warn(_('error unlinking %s\n') % patchpath)
978 raise
977 raise
979 self.removeundo(repo)
978 self.removeundo(repo)
980 finally:
979 finally:
981 release(wlock)
980 release(wlock)
982
981
983 def strip(self, repo, revs, update=True, backup="all", force=None):
982 def strip(self, repo, revs, update=True, backup="all", force=None):
984 wlock = lock = None
983 wlock = lock = None
985 try:
984 try:
986 wlock = repo.wlock()
985 wlock = repo.wlock()
987 lock = repo.lock()
986 lock = repo.lock()
988
987
989 if update:
988 if update:
990 self.check_localchanges(repo, force=force, refresh=False)
989 self.check_localchanges(repo, force=force, refresh=False)
991 urev = self.qparents(repo, revs[0])
990 urev = self.qparents(repo, revs[0])
992 hg.clean(repo, urev)
991 hg.clean(repo, urev)
993 repo.dirstate.write()
992 repo.dirstate.write()
994
993
995 self.removeundo(repo)
994 self.removeundo(repo)
996 for rev in revs:
995 for rev in revs:
997 repair.strip(self.ui, repo, rev, backup)
996 repair.strip(self.ui, repo, rev, backup)
998 # strip may have unbundled a set of backed up revisions after
997 # strip may have unbundled a set of backed up revisions after
999 # the actual strip
998 # the actual strip
1000 self.removeundo(repo)
999 self.removeundo(repo)
1001 finally:
1000 finally:
1002 release(lock, wlock)
1001 release(lock, wlock)
1003
1002
1004 def isapplied(self, patch):
1003 def isapplied(self, patch):
1005 """returns (index, rev, patch)"""
1004 """returns (index, rev, patch)"""
1006 for i, a in enumerate(self.applied):
1005 for i, a in enumerate(self.applied):
1007 if a.name == patch:
1006 if a.name == patch:
1008 return (i, a.node, a.name)
1007 return (i, a.node, a.name)
1009 return None
1008 return None
1010
1009
1011 # 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
1012 # variations. If strict is passed, we try only #1
1011 # variations. If strict is passed, we try only #1
1013 #
1012 #
1014 # 1) a number to indicate an offset in the series file
1013 # 1) a number to indicate an offset in the series file
1015 # 2) a unique substring of the patch name was given
1014 # 2) a unique substring of the patch name was given
1016 # 3) patchname[-+]num to indicate an offset in the series file
1015 # 3) patchname[-+]num to indicate an offset in the series file
1017 def lookup(self, patch, strict=False):
1016 def lookup(self, patch, strict=False):
1018 patch = patch and str(patch)
1017 patch = patch and str(patch)
1019
1018
1020 def partial_name(s):
1019 def partial_name(s):
1021 if s in self.series:
1020 if s in self.series:
1022 return s
1021 return s
1023 matches = [x for x in self.series if s in x]
1022 matches = [x for x in self.series if s in x]
1024 if len(matches) > 1:
1023 if len(matches) > 1:
1025 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1026 for m in matches:
1025 for m in matches:
1027 self.ui.warn(' %s\n' % m)
1026 self.ui.warn(' %s\n' % m)
1028 return None
1027 return None
1029 if matches:
1028 if matches:
1030 return matches[0]
1029 return matches[0]
1031 if self.series and self.applied:
1030 if self.series and self.applied:
1032 if s == 'qtip':
1031 if s == 'qtip':
1033 return self.series[self.series_end(True)-1]
1032 return self.series[self.series_end(True)-1]
1034 if s == 'qbase':
1033 if s == 'qbase':
1035 return self.series[0]
1034 return self.series[0]
1036 return None
1035 return None
1037
1036
1038 if patch is None:
1037 if patch is None:
1039 return None
1038 return None
1040 if patch in self.series:
1039 if patch in self.series:
1041 return patch
1040 return patch
1042
1041
1043 if not os.path.isfile(self.join(patch)):
1042 if not os.path.isfile(self.join(patch)):
1044 try:
1043 try:
1045 sno = int(patch)
1044 sno = int(patch)
1046 except (ValueError, OverflowError):
1045 except (ValueError, OverflowError):
1047 pass
1046 pass
1048 else:
1047 else:
1049 if -len(self.series) <= sno < len(self.series):
1048 if -len(self.series) <= sno < len(self.series):
1050 return self.series[sno]
1049 return self.series[sno]
1051
1050
1052 if not strict:
1051 if not strict:
1053 res = partial_name(patch)
1052 res = partial_name(patch)
1054 if res:
1053 if res:
1055 return res
1054 return res
1056 minus = patch.rfind('-')
1055 minus = patch.rfind('-')
1057 if minus >= 0:
1056 if minus >= 0:
1058 res = partial_name(patch[:minus])
1057 res = partial_name(patch[:minus])
1059 if res:
1058 if res:
1060 i = self.series.index(res)
1059 i = self.series.index(res)
1061 try:
1060 try:
1062 off = int(patch[minus + 1:] or 1)
1061 off = int(patch[minus + 1:] or 1)
1063 except (ValueError, OverflowError):
1062 except (ValueError, OverflowError):
1064 pass
1063 pass
1065 else:
1064 else:
1066 if i - off >= 0:
1065 if i - off >= 0:
1067 return self.series[i - off]
1066 return self.series[i - off]
1068 plus = patch.rfind('+')
1067 plus = patch.rfind('+')
1069 if plus >= 0:
1068 if plus >= 0:
1070 res = partial_name(patch[:plus])
1069 res = partial_name(patch[:plus])
1071 if res:
1070 if res:
1072 i = self.series.index(res)
1071 i = self.series.index(res)
1073 try:
1072 try:
1074 off = int(patch[plus + 1:] or 1)
1073 off = int(patch[plus + 1:] or 1)
1075 except (ValueError, OverflowError):
1074 except (ValueError, OverflowError):
1076 pass
1075 pass
1077 else:
1076 else:
1078 if i + off < len(self.series):
1077 if i + off < len(self.series):
1079 return self.series[i + off]
1078 return self.series[i + off]
1080 raise util.Abort(_("patch %s not in series") % patch)
1079 raise util.Abort(_("patch %s not in series") % patch)
1081
1080
1082 def push(self, repo, patch=None, force=False, list=False,
1081 def push(self, repo, patch=None, force=False, list=False,
1083 mergeq=None, all=False, move=False, exact=False):
1082 mergeq=None, all=False, move=False, exact=False):
1084 diffopts = self.diffopts()
1083 diffopts = self.diffopts()
1085 wlock = repo.wlock()
1084 wlock = repo.wlock()
1086 try:
1085 try:
1087 heads = []
1086 heads = []
1088 for b, ls in repo.branchmap().iteritems():
1087 for b, ls in repo.branchmap().iteritems():
1089 heads += ls
1088 heads += ls
1090 if not heads:
1089 if not heads:
1091 heads = [nullid]
1090 heads = [nullid]
1092 if repo.dirstate.p1() not in heads and not exact:
1091 if repo.dirstate.p1() not in heads and not exact:
1093 self.ui.status(_("(working directory not at a head)\n"))
1092 self.ui.status(_("(working directory not at a head)\n"))
1094
1093
1095 if not self.series:
1094 if not self.series:
1096 self.ui.warn(_('no patches in series\n'))
1095 self.ui.warn(_('no patches in series\n'))
1097 return 0
1096 return 0
1098
1097
1099 patch = self.lookup(patch)
1098 patch = self.lookup(patch)
1100 # 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'
1101 # patch is B. qpush C should be performed (moving forward)
1100 # patch is B. qpush C should be performed (moving forward)
1102 # 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
1103 # go backwards with qpush)
1102 # go backwards with qpush)
1104 if patch:
1103 if patch:
1105 info = self.isapplied(patch)
1104 info = self.isapplied(patch)
1106 if info and info[0] >= len(self.applied) - 1:
1105 if info and info[0] >= len(self.applied) - 1:
1107 self.ui.warn(
1106 self.ui.warn(
1108 _('qpush: %s is already at the top\n') % patch)
1107 _('qpush: %s is already at the top\n') % patch)
1109 return 0
1108 return 0
1110
1109
1111 pushable, reason = self.pushable(patch)
1110 pushable, reason = self.pushable(patch)
1112 if pushable:
1111 if pushable:
1113 if self.series.index(patch) < self.series_end():
1112 if self.series.index(patch) < self.series_end():
1114 raise util.Abort(
1113 raise util.Abort(
1115 _("cannot push to a previous patch: %s") % patch)
1114 _("cannot push to a previous patch: %s") % patch)
1116 else:
1115 else:
1117 if reason:
1116 if reason:
1118 reason = _('guarded by %r') % reason
1117 reason = _('guarded by %r') % reason
1119 else:
1118 else:
1120 reason = _('no matching guards')
1119 reason = _('no matching guards')
1121 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1122 return 1
1121 return 1
1123 elif all:
1122 elif all:
1124 patch = self.series[-1]
1123 patch = self.series[-1]
1125 if self.isapplied(patch):
1124 if self.isapplied(patch):
1126 self.ui.warn(_('all patches are currently applied\n'))
1125 self.ui.warn(_('all patches are currently applied\n'))
1127 return 0
1126 return 0
1128
1127
1129 # Following the above example, starting at 'top' of B:
1128 # Following the above example, starting at 'top' of B:
1130 # qpush should be performed (pushes C), but a subsequent
1129 # qpush should be performed (pushes C), but a subsequent
1131 # qpush without an argument is an error (nothing to
1130 # qpush without an argument is an error (nothing to
1132 # apply). This allows a loop of "...while hg qpush..." to
1131 # apply). This allows a loop of "...while hg qpush..." to
1133 # work as it detects an error when done
1132 # work as it detects an error when done
1134 start = self.series_end()
1133 start = self.series_end()
1135 if start == len(self.series):
1134 if start == len(self.series):
1136 self.ui.warn(_('patch series already fully applied\n'))
1135 self.ui.warn(_('patch series already fully applied\n'))
1137 return 1
1136 return 1
1138
1137
1139 if exact:
1138 if exact:
1140 if move:
1139 if move:
1141 raise util.Abort(_("cannot use --exact and --move together"))
1140 raise util.Abort(_("cannot use --exact and --move together"))
1142 if self.applied:
1141 if self.applied:
1143 raise util.Abort(_("cannot push --exact with applied patches"))
1142 raise util.Abort(_("cannot push --exact with applied patches"))
1144 root = self.series[start]
1143 root = self.series[start]
1145 target = patchheader(self.join(root), self.plainmode).parent
1144 target = patchheader(self.join(root), self.plainmode).parent
1146 if not target:
1145 if not target:
1147 raise util.Abort(_("%s does not have a parent recorded" % root))
1146 raise util.Abort(_("%s does not have a parent recorded" % root))
1148 if not repo[target] == repo['.']:
1147 if not repo[target] == repo['.']:
1149 hg.update(repo, target)
1148 hg.update(repo, target)
1150
1149
1151 if move:
1150 if move:
1152 if not patch:
1151 if not patch:
1153 raise util.Abort(_("please specify the patch to move"))
1152 raise util.Abort(_("please specify the patch to move"))
1154 for i, rpn in enumerate(self.full_series[start:]):
1153 for i, rpn in enumerate(self.full_series[start:]):
1155 # strip markers for patch guards
1154 # strip markers for patch guards
1156 if self.guard_re.split(rpn, 1)[0] == patch:
1155 if self.guard_re.split(rpn, 1)[0] == patch:
1157 break
1156 break
1158 index = start + i
1157 index = start + i
1159 assert index < len(self.full_series)
1158 assert index < len(self.full_series)
1160 fullpatch = self.full_series[index]
1159 fullpatch = self.full_series[index]
1161 del self.full_series[index]
1160 del self.full_series[index]
1162 self.full_series.insert(start, fullpatch)
1161 self.full_series.insert(start, fullpatch)
1163 self.parse_series()
1162 self.parse_series()
1164 self.series_dirty = 1
1163 self.series_dirty = 1
1165
1164
1166 self.applied_dirty = 1
1165 self.applied_dirty = 1
1167 if start > 0:
1166 if start > 0:
1168 self.check_toppatch(repo)
1167 self.check_toppatch(repo)
1169 if not patch:
1168 if not patch:
1170 patch = self.series[start]
1169 patch = self.series[start]
1171 end = start + 1
1170 end = start + 1
1172 else:
1171 else:
1173 end = self.series.index(patch, start) + 1
1172 end = self.series.index(patch, start) + 1
1174
1173
1175 s = self.series[start:end]
1174 s = self.series[start:end]
1176
1175
1177 if not force:
1176 if not force:
1178 mm, aa, rr, dd = repo.status()[:4]
1177 mm, aa, rr, dd = repo.status()[:4]
1179 wcfiles = set(mm + aa + rr + dd)
1178 wcfiles = set(mm + aa + rr + dd)
1180 if wcfiles:
1179 if wcfiles:
1181 for patchname in s:
1180 for patchname in s:
1182 pf = os.path.join(self.path, patchname)
1181 pf = os.path.join(self.path, patchname)
1183 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1182 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1184 if wcfiles.intersection(patchfiles):
1183 if wcfiles.intersection(patchfiles):
1185 self.localchangesfound(self.applied)
1184 self.localchangesfound(self.applied)
1186 elif mergeq:
1185 elif mergeq:
1187 self.check_localchanges(refresh=self.applied)
1186 self.check_localchanges(refresh=self.applied)
1188
1187
1189 all_files = set()
1188 all_files = set()
1190 try:
1189 try:
1191 if mergeq:
1190 if mergeq:
1192 ret = self.mergepatch(repo, mergeq, s, diffopts)
1191 ret = self.mergepatch(repo, mergeq, s, diffopts)
1193 else:
1192 else:
1194 ret = self.apply(repo, s, list, all_files=all_files)
1193 ret = self.apply(repo, s, list, all_files=all_files)
1195 except:
1194 except:
1196 self.ui.warn(_('cleaning up working directory...'))
1195 self.ui.warn(_('cleaning up working directory...'))
1197 node = repo.dirstate.p1()
1196 node = repo.dirstate.p1()
1198 hg.revert(repo, node, None)
1197 hg.revert(repo, node, None)
1199 # only remove unknown files that we know we touched or
1198 # only remove unknown files that we know we touched or
1200 # created while patching
1199 # created while patching
1201 for f in all_files:
1200 for f in all_files:
1202 if f not in repo.dirstate:
1201 if f not in repo.dirstate:
1203 try:
1202 try:
1204 util.unlinkpath(repo.wjoin(f))
1203 util.unlinkpath(repo.wjoin(f))
1205 except OSError, inst:
1204 except OSError, inst:
1206 if inst.errno != errno.ENOENT:
1205 if inst.errno != errno.ENOENT:
1207 raise
1206 raise
1208 self.ui.warn(_('done\n'))
1207 self.ui.warn(_('done\n'))
1209 raise
1208 raise
1210
1209
1211 if not self.applied:
1210 if not self.applied:
1212 return ret[0]
1211 return ret[0]
1213 top = self.applied[-1].name
1212 top = self.applied[-1].name
1214 if ret[0] and ret[0] > 1:
1213 if ret[0] and ret[0] > 1:
1215 msg = _("errors during apply, please fix and refresh %s\n")
1214 msg = _("errors during apply, please fix and refresh %s\n")
1216 self.ui.write(msg % top)
1215 self.ui.write(msg % top)
1217 else:
1216 else:
1218 self.ui.write(_("now at: %s\n") % top)
1217 self.ui.write(_("now at: %s\n") % top)
1219 return ret[0]
1218 return ret[0]
1220
1219
1221 finally:
1220 finally:
1222 wlock.release()
1221 wlock.release()
1223
1222
1224 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):
1225 wlock = repo.wlock()
1224 wlock = repo.wlock()
1226 try:
1225 try:
1227 if patch:
1226 if patch:
1228 # index, rev, patch
1227 # index, rev, patch
1229 info = self.isapplied(patch)
1228 info = self.isapplied(patch)
1230 if not info:
1229 if not info:
1231 patch = self.lookup(patch)
1230 patch = self.lookup(patch)
1232 info = self.isapplied(patch)
1231 info = self.isapplied(patch)
1233 if not info:
1232 if not info:
1234 raise util.Abort(_("patch %s is not applied") % patch)
1233 raise util.Abort(_("patch %s is not applied") % patch)
1235
1234
1236 if not self.applied:
1235 if not self.applied:
1237 # Allow qpop -a to work repeatedly,
1236 # Allow qpop -a to work repeatedly,
1238 # but not qpop without an argument
1237 # but not qpop without an argument
1239 self.ui.warn(_("no patches applied\n"))
1238 self.ui.warn(_("no patches applied\n"))
1240 return not all
1239 return not all
1241
1240
1242 if all:
1241 if all:
1243 start = 0
1242 start = 0
1244 elif patch:
1243 elif patch:
1245 start = info[0] + 1
1244 start = info[0] + 1
1246 else:
1245 else:
1247 start = len(self.applied) - 1
1246 start = len(self.applied) - 1
1248
1247
1249 if start >= len(self.applied):
1248 if start >= len(self.applied):
1250 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)
1251 return
1250 return
1252
1251
1253 if not update:
1252 if not update:
1254 parents = repo.dirstate.parents()
1253 parents = repo.dirstate.parents()
1255 rr = [x.node for x in self.applied]
1254 rr = [x.node for x in self.applied]
1256 for p in parents:
1255 for p in parents:
1257 if p in rr:
1256 if p in rr:
1258 self.ui.warn(_("qpop: forcing dirstate update\n"))
1257 self.ui.warn(_("qpop: forcing dirstate update\n"))
1259 update = True
1258 update = True
1260 else:
1259 else:
1261 parents = [p.node() for p in repo[None].parents()]
1260 parents = [p.node() for p in repo[None].parents()]
1262 needupdate = False
1261 needupdate = False
1263 for entry in self.applied[start:]:
1262 for entry in self.applied[start:]:
1264 if entry.node in parents:
1263 if entry.node in parents:
1265 needupdate = True
1264 needupdate = True
1266 break
1265 break
1267 update = needupdate
1266 update = needupdate
1268
1267
1269 self.applied_dirty = 1
1268 self.applied_dirty = 1
1270 end = len(self.applied)
1269 end = len(self.applied)
1271 rev = self.applied[start].node
1270 rev = self.applied[start].node
1272 if update:
1271 if update:
1273 top = self.check_toppatch(repo)[0]
1272 top = self.check_toppatch(repo)[0]
1274
1273
1275 try:
1274 try:
1276 heads = repo.changelog.heads(rev)
1275 heads = repo.changelog.heads(rev)
1277 except error.LookupError:
1276 except error.LookupError:
1278 node = short(rev)
1277 node = short(rev)
1279 raise util.Abort(_('trying to pop unknown node %s') % node)
1278 raise util.Abort(_('trying to pop unknown node %s') % node)
1280
1279
1281 if heads != [self.applied[-1].node]:
1280 if heads != [self.applied[-1].node]:
1282 raise util.Abort(_("popping would remove a revision not "
1281 raise util.Abort(_("popping would remove a revision not "
1283 "managed by this patch queue"))
1282 "managed by this patch queue"))
1284
1283
1285 # 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
1286 # form of hg.update.
1285 # form of hg.update.
1287 if update:
1286 if update:
1288 qp = self.qparents(repo, rev)
1287 qp = self.qparents(repo, rev)
1289 ctx = repo[qp]
1288 ctx = repo[qp]
1290 m, a, r, d = repo.status(qp, top)[:4]
1289 m, a, r, d = repo.status(qp, top)[:4]
1291 parentfiles = set(m + a + r + d)
1290 parentfiles = set(m + a + r + d)
1292 if not force and parentfiles:
1291 if not force and parentfiles:
1293 mm, aa, rr, dd = repo.status()[:4]
1292 mm, aa, rr, dd = repo.status()[:4]
1294 wcfiles = set(mm + aa + rr + dd)
1293 wcfiles = set(mm + aa + rr + dd)
1295 if wcfiles.intersection(parentfiles):
1294 if wcfiles.intersection(parentfiles):
1296 self.localchangesfound()
1295 self.localchangesfound()
1297 if d:
1296 if d:
1298 raise util.Abort(_("deletions found between repo revs"))
1297 raise util.Abort(_("deletions found between repo revs"))
1299 for f in a:
1298 for f in a:
1300 try:
1299 try:
1301 util.unlinkpath(repo.wjoin(f))
1300 util.unlinkpath(repo.wjoin(f))
1302 except OSError, e:
1301 except OSError, e:
1303 if e.errno != errno.ENOENT:
1302 if e.errno != errno.ENOENT:
1304 raise
1303 raise
1305 repo.dirstate.drop(f)
1304 repo.dirstate.drop(f)
1306 for f in m + r:
1305 for f in m + r:
1307 fctx = ctx[f]
1306 fctx = ctx[f]
1308 repo.wwrite(f, fctx.data(), fctx.flags())
1307 repo.wwrite(f, fctx.data(), fctx.flags())
1309 repo.dirstate.normal(f)
1308 repo.dirstate.normal(f)
1310 repo.dirstate.setparents(qp, nullid)
1309 repo.dirstate.setparents(qp, nullid)
1311 for patch in reversed(self.applied[start:end]):
1310 for patch in reversed(self.applied[start:end]):
1312 self.ui.status(_("popping %s\n") % patch.name)
1311 self.ui.status(_("popping %s\n") % patch.name)
1313 del self.applied[start:end]
1312 del self.applied[start:end]
1314 self.strip(repo, [rev], update=False, backup='strip')
1313 self.strip(repo, [rev], update=False, backup='strip')
1315 if self.applied:
1314 if self.applied:
1316 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1315 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1317 else:
1316 else:
1318 self.ui.write(_("patch queue now empty\n"))
1317 self.ui.write(_("patch queue now empty\n"))
1319 finally:
1318 finally:
1320 wlock.release()
1319 wlock.release()
1321
1320
1322 def diff(self, repo, pats, opts):
1321 def diff(self, repo, pats, opts):
1323 top, patch = self.check_toppatch(repo)
1322 top, patch = self.check_toppatch(repo)
1324 if not top:
1323 if not top:
1325 self.ui.write(_("no patches applied\n"))
1324 self.ui.write(_("no patches applied\n"))
1326 return
1325 return
1327 qp = self.qparents(repo, top)
1326 qp = self.qparents(repo, top)
1328 if opts.get('reverse'):
1327 if opts.get('reverse'):
1329 node1, node2 = None, qp
1328 node1, node2 = None, qp
1330 else:
1329 else:
1331 node1, node2 = qp, None
1330 node1, node2 = qp, None
1332 diffopts = self.diffopts(opts, patch)
1331 diffopts = self.diffopts(opts, patch)
1333 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1332 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1334
1333
1335 def refresh(self, repo, pats=None, **opts):
1334 def refresh(self, repo, pats=None, **opts):
1336 if not self.applied:
1335 if not self.applied:
1337 self.ui.write(_("no patches applied\n"))
1336 self.ui.write(_("no patches applied\n"))
1338 return 1
1337 return 1
1339 msg = opts.get('msg', '').rstrip()
1338 msg = opts.get('msg', '').rstrip()
1340 newuser = opts.get('user')
1339 newuser = opts.get('user')
1341 newdate = opts.get('date')
1340 newdate = opts.get('date')
1342 if newdate:
1341 if newdate:
1343 newdate = '%d %d' % util.parsedate(newdate)
1342 newdate = '%d %d' % util.parsedate(newdate)
1344 wlock = repo.wlock()
1343 wlock = repo.wlock()
1345
1344
1346 try:
1345 try:
1347 self.check_toppatch(repo)
1346 self.check_toppatch(repo)
1348 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1347 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1349 if repo.changelog.heads(top) != [top]:
1348 if repo.changelog.heads(top) != [top]:
1350 raise util.Abort(_("cannot refresh a revision with children"))
1349 raise util.Abort(_("cannot refresh a revision with children"))
1351
1350
1352 inclsubs = self.check_substate(repo)
1351 inclsubs = self.check_substate(repo)
1353
1352
1354 cparents = repo.changelog.parents(top)
1353 cparents = repo.changelog.parents(top)
1355 patchparent = self.qparents(repo, top)
1354 patchparent = self.qparents(repo, top)
1356 ph = patchheader(self.join(patchfn), self.plainmode)
1355 ph = patchheader(self.join(patchfn), self.plainmode)
1357 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1356 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1358 if msg:
1357 if msg:
1359 ph.setmessage(msg)
1358 ph.setmessage(msg)
1360 if newuser:
1359 if newuser:
1361 ph.setuser(newuser)
1360 ph.setuser(newuser)
1362 if newdate:
1361 if newdate:
1363 ph.setdate(newdate)
1362 ph.setdate(newdate)
1364 ph.setparent(hex(patchparent))
1363 ph.setparent(hex(patchparent))
1365
1364
1366 # only commit new patch when write is complete
1365 # only commit new patch when write is complete
1367 patchf = self.opener(patchfn, 'w', atomictemp=True)
1366 patchf = self.opener(patchfn, 'w', atomictemp=True)
1368
1367
1369 comments = str(ph)
1368 comments = str(ph)
1370 if comments:
1369 if comments:
1371 patchf.write(comments)
1370 patchf.write(comments)
1372
1371
1373 # update the dirstate in place, strip off the qtip commit
1372 # update the dirstate in place, strip off the qtip commit
1374 # and then commit.
1373 # and then commit.
1375 #
1374 #
1376 # this should really read:
1375 # this should really read:
1377 # mm, dd, aa = repo.status(top, patchparent)[:3]
1376 # mm, dd, aa = repo.status(top, patchparent)[:3]
1378 # but we do it backwards to take advantage of manifest/chlog
1377 # but we do it backwards to take advantage of manifest/chlog
1379 # caching against the next repo.status call
1378 # caching against the next repo.status call
1380 mm, aa, dd = repo.status(patchparent, top)[:3]
1379 mm, aa, dd = repo.status(patchparent, top)[:3]
1381 changes = repo.changelog.read(top)
1380 changes = repo.changelog.read(top)
1382 man = repo.manifest.read(changes[0])
1381 man = repo.manifest.read(changes[0])
1383 aaa = aa[:]
1382 aaa = aa[:]
1384 matchfn = scmutil.match(repo, pats, opts)
1383 matchfn = scmutil.match(repo, pats, opts)
1385 # in short mode, we only diff the files included in the
1384 # in short mode, we only diff the files included in the
1386 # patch already plus specified files
1385 # patch already plus specified files
1387 if opts.get('short'):
1386 if opts.get('short'):
1388 # if amending a patch, we start with existing
1387 # if amending a patch, we start with existing
1389 # files plus specified files - unfiltered
1388 # files plus specified files - unfiltered
1390 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1389 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1391 # filter with inc/exl options
1390 # filter with inc/exl options
1392 matchfn = scmutil.match(repo, opts=opts)
1391 matchfn = scmutil.match(repo, opts=opts)
1393 else:
1392 else:
1394 match = scmutil.matchall(repo)
1393 match = scmutil.matchall(repo)
1395 m, a, r, d = repo.status(match=match)[:4]
1394 m, a, r, d = repo.status(match=match)[:4]
1396 mm = set(mm)
1395 mm = set(mm)
1397 aa = set(aa)
1396 aa = set(aa)
1398 dd = set(dd)
1397 dd = set(dd)
1399
1398
1400 # we might end up with files that were added between
1399 # we might end up with files that were added between
1401 # qtip and the dirstate parent, but then changed in the
1400 # qtip and the dirstate parent, but then changed in the
1402 # local dirstate. in this case, we want them to only
1401 # local dirstate. in this case, we want them to only
1403 # show up in the added section
1402 # show up in the added section
1404 for x in m:
1403 for x in m:
1405 if x not in aa:
1404 if x not in aa:
1406 mm.add(x)
1405 mm.add(x)
1407 # 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
1408 # were deleted by the patch. In this case, they should only
1407 # were deleted by the patch. In this case, they should only
1409 # show up in the changed section.
1408 # show up in the changed section.
1410 for x in a:
1409 for x in a:
1411 if x in dd:
1410 if x in dd:
1412 dd.remove(x)
1411 dd.remove(x)
1413 mm.add(x)
1412 mm.add(x)
1414 else:
1413 else:
1415 aa.add(x)
1414 aa.add(x)
1416 # make sure any files deleted in the local dirstate
1415 # make sure any files deleted in the local dirstate
1417 # are not in the add or change column of the patch
1416 # are not in the add or change column of the patch
1418 forget = []
1417 forget = []
1419 for x in d + r:
1418 for x in d + r:
1420 if x in aa:
1419 if x in aa:
1421 aa.remove(x)
1420 aa.remove(x)
1422 forget.append(x)
1421 forget.append(x)
1423 continue
1422 continue
1424 else:
1423 else:
1425 mm.discard(x)
1424 mm.discard(x)
1426 dd.add(x)
1425 dd.add(x)
1427
1426
1428 m = list(mm)
1427 m = list(mm)
1429 r = list(dd)
1428 r = list(dd)
1430 a = list(aa)
1429 a = list(aa)
1431 c = [filter(matchfn, l) for l in (m, a, r)]
1430 c = [filter(matchfn, l) for l in (m, a, r)]
1432 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))
1433 chunks = patchmod.diff(repo, patchparent, match=match,
1432 chunks = patchmod.diff(repo, patchparent, match=match,
1434 changes=c, opts=diffopts)
1433 changes=c, opts=diffopts)
1435 for chunk in chunks:
1434 for chunk in chunks:
1436 patchf.write(chunk)
1435 patchf.write(chunk)
1437
1436
1438 try:
1437 try:
1439 if diffopts.git or diffopts.upgrade:
1438 if diffopts.git or diffopts.upgrade:
1440 copies = {}
1439 copies = {}
1441 for dst in a:
1440 for dst in a:
1442 src = repo.dirstate.copied(dst)
1441 src = repo.dirstate.copied(dst)
1443 # during qfold, the source file for copies may
1442 # during qfold, the source file for copies may
1444 # be removed. Treat this as a simple add.
1443 # be removed. Treat this as a simple add.
1445 if src is not None and src in repo.dirstate:
1444 if src is not None and src in repo.dirstate:
1446 copies.setdefault(src, []).append(dst)
1445 copies.setdefault(src, []).append(dst)
1447 repo.dirstate.add(dst)
1446 repo.dirstate.add(dst)
1448 # remember the copies between patchparent and qtip
1447 # remember the copies between patchparent and qtip
1449 for dst in aaa:
1448 for dst in aaa:
1450 f = repo.file(dst)
1449 f = repo.file(dst)
1451 src = f.renamed(man[dst])
1450 src = f.renamed(man[dst])
1452 if src:
1451 if src:
1453 copies.setdefault(src[0], []).extend(
1452 copies.setdefault(src[0], []).extend(
1454 copies.get(dst, []))
1453 copies.get(dst, []))
1455 if dst in a:
1454 if dst in a:
1456 copies[src[0]].append(dst)
1455 copies[src[0]].append(dst)
1457 # we can't copy a file created by the patch itself
1456 # we can't copy a file created by the patch itself
1458 if dst in copies:
1457 if dst in copies:
1459 del copies[dst]
1458 del copies[dst]
1460 for src, dsts in copies.iteritems():
1459 for src, dsts in copies.iteritems():
1461 for dst in dsts:
1460 for dst in dsts:
1462 repo.dirstate.copy(src, dst)
1461 repo.dirstate.copy(src, dst)
1463 else:
1462 else:
1464 for dst in a:
1463 for dst in a:
1465 repo.dirstate.add(dst)
1464 repo.dirstate.add(dst)
1466 # Drop useless copy information
1465 # Drop useless copy information
1467 for f in list(repo.dirstate.copies()):
1466 for f in list(repo.dirstate.copies()):
1468 repo.dirstate.copy(None, f)
1467 repo.dirstate.copy(None, f)
1469 for f in r:
1468 for f in r:
1470 repo.dirstate.remove(f)
1469 repo.dirstate.remove(f)
1471 # if the patch excludes a modified file, mark that
1470 # if the patch excludes a modified file, mark that
1472 # file with mtime=0 so status can see it.
1471 # file with mtime=0 so status can see it.
1473 mm = []
1472 mm = []
1474 for i in xrange(len(m)-1, -1, -1):
1473 for i in xrange(len(m)-1, -1, -1):
1475 if not matchfn(m[i]):
1474 if not matchfn(m[i]):
1476 mm.append(m[i])
1475 mm.append(m[i])
1477 del m[i]
1476 del m[i]
1478 for f in m:
1477 for f in m:
1479 repo.dirstate.normal(f)
1478 repo.dirstate.normal(f)
1480 for f in mm:
1479 for f in mm:
1481 repo.dirstate.normallookup(f)
1480 repo.dirstate.normallookup(f)
1482 for f in forget:
1481 for f in forget:
1483 repo.dirstate.drop(f)
1482 repo.dirstate.drop(f)
1484
1483
1485 if not msg:
1484 if not msg:
1486 if not ph.message:
1485 if not ph.message:
1487 message = "[mq]: %s\n" % patchfn
1486 message = "[mq]: %s\n" % patchfn
1488 else:
1487 else:
1489 message = "\n".join(ph.message)
1488 message = "\n".join(ph.message)
1490 else:
1489 else:
1491 message = msg
1490 message = msg
1492
1491
1493 user = ph.user or changes[1]
1492 user = ph.user or changes[1]
1494
1493
1495 # assumes strip can roll itself back if interrupted
1494 # assumes strip can roll itself back if interrupted
1496 repo.dirstate.setparents(*cparents)
1495 repo.dirstate.setparents(*cparents)
1497 self.applied.pop()
1496 self.applied.pop()
1498 self.applied_dirty = 1
1497 self.applied_dirty = 1
1499 self.strip(repo, [top], update=False,
1498 self.strip(repo, [top], update=False,
1500 backup='strip')
1499 backup='strip')
1501 except:
1500 except:
1502 repo.dirstate.invalidate()
1501 repo.dirstate.invalidate()
1503 raise
1502 raise
1504
1503
1505 try:
1504 try:
1506 # might be nice to attempt to roll back strip after this
1505 # might be nice to attempt to roll back strip after this
1507 n = repo.commit(message, user, ph.date, match=match,
1506 n = repo.commit(message, user, ph.date, match=match,
1508 force=True)
1507 force=True)
1509 # only write patch after a successful commit
1508 # only write patch after a successful commit
1510 patchf.rename()
1509 patchf.rename()
1511 self.applied.append(statusentry(n, patchfn))
1510 self.applied.append(statusentry(n, patchfn))
1512 except:
1511 except:
1513 ctx = repo[cparents[0]]
1512 ctx = repo[cparents[0]]
1514 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1513 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1515 self.save_dirty()
1514 self.save_dirty()
1516 self.ui.warn(_('refresh interrupted while patch was popped! '
1515 self.ui.warn(_('refresh interrupted while patch was popped! '
1517 '(revert --all, qpush to recover)\n'))
1516 '(revert --all, qpush to recover)\n'))
1518 raise
1517 raise
1519 finally:
1518 finally:
1520 wlock.release()
1519 wlock.release()
1521 self.removeundo(repo)
1520 self.removeundo(repo)
1522
1521
1523 def init(self, repo, create=False):
1522 def init(self, repo, create=False):
1524 if not create and os.path.isdir(self.path):
1523 if not create and os.path.isdir(self.path):
1525 raise util.Abort(_("patch queue directory already exists"))
1524 raise util.Abort(_("patch queue directory already exists"))
1526 try:
1525 try:
1527 os.mkdir(self.path)
1526 os.mkdir(self.path)
1528 except OSError, inst:
1527 except OSError, inst:
1529 if inst.errno != errno.EEXIST or not create:
1528 if inst.errno != errno.EEXIST or not create:
1530 raise
1529 raise
1531 if create:
1530 if create:
1532 return self.qrepo(create=True)
1531 return self.qrepo(create=True)
1533
1532
1534 def unapplied(self, repo, patch=None):
1533 def unapplied(self, repo, patch=None):
1535 if patch and patch not in self.series:
1534 if patch and patch not in self.series:
1536 raise util.Abort(_("patch %s is not in series file") % patch)
1535 raise util.Abort(_("patch %s is not in series file") % patch)
1537 if not patch:
1536 if not patch:
1538 start = self.series_end()
1537 start = self.series_end()
1539 else:
1538 else:
1540 start = self.series.index(patch) + 1
1539 start = self.series.index(patch) + 1
1541 unapplied = []
1540 unapplied = []
1542 for i in xrange(start, len(self.series)):
1541 for i in xrange(start, len(self.series)):
1543 pushable, reason = self.pushable(i)
1542 pushable, reason = self.pushable(i)
1544 if pushable:
1543 if pushable:
1545 unapplied.append((i, self.series[i]))
1544 unapplied.append((i, self.series[i]))
1546 self.explain_pushable(i)
1545 self.explain_pushable(i)
1547 return unapplied
1546 return unapplied
1548
1547
1549 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,
1550 summary=False):
1549 summary=False):
1551 def displayname(pfx, patchname, state):
1550 def displayname(pfx, patchname, state):
1552 if pfx:
1551 if pfx:
1553 self.ui.write(pfx)
1552 self.ui.write(pfx)
1554 if summary:
1553 if summary:
1555 ph = patchheader(self.join(patchname), self.plainmode)
1554 ph = patchheader(self.join(patchname), self.plainmode)
1556 msg = ph.message and ph.message[0] or ''
1555 msg = ph.message and ph.message[0] or ''
1557 if self.ui.formatted():
1556 if self.ui.formatted():
1558 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1557 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1559 if width > 0:
1558 if width > 0:
1560 msg = util.ellipsis(msg, width)
1559 msg = util.ellipsis(msg, width)
1561 else:
1560 else:
1562 msg = ''
1561 msg = ''
1563 self.ui.write(patchname, label='qseries.' + state)
1562 self.ui.write(patchname, label='qseries.' + state)
1564 self.ui.write(': ')
1563 self.ui.write(': ')
1565 self.ui.write(msg, label='qseries.message.' + state)
1564 self.ui.write(msg, label='qseries.message.' + state)
1566 else:
1565 else:
1567 self.ui.write(patchname, label='qseries.' + state)
1566 self.ui.write(patchname, label='qseries.' + state)
1568 self.ui.write('\n')
1567 self.ui.write('\n')
1569
1568
1570 applied = set([p.name for p in self.applied])
1569 applied = set([p.name for p in self.applied])
1571 if length is None:
1570 if length is None:
1572 length = len(self.series) - start
1571 length = len(self.series) - start
1573 if not missing:
1572 if not missing:
1574 if self.ui.verbose:
1573 if self.ui.verbose:
1575 idxwidth = len(str(start + length - 1))
1574 idxwidth = len(str(start + length - 1))
1576 for i in xrange(start, start + length):
1575 for i in xrange(start, start + length):
1577 patch = self.series[i]
1576 patch = self.series[i]
1578 if patch in applied:
1577 if patch in applied:
1579 char, state = 'A', 'applied'
1578 char, state = 'A', 'applied'
1580 elif self.pushable(i)[0]:
1579 elif self.pushable(i)[0]:
1581 char, state = 'U', 'unapplied'
1580 char, state = 'U', 'unapplied'
1582 else:
1581 else:
1583 char, state = 'G', 'guarded'
1582 char, state = 'G', 'guarded'
1584 pfx = ''
1583 pfx = ''
1585 if self.ui.verbose:
1584 if self.ui.verbose:
1586 pfx = '%*d %s ' % (idxwidth, i, char)
1585 pfx = '%*d %s ' % (idxwidth, i, char)
1587 elif status and status != char:
1586 elif status and status != char:
1588 continue
1587 continue
1589 displayname(pfx, patch, state)
1588 displayname(pfx, patch, state)
1590 else:
1589 else:
1591 msng_list = []
1590 msng_list = []
1592 for root, dirs, files in os.walk(self.path):
1591 for root, dirs, files in os.walk(self.path):
1593 d = root[len(self.path) + 1:]
1592 d = root[len(self.path) + 1:]
1594 for f in files:
1593 for f in files:
1595 fl = os.path.join(d, f)
1594 fl = os.path.join(d, f)
1596 if (fl not in self.series and
1595 if (fl not in self.series and
1597 fl not in (self.status_path, self.series_path,
1596 fl not in (self.status_path, self.series_path,
1598 self.guards_path)
1597 self.guards_path)
1599 and not fl.startswith('.')):
1598 and not fl.startswith('.')):
1600 msng_list.append(fl)
1599 msng_list.append(fl)
1601 for x in sorted(msng_list):
1600 for x in sorted(msng_list):
1602 pfx = self.ui.verbose and ('D ') or ''
1601 pfx = self.ui.verbose and ('D ') or ''
1603 displayname(pfx, x, 'missing')
1602 displayname(pfx, x, 'missing')
1604
1603
1605 def issaveline(self, l):
1604 def issaveline(self, l):
1606 if l.name == '.hg.patches.save.line':
1605 if l.name == '.hg.patches.save.line':
1607 return True
1606 return True
1608
1607
1609 def qrepo(self, create=False):
1608 def qrepo(self, create=False):
1610 ui = self.ui.copy()
1609 ui = self.ui.copy()
1611 ui.setconfig('paths', 'default', '', overlay=False)
1610 ui.setconfig('paths', 'default', '', overlay=False)
1612 ui.setconfig('paths', 'default-push', '', overlay=False)
1611 ui.setconfig('paths', 'default-push', '', overlay=False)
1613 if create or os.path.isdir(self.join(".hg")):
1612 if create or os.path.isdir(self.join(".hg")):
1614 return hg.repository(ui, path=self.path, create=create)
1613 return hg.repository(ui, path=self.path, create=create)
1615
1614
1616 def restore(self, repo, rev, delete=None, qupdate=None):
1615 def restore(self, repo, rev, delete=None, qupdate=None):
1617 desc = repo[rev].description().strip()
1616 desc = repo[rev].description().strip()
1618 lines = desc.splitlines()
1617 lines = desc.splitlines()
1619 i = 0
1618 i = 0
1620 datastart = None
1619 datastart = None
1621 series = []
1620 series = []
1622 applied = []
1621 applied = []
1623 qpp = None
1622 qpp = None
1624 for i, line in enumerate(lines):
1623 for i, line in enumerate(lines):
1625 if line == 'Patch Data:':
1624 if line == 'Patch Data:':
1626 datastart = i + 1
1625 datastart = i + 1
1627 elif line.startswith('Dirstate:'):
1626 elif line.startswith('Dirstate:'):
1628 l = line.rstrip()
1627 l = line.rstrip()
1629 l = l[10:].split(' ')
1628 l = l[10:].split(' ')
1630 qpp = [bin(x) for x in l]
1629 qpp = [bin(x) for x in l]
1631 elif datastart is not None:
1630 elif datastart is not None:
1632 l = line.rstrip()
1631 l = line.rstrip()
1633 n, name = l.split(':', 1)
1632 n, name = l.split(':', 1)
1634 if n:
1633 if n:
1635 applied.append(statusentry(bin(n), name))
1634 applied.append(statusentry(bin(n), name))
1636 else:
1635 else:
1637 series.append(l)
1636 series.append(l)
1638 if datastart is None:
1637 if datastart is None:
1639 self.ui.warn(_("No saved patch data found\n"))
1638 self.ui.warn(_("No saved patch data found\n"))
1640 return 1
1639 return 1
1641 self.ui.warn(_("restoring status: %s\n") % lines[0])
1640 self.ui.warn(_("restoring status: %s\n") % lines[0])
1642 self.full_series = series
1641 self.full_series = series
1643 self.applied = applied
1642 self.applied = applied
1644 self.parse_series()
1643 self.parse_series()
1645 self.series_dirty = 1
1644 self.series_dirty = 1
1646 self.applied_dirty = 1
1645 self.applied_dirty = 1
1647 heads = repo.changelog.heads()
1646 heads = repo.changelog.heads()
1648 if delete:
1647 if delete:
1649 if rev not in heads:
1648 if rev not in heads:
1650 self.ui.warn(_("save entry has children, leaving it alone\n"))
1649 self.ui.warn(_("save entry has children, leaving it alone\n"))
1651 else:
1650 else:
1652 self.ui.warn(_("removing save entry %s\n") % short(rev))
1651 self.ui.warn(_("removing save entry %s\n") % short(rev))
1653 pp = repo.dirstate.parents()
1652 pp = repo.dirstate.parents()
1654 if rev in pp:
1653 if rev in pp:
1655 update = True
1654 update = True
1656 else:
1655 else:
1657 update = False
1656 update = False
1658 self.strip(repo, [rev], update=update, backup='strip')
1657 self.strip(repo, [rev], update=update, backup='strip')
1659 if qpp:
1658 if qpp:
1660 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1659 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1661 (short(qpp[0]), short(qpp[1])))
1660 (short(qpp[0]), short(qpp[1])))
1662 if qupdate:
1661 if qupdate:
1663 self.ui.status(_("updating queue directory\n"))
1662 self.ui.status(_("updating queue directory\n"))
1664 r = self.qrepo()
1663 r = self.qrepo()
1665 if not r:
1664 if not r:
1666 self.ui.warn(_("Unable to load queue repository\n"))
1665 self.ui.warn(_("Unable to load queue repository\n"))
1667 return 1
1666 return 1
1668 hg.clean(r, qpp[0])
1667 hg.clean(r, qpp[0])
1669
1668
1670 def save(self, repo, msg=None):
1669 def save(self, repo, msg=None):
1671 if not self.applied:
1670 if not self.applied:
1672 self.ui.warn(_("save: no patches applied, exiting\n"))
1671 self.ui.warn(_("save: no patches applied, exiting\n"))
1673 return 1
1672 return 1
1674 if self.issaveline(self.applied[-1]):
1673 if self.issaveline(self.applied[-1]):
1675 self.ui.warn(_("status is already saved\n"))
1674 self.ui.warn(_("status is already saved\n"))
1676 return 1
1675 return 1
1677
1676
1678 if not msg:
1677 if not msg:
1679 msg = _("hg patches saved state")
1678 msg = _("hg patches saved state")
1680 else:
1679 else:
1681 msg = "hg patches: " + msg.rstrip('\r\n')
1680 msg = "hg patches: " + msg.rstrip('\r\n')
1682 r = self.qrepo()
1681 r = self.qrepo()
1683 if r:
1682 if r:
1684 pp = r.dirstate.parents()
1683 pp = r.dirstate.parents()
1685 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1684 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1686 msg += "\n\nPatch Data:\n"
1685 msg += "\n\nPatch Data:\n"
1687 msg += ''.join('%s\n' % x for x in self.applied)
1686 msg += ''.join('%s\n' % x for x in self.applied)
1688 msg += ''.join(':%s\n' % x for x in self.full_series)
1687 msg += ''.join(':%s\n' % x for x in self.full_series)
1689 n = repo.commit(msg, force=True)
1688 n = repo.commit(msg, force=True)
1690 if not n:
1689 if not n:
1691 self.ui.warn(_("repo commit failed\n"))
1690 self.ui.warn(_("repo commit failed\n"))
1692 return 1
1691 return 1
1693 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1692 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1694 self.applied_dirty = 1
1693 self.applied_dirty = 1
1695 self.removeundo(repo)
1694 self.removeundo(repo)
1696
1695
1697 def full_series_end(self):
1696 def full_series_end(self):
1698 if self.applied:
1697 if self.applied:
1699 p = self.applied[-1].name
1698 p = self.applied[-1].name
1700 end = self.find_series(p)
1699 end = self.find_series(p)
1701 if end is None:
1700 if end is None:
1702 return len(self.full_series)
1701 return len(self.full_series)
1703 return end + 1
1702 return end + 1
1704 return 0
1703 return 0
1705
1704
1706 def series_end(self, all_patches=False):
1705 def series_end(self, all_patches=False):
1707 """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
1708 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
1709 index of the first patch past the last applied one.
1708 index of the first patch past the last applied one.
1710 """
1709 """
1711 end = 0
1710 end = 0
1712 def next(start):
1711 def next(start):
1713 if all_patches or start >= len(self.series):
1712 if all_patches or start >= len(self.series):
1714 return start
1713 return start
1715 for i in xrange(start, len(self.series)):
1714 for i in xrange(start, len(self.series)):
1716 p, reason = self.pushable(i)
1715 p, reason = self.pushable(i)
1717 if p:
1716 if p:
1718 break
1717 break
1719 self.explain_pushable(i)
1718 self.explain_pushable(i)
1720 return i
1719 return i
1721 if self.applied:
1720 if self.applied:
1722 p = self.applied[-1].name
1721 p = self.applied[-1].name
1723 try:
1722 try:
1724 end = self.series.index(p)
1723 end = self.series.index(p)
1725 except ValueError:
1724 except ValueError:
1726 return 0
1725 return 0
1727 return next(end + 1)
1726 return next(end + 1)
1728 return next(end)
1727 return next(end)
1729
1728
1730 def appliedname(self, index):
1729 def appliedname(self, index):
1731 pname = self.applied[index].name
1730 pname = self.applied[index].name
1732 if not self.ui.verbose:
1731 if not self.ui.verbose:
1733 p = pname
1732 p = pname
1734 else:
1733 else:
1735 p = str(self.series.index(pname)) + " " + pname
1734 p = str(self.series.index(pname)) + " " + pname
1736 return p
1735 return p
1737
1736
1738 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1737 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1739 force=None, git=False):
1738 force=None, git=False):
1740 def checkseries(patchname):
1739 def checkseries(patchname):
1741 if patchname in self.series:
1740 if patchname in self.series:
1742 raise util.Abort(_('patch %s is already in the series file')
1741 raise util.Abort(_('patch %s is already in the series file')
1743 % patchname)
1742 % patchname)
1744
1743
1745 if rev:
1744 if rev:
1746 if files:
1745 if files:
1747 raise util.Abort(_('option "-r" not valid when importing '
1746 raise util.Abort(_('option "-r" not valid when importing '
1748 'files'))
1747 'files'))
1749 rev = scmutil.revrange(repo, rev)
1748 rev = scmutil.revrange(repo, rev)
1750 rev.sort(reverse=True)
1749 rev.sort(reverse=True)
1751 if (len(files) > 1 or len(rev) > 1) and patchname:
1750 if (len(files) > 1 or len(rev) > 1) and patchname:
1752 raise util.Abort(_('option "-n" not valid when importing multiple '
1751 raise util.Abort(_('option "-n" not valid when importing multiple '
1753 'patches'))
1752 'patches'))
1754 if rev:
1753 if rev:
1755 # If mq patches are applied, we can only import revisions
1754 # If mq patches are applied, we can only import revisions
1756 # that form a linear path to qbase.
1755 # that form a linear path to qbase.
1757 # Otherwise, they should form a linear path to a head.
1756 # Otherwise, they should form a linear path to a head.
1758 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1757 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1759 if len(heads) > 1:
1758 if len(heads) > 1:
1760 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 '
1761 'branch') % rev[-1])
1760 'branch') % rev[-1])
1762 if self.applied:
1761 if self.applied:
1763 base = repo.changelog.node(rev[0])
1762 base = repo.changelog.node(rev[0])
1764 if base in [n.node for n in self.applied]:
1763 if base in [n.node for n in self.applied]:
1765 raise util.Abort(_('revision %d is already managed')
1764 raise util.Abort(_('revision %d is already managed')
1766 % rev[0])
1765 % rev[0])
1767 if heads != [self.applied[-1].node]:
1766 if heads != [self.applied[-1].node]:
1768 raise util.Abort(_('revision %d is not the parent of '
1767 raise util.Abort(_('revision %d is not the parent of '
1769 'the queue') % rev[0])
1768 'the queue') % rev[0])
1770 base = repo.changelog.rev(self.applied[0].node)
1769 base = repo.changelog.rev(self.applied[0].node)
1771 lastparent = repo.changelog.parentrevs(base)[0]
1770 lastparent = repo.changelog.parentrevs(base)[0]
1772 else:
1771 else:
1773 if heads != [repo.changelog.node(rev[0])]:
1772 if heads != [repo.changelog.node(rev[0])]:
1774 raise util.Abort(_('revision %d has unmanaged children')
1773 raise util.Abort(_('revision %d has unmanaged children')
1775 % rev[0])
1774 % rev[0])
1776 lastparent = None
1775 lastparent = None
1777
1776
1778 diffopts = self.diffopts({'git': git})
1777 diffopts = self.diffopts({'git': git})
1779 for r in rev:
1778 for r in rev:
1780 p1, p2 = repo.changelog.parentrevs(r)
1779 p1, p2 = repo.changelog.parentrevs(r)
1781 n = repo.changelog.node(r)
1780 n = repo.changelog.node(r)
1782 if p2 != nullrev:
1781 if p2 != nullrev:
1783 raise util.Abort(_('cannot import merge revision %d') % r)
1782 raise util.Abort(_('cannot import merge revision %d') % r)
1784 if lastparent and lastparent != r:
1783 if lastparent and lastparent != r:
1785 raise util.Abort(_('revision %d is not the parent of %d')
1784 raise util.Abort(_('revision %d is not the parent of %d')
1786 % (r, lastparent))
1785 % (r, lastparent))
1787 lastparent = p1
1786 lastparent = p1
1788
1787
1789 if not patchname:
1788 if not patchname:
1790 patchname = normname('%d.diff' % r)
1789 patchname = normname('%d.diff' % r)
1791 checkseries(patchname)
1790 checkseries(patchname)
1792 self.checkpatchname(patchname, force)
1791 self.checkpatchname(patchname, force)
1793 self.full_series.insert(0, patchname)
1792 self.full_series.insert(0, patchname)
1794
1793
1795 patchf = self.opener(patchname, "w")
1794 patchf = self.opener(patchname, "w")
1796 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1795 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1797 patchf.close()
1796 patchf.close()
1798
1797
1799 se = statusentry(n, patchname)
1798 se = statusentry(n, patchname)
1800 self.applied.insert(0, se)
1799 self.applied.insert(0, se)
1801
1800
1802 self.added.append(patchname)
1801 self.added.append(patchname)
1803 patchname = None
1802 patchname = None
1804 self.parse_series()
1803 self.parse_series()
1805 self.applied_dirty = 1
1804 self.applied_dirty = 1
1806 self.series_dirty = True
1805 self.series_dirty = True
1807
1806
1808 for i, filename in enumerate(files):
1807 for i, filename in enumerate(files):
1809 if existing:
1808 if existing:
1810 if filename == '-':
1809 if filename == '-':
1811 raise util.Abort(_('-e is incompatible with import from -'))
1810 raise util.Abort(_('-e is incompatible with import from -'))
1812 filename = normname(filename)
1811 filename = normname(filename)
1813 self.check_reserved_name(filename)
1812 self.check_reserved_name(filename)
1814 originpath = self.join(filename)
1813 originpath = self.join(filename)
1815 if not os.path.isfile(originpath):
1814 if not os.path.isfile(originpath):
1816 raise util.Abort(_("patch %s does not exist") % filename)
1815 raise util.Abort(_("patch %s does not exist") % filename)
1817
1816
1818 if patchname:
1817 if patchname:
1819 self.checkpatchname(patchname, force)
1818 self.checkpatchname(patchname, force)
1820
1819
1821 self.ui.write(_('renaming %s to %s\n')
1820 self.ui.write(_('renaming %s to %s\n')
1822 % (filename, patchname))
1821 % (filename, patchname))
1823 util.rename(originpath, self.join(patchname))
1822 util.rename(originpath, self.join(patchname))
1824 else:
1823 else:
1825 patchname = filename
1824 patchname = filename
1826
1825
1827 else:
1826 else:
1828 if filename == '-' and not patchname:
1827 if filename == '-' and not patchname:
1829 raise util.Abort(_('need --name to import a patch from -'))
1828 raise util.Abort(_('need --name to import a patch from -'))
1830 elif not patchname:
1829 elif not patchname:
1831 patchname = normname(os.path.basename(filename.rstrip('/')))
1830 patchname = normname(os.path.basename(filename.rstrip('/')))
1832 self.checkpatchname(patchname, force)
1831 self.checkpatchname(patchname, force)
1833 try:
1832 try:
1834 if filename == '-':
1833 if filename == '-':
1835 text = sys.stdin.read()
1834 text = sys.stdin.read()
1836 else:
1835 else:
1837 fp = url.open(self.ui, filename)
1836 fp = url.open(self.ui, filename)
1838 text = fp.read()
1837 text = fp.read()
1839 fp.close()
1838 fp.close()
1840 except (OSError, IOError):
1839 except (OSError, IOError):
1841 raise util.Abort(_("unable to read file %s") % filename)
1840 raise util.Abort(_("unable to read file %s") % filename)
1842 patchf = self.opener(patchname, "w")
1841 patchf = self.opener(patchname, "w")
1843 patchf.write(text)
1842 patchf.write(text)
1844 patchf.close()
1843 patchf.close()
1845 if not force:
1844 if not force:
1846 checkseries(patchname)
1845 checkseries(patchname)
1847 if patchname not in self.series:
1846 if patchname not in self.series:
1848 index = self.full_series_end() + i
1847 index = self.full_series_end() + i
1849 self.full_series[index:index] = [patchname]
1848 self.full_series[index:index] = [patchname]
1850 self.parse_series()
1849 self.parse_series()
1851 self.series_dirty = True
1850 self.series_dirty = True
1852 self.ui.warn(_("adding %s to series file\n") % patchname)
1851 self.ui.warn(_("adding %s to series file\n") % patchname)
1853 self.added.append(patchname)
1852 self.added.append(patchname)
1854 patchname = None
1853 patchname = None
1855
1854
1856 self.removeundo(repo)
1855 self.removeundo(repo)
1857
1856
1858 @command("qdelete|qremove|qrm",
1857 @command("qdelete|qremove|qrm",
1859 [('k', 'keep', None, _('keep patch file')),
1858 [('k', 'keep', None, _('keep patch file')),
1860 ('r', 'rev', [],
1859 ('r', 'rev', [],
1861 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1860 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1862 _('hg qdelete [-k] [PATCH]...'))
1861 _('hg qdelete [-k] [PATCH]...'))
1863 def delete(ui, repo, *patches, **opts):
1862 def delete(ui, repo, *patches, **opts):
1864 """remove patches from queue
1863 """remove patches from queue
1865
1864
1866 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
1867 -k/--keep, the patch files are preserved in the patch directory.
1866 -k/--keep, the patch files are preserved in the patch directory.
1868
1867
1869 To stop managing a patch and move it into permanent history,
1868 To stop managing a patch and move it into permanent history,
1870 use the :hg:`qfinish` command."""
1869 use the :hg:`qfinish` command."""
1871 q = repo.mq
1870 q = repo.mq
1872 q.delete(repo, patches, opts)
1871 q.delete(repo, patches, opts)
1873 q.save_dirty()
1872 q.save_dirty()
1874 return 0
1873 return 0
1875
1874
1876 @command("qapplied",
1875 @command("qapplied",
1877 [('1', 'last', None, _('show only the last patch'))
1876 [('1', 'last', None, _('show only the last patch'))
1878 ] + seriesopts,
1877 ] + seriesopts,
1879 _('hg qapplied [-1] [-s] [PATCH]'))
1878 _('hg qapplied [-1] [-s] [PATCH]'))
1880 def applied(ui, repo, patch=None, **opts):
1879 def applied(ui, repo, patch=None, **opts):
1881 """print the patches already applied
1880 """print the patches already applied
1882
1881
1883 Returns 0 on success."""
1882 Returns 0 on success."""
1884
1883
1885 q = repo.mq
1884 q = repo.mq
1886
1885
1887 if patch:
1886 if patch:
1888 if patch not in q.series:
1887 if patch not in q.series:
1889 raise util.Abort(_("patch %s is not in series file") % patch)
1888 raise util.Abort(_("patch %s is not in series file") % patch)
1890 end = q.series.index(patch) + 1
1889 end = q.series.index(patch) + 1
1891 else:
1890 else:
1892 end = q.series_end(True)
1891 end = q.series_end(True)
1893
1892
1894 if opts.get('last') and not end:
1893 if opts.get('last') and not end:
1895 ui.write(_("no patches applied\n"))
1894 ui.write(_("no patches applied\n"))
1896 return 1
1895 return 1
1897 elif opts.get('last') and end == 1:
1896 elif opts.get('last') and end == 1:
1898 ui.write(_("only one patch applied\n"))
1897 ui.write(_("only one patch applied\n"))
1899 return 1
1898 return 1
1900 elif opts.get('last'):
1899 elif opts.get('last'):
1901 start = end - 2
1900 start = end - 2
1902 end = 1
1901 end = 1
1903 else:
1902 else:
1904 start = 0
1903 start = 0
1905
1904
1906 q.qseries(repo, length=end, start=start, status='A',
1905 q.qseries(repo, length=end, start=start, status='A',
1907 summary=opts.get('summary'))
1906 summary=opts.get('summary'))
1908
1907
1909
1908
1910 @command("qunapplied",
1909 @command("qunapplied",
1911 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1910 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1912 _('hg qunapplied [-1] [-s] [PATCH]'))
1911 _('hg qunapplied [-1] [-s] [PATCH]'))
1913 def unapplied(ui, repo, patch=None, **opts):
1912 def unapplied(ui, repo, patch=None, **opts):
1914 """print the patches not yet applied
1913 """print the patches not yet applied
1915
1914
1916 Returns 0 on success."""
1915 Returns 0 on success."""
1917
1916
1918 q = repo.mq
1917 q = repo.mq
1919 if patch:
1918 if patch:
1920 if patch not in q.series:
1919 if patch not in q.series:
1921 raise util.Abort(_("patch %s is not in series file") % patch)
1920 raise util.Abort(_("patch %s is not in series file") % patch)
1922 start = q.series.index(patch) + 1
1921 start = q.series.index(patch) + 1
1923 else:
1922 else:
1924 start = q.series_end(True)
1923 start = q.series_end(True)
1925
1924
1926 if start == len(q.series) and opts.get('first'):
1925 if start == len(q.series) and opts.get('first'):
1927 ui.write(_("all patches applied\n"))
1926 ui.write(_("all patches applied\n"))
1928 return 1
1927 return 1
1929
1928
1930 length = opts.get('first') and 1 or None
1929 length = opts.get('first') and 1 or None
1931 q.qseries(repo, start=start, length=length, status='U',
1930 q.qseries(repo, start=start, length=length, status='U',
1932 summary=opts.get('summary'))
1931 summary=opts.get('summary'))
1933
1932
1934 @command("qimport",
1933 @command("qimport",
1935 [('e', 'existing', None, _('import file in patch directory')),
1934 [('e', 'existing', None, _('import file in patch directory')),
1936 ('n', 'name', '',
1935 ('n', 'name', '',
1937 _('name of patch file'), _('NAME')),
1936 _('name of patch file'), _('NAME')),
1938 ('f', 'force', None, _('overwrite existing files')),
1937 ('f', 'force', None, _('overwrite existing files')),
1939 ('r', 'rev', [],
1938 ('r', 'rev', [],
1940 _('place existing revisions under mq control'), _('REV')),
1939 _('place existing revisions under mq control'), _('REV')),
1941 ('g', 'git', None, _('use git extended diff format')),
1940 ('g', 'git', None, _('use git extended diff format')),
1942 ('P', 'push', None, _('qpush after importing'))],
1941 ('P', 'push', None, _('qpush after importing'))],
1943 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1942 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1944 def qimport(ui, repo, *filename, **opts):
1943 def qimport(ui, repo, *filename, **opts):
1945 """import a patch
1944 """import a patch
1946
1945
1947 The patch is inserted into the series after the last applied
1946 The patch is inserted into the series after the last applied
1948 patch. If no patches have been applied, qimport prepends the patch
1947 patch. If no patches have been applied, qimport prepends the patch
1949 to the series.
1948 to the series.
1950
1949
1951 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
1952 give it a new one with -n/--name.
1951 give it a new one with -n/--name.
1953
1952
1954 You can register an existing patch inside the patch directory with
1953 You can register an existing patch inside the patch directory with
1955 the -e/--existing flag.
1954 the -e/--existing flag.
1956
1955
1957 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
1958 overwritten.
1957 overwritten.
1959
1958
1960 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
1961 (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).
1962 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
1963 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
1964 important for preserving rename/copy information and permission
1963 important for preserving rename/copy information and permission
1965 changes. Use :hg:`qfinish` to remove changesets from mq control.
1964 changes. Use :hg:`qfinish` to remove changesets from mq control.
1966
1965
1967 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.
1968 When importing from standard input, a patch name must be specified
1967 When importing from standard input, a patch name must be specified
1969 using the --name flag.
1968 using the --name flag.
1970
1969
1971 To import an existing patch while renaming it::
1970 To import an existing patch while renaming it::
1972
1971
1973 hg qimport -e existing-patch -n new-name
1972 hg qimport -e existing-patch -n new-name
1974
1973
1975 Returns 0 if import succeeded.
1974 Returns 0 if import succeeded.
1976 """
1975 """
1977 q = repo.mq
1976 q = repo.mq
1978 try:
1977 try:
1979 q.qimport(repo, filename, patchname=opts.get('name'),
1978 q.qimport(repo, filename, patchname=opts.get('name'),
1980 existing=opts.get('existing'), force=opts.get('force'),
1979 existing=opts.get('existing'), force=opts.get('force'),
1981 rev=opts.get('rev'), git=opts.get('git'))
1980 rev=opts.get('rev'), git=opts.get('git'))
1982 finally:
1981 finally:
1983 q.save_dirty()
1982 q.save_dirty()
1984
1983
1985 if opts.get('push') and not opts.get('rev'):
1984 if opts.get('push') and not opts.get('rev'):
1986 return q.push(repo, None)
1985 return q.push(repo, None)
1987 return 0
1986 return 0
1988
1987
1989 def qinit(ui, repo, create):
1988 def qinit(ui, repo, create):
1990 """initialize a new queue repository
1989 """initialize a new queue repository
1991
1990
1992 This command also creates a series file for ordering patches, and
1991 This command also creates a series file for ordering patches, and
1993 an mq-specific .hgignore file in the queue repository, to exclude
1992 an mq-specific .hgignore file in the queue repository, to exclude
1994 the status and guards files (these contain mostly transient state).
1993 the status and guards files (these contain mostly transient state).
1995
1994
1996 Returns 0 if initialization succeeded."""
1995 Returns 0 if initialization succeeded."""
1997 q = repo.mq
1996 q = repo.mq
1998 r = q.init(repo, create)
1997 r = q.init(repo, create)
1999 q.save_dirty()
1998 q.save_dirty()
2000 if r:
1999 if r:
2001 if not os.path.exists(r.wjoin('.hgignore')):
2000 if not os.path.exists(r.wjoin('.hgignore')):
2002 fp = r.wopener('.hgignore', 'w')
2001 fp = r.wopener('.hgignore', 'w')
2003 fp.write('^\\.hg\n')
2002 fp.write('^\\.hg\n')
2004 fp.write('^\\.mq\n')
2003 fp.write('^\\.mq\n')
2005 fp.write('syntax: glob\n')
2004 fp.write('syntax: glob\n')
2006 fp.write('status\n')
2005 fp.write('status\n')
2007 fp.write('guards\n')
2006 fp.write('guards\n')
2008 fp.close()
2007 fp.close()
2009 if not os.path.exists(r.wjoin('series')):
2008 if not os.path.exists(r.wjoin('series')):
2010 r.wopener('series', 'w').close()
2009 r.wopener('series', 'w').close()
2011 r[None].add(['.hgignore', 'series'])
2010 r[None].add(['.hgignore', 'series'])
2012 commands.add(ui, r)
2011 commands.add(ui, r)
2013 return 0
2012 return 0
2014
2013
2015 @command("^qinit",
2014 @command("^qinit",
2016 [('c', 'create-repo', None, _('create queue repository'))],
2015 [('c', 'create-repo', None, _('create queue repository'))],
2017 _('hg qinit [-c]'))
2016 _('hg qinit [-c]'))
2018 def init(ui, repo, **opts):
2017 def init(ui, repo, **opts):
2019 """init a new queue repository (DEPRECATED)
2018 """init a new queue repository (DEPRECATED)
2020
2019
2021 The queue repository is unversioned by default. If
2020 The queue repository is unversioned by default. If
2022 -c/--create-repo is specified, qinit will create a separate nested
2021 -c/--create-repo is specified, qinit will create a separate nested
2023 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
2024 an unversioned patch repository into a versioned one). You can use
2023 an unversioned patch repository into a versioned one). You can use
2025 qcommit to commit changes to this queue repository.
2024 qcommit to commit changes to this queue repository.
2026
2025
2027 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
2028 commands. With -c, use :hg:`init --mq` instead."""
2027 commands. With -c, use :hg:`init --mq` instead."""
2029 return qinit(ui, repo, create=opts.get('create_repo'))
2028 return qinit(ui, repo, create=opts.get('create_repo'))
2030
2029
2031 @command("qclone",
2030 @command("qclone",
2032 [('', 'pull', None, _('use pull protocol to copy metadata')),
2031 [('', 'pull', None, _('use pull protocol to copy metadata')),
2033 ('U', 'noupdate', None, _('do not update the new working directories')),
2032 ('U', 'noupdate', None, _('do not update the new working directories')),
2034 ('', 'uncompressed', None,
2033 ('', 'uncompressed', None,
2035 _('use uncompressed transfer (fast over LAN)')),
2034 _('use uncompressed transfer (fast over LAN)')),
2036 ('p', 'patches', '',
2035 ('p', 'patches', '',
2037 _('location of source patch repository'), _('REPO')),
2036 _('location of source patch repository'), _('REPO')),
2038 ] + commands.remoteopts,
2037 ] + commands.remoteopts,
2039 _('hg qclone [OPTION]... SOURCE [DEST]'))
2038 _('hg qclone [OPTION]... SOURCE [DEST]'))
2040 def clone(ui, source, dest=None, **opts):
2039 def clone(ui, source, dest=None, **opts):
2041 '''clone main and patch repository at same time
2040 '''clone main and patch repository at same time
2042
2041
2043 If source is local, destination will have no patches applied. If
2042 If source is local, destination will have no patches applied. If
2044 source is remote, this command can not check if patches are
2043 source is remote, this command can not check if patches are
2045 applied in source, so cannot guarantee that patches are not
2044 applied in source, so cannot guarantee that patches are not
2046 applied in destination. If you clone remote repository, be sure
2045 applied in destination. If you clone remote repository, be sure
2047 before that it has no patches applied.
2046 before that it has no patches applied.
2048
2047
2049 Source patch repository is looked for in <src>/.hg/patches by
2048 Source patch repository is looked for in <src>/.hg/patches by
2050 default. Use -p <url> to change.
2049 default. Use -p <url> to change.
2051
2050
2052 The patch directory must be a nested Mercurial repository, as
2051 The patch directory must be a nested Mercurial repository, as
2053 would be created by :hg:`init --mq`.
2052 would be created by :hg:`init --mq`.
2054
2053
2055 Return 0 on success.
2054 Return 0 on success.
2056 '''
2055 '''
2057 def patchdir(repo):
2056 def patchdir(repo):
2058 url = repo.url()
2057 url = repo.url()
2059 if url.endswith('/'):
2058 if url.endswith('/'):
2060 url = url[:-1]
2059 url = url[:-1]
2061 return url + '/.hg/patches'
2060 return url + '/.hg/patches'
2062 if dest is None:
2061 if dest is None:
2063 dest = hg.defaultdest(source)
2062 dest = hg.defaultdest(source)
2064 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2063 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2065 if opts.get('patches'):
2064 if opts.get('patches'):
2066 patchespath = ui.expandpath(opts.get('patches'))
2065 patchespath = ui.expandpath(opts.get('patches'))
2067 else:
2066 else:
2068 patchespath = patchdir(sr)
2067 patchespath = patchdir(sr)
2069 try:
2068 try:
2070 hg.repository(ui, patchespath)
2069 hg.repository(ui, patchespath)
2071 except error.RepoError:
2070 except error.RepoError:
2072 raise util.Abort(_('versioned patch repository not found'
2071 raise util.Abort(_('versioned patch repository not found'
2073 ' (see init --mq)'))
2072 ' (see init --mq)'))
2074 qbase, destrev = None, None
2073 qbase, destrev = None, None
2075 if sr.local():
2074 if sr.local():
2076 if sr.mq.applied:
2075 if sr.mq.applied:
2077 qbase = sr.mq.applied[0].node
2076 qbase = sr.mq.applied[0].node
2078 if not hg.islocal(dest):
2077 if not hg.islocal(dest):
2079 heads = set(sr.heads())
2078 heads = set(sr.heads())
2080 destrev = list(heads.difference(sr.heads(qbase)))
2079 destrev = list(heads.difference(sr.heads(qbase)))
2081 destrev.append(sr.changelog.parents(qbase)[0])
2080 destrev.append(sr.changelog.parents(qbase)[0])
2082 elif sr.capable('lookup'):
2081 elif sr.capable('lookup'):
2083 try:
2082 try:
2084 qbase = sr.lookup('qbase')
2083 qbase = sr.lookup('qbase')
2085 except error.RepoError:
2084 except error.RepoError:
2086 pass
2085 pass
2087 ui.note(_('cloning main repository\n'))
2086 ui.note(_('cloning main repository\n'))
2088 sr, dr = hg.clone(ui, sr.url(), dest,
2087 sr, dr = hg.clone(ui, sr.url(), dest,
2089 pull=opts.get('pull'),
2088 pull=opts.get('pull'),
2090 rev=destrev,
2089 rev=destrev,
2091 update=False,
2090 update=False,
2092 stream=opts.get('uncompressed'))
2091 stream=opts.get('uncompressed'))
2093 ui.note(_('cloning patch repository\n'))
2092 ui.note(_('cloning patch repository\n'))
2094 hg.clone(ui, opts.get('patches') or patchdir(sr), patchdir(dr),
2093 hg.clone(ui, opts.get('patches') or patchdir(sr), patchdir(dr),
2095 pull=opts.get('pull'), update=not opts.get('noupdate'),
2094 pull=opts.get('pull'), update=not opts.get('noupdate'),
2096 stream=opts.get('uncompressed'))
2095 stream=opts.get('uncompressed'))
2097 if dr.local():
2096 if dr.local():
2098 if qbase:
2097 if qbase:
2099 ui.note(_('stripping applied patches from destination '
2098 ui.note(_('stripping applied patches from destination '
2100 'repository\n'))
2099 'repository\n'))
2101 dr.mq.strip(dr, [qbase], update=False, backup=None)
2100 dr.mq.strip(dr, [qbase], update=False, backup=None)
2102 if not opts.get('noupdate'):
2101 if not opts.get('noupdate'):
2103 ui.note(_('updating destination repository\n'))
2102 ui.note(_('updating destination repository\n'))
2104 hg.update(dr, dr.changelog.tip())
2103 hg.update(dr, dr.changelog.tip())
2105
2104
2106 @command("qcommit|qci",
2105 @command("qcommit|qci",
2107 commands.table["^commit|ci"][1],
2106 commands.table["^commit|ci"][1],
2108 _('hg qcommit [OPTION]... [FILE]...'))
2107 _('hg qcommit [OPTION]... [FILE]...'))
2109 def commit(ui, repo, *pats, **opts):
2108 def commit(ui, repo, *pats, **opts):
2110 """commit changes in the queue repository (DEPRECATED)
2109 """commit changes in the queue repository (DEPRECATED)
2111
2110
2112 This command is deprecated; use :hg:`commit --mq` instead."""
2111 This command is deprecated; use :hg:`commit --mq` instead."""
2113 q = repo.mq
2112 q = repo.mq
2114 r = q.qrepo()
2113 r = q.qrepo()
2115 if not r:
2114 if not r:
2116 raise util.Abort('no queue repository')
2115 raise util.Abort('no queue repository')
2117 commands.commit(r.ui, r, *pats, **opts)
2116 commands.commit(r.ui, r, *pats, **opts)
2118
2117
2119 @command("qseries",
2118 @command("qseries",
2120 [('m', 'missing', None, _('print patches not in series')),
2119 [('m', 'missing', None, _('print patches not in series')),
2121 ] + seriesopts,
2120 ] + seriesopts,
2122 _('hg qseries [-ms]'))
2121 _('hg qseries [-ms]'))
2123 def series(ui, repo, **opts):
2122 def series(ui, repo, **opts):
2124 """print the entire series file
2123 """print the entire series file
2125
2124
2126 Returns 0 on success."""
2125 Returns 0 on success."""
2127 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'))
2128 return 0
2127 return 0
2129
2128
2130 @command("qtop", [] + seriesopts, _('hg qtop [-s]'))
2129 @command("qtop", [] + seriesopts, _('hg qtop [-s]'))
2131 def top(ui, repo, **opts):
2130 def top(ui, repo, **opts):
2132 """print the name of the current patch
2131 """print the name of the current patch
2133
2132
2134 Returns 0 on success."""
2133 Returns 0 on success."""
2135 q = repo.mq
2134 q = repo.mq
2136 t = q.applied and q.series_end(True) or 0
2135 t = q.applied and q.series_end(True) or 0
2137 if t:
2136 if t:
2138 q.qseries(repo, start=t - 1, length=1, status='A',
2137 q.qseries(repo, start=t - 1, length=1, status='A',
2139 summary=opts.get('summary'))
2138 summary=opts.get('summary'))
2140 else:
2139 else:
2141 ui.write(_("no patches applied\n"))
2140 ui.write(_("no patches applied\n"))
2142 return 1
2141 return 1
2143
2142
2144 @command("qnext", [] + seriesopts, _('hg qnext [-s]'))
2143 @command("qnext", [] + seriesopts, _('hg qnext [-s]'))
2145 def next(ui, repo, **opts):
2144 def next(ui, repo, **opts):
2146 """print the name of the next patch
2145 """print the name of the next patch
2147
2146
2148 Returns 0 on success."""
2147 Returns 0 on success."""
2149 q = repo.mq
2148 q = repo.mq
2150 end = q.series_end()
2149 end = q.series_end()
2151 if end == len(q.series):
2150 if end == len(q.series):
2152 ui.write(_("all patches applied\n"))
2151 ui.write(_("all patches applied\n"))
2153 return 1
2152 return 1
2154 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2153 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2155
2154
2156 @command("qprev", [] + seriesopts, _('hg qprev [-s]'))
2155 @command("qprev", [] + seriesopts, _('hg qprev [-s]'))
2157 def prev(ui, repo, **opts):
2156 def prev(ui, repo, **opts):
2158 """print the name of the previous patch
2157 """print the name of the previous patch
2159
2158
2160 Returns 0 on success."""
2159 Returns 0 on success."""
2161 q = repo.mq
2160 q = repo.mq
2162 l = len(q.applied)
2161 l = len(q.applied)
2163 if l == 1:
2162 if l == 1:
2164 ui.write(_("only one patch applied\n"))
2163 ui.write(_("only one patch applied\n"))
2165 return 1
2164 return 1
2166 if not l:
2165 if not l:
2167 ui.write(_("no patches applied\n"))
2166 ui.write(_("no patches applied\n"))
2168 return 1
2167 return 1
2169 q.qseries(repo, start=l - 2, length=1, status='A',
2168 q.qseries(repo, start=l - 2, length=1, status='A',
2170 summary=opts.get('summary'))
2169 summary=opts.get('summary'))
2171
2170
2172 def setupheaderopts(ui, opts):
2171 def setupheaderopts(ui, opts):
2173 if not opts.get('user') and opts.get('currentuser'):
2172 if not opts.get('user') and opts.get('currentuser'):
2174 opts['user'] = ui.username()
2173 opts['user'] = ui.username()
2175 if not opts.get('date') and opts.get('currentdate'):
2174 if not opts.get('date') and opts.get('currentdate'):
2176 opts['date'] = "%d %d" % util.makedate()
2175 opts['date'] = "%d %d" % util.makedate()
2177
2176
2178 @command("^qnew",
2177 @command("^qnew",
2179 [('e', 'edit', None, _('edit commit message')),
2178 [('e', 'edit', None, _('edit commit message')),
2180 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2179 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2181 ('g', 'git', None, _('use git extended diff format')),
2180 ('g', 'git', None, _('use git extended diff format')),
2182 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2181 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2183 ('u', 'user', '',
2182 ('u', 'user', '',
2184 _('add "From: <USER>" to patch'), _('USER')),
2183 _('add "From: <USER>" to patch'), _('USER')),
2185 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2184 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2186 ('d', 'date', '',
2185 ('d', 'date', '',
2187 _('add "Date: <DATE>" to patch'), _('DATE'))
2186 _('add "Date: <DATE>" to patch'), _('DATE'))
2188 ] + commands.walkopts + commands.commitopts,
2187 ] + commands.walkopts + commands.commitopts,
2189 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2188 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2190 def new(ui, repo, patch, *args, **opts):
2189 def new(ui, repo, patch, *args, **opts):
2191 """create a new patch
2190 """create a new patch
2192
2191
2193 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
2194 any). The patch will be initialized with any outstanding changes
2193 any). The patch will be initialized with any outstanding changes
2195 in the working directory. You may also use -I/--include,
2194 in the working directory. You may also use -I/--include,
2196 -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
2197 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
2198 as uncommitted modifications.
2197 as uncommitted modifications.
2199
2198
2200 -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
2201 date, respectively. -U/--currentuser and -D/--currentdate set user
2200 date, respectively. -U/--currentuser and -D/--currentdate set user
2202 to current user and date to current date.
2201 to current user and date to current date.
2203
2202
2204 -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
2205 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
2206 empty and the commit message is '[mq]: PATCH'.
2205 empty and the commit message is '[mq]: PATCH'.
2207
2206
2208 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
2209 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
2210 is important for preserving permission changes and copy/rename
2209 is important for preserving permission changes and copy/rename
2211 information.
2210 information.
2212
2211
2213 Returns 0 on successful creation of a new patch.
2212 Returns 0 on successful creation of a new patch.
2214 """
2213 """
2215 msg = cmdutil.logmessage(opts)
2214 msg = cmdutil.logmessage(opts)
2216 def getmsg():
2215 def getmsg():
2217 return ui.edit(msg, opts.get('user') or ui.username())
2216 return ui.edit(msg, opts.get('user') or ui.username())
2218 q = repo.mq
2217 q = repo.mq
2219 opts['msg'] = msg
2218 opts['msg'] = msg
2220 if opts.get('edit'):
2219 if opts.get('edit'):
2221 opts['msg'] = getmsg
2220 opts['msg'] = getmsg
2222 else:
2221 else:
2223 opts['msg'] = msg
2222 opts['msg'] = msg
2224 setupheaderopts(ui, opts)
2223 setupheaderopts(ui, opts)
2225 q.new(repo, patch, *args, **opts)
2224 q.new(repo, patch, *args, **opts)
2226 q.save_dirty()
2225 q.save_dirty()
2227 return 0
2226 return 0
2228
2227
2229 @command("^qrefresh",
2228 @command("^qrefresh",
2230 [('e', 'edit', None, _('edit commit message')),
2229 [('e', 'edit', None, _('edit commit message')),
2231 ('g', 'git', None, _('use git extended diff format')),
2230 ('g', 'git', None, _('use git extended diff format')),
2232 ('s', 'short', None,
2231 ('s', 'short', None,
2233 _('refresh only files already in the patch and specified files')),
2232 _('refresh only files already in the patch and specified files')),
2234 ('U', 'currentuser', None,
2233 ('U', 'currentuser', None,
2235 _('add/update author field in patch with current user')),
2234 _('add/update author field in patch with current user')),
2236 ('u', 'user', '',
2235 ('u', 'user', '',
2237 _('add/update author field in patch with given user'), _('USER')),
2236 _('add/update author field in patch with given user'), _('USER')),
2238 ('D', 'currentdate', None,
2237 ('D', 'currentdate', None,
2239 _('add/update date field in patch with current date')),
2238 _('add/update date field in patch with current date')),
2240 ('d', 'date', '',
2239 ('d', 'date', '',
2241 _('add/update date field in patch with given date'), _('DATE'))
2240 _('add/update date field in patch with given date'), _('DATE'))
2242 ] + commands.walkopts + commands.commitopts,
2241 ] + commands.walkopts + commands.commitopts,
2243 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2242 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2244 def refresh(ui, repo, *pats, **opts):
2243 def refresh(ui, repo, *pats, **opts):
2245 """update the current patch
2244 """update the current patch
2246
2245
2247 If any file patterns are provided, the refreshed patch will
2246 If any file patterns are provided, the refreshed patch will
2248 contain only the modifications that match those patterns; the
2247 contain only the modifications that match those patterns; the
2249 remaining modifications will remain in the working directory.
2248 remaining modifications will remain in the working directory.
2250
2249
2251 If -s/--short is specified, files currently included in the patch
2250 If -s/--short is specified, files currently included in the patch
2252 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.
2253
2252
2254 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
2255 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
2256 your message in ``.hg/last-message.txt``.
2255 your message in ``.hg/last-message.txt``.
2257
2256
2258 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
2259 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
2260 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
2261 git diff format.
2260 git diff format.
2262
2261
2263 Returns 0 on success.
2262 Returns 0 on success.
2264 """
2263 """
2265 q = repo.mq
2264 q = repo.mq
2266 message = cmdutil.logmessage(opts)
2265 message = cmdutil.logmessage(opts)
2267 if opts.get('edit'):
2266 if opts.get('edit'):
2268 if not q.applied:
2267 if not q.applied:
2269 ui.write(_("no patches applied\n"))
2268 ui.write(_("no patches applied\n"))
2270 return 1
2269 return 1
2271 if message:
2270 if message:
2272 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2271 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2273 patch = q.applied[-1].name
2272 patch = q.applied[-1].name
2274 ph = patchheader(q.join(patch), q.plainmode)
2273 ph = patchheader(q.join(patch), q.plainmode)
2275 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())
2276 # 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)
2277 msgfile = repo.opener('last-message.txt', 'wb')
2276 msgfile = repo.opener('last-message.txt', 'wb')
2278 msgfile.write(message)
2277 msgfile.write(message)
2279 msgfile.close()
2278 msgfile.close()
2280 setupheaderopts(ui, opts)
2279 setupheaderopts(ui, opts)
2281 ret = q.refresh(repo, pats, msg=message, **opts)
2280 ret = q.refresh(repo, pats, msg=message, **opts)
2282 q.save_dirty()
2281 q.save_dirty()
2283 return ret
2282 return ret
2284
2283
2285 @command("^qdiff",
2284 @command("^qdiff",
2286 commands.diffopts + commands.diffopts2 + commands.walkopts,
2285 commands.diffopts + commands.diffopts2 + commands.walkopts,
2287 _('hg qdiff [OPTION]... [FILE]...'))
2286 _('hg qdiff [OPTION]... [FILE]...'))
2288 def diff(ui, repo, *pats, **opts):
2287 def diff(ui, repo, *pats, **opts):
2289 """diff of the current patch and subsequent modifications
2288 """diff of the current patch and subsequent modifications
2290
2289
2291 Shows a diff which includes the current patch as well as any
2290 Shows a diff which includes the current patch as well as any
2292 changes which have been made in the working directory since the
2291 changes which have been made in the working directory since the
2293 last refresh (thus showing what the current patch would become
2292 last refresh (thus showing what the current patch would become
2294 after a qrefresh).
2293 after a qrefresh).
2295
2294
2296 Use :hg:`diff` if you only want to see the changes made since the
2295 Use :hg:`diff` if you only want to see the changes made since the
2297 last qrefresh, or :hg:`export qtip` if you want to see changes
2296 last qrefresh, or :hg:`export qtip` if you want to see changes
2298 made by the current patch without including changes made since the
2297 made by the current patch without including changes made since the
2299 qrefresh.
2298 qrefresh.
2300
2299
2301 Returns 0 on success.
2300 Returns 0 on success.
2302 """
2301 """
2303 repo.mq.diff(repo, pats, opts)
2302 repo.mq.diff(repo, pats, opts)
2304 return 0
2303 return 0
2305
2304
2306 @command('qfold',
2305 @command('qfold',
2307 [('e', 'edit', None, _('edit patch header')),
2306 [('e', 'edit', None, _('edit patch header')),
2308 ('k', 'keep', None, _('keep folded patch files')),
2307 ('k', 'keep', None, _('keep folded patch files')),
2309 ] + commands.commitopts,
2308 ] + commands.commitopts,
2310 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2309 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2311 def fold(ui, repo, *files, **opts):
2310 def fold(ui, repo, *files, **opts):
2312 """fold the named patches into the current patch
2311 """fold the named patches into the current patch
2313
2312
2314 Patches must not yet be applied. Each patch will be successively
2313 Patches must not yet be applied. Each patch will be successively
2315 applied to the current patch in the order given. If all the
2314 applied to the current patch in the order given. If all the
2316 patches apply successfully, the current patch will be refreshed
2315 patches apply successfully, the current patch will be refreshed
2317 with the new cumulative patch, and the folded patches will be
2316 with the new cumulative patch, and the folded patches will be
2318 deleted. With -k/--keep, the folded patch files will not be
2317 deleted. With -k/--keep, the folded patch files will not be
2319 removed afterwards.
2318 removed afterwards.
2320
2319
2321 The header for each folded patch will be concatenated with the
2320 The header for each folded patch will be concatenated with the
2322 current patch header, separated by a line of ``* * *``.
2321 current patch header, separated by a line of ``* * *``.
2323
2322
2324 Returns 0 on success."""
2323 Returns 0 on success."""
2325
2324
2326 q = repo.mq
2325 q = repo.mq
2327
2326
2328 if not files:
2327 if not files:
2329 raise util.Abort(_('qfold requires at least one patch name'))
2328 raise util.Abort(_('qfold requires at least one patch name'))
2330 if not q.check_toppatch(repo)[0]:
2329 if not q.check_toppatch(repo)[0]:
2331 raise util.Abort(_('no patches applied'))
2330 raise util.Abort(_('no patches applied'))
2332 q.check_localchanges(repo)
2331 q.check_localchanges(repo)
2333
2332
2334 message = cmdutil.logmessage(opts)
2333 message = cmdutil.logmessage(opts)
2335 if opts.get('edit'):
2334 if opts.get('edit'):
2336 if message:
2335 if message:
2337 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2336 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2338
2337
2339 parent = q.lookup('qtip')
2338 parent = q.lookup('qtip')
2340 patches = []
2339 patches = []
2341 messages = []
2340 messages = []
2342 for f in files:
2341 for f in files:
2343 p = q.lookup(f)
2342 p = q.lookup(f)
2344 if p in patches or p == parent:
2343 if p in patches or p == parent:
2345 ui.warn(_('Skipping already folded patch %s\n') % p)
2344 ui.warn(_('Skipping already folded patch %s\n') % p)
2346 if q.isapplied(p):
2345 if q.isapplied(p):
2347 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2346 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2348 patches.append(p)
2347 patches.append(p)
2349
2348
2350 for p in patches:
2349 for p in patches:
2351 if not message:
2350 if not message:
2352 ph = patchheader(q.join(p), q.plainmode)
2351 ph = patchheader(q.join(p), q.plainmode)
2353 if ph.message:
2352 if ph.message:
2354 messages.append(ph.message)
2353 messages.append(ph.message)
2355 pf = q.join(p)
2354 pf = q.join(p)
2356 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2355 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2357 if not patchsuccess:
2356 if not patchsuccess:
2358 raise util.Abort(_('error folding patch %s') % p)
2357 raise util.Abort(_('error folding patch %s') % p)
2359
2358
2360 if not message:
2359 if not message:
2361 ph = patchheader(q.join(parent), q.plainmode)
2360 ph = patchheader(q.join(parent), q.plainmode)
2362 message, user = ph.message, ph.user
2361 message, user = ph.message, ph.user
2363 for msg in messages:
2362 for msg in messages:
2364 message.append('* * *')
2363 message.append('* * *')
2365 message.extend(msg)
2364 message.extend(msg)
2366 message = '\n'.join(message)
2365 message = '\n'.join(message)
2367
2366
2368 if opts.get('edit'):
2367 if opts.get('edit'):
2369 message = ui.edit(message, user or ui.username())
2368 message = ui.edit(message, user or ui.username())
2370
2369
2371 diffopts = q.patchopts(q.diffopts(), *patches)
2370 diffopts = q.patchopts(q.diffopts(), *patches)
2372 q.refresh(repo, msg=message, git=diffopts.git)
2371 q.refresh(repo, msg=message, git=diffopts.git)
2373 q.delete(repo, patches, opts)
2372 q.delete(repo, patches, opts)
2374 q.save_dirty()
2373 q.save_dirty()
2375
2374
2376 @command("qgoto",
2375 @command("qgoto",
2377 [('f', 'force', None, _('overwrite any local changes'))],
2376 [('f', 'force', None, _('overwrite any local changes'))],
2378 _('hg qgoto [OPTION]... PATCH'))
2377 _('hg qgoto [OPTION]... PATCH'))
2379 def goto(ui, repo, patch, **opts):
2378 def goto(ui, repo, patch, **opts):
2380 '''push or pop patches until named patch is at top of stack
2379 '''push or pop patches until named patch is at top of stack
2381
2380
2382 Returns 0 on success.'''
2381 Returns 0 on success.'''
2383 q = repo.mq
2382 q = repo.mq
2384 patch = q.lookup(patch)
2383 patch = q.lookup(patch)
2385 if q.isapplied(patch):
2384 if q.isapplied(patch):
2386 ret = q.pop(repo, patch, force=opts.get('force'))
2385 ret = q.pop(repo, patch, force=opts.get('force'))
2387 else:
2386 else:
2388 ret = q.push(repo, patch, force=opts.get('force'))
2387 ret = q.push(repo, patch, force=opts.get('force'))
2389 q.save_dirty()
2388 q.save_dirty()
2390 return ret
2389 return ret
2391
2390
2392 @command("qguard",
2391 @command("qguard",
2393 [('l', 'list', None, _('list all patches and guards')),
2392 [('l', 'list', None, _('list all patches and guards')),
2394 ('n', 'none', None, _('drop all guards'))],
2393 ('n', 'none', None, _('drop all guards'))],
2395 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2394 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2396 def guard(ui, repo, *args, **opts):
2395 def guard(ui, repo, *args, **opts):
2397 '''set or print guards for a patch
2396 '''set or print guards for a patch
2398
2397
2399 Guards control whether a patch can be pushed. A patch with no
2398 Guards control whether a patch can be pushed. A patch with no
2400 guards is always pushed. A patch with a positive guard ("+foo") is
2399 guards is always pushed. A patch with a positive guard ("+foo") is
2401 pushed only if the :hg:`qselect` command has activated it. A patch with
2400 pushed only if the :hg:`qselect` command has activated it. A patch with
2402 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2401 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2403 has activated it.
2402 has activated it.
2404
2403
2405 With no arguments, print the currently active guards.
2404 With no arguments, print the currently active guards.
2406 With arguments, set guards for the named patch.
2405 With arguments, set guards for the named patch.
2407
2406
2408 .. note::
2407 .. note::
2409 Specifying negative guards now requires '--'.
2408 Specifying negative guards now requires '--'.
2410
2409
2411 To set guards on another patch::
2410 To set guards on another patch::
2412
2411
2413 hg qguard other.patch -- +2.6.17 -stable
2412 hg qguard other.patch -- +2.6.17 -stable
2414
2413
2415 Returns 0 on success.
2414 Returns 0 on success.
2416 '''
2415 '''
2417 def status(idx):
2416 def status(idx):
2418 guards = q.series_guards[idx] or ['unguarded']
2417 guards = q.series_guards[idx] or ['unguarded']
2419 if q.series[idx] in applied:
2418 if q.series[idx] in applied:
2420 state = 'applied'
2419 state = 'applied'
2421 elif q.pushable(idx)[0]:
2420 elif q.pushable(idx)[0]:
2422 state = 'unapplied'
2421 state = 'unapplied'
2423 else:
2422 else:
2424 state = 'guarded'
2423 state = 'guarded'
2425 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2424 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2426 ui.write('%s: ' % ui.label(q.series[idx], label))
2425 ui.write('%s: ' % ui.label(q.series[idx], label))
2427
2426
2428 for i, guard in enumerate(guards):
2427 for i, guard in enumerate(guards):
2429 if guard.startswith('+'):
2428 if guard.startswith('+'):
2430 ui.write(guard, label='qguard.positive')
2429 ui.write(guard, label='qguard.positive')
2431 elif guard.startswith('-'):
2430 elif guard.startswith('-'):
2432 ui.write(guard, label='qguard.negative')
2431 ui.write(guard, label='qguard.negative')
2433 else:
2432 else:
2434 ui.write(guard, label='qguard.unguarded')
2433 ui.write(guard, label='qguard.unguarded')
2435 if i != len(guards) - 1:
2434 if i != len(guards) - 1:
2436 ui.write(' ')
2435 ui.write(' ')
2437 ui.write('\n')
2436 ui.write('\n')
2438 q = repo.mq
2437 q = repo.mq
2439 applied = set(p.name for p in q.applied)
2438 applied = set(p.name for p in q.applied)
2440 patch = None
2439 patch = None
2441 args = list(args)
2440 args = list(args)
2442 if opts.get('list'):
2441 if opts.get('list'):
2443 if args or opts.get('none'):
2442 if args or opts.get('none'):
2444 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2443 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2445 for i in xrange(len(q.series)):
2444 for i in xrange(len(q.series)):
2446 status(i)
2445 status(i)
2447 return
2446 return
2448 if not args or args[0][0:1] in '-+':
2447 if not args or args[0][0:1] in '-+':
2449 if not q.applied:
2448 if not q.applied:
2450 raise util.Abort(_('no patches applied'))
2449 raise util.Abort(_('no patches applied'))
2451 patch = q.applied[-1].name
2450 patch = q.applied[-1].name
2452 if patch is None and args[0][0:1] not in '-+':
2451 if patch is None and args[0][0:1] not in '-+':
2453 patch = args.pop(0)
2452 patch = args.pop(0)
2454 if patch is None:
2453 if patch is None:
2455 raise util.Abort(_('no patch to work with'))
2454 raise util.Abort(_('no patch to work with'))
2456 if args or opts.get('none'):
2455 if args or opts.get('none'):
2457 idx = q.find_series(patch)
2456 idx = q.find_series(patch)
2458 if idx is None:
2457 if idx is None:
2459 raise util.Abort(_('no patch named %s') % patch)
2458 raise util.Abort(_('no patch named %s') % patch)
2460 q.set_guards(idx, args)
2459 q.set_guards(idx, args)
2461 q.save_dirty()
2460 q.save_dirty()
2462 else:
2461 else:
2463 status(q.series.index(q.lookup(patch)))
2462 status(q.series.index(q.lookup(patch)))
2464
2463
2465 @command("qheader", [], _('hg qheader [PATCH]'))
2464 @command("qheader", [], _('hg qheader [PATCH]'))
2466 def header(ui, repo, patch=None):
2465 def header(ui, repo, patch=None):
2467 """print the header of the topmost or specified patch
2466 """print the header of the topmost or specified patch
2468
2467
2469 Returns 0 on success."""
2468 Returns 0 on success."""
2470 q = repo.mq
2469 q = repo.mq
2471
2470
2472 if patch:
2471 if patch:
2473 patch = q.lookup(patch)
2472 patch = q.lookup(patch)
2474 else:
2473 else:
2475 if not q.applied:
2474 if not q.applied:
2476 ui.write(_('no patches applied\n'))
2475 ui.write(_('no patches applied\n'))
2477 return 1
2476 return 1
2478 patch = q.lookup('qtip')
2477 patch = q.lookup('qtip')
2479 ph = patchheader(q.join(patch), q.plainmode)
2478 ph = patchheader(q.join(patch), q.plainmode)
2480
2479
2481 ui.write('\n'.join(ph.message) + '\n')
2480 ui.write('\n'.join(ph.message) + '\n')
2482
2481
2483 def lastsavename(path):
2482 def lastsavename(path):
2484 (directory, base) = os.path.split(path)
2483 (directory, base) = os.path.split(path)
2485 names = os.listdir(directory)
2484 names = os.listdir(directory)
2486 namere = re.compile("%s.([0-9]+)" % base)
2485 namere = re.compile("%s.([0-9]+)" % base)
2487 maxindex = None
2486 maxindex = None
2488 maxname = None
2487 maxname = None
2489 for f in names:
2488 for f in names:
2490 m = namere.match(f)
2489 m = namere.match(f)
2491 if m:
2490 if m:
2492 index = int(m.group(1))
2491 index = int(m.group(1))
2493 if maxindex is None or index > maxindex:
2492 if maxindex is None or index > maxindex:
2494 maxindex = index
2493 maxindex = index
2495 maxname = f
2494 maxname = f
2496 if maxname:
2495 if maxname:
2497 return (os.path.join(directory, maxname), maxindex)
2496 return (os.path.join(directory, maxname), maxindex)
2498 return (None, None)
2497 return (None, None)
2499
2498
2500 def savename(path):
2499 def savename(path):
2501 (last, index) = lastsavename(path)
2500 (last, index) = lastsavename(path)
2502 if last is None:
2501 if last is None:
2503 index = 0
2502 index = 0
2504 newpath = path + ".%d" % (index + 1)
2503 newpath = path + ".%d" % (index + 1)
2505 return newpath
2504 return newpath
2506
2505
2507 @command("^qpush",
2506 @command("^qpush",
2508 [('f', 'force', None, _('apply on top of local changes')),
2507 [('f', 'force', None, _('apply on top of local changes')),
2509 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2508 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2510 ('l', 'list', None, _('list patch name in commit text')),
2509 ('l', 'list', None, _('list patch name in commit text')),
2511 ('a', 'all', None, _('apply all patches')),
2510 ('a', 'all', None, _('apply all patches')),
2512 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2511 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2513 ('n', 'name', '',
2512 ('n', 'name', '',
2514 _('merge queue name (DEPRECATED)'), _('NAME')),
2513 _('merge queue name (DEPRECATED)'), _('NAME')),
2515 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2514 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2516 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2515 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2517 def push(ui, repo, patch=None, **opts):
2516 def push(ui, repo, patch=None, **opts):
2518 """push the next patch onto the stack
2517 """push the next patch onto the stack
2519
2518
2520 When -f/--force is applied, all local changes in patched files
2519 When -f/--force is applied, all local changes in patched files
2521 will be lost.
2520 will be lost.
2522
2521
2523 Return 0 on success.
2522 Return 0 on success.
2524 """
2523 """
2525 q = repo.mq
2524 q = repo.mq
2526 mergeq = None
2525 mergeq = None
2527
2526
2528 if opts.get('merge'):
2527 if opts.get('merge'):
2529 if opts.get('name'):
2528 if opts.get('name'):
2530 newpath = repo.join(opts.get('name'))
2529 newpath = repo.join(opts.get('name'))
2531 else:
2530 else:
2532 newpath, i = lastsavename(q.path)
2531 newpath, i = lastsavename(q.path)
2533 if not newpath:
2532 if not newpath:
2534 ui.warn(_("no saved queues found, please use -n\n"))
2533 ui.warn(_("no saved queues found, please use -n\n"))
2535 return 1
2534 return 1
2536 mergeq = queue(ui, repo.join(""), newpath)
2535 mergeq = queue(ui, repo.join(""), newpath)
2537 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2536 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2538 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2537 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2539 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2538 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2540 exact=opts.get('exact'))
2539 exact=opts.get('exact'))
2541 return ret
2540 return ret
2542
2541
2543 @command("^qpop",
2542 @command("^qpop",
2544 [('a', 'all', None, _('pop all patches')),
2543 [('a', 'all', None, _('pop all patches')),
2545 ('n', 'name', '',
2544 ('n', 'name', '',
2546 _('queue name to pop (DEPRECATED)'), _('NAME')),
2545 _('queue name to pop (DEPRECATED)'), _('NAME')),
2547 ('f', 'force', None, _('forget any local changes to patched files'))],
2546 ('f', 'force', None, _('forget any local changes to patched files'))],
2548 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2547 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2549 def pop(ui, repo, patch=None, **opts):
2548 def pop(ui, repo, patch=None, **opts):
2550 """pop the current patch off the stack
2549 """pop the current patch off the stack
2551
2550
2552 By default, pops off the top of the patch stack. If given a patch
2551 By default, pops off the top of the patch stack. If given a patch
2553 name, keeps popping off patches until the named patch is at the
2552 name, keeps popping off patches until the named patch is at the
2554 top of the stack.
2553 top of the stack.
2555
2554
2556 Return 0 on success.
2555 Return 0 on success.
2557 """
2556 """
2558 localupdate = True
2557 localupdate = True
2559 if opts.get('name'):
2558 if opts.get('name'):
2560 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2559 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2561 ui.warn(_('using patch queue: %s\n') % q.path)
2560 ui.warn(_('using patch queue: %s\n') % q.path)
2562 localupdate = False
2561 localupdate = False
2563 else:
2562 else:
2564 q = repo.mq
2563 q = repo.mq
2565 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2564 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2566 all=opts.get('all'))
2565 all=opts.get('all'))
2567 q.save_dirty()
2566 q.save_dirty()
2568 return ret
2567 return ret
2569
2568
2570 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2569 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2571 def rename(ui, repo, patch, name=None, **opts):
2570 def rename(ui, repo, patch, name=None, **opts):
2572 """rename a patch
2571 """rename a patch
2573
2572
2574 With one argument, renames the current patch to PATCH1.
2573 With one argument, renames the current patch to PATCH1.
2575 With two arguments, renames PATCH1 to PATCH2.
2574 With two arguments, renames PATCH1 to PATCH2.
2576
2575
2577 Returns 0 on success."""
2576 Returns 0 on success."""
2578
2577
2579 q = repo.mq
2578 q = repo.mq
2580
2579
2581 if not name:
2580 if not name:
2582 name = patch
2581 name = patch
2583 patch = None
2582 patch = None
2584
2583
2585 if patch:
2584 if patch:
2586 patch = q.lookup(patch)
2585 patch = q.lookup(patch)
2587 else:
2586 else:
2588 if not q.applied:
2587 if not q.applied:
2589 ui.write(_('no patches applied\n'))
2588 ui.write(_('no patches applied\n'))
2590 return
2589 return
2591 patch = q.lookup('qtip')
2590 patch = q.lookup('qtip')
2592 absdest = q.join(name)
2591 absdest = q.join(name)
2593 if os.path.isdir(absdest):
2592 if os.path.isdir(absdest):
2594 name = normname(os.path.join(name, os.path.basename(patch)))
2593 name = normname(os.path.join(name, os.path.basename(patch)))
2595 absdest = q.join(name)
2594 absdest = q.join(name)
2596 q.checkpatchname(name)
2595 q.checkpatchname(name)
2597
2596
2598 ui.note(_('renaming %s to %s\n') % (patch, name))
2597 ui.note(_('renaming %s to %s\n') % (patch, name))
2599 i = q.find_series(patch)
2598 i = q.find_series(patch)
2600 guards = q.guard_re.findall(q.full_series[i])
2599 guards = q.guard_re.findall(q.full_series[i])
2601 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2600 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2602 q.parse_series()
2601 q.parse_series()
2603 q.series_dirty = 1
2602 q.series_dirty = 1
2604
2603
2605 info = q.isapplied(patch)
2604 info = q.isapplied(patch)
2606 if info:
2605 if info:
2607 q.applied[info[0]] = statusentry(info[1], name)
2606 q.applied[info[0]] = statusentry(info[1], name)
2608 q.applied_dirty = 1
2607 q.applied_dirty = 1
2609
2608
2610 destdir = os.path.dirname(absdest)
2609 destdir = os.path.dirname(absdest)
2611 if not os.path.isdir(destdir):
2610 if not os.path.isdir(destdir):
2612 os.makedirs(destdir)
2611 os.makedirs(destdir)
2613 util.rename(q.join(patch), absdest)
2612 util.rename(q.join(patch), absdest)
2614 r = q.qrepo()
2613 r = q.qrepo()
2615 if r and patch in r.dirstate:
2614 if r and patch in r.dirstate:
2616 wctx = r[None]
2615 wctx = r[None]
2617 wlock = r.wlock()
2616 wlock = r.wlock()
2618 try:
2617 try:
2619 if r.dirstate[patch] == 'a':
2618 if r.dirstate[patch] == 'a':
2620 r.dirstate.drop(patch)
2619 r.dirstate.drop(patch)
2621 r.dirstate.add(name)
2620 r.dirstate.add(name)
2622 else:
2621 else:
2623 if r.dirstate[name] == 'r':
2622 if r.dirstate[name] == 'r':
2624 wctx.undelete([name])
2623 wctx.undelete([name])
2625 wctx.copy(patch, name)
2624 wctx.copy(patch, name)
2626 wctx.remove([patch], False)
2625 wctx.forget([patch])
2627 finally:
2626 finally:
2628 wlock.release()
2627 wlock.release()
2629
2628
2630 q.save_dirty()
2629 q.save_dirty()
2631
2630
2632 @command("qrestore",
2631 @command("qrestore",
2633 [('d', 'delete', None, _('delete save entry')),
2632 [('d', 'delete', None, _('delete save entry')),
2634 ('u', 'update', None, _('update queue working directory'))],
2633 ('u', 'update', None, _('update queue working directory'))],
2635 _('hg qrestore [-d] [-u] REV'))
2634 _('hg qrestore [-d] [-u] REV'))
2636 def restore(ui, repo, rev, **opts):
2635 def restore(ui, repo, rev, **opts):
2637 """restore the queue state saved by a revision (DEPRECATED)
2636 """restore the queue state saved by a revision (DEPRECATED)
2638
2637
2639 This command is deprecated, use :hg:`rebase` instead."""
2638 This command is deprecated, use :hg:`rebase` instead."""
2640 rev = repo.lookup(rev)
2639 rev = repo.lookup(rev)
2641 q = repo.mq
2640 q = repo.mq
2642 q.restore(repo, rev, delete=opts.get('delete'),
2641 q.restore(repo, rev, delete=opts.get('delete'),
2643 qupdate=opts.get('update'))
2642 qupdate=opts.get('update'))
2644 q.save_dirty()
2643 q.save_dirty()
2645 return 0
2644 return 0
2646
2645
2647 @command("qsave",
2646 @command("qsave",
2648 [('c', 'copy', None, _('copy patch directory')),
2647 [('c', 'copy', None, _('copy patch directory')),
2649 ('n', 'name', '',
2648 ('n', 'name', '',
2650 _('copy directory name'), _('NAME')),
2649 _('copy directory name'), _('NAME')),
2651 ('e', 'empty', None, _('clear queue status file')),
2650 ('e', 'empty', None, _('clear queue status file')),
2652 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2651 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2653 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2652 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2654 def save(ui, repo, **opts):
2653 def save(ui, repo, **opts):
2655 """save current queue state (DEPRECATED)
2654 """save current queue state (DEPRECATED)
2656
2655
2657 This command is deprecated, use :hg:`rebase` instead."""
2656 This command is deprecated, use :hg:`rebase` instead."""
2658 q = repo.mq
2657 q = repo.mq
2659 message = cmdutil.logmessage(opts)
2658 message = cmdutil.logmessage(opts)
2660 ret = q.save(repo, msg=message)
2659 ret = q.save(repo, msg=message)
2661 if ret:
2660 if ret:
2662 return ret
2661 return ret
2663 q.save_dirty()
2662 q.save_dirty()
2664 if opts.get('copy'):
2663 if opts.get('copy'):
2665 path = q.path
2664 path = q.path
2666 if opts.get('name'):
2665 if opts.get('name'):
2667 newpath = os.path.join(q.basepath, opts.get('name'))
2666 newpath = os.path.join(q.basepath, opts.get('name'))
2668 if os.path.exists(newpath):
2667 if os.path.exists(newpath):
2669 if not os.path.isdir(newpath):
2668 if not os.path.isdir(newpath):
2670 raise util.Abort(_('destination %s exists and is not '
2669 raise util.Abort(_('destination %s exists and is not '
2671 'a directory') % newpath)
2670 'a directory') % newpath)
2672 if not opts.get('force'):
2671 if not opts.get('force'):
2673 raise util.Abort(_('destination %s exists, '
2672 raise util.Abort(_('destination %s exists, '
2674 'use -f to force') % newpath)
2673 'use -f to force') % newpath)
2675 else:
2674 else:
2676 newpath = savename(path)
2675 newpath = savename(path)
2677 ui.warn(_("copy %s to %s\n") % (path, newpath))
2676 ui.warn(_("copy %s to %s\n") % (path, newpath))
2678 util.copyfiles(path, newpath)
2677 util.copyfiles(path, newpath)
2679 if opts.get('empty'):
2678 if opts.get('empty'):
2680 try:
2679 try:
2681 os.unlink(q.join(q.status_path))
2680 os.unlink(q.join(q.status_path))
2682 except:
2681 except:
2683 pass
2682 pass
2684 return 0
2683 return 0
2685
2684
2686 @command("strip",
2685 @command("strip",
2687 [('f', 'force', None, _('force removal of changesets, discard '
2686 [('f', 'force', None, _('force removal of changesets, discard '
2688 'uncommitted changes (no backup)')),
2687 'uncommitted changes (no backup)')),
2689 ('b', 'backup', None, _('bundle only changesets with local revision'
2688 ('b', 'backup', None, _('bundle only changesets with local revision'
2690 ' number greater than REV which are not'
2689 ' number greater than REV which are not'
2691 ' descendants of REV (DEPRECATED)')),
2690 ' descendants of REV (DEPRECATED)')),
2692 ('n', 'no-backup', None, _('no backups')),
2691 ('n', 'no-backup', None, _('no backups')),
2693 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2692 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2694 ('k', 'keep', None, _("do not modify working copy during strip"))],
2693 ('k', 'keep', None, _("do not modify working copy during strip"))],
2695 _('hg strip [-k] [-f] [-n] REV...'))
2694 _('hg strip [-k] [-f] [-n] REV...'))
2696 def strip(ui, repo, *revs, **opts):
2695 def strip(ui, repo, *revs, **opts):
2697 """strip changesets and all their descendants from the repository
2696 """strip changesets and all their descendants from the repository
2698
2697
2699 The strip command removes the specified changesets and all their
2698 The strip command removes the specified changesets and all their
2700 descendants. If the working directory has uncommitted changes, the
2699 descendants. If the working directory has uncommitted changes, the
2701 operation is aborted unless the --force flag is supplied, in which
2700 operation is aborted unless the --force flag is supplied, in which
2702 case changes will be discarded.
2701 case changes will be discarded.
2703
2702
2704 If a parent of the working directory is stripped, then the working
2703 If a parent of the working directory is stripped, then the working
2705 directory will automatically be updated to the most recent
2704 directory will automatically be updated to the most recent
2706 available ancestor of the stripped parent after the operation
2705 available ancestor of the stripped parent after the operation
2707 completes.
2706 completes.
2708
2707
2709 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2708 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2710 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2709 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2711 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2710 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2712 where BUNDLE is the bundle file created by the strip. Note that
2711 where BUNDLE is the bundle file created by the strip. Note that
2713 the local revision numbers will in general be different after the
2712 the local revision numbers will in general be different after the
2714 restore.
2713 restore.
2715
2714
2716 Use the --no-backup option to discard the backup bundle once the
2715 Use the --no-backup option to discard the backup bundle once the
2717 operation completes.
2716 operation completes.
2718
2717
2719 Return 0 on success.
2718 Return 0 on success.
2720 """
2719 """
2721 backup = 'all'
2720 backup = 'all'
2722 if opts.get('backup'):
2721 if opts.get('backup'):
2723 backup = 'strip'
2722 backup = 'strip'
2724 elif opts.get('no_backup') or opts.get('nobackup'):
2723 elif opts.get('no_backup') or opts.get('nobackup'):
2725 backup = 'none'
2724 backup = 'none'
2726
2725
2727 cl = repo.changelog
2726 cl = repo.changelog
2728 revs = set(scmutil.revrange(repo, revs))
2727 revs = set(scmutil.revrange(repo, revs))
2729 if not revs:
2728 if not revs:
2730 raise util.Abort(_('empty revision set'))
2729 raise util.Abort(_('empty revision set'))
2731
2730
2732 descendants = set(cl.descendants(*revs))
2731 descendants = set(cl.descendants(*revs))
2733 strippedrevs = revs.union(descendants)
2732 strippedrevs = revs.union(descendants)
2734 roots = revs.difference(descendants)
2733 roots = revs.difference(descendants)
2735
2734
2736 update = False
2735 update = False
2737 # if one of the wdir parent is stripped we'll need
2736 # if one of the wdir parent is stripped we'll need
2738 # to update away to an earlier revision
2737 # to update away to an earlier revision
2739 for p in repo.dirstate.parents():
2738 for p in repo.dirstate.parents():
2740 if p != nullid and cl.rev(p) in strippedrevs:
2739 if p != nullid and cl.rev(p) in strippedrevs:
2741 update = True
2740 update = True
2742 break
2741 break
2743
2742
2744 rootnodes = set(cl.node(r) for r in roots)
2743 rootnodes = set(cl.node(r) for r in roots)
2745
2744
2746 q = repo.mq
2745 q = repo.mq
2747 if q.applied:
2746 if q.applied:
2748 # refresh queue state if we're about to strip
2747 # refresh queue state if we're about to strip
2749 # applied patches
2748 # applied patches
2750 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2749 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2751 q.applied_dirty = True
2750 q.applied_dirty = True
2752 start = 0
2751 start = 0
2753 end = len(q.applied)
2752 end = len(q.applied)
2754 for i, statusentry in enumerate(q.applied):
2753 for i, statusentry in enumerate(q.applied):
2755 if statusentry.node in rootnodes:
2754 if statusentry.node in rootnodes:
2756 # if one of the stripped roots is an applied
2755 # if one of the stripped roots is an applied
2757 # patch, only part of the queue is stripped
2756 # patch, only part of the queue is stripped
2758 start = i
2757 start = i
2759 break
2758 break
2760 del q.applied[start:end]
2759 del q.applied[start:end]
2761 q.save_dirty()
2760 q.save_dirty()
2762
2761
2763 revs = list(rootnodes)
2762 revs = list(rootnodes)
2764 if update and opts.get('keep'):
2763 if update and opts.get('keep'):
2765 wlock = repo.wlock()
2764 wlock = repo.wlock()
2766 try:
2765 try:
2767 urev = repo.mq.qparents(repo, revs[0])
2766 urev = repo.mq.qparents(repo, revs[0])
2768 repo.dirstate.rebuild(urev, repo[urev].manifest())
2767 repo.dirstate.rebuild(urev, repo[urev].manifest())
2769 repo.dirstate.write()
2768 repo.dirstate.write()
2770 update = False
2769 update = False
2771 finally:
2770 finally:
2772 wlock.release()
2771 wlock.release()
2773
2772
2774 repo.mq.strip(repo, revs, backup=backup, update=update,
2773 repo.mq.strip(repo, revs, backup=backup, update=update,
2775 force=opts.get('force'))
2774 force=opts.get('force'))
2776 return 0
2775 return 0
2777
2776
2778 @command("qselect",
2777 @command("qselect",
2779 [('n', 'none', None, _('disable all guards')),
2778 [('n', 'none', None, _('disable all guards')),
2780 ('s', 'series', None, _('list all guards in series file')),
2779 ('s', 'series', None, _('list all guards in series file')),
2781 ('', 'pop', None, _('pop to before first guarded applied patch')),
2780 ('', 'pop', None, _('pop to before first guarded applied patch')),
2782 ('', 'reapply', None, _('pop, then reapply patches'))],
2781 ('', 'reapply', None, _('pop, then reapply patches'))],
2783 _('hg qselect [OPTION]... [GUARD]...'))
2782 _('hg qselect [OPTION]... [GUARD]...'))
2784 def select(ui, repo, *args, **opts):
2783 def select(ui, repo, *args, **opts):
2785 '''set or print guarded patches to push
2784 '''set or print guarded patches to push
2786
2785
2787 Use the :hg:`qguard` command to set or print guards on patch, then use
2786 Use the :hg:`qguard` command to set or print guards on patch, then use
2788 qselect to tell mq which guards to use. A patch will be pushed if
2787 qselect to tell mq which guards to use. A patch will be pushed if
2789 it has no guards or any positive guards match the currently
2788 it has no guards or any positive guards match the currently
2790 selected guard, but will not be pushed if any negative guards
2789 selected guard, but will not be pushed if any negative guards
2791 match the current guard. For example::
2790 match the current guard. For example::
2792
2791
2793 qguard foo.patch -- -stable (negative guard)
2792 qguard foo.patch -- -stable (negative guard)
2794 qguard bar.patch +stable (positive guard)
2793 qguard bar.patch +stable (positive guard)
2795 qselect stable
2794 qselect stable
2796
2795
2797 This activates the "stable" guard. mq will skip foo.patch (because
2796 This activates the "stable" guard. mq will skip foo.patch (because
2798 it has a negative match) but push bar.patch (because it has a
2797 it has a negative match) but push bar.patch (because it has a
2799 positive match).
2798 positive match).
2800
2799
2801 With no arguments, prints the currently active guards.
2800 With no arguments, prints the currently active guards.
2802 With one argument, sets the active guard.
2801 With one argument, sets the active guard.
2803
2802
2804 Use -n/--none to deactivate guards (no other arguments needed).
2803 Use -n/--none to deactivate guards (no other arguments needed).
2805 When no guards are active, patches with positive guards are
2804 When no guards are active, patches with positive guards are
2806 skipped and patches with negative guards are pushed.
2805 skipped and patches with negative guards are pushed.
2807
2806
2808 qselect can change the guards on applied patches. It does not pop
2807 qselect can change the guards on applied patches. It does not pop
2809 guarded patches by default. Use --pop to pop back to the last
2808 guarded patches by default. Use --pop to pop back to the last
2810 applied patch that is not guarded. Use --reapply (which implies
2809 applied patch that is not guarded. Use --reapply (which implies
2811 --pop) to push back to the current patch afterwards, but skip
2810 --pop) to push back to the current patch afterwards, but skip
2812 guarded patches.
2811 guarded patches.
2813
2812
2814 Use -s/--series to print a list of all guards in the series file
2813 Use -s/--series to print a list of all guards in the series file
2815 (no other arguments needed). Use -v for more information.
2814 (no other arguments needed). Use -v for more information.
2816
2815
2817 Returns 0 on success.'''
2816 Returns 0 on success.'''
2818
2817
2819 q = repo.mq
2818 q = repo.mq
2820 guards = q.active()
2819 guards = q.active()
2821 if args or opts.get('none'):
2820 if args or opts.get('none'):
2822 old_unapplied = q.unapplied(repo)
2821 old_unapplied = q.unapplied(repo)
2823 old_guarded = [i for i in xrange(len(q.applied)) if
2822 old_guarded = [i for i in xrange(len(q.applied)) if
2824 not q.pushable(i)[0]]
2823 not q.pushable(i)[0]]
2825 q.set_active(args)
2824 q.set_active(args)
2826 q.save_dirty()
2825 q.save_dirty()
2827 if not args:
2826 if not args:
2828 ui.status(_('guards deactivated\n'))
2827 ui.status(_('guards deactivated\n'))
2829 if not opts.get('pop') and not opts.get('reapply'):
2828 if not opts.get('pop') and not opts.get('reapply'):
2830 unapplied = q.unapplied(repo)
2829 unapplied = q.unapplied(repo)
2831 guarded = [i for i in xrange(len(q.applied))
2830 guarded = [i for i in xrange(len(q.applied))
2832 if not q.pushable(i)[0]]
2831 if not q.pushable(i)[0]]
2833 if len(unapplied) != len(old_unapplied):
2832 if len(unapplied) != len(old_unapplied):
2834 ui.status(_('number of unguarded, unapplied patches has '
2833 ui.status(_('number of unguarded, unapplied patches has '
2835 'changed from %d to %d\n') %
2834 'changed from %d to %d\n') %
2836 (len(old_unapplied), len(unapplied)))
2835 (len(old_unapplied), len(unapplied)))
2837 if len(guarded) != len(old_guarded):
2836 if len(guarded) != len(old_guarded):
2838 ui.status(_('number of guarded, applied patches has changed '
2837 ui.status(_('number of guarded, applied patches has changed '
2839 'from %d to %d\n') %
2838 'from %d to %d\n') %
2840 (len(old_guarded), len(guarded)))
2839 (len(old_guarded), len(guarded)))
2841 elif opts.get('series'):
2840 elif opts.get('series'):
2842 guards = {}
2841 guards = {}
2843 noguards = 0
2842 noguards = 0
2844 for gs in q.series_guards:
2843 for gs in q.series_guards:
2845 if not gs:
2844 if not gs:
2846 noguards += 1
2845 noguards += 1
2847 for g in gs:
2846 for g in gs:
2848 guards.setdefault(g, 0)
2847 guards.setdefault(g, 0)
2849 guards[g] += 1
2848 guards[g] += 1
2850 if ui.verbose:
2849 if ui.verbose:
2851 guards['NONE'] = noguards
2850 guards['NONE'] = noguards
2852 guards = guards.items()
2851 guards = guards.items()
2853 guards.sort(key=lambda x: x[0][1:])
2852 guards.sort(key=lambda x: x[0][1:])
2854 if guards:
2853 if guards:
2855 ui.note(_('guards in series file:\n'))
2854 ui.note(_('guards in series file:\n'))
2856 for guard, count in guards:
2855 for guard, count in guards:
2857 ui.note('%2d ' % count)
2856 ui.note('%2d ' % count)
2858 ui.write(guard, '\n')
2857 ui.write(guard, '\n')
2859 else:
2858 else:
2860 ui.note(_('no guards in series file\n'))
2859 ui.note(_('no guards in series file\n'))
2861 else:
2860 else:
2862 if guards:
2861 if guards:
2863 ui.note(_('active guards:\n'))
2862 ui.note(_('active guards:\n'))
2864 for g in guards:
2863 for g in guards:
2865 ui.write(g, '\n')
2864 ui.write(g, '\n')
2866 else:
2865 else:
2867 ui.write(_('no active guards\n'))
2866 ui.write(_('no active guards\n'))
2868 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2867 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2869 popped = False
2868 popped = False
2870 if opts.get('pop') or opts.get('reapply'):
2869 if opts.get('pop') or opts.get('reapply'):
2871 for i in xrange(len(q.applied)):
2870 for i in xrange(len(q.applied)):
2872 pushable, reason = q.pushable(i)
2871 pushable, reason = q.pushable(i)
2873 if not pushable:
2872 if not pushable:
2874 ui.status(_('popping guarded patches\n'))
2873 ui.status(_('popping guarded patches\n'))
2875 popped = True
2874 popped = True
2876 if i == 0:
2875 if i == 0:
2877 q.pop(repo, all=True)
2876 q.pop(repo, all=True)
2878 else:
2877 else:
2879 q.pop(repo, i - 1)
2878 q.pop(repo, i - 1)
2880 break
2879 break
2881 if popped:
2880 if popped:
2882 try:
2881 try:
2883 if reapply:
2882 if reapply:
2884 ui.status(_('reapplying unguarded patches\n'))
2883 ui.status(_('reapplying unguarded patches\n'))
2885 q.push(repo, reapply)
2884 q.push(repo, reapply)
2886 finally:
2885 finally:
2887 q.save_dirty()
2886 q.save_dirty()
2888
2887
2889 @command("qfinish",
2888 @command("qfinish",
2890 [('a', 'applied', None, _('finish all applied changesets'))],
2889 [('a', 'applied', None, _('finish all applied changesets'))],
2891 _('hg qfinish [-a] [REV]...'))
2890 _('hg qfinish [-a] [REV]...'))
2892 def finish(ui, repo, *revrange, **opts):
2891 def finish(ui, repo, *revrange, **opts):
2893 """move applied patches into repository history
2892 """move applied patches into repository history
2894
2893
2895 Finishes the specified revisions (corresponding to applied
2894 Finishes the specified revisions (corresponding to applied
2896 patches) by moving them out of mq control into regular repository
2895 patches) by moving them out of mq control into regular repository
2897 history.
2896 history.
2898
2897
2899 Accepts a revision range or the -a/--applied option. If --applied
2898 Accepts a revision range or the -a/--applied option. If --applied
2900 is specified, all applied mq revisions are removed from mq
2899 is specified, all applied mq revisions are removed from mq
2901 control. Otherwise, the given revisions must be at the base of the
2900 control. Otherwise, the given revisions must be at the base of the
2902 stack of applied patches.
2901 stack of applied patches.
2903
2902
2904 This can be especially useful if your changes have been applied to
2903 This can be especially useful if your changes have been applied to
2905 an upstream repository, or if you are about to push your changes
2904 an upstream repository, or if you are about to push your changes
2906 to upstream.
2905 to upstream.
2907
2906
2908 Returns 0 on success.
2907 Returns 0 on success.
2909 """
2908 """
2910 if not opts.get('applied') and not revrange:
2909 if not opts.get('applied') and not revrange:
2911 raise util.Abort(_('no revisions specified'))
2910 raise util.Abort(_('no revisions specified'))
2912 elif opts.get('applied'):
2911 elif opts.get('applied'):
2913 revrange = ('qbase::qtip',) + revrange
2912 revrange = ('qbase::qtip',) + revrange
2914
2913
2915 q = repo.mq
2914 q = repo.mq
2916 if not q.applied:
2915 if not q.applied:
2917 ui.status(_('no patches applied\n'))
2916 ui.status(_('no patches applied\n'))
2918 return 0
2917 return 0
2919
2918
2920 revs = scmutil.revrange(repo, revrange)
2919 revs = scmutil.revrange(repo, revrange)
2921 q.finish(repo, revs)
2920 q.finish(repo, revs)
2922 q.save_dirty()
2921 q.save_dirty()
2923 return 0
2922 return 0
2924
2923
2925 @command("qqueue",
2924 @command("qqueue",
2926 [('l', 'list', False, _('list all available queues')),
2925 [('l', 'list', False, _('list all available queues')),
2927 ('c', 'create', False, _('create new queue')),
2926 ('c', 'create', False, _('create new queue')),
2928 ('', 'rename', False, _('rename active queue')),
2927 ('', 'rename', False, _('rename active queue')),
2929 ('', 'delete', False, _('delete reference to queue')),
2928 ('', 'delete', False, _('delete reference to queue')),
2930 ('', 'purge', False, _('delete queue, and remove patch dir')),
2929 ('', 'purge', False, _('delete queue, and remove patch dir')),
2931 ],
2930 ],
2932 _('[OPTION] [QUEUE]'))
2931 _('[OPTION] [QUEUE]'))
2933 def qqueue(ui, repo, name=None, **opts):
2932 def qqueue(ui, repo, name=None, **opts):
2934 '''manage multiple patch queues
2933 '''manage multiple patch queues
2935
2934
2936 Supports switching between different patch queues, as well as creating
2935 Supports switching between different patch queues, as well as creating
2937 new patch queues and deleting existing ones.
2936 new patch queues and deleting existing ones.
2938
2937
2939 Omitting a queue name or specifying -l/--list will show you the registered
2938 Omitting a queue name or specifying -l/--list will show you the registered
2940 queues - by default the "normal" patches queue is registered. The currently
2939 queues - by default the "normal" patches queue is registered. The currently
2941 active queue will be marked with "(active)".
2940 active queue will be marked with "(active)".
2942
2941
2943 To create a new queue, use -c/--create. The queue is automatically made
2942 To create a new queue, use -c/--create. The queue is automatically made
2944 active, except in the case where there are applied patches from the
2943 active, except in the case where there are applied patches from the
2945 currently active queue in the repository. Then the queue will only be
2944 currently active queue in the repository. Then the queue will only be
2946 created and switching will fail.
2945 created and switching will fail.
2947
2946
2948 To delete an existing queue, use --delete. You cannot delete the currently
2947 To delete an existing queue, use --delete. You cannot delete the currently
2949 active queue.
2948 active queue.
2950
2949
2951 Returns 0 on success.
2950 Returns 0 on success.
2952 '''
2951 '''
2953
2952
2954 q = repo.mq
2953 q = repo.mq
2955
2954
2956 _defaultqueue = 'patches'
2955 _defaultqueue = 'patches'
2957 _allqueues = 'patches.queues'
2956 _allqueues = 'patches.queues'
2958 _activequeue = 'patches.queue'
2957 _activequeue = 'patches.queue'
2959
2958
2960 def _getcurrent():
2959 def _getcurrent():
2961 cur = os.path.basename(q.path)
2960 cur = os.path.basename(q.path)
2962 if cur.startswith('patches-'):
2961 if cur.startswith('patches-'):
2963 cur = cur[8:]
2962 cur = cur[8:]
2964 return cur
2963 return cur
2965
2964
2966 def _noqueues():
2965 def _noqueues():
2967 try:
2966 try:
2968 fh = repo.opener(_allqueues, 'r')
2967 fh = repo.opener(_allqueues, 'r')
2969 fh.close()
2968 fh.close()
2970 except IOError:
2969 except IOError:
2971 return True
2970 return True
2972
2971
2973 return False
2972 return False
2974
2973
2975 def _getqueues():
2974 def _getqueues():
2976 current = _getcurrent()
2975 current = _getcurrent()
2977
2976
2978 try:
2977 try:
2979 fh = repo.opener(_allqueues, 'r')
2978 fh = repo.opener(_allqueues, 'r')
2980 queues = [queue.strip() for queue in fh if queue.strip()]
2979 queues = [queue.strip() for queue in fh if queue.strip()]
2981 fh.close()
2980 fh.close()
2982 if current not in queues:
2981 if current not in queues:
2983 queues.append(current)
2982 queues.append(current)
2984 except IOError:
2983 except IOError:
2985 queues = [_defaultqueue]
2984 queues = [_defaultqueue]
2986
2985
2987 return sorted(queues)
2986 return sorted(queues)
2988
2987
2989 def _setactive(name):
2988 def _setactive(name):
2990 if q.applied:
2989 if q.applied:
2991 raise util.Abort(_('patches applied - cannot set new queue active'))
2990 raise util.Abort(_('patches applied - cannot set new queue active'))
2992 _setactivenocheck(name)
2991 _setactivenocheck(name)
2993
2992
2994 def _setactivenocheck(name):
2993 def _setactivenocheck(name):
2995 fh = repo.opener(_activequeue, 'w')
2994 fh = repo.opener(_activequeue, 'w')
2996 if name != 'patches':
2995 if name != 'patches':
2997 fh.write(name)
2996 fh.write(name)
2998 fh.close()
2997 fh.close()
2999
2998
3000 def _addqueue(name):
2999 def _addqueue(name):
3001 fh = repo.opener(_allqueues, 'a')
3000 fh = repo.opener(_allqueues, 'a')
3002 fh.write('%s\n' % (name,))
3001 fh.write('%s\n' % (name,))
3003 fh.close()
3002 fh.close()
3004
3003
3005 def _queuedir(name):
3004 def _queuedir(name):
3006 if name == 'patches':
3005 if name == 'patches':
3007 return repo.join('patches')
3006 return repo.join('patches')
3008 else:
3007 else:
3009 return repo.join('patches-' + name)
3008 return repo.join('patches-' + name)
3010
3009
3011 def _validname(name):
3010 def _validname(name):
3012 for n in name:
3011 for n in name:
3013 if n in ':\\/.':
3012 if n in ':\\/.':
3014 return False
3013 return False
3015 return True
3014 return True
3016
3015
3017 def _delete(name):
3016 def _delete(name):
3018 if name not in existing:
3017 if name not in existing:
3019 raise util.Abort(_('cannot delete queue that does not exist'))
3018 raise util.Abort(_('cannot delete queue that does not exist'))
3020
3019
3021 current = _getcurrent()
3020 current = _getcurrent()
3022
3021
3023 if name == current:
3022 if name == current:
3024 raise util.Abort(_('cannot delete currently active queue'))
3023 raise util.Abort(_('cannot delete currently active queue'))
3025
3024
3026 fh = repo.opener('patches.queues.new', 'w')
3025 fh = repo.opener('patches.queues.new', 'w')
3027 for queue in existing:
3026 for queue in existing:
3028 if queue == name:
3027 if queue == name:
3029 continue
3028 continue
3030 fh.write('%s\n' % (queue,))
3029 fh.write('%s\n' % (queue,))
3031 fh.close()
3030 fh.close()
3032 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3031 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3033
3032
3034 if not name or opts.get('list'):
3033 if not name or opts.get('list'):
3035 current = _getcurrent()
3034 current = _getcurrent()
3036 for queue in _getqueues():
3035 for queue in _getqueues():
3037 ui.write('%s' % (queue,))
3036 ui.write('%s' % (queue,))
3038 if queue == current and not ui.quiet:
3037 if queue == current and not ui.quiet:
3039 ui.write(_(' (active)\n'))
3038 ui.write(_(' (active)\n'))
3040 else:
3039 else:
3041 ui.write('\n')
3040 ui.write('\n')
3042 return
3041 return
3043
3042
3044 if not _validname(name):
3043 if not _validname(name):
3045 raise util.Abort(
3044 raise util.Abort(
3046 _('invalid queue name, may not contain the characters ":\\/."'))
3045 _('invalid queue name, may not contain the characters ":\\/."'))
3047
3046
3048 existing = _getqueues()
3047 existing = _getqueues()
3049
3048
3050 if opts.get('create'):
3049 if opts.get('create'):
3051 if name in existing:
3050 if name in existing:
3052 raise util.Abort(_('queue "%s" already exists') % name)
3051 raise util.Abort(_('queue "%s" already exists') % name)
3053 if _noqueues():
3052 if _noqueues():
3054 _addqueue(_defaultqueue)
3053 _addqueue(_defaultqueue)
3055 _addqueue(name)
3054 _addqueue(name)
3056 _setactive(name)
3055 _setactive(name)
3057 elif opts.get('rename'):
3056 elif opts.get('rename'):
3058 current = _getcurrent()
3057 current = _getcurrent()
3059 if name == current:
3058 if name == current:
3060 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3059 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3061 if name in existing:
3060 if name in existing:
3062 raise util.Abort(_('queue "%s" already exists') % name)
3061 raise util.Abort(_('queue "%s" already exists') % name)
3063
3062
3064 olddir = _queuedir(current)
3063 olddir = _queuedir(current)
3065 newdir = _queuedir(name)
3064 newdir = _queuedir(name)
3066
3065
3067 if os.path.exists(newdir):
3066 if os.path.exists(newdir):
3068 raise util.Abort(_('non-queue directory "%s" already exists') %
3067 raise util.Abort(_('non-queue directory "%s" already exists') %
3069 newdir)
3068 newdir)
3070
3069
3071 fh = repo.opener('patches.queues.new', 'w')
3070 fh = repo.opener('patches.queues.new', 'w')
3072 for queue in existing:
3071 for queue in existing:
3073 if queue == current:
3072 if queue == current:
3074 fh.write('%s\n' % (name,))
3073 fh.write('%s\n' % (name,))
3075 if os.path.exists(olddir):
3074 if os.path.exists(olddir):
3076 util.rename(olddir, newdir)
3075 util.rename(olddir, newdir)
3077 else:
3076 else:
3078 fh.write('%s\n' % (queue,))
3077 fh.write('%s\n' % (queue,))
3079 fh.close()
3078 fh.close()
3080 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3079 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3081 _setactivenocheck(name)
3080 _setactivenocheck(name)
3082 elif opts.get('delete'):
3081 elif opts.get('delete'):
3083 _delete(name)
3082 _delete(name)
3084 elif opts.get('purge'):
3083 elif opts.get('purge'):
3085 if name in existing:
3084 if name in existing:
3086 _delete(name)
3085 _delete(name)
3087 qdir = _queuedir(name)
3086 qdir = _queuedir(name)
3088 if os.path.exists(qdir):
3087 if os.path.exists(qdir):
3089 shutil.rmtree(qdir)
3088 shutil.rmtree(qdir)
3090 else:
3089 else:
3091 if name not in existing:
3090 if name not in existing:
3092 raise util.Abort(_('use --create to create a new queue'))
3091 raise util.Abort(_('use --create to create a new queue'))
3093 _setactive(name)
3092 _setactive(name)
3094
3093
3095 def reposetup(ui, repo):
3094 def reposetup(ui, repo):
3096 class mqrepo(repo.__class__):
3095 class mqrepo(repo.__class__):
3097 @util.propertycache
3096 @util.propertycache
3098 def mq(self):
3097 def mq(self):
3099 return queue(self.ui, self.join(""))
3098 return queue(self.ui, self.join(""))
3100
3099
3101 def abort_if_wdir_patched(self, errmsg, force=False):
3100 def abort_if_wdir_patched(self, errmsg, force=False):
3102 if self.mq.applied and not force:
3101 if self.mq.applied and not force:
3103 parents = self.dirstate.parents()
3102 parents = self.dirstate.parents()
3104 patches = [s.node for s in self.mq.applied]
3103 patches = [s.node for s in self.mq.applied]
3105 if parents[0] in patches or parents[1] in patches:
3104 if parents[0] in patches or parents[1] in patches:
3106 raise util.Abort(errmsg)
3105 raise util.Abort(errmsg)
3107
3106
3108 def commit(self, text="", user=None, date=None, match=None,
3107 def commit(self, text="", user=None, date=None, match=None,
3109 force=False, editor=False, extra={}):
3108 force=False, editor=False, extra={}):
3110 self.abort_if_wdir_patched(
3109 self.abort_if_wdir_patched(
3111 _('cannot commit over an applied mq patch'),
3110 _('cannot commit over an applied mq patch'),
3112 force)
3111 force)
3113
3112
3114 return super(mqrepo, self).commit(text, user, date, match, force,
3113 return super(mqrepo, self).commit(text, user, date, match, force,
3115 editor, extra)
3114 editor, extra)
3116
3115
3117 def checkpush(self, force, revs):
3116 def checkpush(self, force, revs):
3118 if self.mq.applied and not force:
3117 if self.mq.applied and not force:
3119 haspatches = True
3118 haspatches = True
3120 if revs:
3119 if revs:
3121 # Assume applied patches have no non-patch descendants
3120 # Assume applied patches have no non-patch descendants
3122 # and are not on remote already. If they appear in the
3121 # and are not on remote already. If they appear in the
3123 # set of resolved 'revs', bail out.
3122 # set of resolved 'revs', bail out.
3124 applied = set(e.node for e in self.mq.applied)
3123 applied = set(e.node for e in self.mq.applied)
3125 haspatches = bool([n for n in revs if n in applied])
3124 haspatches = bool([n for n in revs if n in applied])
3126 if haspatches:
3125 if haspatches:
3127 raise util.Abort(_('source has mq patches applied'))
3126 raise util.Abort(_('source has mq patches applied'))
3128 super(mqrepo, self).checkpush(force, revs)
3127 super(mqrepo, self).checkpush(force, revs)
3129
3128
3130 def _findtags(self):
3129 def _findtags(self):
3131 '''augment tags from base class with patch tags'''
3130 '''augment tags from base class with patch tags'''
3132 result = super(mqrepo, self)._findtags()
3131 result = super(mqrepo, self)._findtags()
3133
3132
3134 q = self.mq
3133 q = self.mq
3135 if not q.applied:
3134 if not q.applied:
3136 return result
3135 return result
3137
3136
3138 mqtags = [(patch.node, patch.name) for patch in q.applied]
3137 mqtags = [(patch.node, patch.name) for patch in q.applied]
3139
3138
3140 try:
3139 try:
3141 self.changelog.rev(mqtags[-1][0])
3140 self.changelog.rev(mqtags[-1][0])
3142 except error.RepoLookupError:
3141 except error.RepoLookupError:
3143 self.ui.warn(_('mq status file refers to unknown node %s\n')
3142 self.ui.warn(_('mq status file refers to unknown node %s\n')
3144 % short(mqtags[-1][0]))
3143 % short(mqtags[-1][0]))
3145 return result
3144 return result
3146
3145
3147 mqtags.append((mqtags[-1][0], 'qtip'))
3146 mqtags.append((mqtags[-1][0], 'qtip'))
3148 mqtags.append((mqtags[0][0], 'qbase'))
3147 mqtags.append((mqtags[0][0], 'qbase'))
3149 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3148 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3150 tags = result[0]
3149 tags = result[0]
3151 for patch in mqtags:
3150 for patch in mqtags:
3152 if patch[1] in tags:
3151 if patch[1] in tags:
3153 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3152 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3154 % patch[1])
3153 % patch[1])
3155 else:
3154 else:
3156 tags[patch[1]] = patch[0]
3155 tags[patch[1]] = patch[0]
3157
3156
3158 return result
3157 return result
3159
3158
3160 def _branchtags(self, partial, lrev):
3159 def _branchtags(self, partial, lrev):
3161 q = self.mq
3160 q = self.mq
3162 if not q.applied:
3161 if not q.applied:
3163 return super(mqrepo, self)._branchtags(partial, lrev)
3162 return super(mqrepo, self)._branchtags(partial, lrev)
3164
3163
3165 cl = self.changelog
3164 cl = self.changelog
3166 qbasenode = q.applied[0].node
3165 qbasenode = q.applied[0].node
3167 try:
3166 try:
3168 qbase = cl.rev(qbasenode)
3167 qbase = cl.rev(qbasenode)
3169 except error.LookupError:
3168 except error.LookupError:
3170 self.ui.warn(_('mq status file refers to unknown node %s\n')
3169 self.ui.warn(_('mq status file refers to unknown node %s\n')
3171 % short(qbasenode))
3170 % short(qbasenode))
3172 return super(mqrepo, self)._branchtags(partial, lrev)
3171 return super(mqrepo, self)._branchtags(partial, lrev)
3173
3172
3174 start = lrev + 1
3173 start = lrev + 1
3175 if start < qbase:
3174 if start < qbase:
3176 # update the cache (excluding the patches) and save it
3175 # update the cache (excluding the patches) and save it
3177 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3176 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3178 self._updatebranchcache(partial, ctxgen)
3177 self._updatebranchcache(partial, ctxgen)
3179 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3178 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3180 start = qbase
3179 start = qbase
3181 # if start = qbase, the cache is as updated as it should be.
3180 # if start = qbase, the cache is as updated as it should be.
3182 # if start > qbase, the cache includes (part of) the patches.
3181 # if start > qbase, the cache includes (part of) the patches.
3183 # we might as well use it, but we won't save it.
3182 # we might as well use it, but we won't save it.
3184
3183
3185 # update the cache up to the tip
3184 # update the cache up to the tip
3186 ctxgen = (self[r] for r in xrange(start, len(cl)))
3185 ctxgen = (self[r] for r in xrange(start, len(cl)))
3187 self._updatebranchcache(partial, ctxgen)
3186 self._updatebranchcache(partial, ctxgen)
3188
3187
3189 return partial
3188 return partial
3190
3189
3191 if repo.local():
3190 if repo.local():
3192 repo.__class__ = mqrepo
3191 repo.__class__ = mqrepo
3193
3192
3194 def mqimport(orig, ui, repo, *args, **kwargs):
3193 def mqimport(orig, ui, repo, *args, **kwargs):
3195 if (hasattr(repo, 'abort_if_wdir_patched')
3194 if (hasattr(repo, 'abort_if_wdir_patched')
3196 and not kwargs.get('no_commit', False)):
3195 and not kwargs.get('no_commit', False)):
3197 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3196 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3198 kwargs.get('force'))
3197 kwargs.get('force'))
3199 return orig(ui, repo, *args, **kwargs)
3198 return orig(ui, repo, *args, **kwargs)
3200
3199
3201 def mqinit(orig, ui, *args, **kwargs):
3200 def mqinit(orig, ui, *args, **kwargs):
3202 mq = kwargs.pop('mq', None)
3201 mq = kwargs.pop('mq', None)
3203
3202
3204 if not mq:
3203 if not mq:
3205 return orig(ui, *args, **kwargs)
3204 return orig(ui, *args, **kwargs)
3206
3205
3207 if args:
3206 if args:
3208 repopath = args[0]
3207 repopath = args[0]
3209 if not hg.islocal(repopath):
3208 if not hg.islocal(repopath):
3210 raise util.Abort(_('only a local queue repository '
3209 raise util.Abort(_('only a local queue repository '
3211 'may be initialized'))
3210 'may be initialized'))
3212 else:
3211 else:
3213 repopath = cmdutil.findrepo(os.getcwd())
3212 repopath = cmdutil.findrepo(os.getcwd())
3214 if not repopath:
3213 if not repopath:
3215 raise util.Abort(_('there is no Mercurial repository here '
3214 raise util.Abort(_('there is no Mercurial repository here '
3216 '(.hg not found)'))
3215 '(.hg not found)'))
3217 repo = hg.repository(ui, repopath)
3216 repo = hg.repository(ui, repopath)
3218 return qinit(ui, repo, True)
3217 return qinit(ui, repo, True)
3219
3218
3220 def mqcommand(orig, ui, repo, *args, **kwargs):
3219 def mqcommand(orig, ui, repo, *args, **kwargs):
3221 """Add --mq option to operate on patch repository instead of main"""
3220 """Add --mq option to operate on patch repository instead of main"""
3222
3221
3223 # some commands do not like getting unknown options
3222 # some commands do not like getting unknown options
3224 mq = kwargs.pop('mq', None)
3223 mq = kwargs.pop('mq', None)
3225
3224
3226 if not mq:
3225 if not mq:
3227 return orig(ui, repo, *args, **kwargs)
3226 return orig(ui, repo, *args, **kwargs)
3228
3227
3229 q = repo.mq
3228 q = repo.mq
3230 r = q.qrepo()
3229 r = q.qrepo()
3231 if not r:
3230 if not r:
3232 raise util.Abort(_('no queue repository'))
3231 raise util.Abort(_('no queue repository'))
3233 return orig(r.ui, r, *args, **kwargs)
3232 return orig(r.ui, r, *args, **kwargs)
3234
3233
3235 def summary(orig, ui, repo, *args, **kwargs):
3234 def summary(orig, ui, repo, *args, **kwargs):
3236 r = orig(ui, repo, *args, **kwargs)
3235 r = orig(ui, repo, *args, **kwargs)
3237 q = repo.mq
3236 q = repo.mq
3238 m = []
3237 m = []
3239 a, u = len(q.applied), len(q.unapplied(repo))
3238 a, u = len(q.applied), len(q.unapplied(repo))
3240 if a:
3239 if a:
3241 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3240 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3242 if u:
3241 if u:
3243 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3242 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3244 if m:
3243 if m:
3245 ui.write("mq: %s\n" % ', '.join(m))
3244 ui.write("mq: %s\n" % ', '.join(m))
3246 else:
3245 else:
3247 ui.note(_("mq: (empty queue)\n"))
3246 ui.note(_("mq: (empty queue)\n"))
3248 return r
3247 return r
3249
3248
3250 def revsetmq(repo, subset, x):
3249 def revsetmq(repo, subset, x):
3251 """``mq()``
3250 """``mq()``
3252 Changesets managed by MQ.
3251 Changesets managed by MQ.
3253 """
3252 """
3254 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3253 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3255 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3254 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3256 return [r for r in subset if r in applied]
3255 return [r for r in subset if r in applied]
3257
3256
3258 def extsetup(ui):
3257 def extsetup(ui):
3259 revset.symbols['mq'] = revsetmq
3258 revset.symbols['mq'] = revsetmq
3260
3259
3261 # tell hggettext to extract docstrings from these functions:
3260 # tell hggettext to extract docstrings from these functions:
3262 i18nfunctions = [revsetmq]
3261 i18nfunctions = [revsetmq]
3263
3262
3264 def uisetup(ui):
3263 def uisetup(ui):
3265 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3264 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3266
3265
3267 extensions.wrapcommand(commands.table, 'import', mqimport)
3266 extensions.wrapcommand(commands.table, 'import', mqimport)
3268 extensions.wrapcommand(commands.table, 'summary', summary)
3267 extensions.wrapcommand(commands.table, 'summary', summary)
3269
3268
3270 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3269 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3271 entry[1].extend(mqopt)
3270 entry[1].extend(mqopt)
3272
3271
3273 nowrap = set(commands.norepo.split(" ") + ['qrecord'])
3272 nowrap = set(commands.norepo.split(" ") + ['qrecord'])
3274
3273
3275 def dotable(cmdtable):
3274 def dotable(cmdtable):
3276 for cmd in cmdtable.keys():
3275 for cmd in cmdtable.keys():
3277 cmd = cmdutil.parsealiases(cmd)[0]
3276 cmd = cmdutil.parsealiases(cmd)[0]
3278 if cmd in nowrap:
3277 if cmd in nowrap:
3279 continue
3278 continue
3280 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3279 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3281 entry[1].extend(mqopt)
3280 entry[1].extend(mqopt)
3282
3281
3283 dotable(commands.table)
3282 dotable(commands.table)
3284
3283
3285 for extname, extmodule in extensions.extensions():
3284 for extname, extmodule in extensions.extensions():
3286 if extmodule.__file__ != __file__:
3285 if extmodule.__file__ != __file__:
3287 dotable(getattr(extmodule, 'cmdtable', {}))
3286 dotable(getattr(extmodule, 'cmdtable', {}))
3288
3287
3289
3288
3290 colortable = {'qguard.negative': 'red',
3289 colortable = {'qguard.negative': 'red',
3291 'qguard.positive': 'yellow',
3290 'qguard.positive': 'yellow',
3292 'qguard.unguarded': 'green',
3291 'qguard.unguarded': 'green',
3293 'qseries.applied': 'blue bold underline',
3292 'qseries.applied': 'blue bold underline',
3294 'qseries.guarded': 'black bold',
3293 'qseries.guarded': 'black bold',
3295 'qseries.missing': 'red bold',
3294 'qseries.missing': 'red bold',
3296 'qseries.unapplied': 'black bold'}
3295 'qseries.unapplied': 'black bold'}
@@ -1,5077 +1,5077 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
11 import os, re, sys, difflib, time, tempfile
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
16 import minirst, revset
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.repository(hg.remoteui(repo, opts), dest)
894 other = hg.repository(hg.remoteui(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(hg.remoteui(ui, opts), source, dest,
1029 r = hg.clone(hg.remoteui(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 1:
1345 while 1:
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 1:
1364 while 1:
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 1:
1373 while 1:
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.repository(hg.remoteui(repo, opts), remoteurl)
1545 remote = hg.repository(hg.remoteui(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('debugfsinfo', [], _('[PATH]'))
1600 @command('debugfsinfo', [], _('[PATH]'))
1601 def debugfsinfo(ui, path = "."):
1601 def debugfsinfo(ui, path = "."):
1602 """show information detected about current filesystem"""
1602 """show information detected about current filesystem"""
1603 util.writefile('.debugfsinfo', '')
1603 util.writefile('.debugfsinfo', '')
1604 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1604 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1605 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1605 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1606 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1606 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1607 and 'yes' or 'no'))
1607 and 'yes' or 'no'))
1608 os.unlink('.debugfsinfo')
1608 os.unlink('.debugfsinfo')
1609
1609
1610 @command('debuggetbundle',
1610 @command('debuggetbundle',
1611 [('H', 'head', [], _('id of head node'), _('ID')),
1611 [('H', 'head', [], _('id of head node'), _('ID')),
1612 ('C', 'common', [], _('id of common node'), _('ID')),
1612 ('C', 'common', [], _('id of common node'), _('ID')),
1613 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1613 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1614 _('REPO FILE [-H|-C ID]...'))
1614 _('REPO FILE [-H|-C ID]...'))
1615 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1615 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1616 """retrieves a bundle from a repo
1616 """retrieves a bundle from a repo
1617
1617
1618 Every ID must be a full-length hex node id string. Saves the bundle to the
1618 Every ID must be a full-length hex node id string. Saves the bundle to the
1619 given file.
1619 given file.
1620 """
1620 """
1621 repo = hg.repository(ui, repopath)
1621 repo = hg.repository(ui, repopath)
1622 if not repo.capable('getbundle'):
1622 if not repo.capable('getbundle'):
1623 raise util.Abort("getbundle() not supported by target repository")
1623 raise util.Abort("getbundle() not supported by target repository")
1624 args = {}
1624 args = {}
1625 if common:
1625 if common:
1626 args['common'] = [bin(s) for s in common]
1626 args['common'] = [bin(s) for s in common]
1627 if head:
1627 if head:
1628 args['heads'] = [bin(s) for s in head]
1628 args['heads'] = [bin(s) for s in head]
1629 bundle = repo.getbundle('debug', **args)
1629 bundle = repo.getbundle('debug', **args)
1630
1630
1631 bundletype = opts.get('type', 'bzip2').lower()
1631 bundletype = opts.get('type', 'bzip2').lower()
1632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1633 bundletype = btypes.get(bundletype)
1633 bundletype = btypes.get(bundletype)
1634 if bundletype not in changegroup.bundletypes:
1634 if bundletype not in changegroup.bundletypes:
1635 raise util.Abort(_('unknown bundle type specified with --type'))
1635 raise util.Abort(_('unknown bundle type specified with --type'))
1636 changegroup.writebundle(bundle, bundlepath, bundletype)
1636 changegroup.writebundle(bundle, bundlepath, bundletype)
1637
1637
1638 @command('debugignore', [], '')
1638 @command('debugignore', [], '')
1639 def debugignore(ui, repo, *values, **opts):
1639 def debugignore(ui, repo, *values, **opts):
1640 """display the combined ignore pattern"""
1640 """display the combined ignore pattern"""
1641 ignore = repo.dirstate._ignore
1641 ignore = repo.dirstate._ignore
1642 if hasattr(ignore, 'includepat'):
1642 if hasattr(ignore, 'includepat'):
1643 ui.write("%s\n" % ignore.includepat)
1643 ui.write("%s\n" % ignore.includepat)
1644 else:
1644 else:
1645 raise util.Abort(_("no ignore patterns found"))
1645 raise util.Abort(_("no ignore patterns found"))
1646
1646
1647 @command('debugindex',
1647 @command('debugindex',
1648 [('c', 'changelog', False, _('open changelog')),
1648 [('c', 'changelog', False, _('open changelog')),
1649 ('m', 'manifest', False, _('open manifest')),
1649 ('m', 'manifest', False, _('open manifest')),
1650 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1650 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1651 _('[-f FORMAT] -c|-m|FILE'))
1651 _('[-f FORMAT] -c|-m|FILE'))
1652 def debugindex(ui, repo, file_ = None, **opts):
1652 def debugindex(ui, repo, file_ = None, **opts):
1653 """dump the contents of an index file"""
1653 """dump the contents of an index file"""
1654 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1654 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1655 format = opts.get('format', 0)
1655 format = opts.get('format', 0)
1656 if format not in (0, 1):
1656 if format not in (0, 1):
1657 raise util.Abort(_("unknown format %d") % format)
1657 raise util.Abort(_("unknown format %d") % format)
1658
1658
1659 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1659 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1660 if generaldelta:
1660 if generaldelta:
1661 basehdr = ' delta'
1661 basehdr = ' delta'
1662 else:
1662 else:
1663 basehdr = ' base'
1663 basehdr = ' base'
1664
1664
1665 if format == 0:
1665 if format == 0:
1666 ui.write(" rev offset length " + basehdr + " linkrev"
1666 ui.write(" rev offset length " + basehdr + " linkrev"
1667 " nodeid p1 p2\n")
1667 " nodeid p1 p2\n")
1668 elif format == 1:
1668 elif format == 1:
1669 ui.write(" rev flag offset length"
1669 ui.write(" rev flag offset length"
1670 " size " + basehdr + " link p1 p2 nodeid\n")
1670 " size " + basehdr + " link p1 p2 nodeid\n")
1671
1671
1672 for i in r:
1672 for i in r:
1673 node = r.node(i)
1673 node = r.node(i)
1674 if generaldelta:
1674 if generaldelta:
1675 base = r.deltaparent(i)
1675 base = r.deltaparent(i)
1676 else:
1676 else:
1677 base = r.chainbase(i)
1677 base = r.chainbase(i)
1678 if format == 0:
1678 if format == 0:
1679 try:
1679 try:
1680 pp = r.parents(node)
1680 pp = r.parents(node)
1681 except:
1681 except:
1682 pp = [nullid, nullid]
1682 pp = [nullid, nullid]
1683 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1683 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1684 i, r.start(i), r.length(i), base, r.linkrev(i),
1684 i, r.start(i), r.length(i), base, r.linkrev(i),
1685 short(node), short(pp[0]), short(pp[1])))
1685 short(node), short(pp[0]), short(pp[1])))
1686 elif format == 1:
1686 elif format == 1:
1687 pr = r.parentrevs(i)
1687 pr = r.parentrevs(i)
1688 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1688 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1689 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1689 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1690 base, r.linkrev(i), pr[0], pr[1], short(node)))
1690 base, r.linkrev(i), pr[0], pr[1], short(node)))
1691
1691
1692 @command('debugindexdot', [], _('FILE'))
1692 @command('debugindexdot', [], _('FILE'))
1693 def debugindexdot(ui, repo, file_):
1693 def debugindexdot(ui, repo, file_):
1694 """dump an index DAG as a graphviz dot file"""
1694 """dump an index DAG as a graphviz dot file"""
1695 r = None
1695 r = None
1696 if repo:
1696 if repo:
1697 filelog = repo.file(file_)
1697 filelog = repo.file(file_)
1698 if len(filelog):
1698 if len(filelog):
1699 r = filelog
1699 r = filelog
1700 if not r:
1700 if not r:
1701 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1701 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1702 ui.write("digraph G {\n")
1702 ui.write("digraph G {\n")
1703 for i in r:
1703 for i in r:
1704 node = r.node(i)
1704 node = r.node(i)
1705 pp = r.parents(node)
1705 pp = r.parents(node)
1706 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1706 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1707 if pp[1] != nullid:
1707 if pp[1] != nullid:
1708 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1708 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1709 ui.write("}\n")
1709 ui.write("}\n")
1710
1710
1711 @command('debuginstall', [], '')
1711 @command('debuginstall', [], '')
1712 def debuginstall(ui):
1712 def debuginstall(ui):
1713 '''test Mercurial installation
1713 '''test Mercurial installation
1714
1714
1715 Returns 0 on success.
1715 Returns 0 on success.
1716 '''
1716 '''
1717
1717
1718 def writetemp(contents):
1718 def writetemp(contents):
1719 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1719 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1720 f = os.fdopen(fd, "wb")
1720 f = os.fdopen(fd, "wb")
1721 f.write(contents)
1721 f.write(contents)
1722 f.close()
1722 f.close()
1723 return name
1723 return name
1724
1724
1725 problems = 0
1725 problems = 0
1726
1726
1727 # encoding
1727 # encoding
1728 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1728 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1729 try:
1729 try:
1730 encoding.fromlocal("test")
1730 encoding.fromlocal("test")
1731 except util.Abort, inst:
1731 except util.Abort, inst:
1732 ui.write(" %s\n" % inst)
1732 ui.write(" %s\n" % inst)
1733 ui.write(_(" (check that your locale is properly set)\n"))
1733 ui.write(_(" (check that your locale is properly set)\n"))
1734 problems += 1
1734 problems += 1
1735
1735
1736 # compiled modules
1736 # compiled modules
1737 ui.status(_("Checking installed modules (%s)...\n")
1737 ui.status(_("Checking installed modules (%s)...\n")
1738 % os.path.dirname(__file__))
1738 % os.path.dirname(__file__))
1739 try:
1739 try:
1740 import bdiff, mpatch, base85, osutil
1740 import bdiff, mpatch, base85, osutil
1741 except Exception, inst:
1741 except Exception, inst:
1742 ui.write(" %s\n" % inst)
1742 ui.write(" %s\n" % inst)
1743 ui.write(_(" One or more extensions could not be found"))
1743 ui.write(_(" One or more extensions could not be found"))
1744 ui.write(_(" (check that you compiled the extensions)\n"))
1744 ui.write(_(" (check that you compiled the extensions)\n"))
1745 problems += 1
1745 problems += 1
1746
1746
1747 # templates
1747 # templates
1748 ui.status(_("Checking templates...\n"))
1748 ui.status(_("Checking templates...\n"))
1749 try:
1749 try:
1750 import templater
1750 import templater
1751 templater.templater(templater.templatepath("map-cmdline.default"))
1751 templater.templater(templater.templatepath("map-cmdline.default"))
1752 except Exception, inst:
1752 except Exception, inst:
1753 ui.write(" %s\n" % inst)
1753 ui.write(" %s\n" % inst)
1754 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1754 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1755 problems += 1
1755 problems += 1
1756
1756
1757 # editor
1757 # editor
1758 ui.status(_("Checking commit editor...\n"))
1758 ui.status(_("Checking commit editor...\n"))
1759 editor = ui.geteditor()
1759 editor = ui.geteditor()
1760 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1760 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1761 if not cmdpath:
1761 if not cmdpath:
1762 if editor == 'vi':
1762 if editor == 'vi':
1763 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1763 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1764 ui.write(_(" (specify a commit editor in your configuration"
1764 ui.write(_(" (specify a commit editor in your configuration"
1765 " file)\n"))
1765 " file)\n"))
1766 else:
1766 else:
1767 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1767 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1768 ui.write(_(" (specify a commit editor in your configuration"
1768 ui.write(_(" (specify a commit editor in your configuration"
1769 " file)\n"))
1769 " file)\n"))
1770 problems += 1
1770 problems += 1
1771
1771
1772 # check username
1772 # check username
1773 ui.status(_("Checking username...\n"))
1773 ui.status(_("Checking username...\n"))
1774 try:
1774 try:
1775 ui.username()
1775 ui.username()
1776 except util.Abort, e:
1776 except util.Abort, e:
1777 ui.write(" %s\n" % e)
1777 ui.write(" %s\n" % e)
1778 ui.write(_(" (specify a username in your configuration file)\n"))
1778 ui.write(_(" (specify a username in your configuration file)\n"))
1779 problems += 1
1779 problems += 1
1780
1780
1781 if not problems:
1781 if not problems:
1782 ui.status(_("No problems detected\n"))
1782 ui.status(_("No problems detected\n"))
1783 else:
1783 else:
1784 ui.write(_("%s problems detected,"
1784 ui.write(_("%s problems detected,"
1785 " please check your install!\n") % problems)
1785 " please check your install!\n") % problems)
1786
1786
1787 return problems
1787 return problems
1788
1788
1789 @command('debugknown', [], _('REPO ID...'))
1789 @command('debugknown', [], _('REPO ID...'))
1790 def debugknown(ui, repopath, *ids, **opts):
1790 def debugknown(ui, repopath, *ids, **opts):
1791 """test whether node ids are known to a repo
1791 """test whether node ids are known to a repo
1792
1792
1793 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1793 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1794 indicating unknown/known.
1794 indicating unknown/known.
1795 """
1795 """
1796 repo = hg.repository(ui, repopath)
1796 repo = hg.repository(ui, repopath)
1797 if not repo.capable('known'):
1797 if not repo.capable('known'):
1798 raise util.Abort("known() not supported by target repository")
1798 raise util.Abort("known() not supported by target repository")
1799 flags = repo.known([bin(s) for s in ids])
1799 flags = repo.known([bin(s) for s in ids])
1800 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1800 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1801
1801
1802 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1802 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1803 def debugpushkey(ui, repopath, namespace, *keyinfo):
1803 def debugpushkey(ui, repopath, namespace, *keyinfo):
1804 '''access the pushkey key/value protocol
1804 '''access the pushkey key/value protocol
1805
1805
1806 With two args, list the keys in the given namespace.
1806 With two args, list the keys in the given namespace.
1807
1807
1808 With five args, set a key to new if it currently is set to old.
1808 With five args, set a key to new if it currently is set to old.
1809 Reports success or failure.
1809 Reports success or failure.
1810 '''
1810 '''
1811
1811
1812 target = hg.repository(ui, repopath)
1812 target = hg.repository(ui, repopath)
1813 if keyinfo:
1813 if keyinfo:
1814 key, old, new = keyinfo
1814 key, old, new = keyinfo
1815 r = target.pushkey(namespace, key, old, new)
1815 r = target.pushkey(namespace, key, old, new)
1816 ui.status(str(r) + '\n')
1816 ui.status(str(r) + '\n')
1817 return not r
1817 return not r
1818 else:
1818 else:
1819 for k, v in target.listkeys(namespace).iteritems():
1819 for k, v in target.listkeys(namespace).iteritems():
1820 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1820 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1821 v.encode('string-escape')))
1821 v.encode('string-escape')))
1822
1822
1823 @command('debugrebuildstate',
1823 @command('debugrebuildstate',
1824 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1824 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1825 _('[-r REV] [REV]'))
1825 _('[-r REV] [REV]'))
1826 def debugrebuildstate(ui, repo, rev="tip"):
1826 def debugrebuildstate(ui, repo, rev="tip"):
1827 """rebuild the dirstate as it would look like for the given revision"""
1827 """rebuild the dirstate as it would look like for the given revision"""
1828 ctx = scmutil.revsingle(repo, rev)
1828 ctx = scmutil.revsingle(repo, rev)
1829 wlock = repo.wlock()
1829 wlock = repo.wlock()
1830 try:
1830 try:
1831 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1831 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1832 finally:
1832 finally:
1833 wlock.release()
1833 wlock.release()
1834
1834
1835 @command('debugrename',
1835 @command('debugrename',
1836 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1836 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1837 _('[-r REV] FILE'))
1837 _('[-r REV] FILE'))
1838 def debugrename(ui, repo, file1, *pats, **opts):
1838 def debugrename(ui, repo, file1, *pats, **opts):
1839 """dump rename information"""
1839 """dump rename information"""
1840
1840
1841 ctx = scmutil.revsingle(repo, opts.get('rev'))
1841 ctx = scmutil.revsingle(repo, opts.get('rev'))
1842 m = scmutil.match(repo, (file1,) + pats, opts)
1842 m = scmutil.match(repo, (file1,) + pats, opts)
1843 for abs in ctx.walk(m):
1843 for abs in ctx.walk(m):
1844 fctx = ctx[abs]
1844 fctx = ctx[abs]
1845 o = fctx.filelog().renamed(fctx.filenode())
1845 o = fctx.filelog().renamed(fctx.filenode())
1846 rel = m.rel(abs)
1846 rel = m.rel(abs)
1847 if o:
1847 if o:
1848 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1848 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1849 else:
1849 else:
1850 ui.write(_("%s not renamed\n") % rel)
1850 ui.write(_("%s not renamed\n") % rel)
1851
1851
1852 @command('debugrevlog',
1852 @command('debugrevlog',
1853 [('c', 'changelog', False, _('open changelog')),
1853 [('c', 'changelog', False, _('open changelog')),
1854 ('m', 'manifest', False, _('open manifest')),
1854 ('m', 'manifest', False, _('open manifest')),
1855 ('d', 'dump', False, _('dump index data'))],
1855 ('d', 'dump', False, _('dump index data'))],
1856 _('-c|-m|FILE'))
1856 _('-c|-m|FILE'))
1857 def debugrevlog(ui, repo, file_ = None, **opts):
1857 def debugrevlog(ui, repo, file_ = None, **opts):
1858 """show data and statistics about a revlog"""
1858 """show data and statistics about a revlog"""
1859 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1859 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1860
1860
1861 if opts.get("dump"):
1861 if opts.get("dump"):
1862 numrevs = len(r)
1862 numrevs = len(r)
1863 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1863 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1864 " rawsize totalsize compression heads\n")
1864 " rawsize totalsize compression heads\n")
1865 ts = 0
1865 ts = 0
1866 heads = set()
1866 heads = set()
1867 for rev in xrange(numrevs):
1867 for rev in xrange(numrevs):
1868 dbase = r.deltaparent(rev)
1868 dbase = r.deltaparent(rev)
1869 if dbase == -1:
1869 if dbase == -1:
1870 dbase = rev
1870 dbase = rev
1871 cbase = r.chainbase(rev)
1871 cbase = r.chainbase(rev)
1872 p1, p2 = r.parentrevs(rev)
1872 p1, p2 = r.parentrevs(rev)
1873 rs = r.rawsize(rev)
1873 rs = r.rawsize(rev)
1874 ts = ts + rs
1874 ts = ts + rs
1875 heads -= set(r.parentrevs(rev))
1875 heads -= set(r.parentrevs(rev))
1876 heads.add(rev)
1876 heads.add(rev)
1877 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1877 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1878 (rev, p1, p2, r.start(rev), r.end(rev),
1878 (rev, p1, p2, r.start(rev), r.end(rev),
1879 r.start(dbase), r.start(cbase),
1879 r.start(dbase), r.start(cbase),
1880 r.start(p1), r.start(p2),
1880 r.start(p1), r.start(p2),
1881 rs, ts, ts / r.end(rev), len(heads)))
1881 rs, ts, ts / r.end(rev), len(heads)))
1882 return 0
1882 return 0
1883
1883
1884 v = r.version
1884 v = r.version
1885 format = v & 0xFFFF
1885 format = v & 0xFFFF
1886 flags = []
1886 flags = []
1887 gdelta = False
1887 gdelta = False
1888 if v & revlog.REVLOGNGINLINEDATA:
1888 if v & revlog.REVLOGNGINLINEDATA:
1889 flags.append('inline')
1889 flags.append('inline')
1890 if v & revlog.REVLOGGENERALDELTA:
1890 if v & revlog.REVLOGGENERALDELTA:
1891 gdelta = True
1891 gdelta = True
1892 flags.append('generaldelta')
1892 flags.append('generaldelta')
1893 if not flags:
1893 if not flags:
1894 flags = ['(none)']
1894 flags = ['(none)']
1895
1895
1896 nummerges = 0
1896 nummerges = 0
1897 numfull = 0
1897 numfull = 0
1898 numprev = 0
1898 numprev = 0
1899 nump1 = 0
1899 nump1 = 0
1900 nump2 = 0
1900 nump2 = 0
1901 numother = 0
1901 numother = 0
1902 nump1prev = 0
1902 nump1prev = 0
1903 nump2prev = 0
1903 nump2prev = 0
1904 chainlengths = []
1904 chainlengths = []
1905
1905
1906 datasize = [None, 0, 0L]
1906 datasize = [None, 0, 0L]
1907 fullsize = [None, 0, 0L]
1907 fullsize = [None, 0, 0L]
1908 deltasize = [None, 0, 0L]
1908 deltasize = [None, 0, 0L]
1909
1909
1910 def addsize(size, l):
1910 def addsize(size, l):
1911 if l[0] is None or size < l[0]:
1911 if l[0] is None or size < l[0]:
1912 l[0] = size
1912 l[0] = size
1913 if size > l[1]:
1913 if size > l[1]:
1914 l[1] = size
1914 l[1] = size
1915 l[2] += size
1915 l[2] += size
1916
1916
1917 numrevs = len(r)
1917 numrevs = len(r)
1918 for rev in xrange(numrevs):
1918 for rev in xrange(numrevs):
1919 p1, p2 = r.parentrevs(rev)
1919 p1, p2 = r.parentrevs(rev)
1920 delta = r.deltaparent(rev)
1920 delta = r.deltaparent(rev)
1921 if format > 0:
1921 if format > 0:
1922 addsize(r.rawsize(rev), datasize)
1922 addsize(r.rawsize(rev), datasize)
1923 if p2 != nullrev:
1923 if p2 != nullrev:
1924 nummerges += 1
1924 nummerges += 1
1925 size = r.length(rev)
1925 size = r.length(rev)
1926 if delta == nullrev:
1926 if delta == nullrev:
1927 chainlengths.append(0)
1927 chainlengths.append(0)
1928 numfull += 1
1928 numfull += 1
1929 addsize(size, fullsize)
1929 addsize(size, fullsize)
1930 else:
1930 else:
1931 chainlengths.append(chainlengths[delta] + 1)
1931 chainlengths.append(chainlengths[delta] + 1)
1932 addsize(size, deltasize)
1932 addsize(size, deltasize)
1933 if delta == rev - 1:
1933 if delta == rev - 1:
1934 numprev += 1
1934 numprev += 1
1935 if delta == p1:
1935 if delta == p1:
1936 nump1prev += 1
1936 nump1prev += 1
1937 elif delta == p2:
1937 elif delta == p2:
1938 nump2prev += 1
1938 nump2prev += 1
1939 elif delta == p1:
1939 elif delta == p1:
1940 nump1 += 1
1940 nump1 += 1
1941 elif delta == p2:
1941 elif delta == p2:
1942 nump2 += 1
1942 nump2 += 1
1943 elif delta != nullrev:
1943 elif delta != nullrev:
1944 numother += 1
1944 numother += 1
1945
1945
1946 numdeltas = numrevs - numfull
1946 numdeltas = numrevs - numfull
1947 numoprev = numprev - nump1prev - nump2prev
1947 numoprev = numprev - nump1prev - nump2prev
1948 totalrawsize = datasize[2]
1948 totalrawsize = datasize[2]
1949 datasize[2] /= numrevs
1949 datasize[2] /= numrevs
1950 fulltotal = fullsize[2]
1950 fulltotal = fullsize[2]
1951 fullsize[2] /= numfull
1951 fullsize[2] /= numfull
1952 deltatotal = deltasize[2]
1952 deltatotal = deltasize[2]
1953 deltasize[2] /= numrevs - numfull
1953 deltasize[2] /= numrevs - numfull
1954 totalsize = fulltotal + deltatotal
1954 totalsize = fulltotal + deltatotal
1955 avgchainlen = sum(chainlengths) / numrevs
1955 avgchainlen = sum(chainlengths) / numrevs
1956 compratio = totalrawsize / totalsize
1956 compratio = totalrawsize / totalsize
1957
1957
1958 basedfmtstr = '%%%dd\n'
1958 basedfmtstr = '%%%dd\n'
1959 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1959 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1960
1960
1961 def dfmtstr(max):
1961 def dfmtstr(max):
1962 return basedfmtstr % len(str(max))
1962 return basedfmtstr % len(str(max))
1963 def pcfmtstr(max, padding=0):
1963 def pcfmtstr(max, padding=0):
1964 return basepcfmtstr % (len(str(max)), ' ' * padding)
1964 return basepcfmtstr % (len(str(max)), ' ' * padding)
1965
1965
1966 def pcfmt(value, total):
1966 def pcfmt(value, total):
1967 return (value, 100 * float(value) / total)
1967 return (value, 100 * float(value) / total)
1968
1968
1969 ui.write('format : %d\n' % format)
1969 ui.write('format : %d\n' % format)
1970 ui.write('flags : %s\n' % ', '.join(flags))
1970 ui.write('flags : %s\n' % ', '.join(flags))
1971
1971
1972 ui.write('\n')
1972 ui.write('\n')
1973 fmt = pcfmtstr(totalsize)
1973 fmt = pcfmtstr(totalsize)
1974 fmt2 = dfmtstr(totalsize)
1974 fmt2 = dfmtstr(totalsize)
1975 ui.write('revisions : ' + fmt2 % numrevs)
1975 ui.write('revisions : ' + fmt2 % numrevs)
1976 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1976 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1977 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1977 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1978 ui.write('revisions : ' + fmt2 % numrevs)
1978 ui.write('revisions : ' + fmt2 % numrevs)
1979 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1979 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1980 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1980 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1981 ui.write('revision size : ' + fmt2 % totalsize)
1981 ui.write('revision size : ' + fmt2 % totalsize)
1982 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1982 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1983 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1983 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1984
1984
1985 ui.write('\n')
1985 ui.write('\n')
1986 fmt = dfmtstr(max(avgchainlen, compratio))
1986 fmt = dfmtstr(max(avgchainlen, compratio))
1987 ui.write('avg chain length : ' + fmt % avgchainlen)
1987 ui.write('avg chain length : ' + fmt % avgchainlen)
1988 ui.write('compression ratio : ' + fmt % compratio)
1988 ui.write('compression ratio : ' + fmt % compratio)
1989
1989
1990 if format > 0:
1990 if format > 0:
1991 ui.write('\n')
1991 ui.write('\n')
1992 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1992 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1993 % tuple(datasize))
1993 % tuple(datasize))
1994 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
1994 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
1995 % tuple(fullsize))
1995 % tuple(fullsize))
1996 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
1996 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
1997 % tuple(deltasize))
1997 % tuple(deltasize))
1998
1998
1999 if numdeltas > 0:
1999 if numdeltas > 0:
2000 ui.write('\n')
2000 ui.write('\n')
2001 fmt = pcfmtstr(numdeltas)
2001 fmt = pcfmtstr(numdeltas)
2002 fmt2 = pcfmtstr(numdeltas, 4)
2002 fmt2 = pcfmtstr(numdeltas, 4)
2003 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2003 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2004 if numprev > 0:
2004 if numprev > 0:
2005 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2005 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2006 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2006 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2007 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2007 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2008 if gdelta:
2008 if gdelta:
2009 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2009 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2010 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2010 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2011 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2011 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2012
2012
2013 @command('debugrevspec', [], ('REVSPEC'))
2013 @command('debugrevspec', [], ('REVSPEC'))
2014 def debugrevspec(ui, repo, expr):
2014 def debugrevspec(ui, repo, expr):
2015 '''parse and apply a revision specification'''
2015 '''parse and apply a revision specification'''
2016 if ui.verbose:
2016 if ui.verbose:
2017 tree = revset.parse(expr)[0]
2017 tree = revset.parse(expr)[0]
2018 ui.note(tree, "\n")
2018 ui.note(tree, "\n")
2019 newtree = revset.findaliases(ui, tree)
2019 newtree = revset.findaliases(ui, tree)
2020 if newtree != tree:
2020 if newtree != tree:
2021 ui.note(newtree, "\n")
2021 ui.note(newtree, "\n")
2022 func = revset.match(ui, expr)
2022 func = revset.match(ui, expr)
2023 for c in func(repo, range(len(repo))):
2023 for c in func(repo, range(len(repo))):
2024 ui.write("%s\n" % c)
2024 ui.write("%s\n" % c)
2025
2025
2026 @command('debugsetparents', [], _('REV1 [REV2]'))
2026 @command('debugsetparents', [], _('REV1 [REV2]'))
2027 def debugsetparents(ui, repo, rev1, rev2=None):
2027 def debugsetparents(ui, repo, rev1, rev2=None):
2028 """manually set the parents of the current working directory
2028 """manually set the parents of the current working directory
2029
2029
2030 This is useful for writing repository conversion tools, but should
2030 This is useful for writing repository conversion tools, but should
2031 be used with care.
2031 be used with care.
2032
2032
2033 Returns 0 on success.
2033 Returns 0 on success.
2034 """
2034 """
2035
2035
2036 r1 = scmutil.revsingle(repo, rev1).node()
2036 r1 = scmutil.revsingle(repo, rev1).node()
2037 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2037 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2038
2038
2039 wlock = repo.wlock()
2039 wlock = repo.wlock()
2040 try:
2040 try:
2041 repo.dirstate.setparents(r1, r2)
2041 repo.dirstate.setparents(r1, r2)
2042 finally:
2042 finally:
2043 wlock.release()
2043 wlock.release()
2044
2044
2045 @command('debugstate',
2045 @command('debugstate',
2046 [('', 'nodates', None, _('do not display the saved mtime')),
2046 [('', 'nodates', None, _('do not display the saved mtime')),
2047 ('', 'datesort', None, _('sort by saved mtime'))],
2047 ('', 'datesort', None, _('sort by saved mtime'))],
2048 _('[OPTION]...'))
2048 _('[OPTION]...'))
2049 def debugstate(ui, repo, nodates=None, datesort=None):
2049 def debugstate(ui, repo, nodates=None, datesort=None):
2050 """show the contents of the current dirstate"""
2050 """show the contents of the current dirstate"""
2051 timestr = ""
2051 timestr = ""
2052 showdate = not nodates
2052 showdate = not nodates
2053 if datesort:
2053 if datesort:
2054 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2054 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2055 else:
2055 else:
2056 keyfunc = None # sort by filename
2056 keyfunc = None # sort by filename
2057 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2057 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2058 if showdate:
2058 if showdate:
2059 if ent[3] == -1:
2059 if ent[3] == -1:
2060 # Pad or slice to locale representation
2060 # Pad or slice to locale representation
2061 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2061 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2062 time.localtime(0)))
2062 time.localtime(0)))
2063 timestr = 'unset'
2063 timestr = 'unset'
2064 timestr = (timestr[:locale_len] +
2064 timestr = (timestr[:locale_len] +
2065 ' ' * (locale_len - len(timestr)))
2065 ' ' * (locale_len - len(timestr)))
2066 else:
2066 else:
2067 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2067 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2068 time.localtime(ent[3]))
2068 time.localtime(ent[3]))
2069 if ent[1] & 020000:
2069 if ent[1] & 020000:
2070 mode = 'lnk'
2070 mode = 'lnk'
2071 else:
2071 else:
2072 mode = '%3o' % (ent[1] & 0777)
2072 mode = '%3o' % (ent[1] & 0777)
2073 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2073 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2074 for f in repo.dirstate.copies():
2074 for f in repo.dirstate.copies():
2075 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2075 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2076
2076
2077 @command('debugsub',
2077 @command('debugsub',
2078 [('r', 'rev', '',
2078 [('r', 'rev', '',
2079 _('revision to check'), _('REV'))],
2079 _('revision to check'), _('REV'))],
2080 _('[-r REV] [REV]'))
2080 _('[-r REV] [REV]'))
2081 def debugsub(ui, repo, rev=None):
2081 def debugsub(ui, repo, rev=None):
2082 ctx = scmutil.revsingle(repo, rev, None)
2082 ctx = scmutil.revsingle(repo, rev, None)
2083 for k, v in sorted(ctx.substate.items()):
2083 for k, v in sorted(ctx.substate.items()):
2084 ui.write('path %s\n' % k)
2084 ui.write('path %s\n' % k)
2085 ui.write(' source %s\n' % v[0])
2085 ui.write(' source %s\n' % v[0])
2086 ui.write(' revision %s\n' % v[1])
2086 ui.write(' revision %s\n' % v[1])
2087
2087
2088 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2088 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2089 def debugwalk(ui, repo, *pats, **opts):
2089 def debugwalk(ui, repo, *pats, **opts):
2090 """show how files match on given patterns"""
2090 """show how files match on given patterns"""
2091 m = scmutil.match(repo, pats, opts)
2091 m = scmutil.match(repo, pats, opts)
2092 items = list(repo.walk(m))
2092 items = list(repo.walk(m))
2093 if not items:
2093 if not items:
2094 return
2094 return
2095 fmt = 'f %%-%ds %%-%ds %%s' % (
2095 fmt = 'f %%-%ds %%-%ds %%s' % (
2096 max([len(abs) for abs in items]),
2096 max([len(abs) for abs in items]),
2097 max([len(m.rel(abs)) for abs in items]))
2097 max([len(m.rel(abs)) for abs in items]))
2098 for abs in items:
2098 for abs in items:
2099 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2099 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2100 ui.write("%s\n" % line.rstrip())
2100 ui.write("%s\n" % line.rstrip())
2101
2101
2102 @command('debugwireargs',
2102 @command('debugwireargs',
2103 [('', 'three', '', 'three'),
2103 [('', 'three', '', 'three'),
2104 ('', 'four', '', 'four'),
2104 ('', 'four', '', 'four'),
2105 ('', 'five', '', 'five'),
2105 ('', 'five', '', 'five'),
2106 ] + remoteopts,
2106 ] + remoteopts,
2107 _('REPO [OPTIONS]... [ONE [TWO]]'))
2107 _('REPO [OPTIONS]... [ONE [TWO]]'))
2108 def debugwireargs(ui, repopath, *vals, **opts):
2108 def debugwireargs(ui, repopath, *vals, **opts):
2109 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2109 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2110 for opt in remoteopts:
2110 for opt in remoteopts:
2111 del opts[opt[1]]
2111 del opts[opt[1]]
2112 args = {}
2112 args = {}
2113 for k, v in opts.iteritems():
2113 for k, v in opts.iteritems():
2114 if v:
2114 if v:
2115 args[k] = v
2115 args[k] = v
2116 # run twice to check that we don't mess up the stream for the next command
2116 # run twice to check that we don't mess up the stream for the next command
2117 res1 = repo.debugwireargs(*vals, **args)
2117 res1 = repo.debugwireargs(*vals, **args)
2118 res2 = repo.debugwireargs(*vals, **args)
2118 res2 = repo.debugwireargs(*vals, **args)
2119 ui.write("%s\n" % res1)
2119 ui.write("%s\n" % res1)
2120 if res1 != res2:
2120 if res1 != res2:
2121 ui.warn("%s\n" % res2)
2121 ui.warn("%s\n" % res2)
2122
2122
2123 @command('^diff',
2123 @command('^diff',
2124 [('r', 'rev', [], _('revision'), _('REV')),
2124 [('r', 'rev', [], _('revision'), _('REV')),
2125 ('c', 'change', '', _('change made by revision'), _('REV'))
2125 ('c', 'change', '', _('change made by revision'), _('REV'))
2126 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2126 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2127 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2127 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2128 def diff(ui, repo, *pats, **opts):
2128 def diff(ui, repo, *pats, **opts):
2129 """diff repository (or selected files)
2129 """diff repository (or selected files)
2130
2130
2131 Show differences between revisions for the specified files.
2131 Show differences between revisions for the specified files.
2132
2132
2133 Differences between files are shown using the unified diff format.
2133 Differences between files are shown using the unified diff format.
2134
2134
2135 .. note::
2135 .. note::
2136 diff may generate unexpected results for merges, as it will
2136 diff may generate unexpected results for merges, as it will
2137 default to comparing against the working directory's first
2137 default to comparing against the working directory's first
2138 parent changeset if no revisions are specified.
2138 parent changeset if no revisions are specified.
2139
2139
2140 When two revision arguments are given, then changes are shown
2140 When two revision arguments are given, then changes are shown
2141 between those revisions. If only one revision is specified then
2141 between those revisions. If only one revision is specified then
2142 that revision is compared to the working directory, and, when no
2142 that revision is compared to the working directory, and, when no
2143 revisions are specified, the working directory files are compared
2143 revisions are specified, the working directory files are compared
2144 to its parent.
2144 to its parent.
2145
2145
2146 Alternatively you can specify -c/--change with a revision to see
2146 Alternatively you can specify -c/--change with a revision to see
2147 the changes in that changeset relative to its first parent.
2147 the changes in that changeset relative to its first parent.
2148
2148
2149 Without the -a/--text option, diff will avoid generating diffs of
2149 Without the -a/--text option, diff will avoid generating diffs of
2150 files it detects as binary. With -a, diff will generate a diff
2150 files it detects as binary. With -a, diff will generate a diff
2151 anyway, probably with undesirable results.
2151 anyway, probably with undesirable results.
2152
2152
2153 Use the -g/--git option to generate diffs in the git extended diff
2153 Use the -g/--git option to generate diffs in the git extended diff
2154 format. For more information, read :hg:`help diffs`.
2154 format. For more information, read :hg:`help diffs`.
2155
2155
2156 Returns 0 on success.
2156 Returns 0 on success.
2157 """
2157 """
2158
2158
2159 revs = opts.get('rev')
2159 revs = opts.get('rev')
2160 change = opts.get('change')
2160 change = opts.get('change')
2161 stat = opts.get('stat')
2161 stat = opts.get('stat')
2162 reverse = opts.get('reverse')
2162 reverse = opts.get('reverse')
2163
2163
2164 if revs and change:
2164 if revs and change:
2165 msg = _('cannot specify --rev and --change at the same time')
2165 msg = _('cannot specify --rev and --change at the same time')
2166 raise util.Abort(msg)
2166 raise util.Abort(msg)
2167 elif change:
2167 elif change:
2168 node2 = scmutil.revsingle(repo, change, None).node()
2168 node2 = scmutil.revsingle(repo, change, None).node()
2169 node1 = repo[node2].p1().node()
2169 node1 = repo[node2].p1().node()
2170 else:
2170 else:
2171 node1, node2 = scmutil.revpair(repo, revs)
2171 node1, node2 = scmutil.revpair(repo, revs)
2172
2172
2173 if reverse:
2173 if reverse:
2174 node1, node2 = node2, node1
2174 node1, node2 = node2, node1
2175
2175
2176 diffopts = patch.diffopts(ui, opts)
2176 diffopts = patch.diffopts(ui, opts)
2177 m = scmutil.match(repo, pats, opts)
2177 m = scmutil.match(repo, pats, opts)
2178 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2178 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2179 listsubrepos=opts.get('subrepos'))
2179 listsubrepos=opts.get('subrepos'))
2180
2180
2181 @command('^export',
2181 @command('^export',
2182 [('o', 'output', '',
2182 [('o', 'output', '',
2183 _('print output to file with formatted name'), _('FORMAT')),
2183 _('print output to file with formatted name'), _('FORMAT')),
2184 ('', 'switch-parent', None, _('diff against the second parent')),
2184 ('', 'switch-parent', None, _('diff against the second parent')),
2185 ('r', 'rev', [], _('revisions to export'), _('REV')),
2185 ('r', 'rev', [], _('revisions to export'), _('REV')),
2186 ] + diffopts,
2186 ] + diffopts,
2187 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2187 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2188 def export(ui, repo, *changesets, **opts):
2188 def export(ui, repo, *changesets, **opts):
2189 """dump the header and diffs for one or more changesets
2189 """dump the header and diffs for one or more changesets
2190
2190
2191 Print the changeset header and diffs for one or more revisions.
2191 Print the changeset header and diffs for one or more revisions.
2192
2192
2193 The information shown in the changeset header is: author, date,
2193 The information shown in the changeset header is: author, date,
2194 branch name (if non-default), changeset hash, parent(s) and commit
2194 branch name (if non-default), changeset hash, parent(s) and commit
2195 comment.
2195 comment.
2196
2196
2197 .. note::
2197 .. note::
2198 export may generate unexpected diff output for merge
2198 export may generate unexpected diff output for merge
2199 changesets, as it will compare the merge changeset against its
2199 changesets, as it will compare the merge changeset against its
2200 first parent only.
2200 first parent only.
2201
2201
2202 Output may be to a file, in which case the name of the file is
2202 Output may be to a file, in which case the name of the file is
2203 given using a format string. The formatting rules are as follows:
2203 given using a format string. The formatting rules are as follows:
2204
2204
2205 :``%%``: literal "%" character
2205 :``%%``: literal "%" character
2206 :``%H``: changeset hash (40 hexadecimal digits)
2206 :``%H``: changeset hash (40 hexadecimal digits)
2207 :``%N``: number of patches being generated
2207 :``%N``: number of patches being generated
2208 :``%R``: changeset revision number
2208 :``%R``: changeset revision number
2209 :``%b``: basename of the exporting repository
2209 :``%b``: basename of the exporting repository
2210 :``%h``: short-form changeset hash (12 hexadecimal digits)
2210 :``%h``: short-form changeset hash (12 hexadecimal digits)
2211 :``%n``: zero-padded sequence number, starting at 1
2211 :``%n``: zero-padded sequence number, starting at 1
2212 :``%r``: zero-padded changeset revision number
2212 :``%r``: zero-padded changeset revision number
2213
2213
2214 Without the -a/--text option, export will avoid generating diffs
2214 Without the -a/--text option, export will avoid generating diffs
2215 of files it detects as binary. With -a, export will generate a
2215 of files it detects as binary. With -a, export will generate a
2216 diff anyway, probably with undesirable results.
2216 diff anyway, probably with undesirable results.
2217
2217
2218 Use the -g/--git option to generate diffs in the git extended diff
2218 Use the -g/--git option to generate diffs in the git extended diff
2219 format. See :hg:`help diffs` for more information.
2219 format. See :hg:`help diffs` for more information.
2220
2220
2221 With the --switch-parent option, the diff will be against the
2221 With the --switch-parent option, the diff will be against the
2222 second parent. It can be useful to review a merge.
2222 second parent. It can be useful to review a merge.
2223
2223
2224 Returns 0 on success.
2224 Returns 0 on success.
2225 """
2225 """
2226 changesets += tuple(opts.get('rev', []))
2226 changesets += tuple(opts.get('rev', []))
2227 if not changesets:
2227 if not changesets:
2228 raise util.Abort(_("export requires at least one changeset"))
2228 raise util.Abort(_("export requires at least one changeset"))
2229 revs = scmutil.revrange(repo, changesets)
2229 revs = scmutil.revrange(repo, changesets)
2230 if len(revs) > 1:
2230 if len(revs) > 1:
2231 ui.note(_('exporting patches:\n'))
2231 ui.note(_('exporting patches:\n'))
2232 else:
2232 else:
2233 ui.note(_('exporting patch:\n'))
2233 ui.note(_('exporting patch:\n'))
2234 cmdutil.export(repo, revs, template=opts.get('output'),
2234 cmdutil.export(repo, revs, template=opts.get('output'),
2235 switch_parent=opts.get('switch_parent'),
2235 switch_parent=opts.get('switch_parent'),
2236 opts=patch.diffopts(ui, opts))
2236 opts=patch.diffopts(ui, opts))
2237
2237
2238 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2238 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2239 def forget(ui, repo, *pats, **opts):
2239 def forget(ui, repo, *pats, **opts):
2240 """forget the specified files on the next commit
2240 """forget the specified files on the next commit
2241
2241
2242 Mark the specified files so they will no longer be tracked
2242 Mark the specified files so they will no longer be tracked
2243 after the next commit.
2243 after the next commit.
2244
2244
2245 This only removes files from the current branch, not from the
2245 This only removes files from the current branch, not from the
2246 entire project history, and it does not delete them from the
2246 entire project history, and it does not delete them from the
2247 working directory.
2247 working directory.
2248
2248
2249 To undo a forget before the next commit, see :hg:`add`.
2249 To undo a forget before the next commit, see :hg:`add`.
2250
2250
2251 Returns 0 on success.
2251 Returns 0 on success.
2252 """
2252 """
2253
2253
2254 if not pats:
2254 if not pats:
2255 raise util.Abort(_('no files specified'))
2255 raise util.Abort(_('no files specified'))
2256
2256
2257 m = scmutil.match(repo, pats, opts)
2257 m = scmutil.match(repo, pats, opts)
2258 s = repo.status(match=m, clean=True)
2258 s = repo.status(match=m, clean=True)
2259 forget = sorted(s[0] + s[1] + s[3] + s[6])
2259 forget = sorted(s[0] + s[1] + s[3] + s[6])
2260 errs = 0
2260 errs = 0
2261
2261
2262 for f in m.files():
2262 for f in m.files():
2263 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2263 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2264 ui.warn(_('not removing %s: file is already untracked\n')
2264 ui.warn(_('not removing %s: file is already untracked\n')
2265 % m.rel(f))
2265 % m.rel(f))
2266 errs = 1
2266 errs = 1
2267
2267
2268 for f in forget:
2268 for f in forget:
2269 if ui.verbose or not m.exact(f):
2269 if ui.verbose or not m.exact(f):
2270 ui.status(_('removing %s\n') % m.rel(f))
2270 ui.status(_('removing %s\n') % m.rel(f))
2271
2271
2272 repo[None].remove(forget, unlink=False)
2272 repo[None].forget(forget)
2273 return errs
2273 return errs
2274
2274
2275 @command('grep',
2275 @command('grep',
2276 [('0', 'print0', None, _('end fields with NUL')),
2276 [('0', 'print0', None, _('end fields with NUL')),
2277 ('', 'all', None, _('print all revisions that match')),
2277 ('', 'all', None, _('print all revisions that match')),
2278 ('a', 'text', None, _('treat all files as text')),
2278 ('a', 'text', None, _('treat all files as text')),
2279 ('f', 'follow', None,
2279 ('f', 'follow', None,
2280 _('follow changeset history,'
2280 _('follow changeset history,'
2281 ' or file history across copies and renames')),
2281 ' or file history across copies and renames')),
2282 ('i', 'ignore-case', None, _('ignore case when matching')),
2282 ('i', 'ignore-case', None, _('ignore case when matching')),
2283 ('l', 'files-with-matches', None,
2283 ('l', 'files-with-matches', None,
2284 _('print only filenames and revisions that match')),
2284 _('print only filenames and revisions that match')),
2285 ('n', 'line-number', None, _('print matching line numbers')),
2285 ('n', 'line-number', None, _('print matching line numbers')),
2286 ('r', 'rev', [],
2286 ('r', 'rev', [],
2287 _('only search files changed within revision range'), _('REV')),
2287 _('only search files changed within revision range'), _('REV')),
2288 ('u', 'user', None, _('list the author (long with -v)')),
2288 ('u', 'user', None, _('list the author (long with -v)')),
2289 ('d', 'date', None, _('list the date (short with -q)')),
2289 ('d', 'date', None, _('list the date (short with -q)')),
2290 ] + walkopts,
2290 ] + walkopts,
2291 _('[OPTION]... PATTERN [FILE]...'))
2291 _('[OPTION]... PATTERN [FILE]...'))
2292 def grep(ui, repo, pattern, *pats, **opts):
2292 def grep(ui, repo, pattern, *pats, **opts):
2293 """search for a pattern in specified files and revisions
2293 """search for a pattern in specified files and revisions
2294
2294
2295 Search revisions of files for a regular expression.
2295 Search revisions of files for a regular expression.
2296
2296
2297 This command behaves differently than Unix grep. It only accepts
2297 This command behaves differently than Unix grep. It only accepts
2298 Python/Perl regexps. It searches repository history, not the
2298 Python/Perl regexps. It searches repository history, not the
2299 working directory. It always prints the revision number in which a
2299 working directory. It always prints the revision number in which a
2300 match appears.
2300 match appears.
2301
2301
2302 By default, grep only prints output for the first revision of a
2302 By default, grep only prints output for the first revision of a
2303 file in which it finds a match. To get it to print every revision
2303 file in which it finds a match. To get it to print every revision
2304 that contains a change in match status ("-" for a match that
2304 that contains a change in match status ("-" for a match that
2305 becomes a non-match, or "+" for a non-match that becomes a match),
2305 becomes a non-match, or "+" for a non-match that becomes a match),
2306 use the --all flag.
2306 use the --all flag.
2307
2307
2308 Returns 0 if a match is found, 1 otherwise.
2308 Returns 0 if a match is found, 1 otherwise.
2309 """
2309 """
2310 reflags = 0
2310 reflags = 0
2311 if opts.get('ignore_case'):
2311 if opts.get('ignore_case'):
2312 reflags |= re.I
2312 reflags |= re.I
2313 try:
2313 try:
2314 regexp = re.compile(pattern, reflags)
2314 regexp = re.compile(pattern, reflags)
2315 except re.error, inst:
2315 except re.error, inst:
2316 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2316 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2317 return 1
2317 return 1
2318 sep, eol = ':', '\n'
2318 sep, eol = ':', '\n'
2319 if opts.get('print0'):
2319 if opts.get('print0'):
2320 sep = eol = '\0'
2320 sep = eol = '\0'
2321
2321
2322 getfile = util.lrucachefunc(repo.file)
2322 getfile = util.lrucachefunc(repo.file)
2323
2323
2324 def matchlines(body):
2324 def matchlines(body):
2325 begin = 0
2325 begin = 0
2326 linenum = 0
2326 linenum = 0
2327 while True:
2327 while True:
2328 match = regexp.search(body, begin)
2328 match = regexp.search(body, begin)
2329 if not match:
2329 if not match:
2330 break
2330 break
2331 mstart, mend = match.span()
2331 mstart, mend = match.span()
2332 linenum += body.count('\n', begin, mstart) + 1
2332 linenum += body.count('\n', begin, mstart) + 1
2333 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2333 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2334 begin = body.find('\n', mend) + 1 or len(body)
2334 begin = body.find('\n', mend) + 1 or len(body)
2335 lend = begin - 1
2335 lend = begin - 1
2336 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2336 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2337
2337
2338 class linestate(object):
2338 class linestate(object):
2339 def __init__(self, line, linenum, colstart, colend):
2339 def __init__(self, line, linenum, colstart, colend):
2340 self.line = line
2340 self.line = line
2341 self.linenum = linenum
2341 self.linenum = linenum
2342 self.colstart = colstart
2342 self.colstart = colstart
2343 self.colend = colend
2343 self.colend = colend
2344
2344
2345 def __hash__(self):
2345 def __hash__(self):
2346 return hash((self.linenum, self.line))
2346 return hash((self.linenum, self.line))
2347
2347
2348 def __eq__(self, other):
2348 def __eq__(self, other):
2349 return self.line == other.line
2349 return self.line == other.line
2350
2350
2351 matches = {}
2351 matches = {}
2352 copies = {}
2352 copies = {}
2353 def grepbody(fn, rev, body):
2353 def grepbody(fn, rev, body):
2354 matches[rev].setdefault(fn, [])
2354 matches[rev].setdefault(fn, [])
2355 m = matches[rev][fn]
2355 m = matches[rev][fn]
2356 for lnum, cstart, cend, line in matchlines(body):
2356 for lnum, cstart, cend, line in matchlines(body):
2357 s = linestate(line, lnum, cstart, cend)
2357 s = linestate(line, lnum, cstart, cend)
2358 m.append(s)
2358 m.append(s)
2359
2359
2360 def difflinestates(a, b):
2360 def difflinestates(a, b):
2361 sm = difflib.SequenceMatcher(None, a, b)
2361 sm = difflib.SequenceMatcher(None, a, b)
2362 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2362 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2363 if tag == 'insert':
2363 if tag == 'insert':
2364 for i in xrange(blo, bhi):
2364 for i in xrange(blo, bhi):
2365 yield ('+', b[i])
2365 yield ('+', b[i])
2366 elif tag == 'delete':
2366 elif tag == 'delete':
2367 for i in xrange(alo, ahi):
2367 for i in xrange(alo, ahi):
2368 yield ('-', a[i])
2368 yield ('-', a[i])
2369 elif tag == 'replace':
2369 elif tag == 'replace':
2370 for i in xrange(alo, ahi):
2370 for i in xrange(alo, ahi):
2371 yield ('-', a[i])
2371 yield ('-', a[i])
2372 for i in xrange(blo, bhi):
2372 for i in xrange(blo, bhi):
2373 yield ('+', b[i])
2373 yield ('+', b[i])
2374
2374
2375 def display(fn, ctx, pstates, states):
2375 def display(fn, ctx, pstates, states):
2376 rev = ctx.rev()
2376 rev = ctx.rev()
2377 datefunc = ui.quiet and util.shortdate or util.datestr
2377 datefunc = ui.quiet and util.shortdate or util.datestr
2378 found = False
2378 found = False
2379 filerevmatches = {}
2379 filerevmatches = {}
2380 def binary():
2380 def binary():
2381 flog = getfile(fn)
2381 flog = getfile(fn)
2382 return util.binary(flog.read(ctx.filenode(fn)))
2382 return util.binary(flog.read(ctx.filenode(fn)))
2383
2383
2384 if opts.get('all'):
2384 if opts.get('all'):
2385 iter = difflinestates(pstates, states)
2385 iter = difflinestates(pstates, states)
2386 else:
2386 else:
2387 iter = [('', l) for l in states]
2387 iter = [('', l) for l in states]
2388 for change, l in iter:
2388 for change, l in iter:
2389 cols = [fn, str(rev)]
2389 cols = [fn, str(rev)]
2390 before, match, after = None, None, None
2390 before, match, after = None, None, None
2391 if opts.get('line_number'):
2391 if opts.get('line_number'):
2392 cols.append(str(l.linenum))
2392 cols.append(str(l.linenum))
2393 if opts.get('all'):
2393 if opts.get('all'):
2394 cols.append(change)
2394 cols.append(change)
2395 if opts.get('user'):
2395 if opts.get('user'):
2396 cols.append(ui.shortuser(ctx.user()))
2396 cols.append(ui.shortuser(ctx.user()))
2397 if opts.get('date'):
2397 if opts.get('date'):
2398 cols.append(datefunc(ctx.date()))
2398 cols.append(datefunc(ctx.date()))
2399 if opts.get('files_with_matches'):
2399 if opts.get('files_with_matches'):
2400 c = (fn, rev)
2400 c = (fn, rev)
2401 if c in filerevmatches:
2401 if c in filerevmatches:
2402 continue
2402 continue
2403 filerevmatches[c] = 1
2403 filerevmatches[c] = 1
2404 else:
2404 else:
2405 before = l.line[:l.colstart]
2405 before = l.line[:l.colstart]
2406 match = l.line[l.colstart:l.colend]
2406 match = l.line[l.colstart:l.colend]
2407 after = l.line[l.colend:]
2407 after = l.line[l.colend:]
2408 ui.write(sep.join(cols))
2408 ui.write(sep.join(cols))
2409 if before is not None:
2409 if before is not None:
2410 if not opts.get('text') and binary():
2410 if not opts.get('text') and binary():
2411 ui.write(sep + " Binary file matches")
2411 ui.write(sep + " Binary file matches")
2412 else:
2412 else:
2413 ui.write(sep + before)
2413 ui.write(sep + before)
2414 ui.write(match, label='grep.match')
2414 ui.write(match, label='grep.match')
2415 ui.write(after)
2415 ui.write(after)
2416 ui.write(eol)
2416 ui.write(eol)
2417 found = True
2417 found = True
2418 return found
2418 return found
2419
2419
2420 skip = {}
2420 skip = {}
2421 revfiles = {}
2421 revfiles = {}
2422 matchfn = scmutil.match(repo, pats, opts)
2422 matchfn = scmutil.match(repo, pats, opts)
2423 found = False
2423 found = False
2424 follow = opts.get('follow')
2424 follow = opts.get('follow')
2425
2425
2426 def prep(ctx, fns):
2426 def prep(ctx, fns):
2427 rev = ctx.rev()
2427 rev = ctx.rev()
2428 pctx = ctx.p1()
2428 pctx = ctx.p1()
2429 parent = pctx.rev()
2429 parent = pctx.rev()
2430 matches.setdefault(rev, {})
2430 matches.setdefault(rev, {})
2431 matches.setdefault(parent, {})
2431 matches.setdefault(parent, {})
2432 files = revfiles.setdefault(rev, [])
2432 files = revfiles.setdefault(rev, [])
2433 for fn in fns:
2433 for fn in fns:
2434 flog = getfile(fn)
2434 flog = getfile(fn)
2435 try:
2435 try:
2436 fnode = ctx.filenode(fn)
2436 fnode = ctx.filenode(fn)
2437 except error.LookupError:
2437 except error.LookupError:
2438 continue
2438 continue
2439
2439
2440 copied = flog.renamed(fnode)
2440 copied = flog.renamed(fnode)
2441 copy = follow and copied and copied[0]
2441 copy = follow and copied and copied[0]
2442 if copy:
2442 if copy:
2443 copies.setdefault(rev, {})[fn] = copy
2443 copies.setdefault(rev, {})[fn] = copy
2444 if fn in skip:
2444 if fn in skip:
2445 if copy:
2445 if copy:
2446 skip[copy] = True
2446 skip[copy] = True
2447 continue
2447 continue
2448 files.append(fn)
2448 files.append(fn)
2449
2449
2450 if fn not in matches[rev]:
2450 if fn not in matches[rev]:
2451 grepbody(fn, rev, flog.read(fnode))
2451 grepbody(fn, rev, flog.read(fnode))
2452
2452
2453 pfn = copy or fn
2453 pfn = copy or fn
2454 if pfn not in matches[parent]:
2454 if pfn not in matches[parent]:
2455 try:
2455 try:
2456 fnode = pctx.filenode(pfn)
2456 fnode = pctx.filenode(pfn)
2457 grepbody(pfn, parent, flog.read(fnode))
2457 grepbody(pfn, parent, flog.read(fnode))
2458 except error.LookupError:
2458 except error.LookupError:
2459 pass
2459 pass
2460
2460
2461 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2461 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2462 rev = ctx.rev()
2462 rev = ctx.rev()
2463 parent = ctx.p1().rev()
2463 parent = ctx.p1().rev()
2464 for fn in sorted(revfiles.get(rev, [])):
2464 for fn in sorted(revfiles.get(rev, [])):
2465 states = matches[rev][fn]
2465 states = matches[rev][fn]
2466 copy = copies.get(rev, {}).get(fn)
2466 copy = copies.get(rev, {}).get(fn)
2467 if fn in skip:
2467 if fn in skip:
2468 if copy:
2468 if copy:
2469 skip[copy] = True
2469 skip[copy] = True
2470 continue
2470 continue
2471 pstates = matches.get(parent, {}).get(copy or fn, [])
2471 pstates = matches.get(parent, {}).get(copy or fn, [])
2472 if pstates or states:
2472 if pstates or states:
2473 r = display(fn, ctx, pstates, states)
2473 r = display(fn, ctx, pstates, states)
2474 found = found or r
2474 found = found or r
2475 if r and not opts.get('all'):
2475 if r and not opts.get('all'):
2476 skip[fn] = True
2476 skip[fn] = True
2477 if copy:
2477 if copy:
2478 skip[copy] = True
2478 skip[copy] = True
2479 del matches[rev]
2479 del matches[rev]
2480 del revfiles[rev]
2480 del revfiles[rev]
2481
2481
2482 return not found
2482 return not found
2483
2483
2484 @command('heads',
2484 @command('heads',
2485 [('r', 'rev', '',
2485 [('r', 'rev', '',
2486 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2486 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2487 ('t', 'topo', False, _('show topological heads only')),
2487 ('t', 'topo', False, _('show topological heads only')),
2488 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2488 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2489 ('c', 'closed', False, _('show normal and closed branch heads')),
2489 ('c', 'closed', False, _('show normal and closed branch heads')),
2490 ] + templateopts,
2490 ] + templateopts,
2491 _('[-ac] [-r STARTREV] [REV]...'))
2491 _('[-ac] [-r STARTREV] [REV]...'))
2492 def heads(ui, repo, *branchrevs, **opts):
2492 def heads(ui, repo, *branchrevs, **opts):
2493 """show current repository heads or show branch heads
2493 """show current repository heads or show branch heads
2494
2494
2495 With no arguments, show all repository branch heads.
2495 With no arguments, show all repository branch heads.
2496
2496
2497 Repository "heads" are changesets with no child changesets. They are
2497 Repository "heads" are changesets with no child changesets. They are
2498 where development generally takes place and are the usual targets
2498 where development generally takes place and are the usual targets
2499 for update and merge operations. Branch heads are changesets that have
2499 for update and merge operations. Branch heads are changesets that have
2500 no child changeset on the same branch.
2500 no child changeset on the same branch.
2501
2501
2502 If one or more REVs are given, only branch heads on the branches
2502 If one or more REVs are given, only branch heads on the branches
2503 associated with the specified changesets are shown.
2503 associated with the specified changesets are shown.
2504
2504
2505 If -c/--closed is specified, also show branch heads marked closed
2505 If -c/--closed is specified, also show branch heads marked closed
2506 (see :hg:`commit --close-branch`).
2506 (see :hg:`commit --close-branch`).
2507
2507
2508 If STARTREV is specified, only those heads that are descendants of
2508 If STARTREV is specified, only those heads that are descendants of
2509 STARTREV will be displayed.
2509 STARTREV will be displayed.
2510
2510
2511 If -t/--topo is specified, named branch mechanics will be ignored and only
2511 If -t/--topo is specified, named branch mechanics will be ignored and only
2512 changesets without children will be shown.
2512 changesets without children will be shown.
2513
2513
2514 Returns 0 if matching heads are found, 1 if not.
2514 Returns 0 if matching heads are found, 1 if not.
2515 """
2515 """
2516
2516
2517 start = None
2517 start = None
2518 if 'rev' in opts:
2518 if 'rev' in opts:
2519 start = scmutil.revsingle(repo, opts['rev'], None).node()
2519 start = scmutil.revsingle(repo, opts['rev'], None).node()
2520
2520
2521 if opts.get('topo'):
2521 if opts.get('topo'):
2522 heads = [repo[h] for h in repo.heads(start)]
2522 heads = [repo[h] for h in repo.heads(start)]
2523 else:
2523 else:
2524 heads = []
2524 heads = []
2525 for b, ls in repo.branchmap().iteritems():
2525 for b, ls in repo.branchmap().iteritems():
2526 if start is None:
2526 if start is None:
2527 heads += [repo[h] for h in ls]
2527 heads += [repo[h] for h in ls]
2528 continue
2528 continue
2529 startrev = repo.changelog.rev(start)
2529 startrev = repo.changelog.rev(start)
2530 descendants = set(repo.changelog.descendants(startrev))
2530 descendants = set(repo.changelog.descendants(startrev))
2531 descendants.add(startrev)
2531 descendants.add(startrev)
2532 rev = repo.changelog.rev
2532 rev = repo.changelog.rev
2533 heads += [repo[h] for h in ls if rev(h) in descendants]
2533 heads += [repo[h] for h in ls if rev(h) in descendants]
2534
2534
2535 if branchrevs:
2535 if branchrevs:
2536 branches = set(repo[br].branch() for br in branchrevs)
2536 branches = set(repo[br].branch() for br in branchrevs)
2537 heads = [h for h in heads if h.branch() in branches]
2537 heads = [h for h in heads if h.branch() in branches]
2538
2538
2539 if not opts.get('closed'):
2539 if not opts.get('closed'):
2540 heads = [h for h in heads if not h.extra().get('close')]
2540 heads = [h for h in heads if not h.extra().get('close')]
2541
2541
2542 if opts.get('active') and branchrevs:
2542 if opts.get('active') and branchrevs:
2543 dagheads = repo.heads(start)
2543 dagheads = repo.heads(start)
2544 heads = [h for h in heads if h.node() in dagheads]
2544 heads = [h for h in heads if h.node() in dagheads]
2545
2545
2546 if branchrevs:
2546 if branchrevs:
2547 haveheads = set(h.branch() for h in heads)
2547 haveheads = set(h.branch() for h in heads)
2548 if branches - haveheads:
2548 if branches - haveheads:
2549 headless = ', '.join(b for b in branches - haveheads)
2549 headless = ', '.join(b for b in branches - haveheads)
2550 msg = _('no open branch heads found on branches %s')
2550 msg = _('no open branch heads found on branches %s')
2551 if opts.get('rev'):
2551 if opts.get('rev'):
2552 msg += _(' (started at %s)' % opts['rev'])
2552 msg += _(' (started at %s)' % opts['rev'])
2553 ui.warn((msg + '\n') % headless)
2553 ui.warn((msg + '\n') % headless)
2554
2554
2555 if not heads:
2555 if not heads:
2556 return 1
2556 return 1
2557
2557
2558 heads = sorted(heads, key=lambda x: -x.rev())
2558 heads = sorted(heads, key=lambda x: -x.rev())
2559 displayer = cmdutil.show_changeset(ui, repo, opts)
2559 displayer = cmdutil.show_changeset(ui, repo, opts)
2560 for ctx in heads:
2560 for ctx in heads:
2561 displayer.show(ctx)
2561 displayer.show(ctx)
2562 displayer.close()
2562 displayer.close()
2563
2563
2564 @command('help',
2564 @command('help',
2565 [('e', 'extension', None, _('show only help for extensions')),
2565 [('e', 'extension', None, _('show only help for extensions')),
2566 ('c', 'command', None, _('show only help for commands'))],
2566 ('c', 'command', None, _('show only help for commands'))],
2567 _('[-ec] [TOPIC]'))
2567 _('[-ec] [TOPIC]'))
2568 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2568 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2569 """show help for a given topic or a help overview
2569 """show help for a given topic or a help overview
2570
2570
2571 With no arguments, print a list of commands with short help messages.
2571 With no arguments, print a list of commands with short help messages.
2572
2572
2573 Given a topic, extension, or command name, print help for that
2573 Given a topic, extension, or command name, print help for that
2574 topic.
2574 topic.
2575
2575
2576 Returns 0 if successful.
2576 Returns 0 if successful.
2577 """
2577 """
2578 option_lists = []
2578 option_lists = []
2579 textwidth = min(ui.termwidth(), 80) - 2
2579 textwidth = min(ui.termwidth(), 80) - 2
2580
2580
2581 def addglobalopts(aliases):
2581 def addglobalopts(aliases):
2582 if ui.verbose:
2582 if ui.verbose:
2583 option_lists.append((_("global options:"), globalopts))
2583 option_lists.append((_("global options:"), globalopts))
2584 if name == 'shortlist':
2584 if name == 'shortlist':
2585 option_lists.append((_('use "hg help" for the full list '
2585 option_lists.append((_('use "hg help" for the full list '
2586 'of commands'), ()))
2586 'of commands'), ()))
2587 else:
2587 else:
2588 if name == 'shortlist':
2588 if name == 'shortlist':
2589 msg = _('use "hg help" for the full list of commands '
2589 msg = _('use "hg help" for the full list of commands '
2590 'or "hg -v" for details')
2590 'or "hg -v" for details')
2591 elif name and not full:
2591 elif name and not full:
2592 msg = _('use "hg help %s" to show the full help text' % name)
2592 msg = _('use "hg help %s" to show the full help text' % name)
2593 elif aliases:
2593 elif aliases:
2594 msg = _('use "hg -v help%s" to show builtin aliases and '
2594 msg = _('use "hg -v help%s" to show builtin aliases and '
2595 'global options') % (name and " " + name or "")
2595 'global options') % (name and " " + name or "")
2596 else:
2596 else:
2597 msg = _('use "hg -v help %s" to show global options') % name
2597 msg = _('use "hg -v help %s" to show global options') % name
2598 option_lists.append((msg, ()))
2598 option_lists.append((msg, ()))
2599
2599
2600 def helpcmd(name):
2600 def helpcmd(name):
2601 if with_version:
2601 if with_version:
2602 version_(ui)
2602 version_(ui)
2603 ui.write('\n')
2603 ui.write('\n')
2604
2604
2605 try:
2605 try:
2606 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2606 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2607 except error.AmbiguousCommand, inst:
2607 except error.AmbiguousCommand, inst:
2608 # py3k fix: except vars can't be used outside the scope of the
2608 # py3k fix: except vars can't be used outside the scope of the
2609 # except block, nor can be used inside a lambda. python issue4617
2609 # except block, nor can be used inside a lambda. python issue4617
2610 prefix = inst.args[0]
2610 prefix = inst.args[0]
2611 select = lambda c: c.lstrip('^').startswith(prefix)
2611 select = lambda c: c.lstrip('^').startswith(prefix)
2612 helplist(_('list of commands:\n\n'), select)
2612 helplist(_('list of commands:\n\n'), select)
2613 return
2613 return
2614
2614
2615 # check if it's an invalid alias and display its error if it is
2615 # check if it's an invalid alias and display its error if it is
2616 if getattr(entry[0], 'badalias', False):
2616 if getattr(entry[0], 'badalias', False):
2617 if not unknowncmd:
2617 if not unknowncmd:
2618 entry[0](ui)
2618 entry[0](ui)
2619 return
2619 return
2620
2620
2621 # synopsis
2621 # synopsis
2622 if len(entry) > 2:
2622 if len(entry) > 2:
2623 if entry[2].startswith('hg'):
2623 if entry[2].startswith('hg'):
2624 ui.write("%s\n" % entry[2])
2624 ui.write("%s\n" % entry[2])
2625 else:
2625 else:
2626 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2626 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2627 else:
2627 else:
2628 ui.write('hg %s\n' % aliases[0])
2628 ui.write('hg %s\n' % aliases[0])
2629
2629
2630 # aliases
2630 # aliases
2631 if full and not ui.quiet and len(aliases) > 1:
2631 if full and not ui.quiet and len(aliases) > 1:
2632 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2632 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2633
2633
2634 # description
2634 # description
2635 doc = gettext(entry[0].__doc__)
2635 doc = gettext(entry[0].__doc__)
2636 if not doc:
2636 if not doc:
2637 doc = _("(no help text available)")
2637 doc = _("(no help text available)")
2638 if hasattr(entry[0], 'definition'): # aliased command
2638 if hasattr(entry[0], 'definition'): # aliased command
2639 if entry[0].definition.startswith('!'): # shell alias
2639 if entry[0].definition.startswith('!'): # shell alias
2640 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2640 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2641 else:
2641 else:
2642 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2642 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2643 if ui.quiet or not full:
2643 if ui.quiet or not full:
2644 doc = doc.splitlines()[0]
2644 doc = doc.splitlines()[0]
2645 keep = ui.verbose and ['verbose'] or []
2645 keep = ui.verbose and ['verbose'] or []
2646 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2646 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2647 ui.write("\n%s\n" % formatted)
2647 ui.write("\n%s\n" % formatted)
2648 if pruned:
2648 if pruned:
2649 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2649 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2650
2650
2651 if not ui.quiet:
2651 if not ui.quiet:
2652 # options
2652 # options
2653 if entry[1]:
2653 if entry[1]:
2654 option_lists.append((_("options:\n"), entry[1]))
2654 option_lists.append((_("options:\n"), entry[1]))
2655
2655
2656 addglobalopts(False)
2656 addglobalopts(False)
2657
2657
2658 # check if this command shadows a non-trivial (multi-line)
2658 # check if this command shadows a non-trivial (multi-line)
2659 # extension help text
2659 # extension help text
2660 try:
2660 try:
2661 mod = extensions.find(name)
2661 mod = extensions.find(name)
2662 doc = gettext(mod.__doc__) or ''
2662 doc = gettext(mod.__doc__) or ''
2663 if '\n' in doc.strip():
2663 if '\n' in doc.strip():
2664 msg = _('use "hg help -e %s" to show help for '
2664 msg = _('use "hg help -e %s" to show help for '
2665 'the %s extension') % (name, name)
2665 'the %s extension') % (name, name)
2666 ui.write('\n%s\n' % msg)
2666 ui.write('\n%s\n' % msg)
2667 except KeyError:
2667 except KeyError:
2668 pass
2668 pass
2669
2669
2670 def helplist(header, select=None):
2670 def helplist(header, select=None):
2671 h = {}
2671 h = {}
2672 cmds = {}
2672 cmds = {}
2673 for c, e in table.iteritems():
2673 for c, e in table.iteritems():
2674 f = c.split("|", 1)[0]
2674 f = c.split("|", 1)[0]
2675 if select and not select(f):
2675 if select and not select(f):
2676 continue
2676 continue
2677 if (not select and name != 'shortlist' and
2677 if (not select and name != 'shortlist' and
2678 e[0].__module__ != __name__):
2678 e[0].__module__ != __name__):
2679 continue
2679 continue
2680 if name == "shortlist" and not f.startswith("^"):
2680 if name == "shortlist" and not f.startswith("^"):
2681 continue
2681 continue
2682 f = f.lstrip("^")
2682 f = f.lstrip("^")
2683 if not ui.debugflag and f.startswith("debug"):
2683 if not ui.debugflag and f.startswith("debug"):
2684 continue
2684 continue
2685 doc = e[0].__doc__
2685 doc = e[0].__doc__
2686 if doc and 'DEPRECATED' in doc and not ui.verbose:
2686 if doc and 'DEPRECATED' in doc and not ui.verbose:
2687 continue
2687 continue
2688 doc = gettext(doc)
2688 doc = gettext(doc)
2689 if not doc:
2689 if not doc:
2690 doc = _("(no help text available)")
2690 doc = _("(no help text available)")
2691 h[f] = doc.splitlines()[0].rstrip()
2691 h[f] = doc.splitlines()[0].rstrip()
2692 cmds[f] = c.lstrip("^")
2692 cmds[f] = c.lstrip("^")
2693
2693
2694 if not h:
2694 if not h:
2695 ui.status(_('no commands defined\n'))
2695 ui.status(_('no commands defined\n'))
2696 return
2696 return
2697
2697
2698 ui.status(header)
2698 ui.status(header)
2699 fns = sorted(h)
2699 fns = sorted(h)
2700 m = max(map(len, fns))
2700 m = max(map(len, fns))
2701 for f in fns:
2701 for f in fns:
2702 if ui.verbose:
2702 if ui.verbose:
2703 commands = cmds[f].replace("|",", ")
2703 commands = cmds[f].replace("|",", ")
2704 ui.write(" %s:\n %s\n"%(commands, h[f]))
2704 ui.write(" %s:\n %s\n"%(commands, h[f]))
2705 else:
2705 else:
2706 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2706 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2707 initindent=' %-*s ' % (m, f),
2707 initindent=' %-*s ' % (m, f),
2708 hangindent=' ' * (m + 4))))
2708 hangindent=' ' * (m + 4))))
2709
2709
2710 if not ui.quiet:
2710 if not ui.quiet:
2711 addglobalopts(True)
2711 addglobalopts(True)
2712
2712
2713 def helptopic(name):
2713 def helptopic(name):
2714 for names, header, doc in help.helptable:
2714 for names, header, doc in help.helptable:
2715 if name in names:
2715 if name in names:
2716 break
2716 break
2717 else:
2717 else:
2718 raise error.UnknownCommand(name)
2718 raise error.UnknownCommand(name)
2719
2719
2720 # description
2720 # description
2721 if not doc:
2721 if not doc:
2722 doc = _("(no help text available)")
2722 doc = _("(no help text available)")
2723 if hasattr(doc, '__call__'):
2723 if hasattr(doc, '__call__'):
2724 doc = doc()
2724 doc = doc()
2725
2725
2726 ui.write("%s\n\n" % header)
2726 ui.write("%s\n\n" % header)
2727 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2727 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2728 try:
2728 try:
2729 cmdutil.findcmd(name, table)
2729 cmdutil.findcmd(name, table)
2730 ui.write(_('\nuse "hg help -c %s" to see help for '
2730 ui.write(_('\nuse "hg help -c %s" to see help for '
2731 'the %s command\n') % (name, name))
2731 'the %s command\n') % (name, name))
2732 except error.UnknownCommand:
2732 except error.UnknownCommand:
2733 pass
2733 pass
2734
2734
2735 def helpext(name):
2735 def helpext(name):
2736 try:
2736 try:
2737 mod = extensions.find(name)
2737 mod = extensions.find(name)
2738 doc = gettext(mod.__doc__) or _('no help text available')
2738 doc = gettext(mod.__doc__) or _('no help text available')
2739 except KeyError:
2739 except KeyError:
2740 mod = None
2740 mod = None
2741 doc = extensions.disabledext(name)
2741 doc = extensions.disabledext(name)
2742 if not doc:
2742 if not doc:
2743 raise error.UnknownCommand(name)
2743 raise error.UnknownCommand(name)
2744
2744
2745 if '\n' not in doc:
2745 if '\n' not in doc:
2746 head, tail = doc, ""
2746 head, tail = doc, ""
2747 else:
2747 else:
2748 head, tail = doc.split('\n', 1)
2748 head, tail = doc.split('\n', 1)
2749 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2749 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2750 if tail:
2750 if tail:
2751 ui.write(minirst.format(tail, textwidth))
2751 ui.write(minirst.format(tail, textwidth))
2752 ui.status('\n\n')
2752 ui.status('\n\n')
2753
2753
2754 if mod:
2754 if mod:
2755 try:
2755 try:
2756 ct = mod.cmdtable
2756 ct = mod.cmdtable
2757 except AttributeError:
2757 except AttributeError:
2758 ct = {}
2758 ct = {}
2759 modcmds = set([c.split('|', 1)[0] for c in ct])
2759 modcmds = set([c.split('|', 1)[0] for c in ct])
2760 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2760 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2761 else:
2761 else:
2762 ui.write(_('use "hg help extensions" for information on enabling '
2762 ui.write(_('use "hg help extensions" for information on enabling '
2763 'extensions\n'))
2763 'extensions\n'))
2764
2764
2765 def helpextcmd(name):
2765 def helpextcmd(name):
2766 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2766 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2767 doc = gettext(mod.__doc__).splitlines()[0]
2767 doc = gettext(mod.__doc__).splitlines()[0]
2768
2768
2769 msg = help.listexts(_("'%s' is provided by the following "
2769 msg = help.listexts(_("'%s' is provided by the following "
2770 "extension:") % cmd, {ext: doc}, indent=4)
2770 "extension:") % cmd, {ext: doc}, indent=4)
2771 ui.write(minirst.format(msg, textwidth))
2771 ui.write(minirst.format(msg, textwidth))
2772 ui.write('\n\n')
2772 ui.write('\n\n')
2773 ui.write(_('use "hg help extensions" for information on enabling '
2773 ui.write(_('use "hg help extensions" for information on enabling '
2774 'extensions\n'))
2774 'extensions\n'))
2775
2775
2776 if name and name != 'shortlist':
2776 if name and name != 'shortlist':
2777 i = None
2777 i = None
2778 if unknowncmd:
2778 if unknowncmd:
2779 queries = (helpextcmd,)
2779 queries = (helpextcmd,)
2780 elif opts.get('extension'):
2780 elif opts.get('extension'):
2781 queries = (helpext,)
2781 queries = (helpext,)
2782 elif opts.get('command'):
2782 elif opts.get('command'):
2783 queries = (helpcmd,)
2783 queries = (helpcmd,)
2784 else:
2784 else:
2785 queries = (helptopic, helpcmd, helpext, helpextcmd)
2785 queries = (helptopic, helpcmd, helpext, helpextcmd)
2786 for f in queries:
2786 for f in queries:
2787 try:
2787 try:
2788 f(name)
2788 f(name)
2789 i = None
2789 i = None
2790 break
2790 break
2791 except error.UnknownCommand, inst:
2791 except error.UnknownCommand, inst:
2792 i = inst
2792 i = inst
2793 if i:
2793 if i:
2794 raise i
2794 raise i
2795
2795
2796 else:
2796 else:
2797 # program name
2797 # program name
2798 if ui.verbose or with_version:
2798 if ui.verbose or with_version:
2799 version_(ui)
2799 version_(ui)
2800 else:
2800 else:
2801 ui.status(_("Mercurial Distributed SCM\n"))
2801 ui.status(_("Mercurial Distributed SCM\n"))
2802 ui.status('\n')
2802 ui.status('\n')
2803
2803
2804 # list of commands
2804 # list of commands
2805 if name == "shortlist":
2805 if name == "shortlist":
2806 header = _('basic commands:\n\n')
2806 header = _('basic commands:\n\n')
2807 else:
2807 else:
2808 header = _('list of commands:\n\n')
2808 header = _('list of commands:\n\n')
2809
2809
2810 helplist(header)
2810 helplist(header)
2811 if name != 'shortlist':
2811 if name != 'shortlist':
2812 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2812 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2813 if text:
2813 if text:
2814 ui.write("\n%s\n" % minirst.format(text, textwidth))
2814 ui.write("\n%s\n" % minirst.format(text, textwidth))
2815
2815
2816 # list all option lists
2816 # list all option lists
2817 opt_output = []
2817 opt_output = []
2818 multioccur = False
2818 multioccur = False
2819 for title, options in option_lists:
2819 for title, options in option_lists:
2820 opt_output.append(("\n%s" % title, None))
2820 opt_output.append(("\n%s" % title, None))
2821 for option in options:
2821 for option in options:
2822 if len(option) == 5:
2822 if len(option) == 5:
2823 shortopt, longopt, default, desc, optlabel = option
2823 shortopt, longopt, default, desc, optlabel = option
2824 else:
2824 else:
2825 shortopt, longopt, default, desc = option
2825 shortopt, longopt, default, desc = option
2826 optlabel = _("VALUE") # default label
2826 optlabel = _("VALUE") # default label
2827
2827
2828 if _("DEPRECATED") in desc and not ui.verbose:
2828 if _("DEPRECATED") in desc and not ui.verbose:
2829 continue
2829 continue
2830 if isinstance(default, list):
2830 if isinstance(default, list):
2831 numqualifier = " %s [+]" % optlabel
2831 numqualifier = " %s [+]" % optlabel
2832 multioccur = True
2832 multioccur = True
2833 elif (default is not None) and not isinstance(default, bool):
2833 elif (default is not None) and not isinstance(default, bool):
2834 numqualifier = " %s" % optlabel
2834 numqualifier = " %s" % optlabel
2835 else:
2835 else:
2836 numqualifier = ""
2836 numqualifier = ""
2837 opt_output.append(("%2s%s" %
2837 opt_output.append(("%2s%s" %
2838 (shortopt and "-%s" % shortopt,
2838 (shortopt and "-%s" % shortopt,
2839 longopt and " --%s%s" %
2839 longopt and " --%s%s" %
2840 (longopt, numqualifier)),
2840 (longopt, numqualifier)),
2841 "%s%s" % (desc,
2841 "%s%s" % (desc,
2842 default
2842 default
2843 and _(" (default: %s)") % default
2843 and _(" (default: %s)") % default
2844 or "")))
2844 or "")))
2845 if multioccur:
2845 if multioccur:
2846 msg = _("\n[+] marked option can be specified multiple times")
2846 msg = _("\n[+] marked option can be specified multiple times")
2847 if ui.verbose and name != 'shortlist':
2847 if ui.verbose and name != 'shortlist':
2848 opt_output.append((msg, None))
2848 opt_output.append((msg, None))
2849 else:
2849 else:
2850 opt_output.insert(-1, (msg, None))
2850 opt_output.insert(-1, (msg, None))
2851
2851
2852 if not name:
2852 if not name:
2853 ui.write(_("\nadditional help topics:\n\n"))
2853 ui.write(_("\nadditional help topics:\n\n"))
2854 topics = []
2854 topics = []
2855 for names, header, doc in help.helptable:
2855 for names, header, doc in help.helptable:
2856 topics.append((sorted(names, key=len, reverse=True)[0], header))
2856 topics.append((sorted(names, key=len, reverse=True)[0], header))
2857 topics_len = max([len(s[0]) for s in topics])
2857 topics_len = max([len(s[0]) for s in topics])
2858 for t, desc in topics:
2858 for t, desc in topics:
2859 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2859 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2860
2860
2861 if opt_output:
2861 if opt_output:
2862 colwidth = encoding.colwidth
2862 colwidth = encoding.colwidth
2863 # normalize: (opt or message, desc or None, width of opt)
2863 # normalize: (opt or message, desc or None, width of opt)
2864 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2864 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2865 for opt, desc in opt_output]
2865 for opt, desc in opt_output]
2866 hanging = max([e[2] for e in entries])
2866 hanging = max([e[2] for e in entries])
2867 for opt, desc, width in entries:
2867 for opt, desc, width in entries:
2868 if desc:
2868 if desc:
2869 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2869 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2870 hangindent = ' ' * (hanging + 3)
2870 hangindent = ' ' * (hanging + 3)
2871 ui.write('%s\n' % (util.wrap(desc, textwidth,
2871 ui.write('%s\n' % (util.wrap(desc, textwidth,
2872 initindent=initindent,
2872 initindent=initindent,
2873 hangindent=hangindent)))
2873 hangindent=hangindent)))
2874 else:
2874 else:
2875 ui.write("%s\n" % opt)
2875 ui.write("%s\n" % opt)
2876
2876
2877 @command('identify|id',
2877 @command('identify|id',
2878 [('r', 'rev', '',
2878 [('r', 'rev', '',
2879 _('identify the specified revision'), _('REV')),
2879 _('identify the specified revision'), _('REV')),
2880 ('n', 'num', None, _('show local revision number')),
2880 ('n', 'num', None, _('show local revision number')),
2881 ('i', 'id', None, _('show global revision id')),
2881 ('i', 'id', None, _('show global revision id')),
2882 ('b', 'branch', None, _('show branch')),
2882 ('b', 'branch', None, _('show branch')),
2883 ('t', 'tags', None, _('show tags')),
2883 ('t', 'tags', None, _('show tags')),
2884 ('B', 'bookmarks', None, _('show bookmarks'))],
2884 ('B', 'bookmarks', None, _('show bookmarks'))],
2885 _('[-nibtB] [-r REV] [SOURCE]'))
2885 _('[-nibtB] [-r REV] [SOURCE]'))
2886 def identify(ui, repo, source=None, rev=None,
2886 def identify(ui, repo, source=None, rev=None,
2887 num=None, id=None, branch=None, tags=None, bookmarks=None):
2887 num=None, id=None, branch=None, tags=None, bookmarks=None):
2888 """identify the working copy or specified revision
2888 """identify the working copy or specified revision
2889
2889
2890 Print a summary identifying the repository state at REV using one or
2890 Print a summary identifying the repository state at REV using one or
2891 two parent hash identifiers, followed by a "+" if the working
2891 two parent hash identifiers, followed by a "+" if the working
2892 directory has uncommitted changes, the branch name (if not default),
2892 directory has uncommitted changes, the branch name (if not default),
2893 a list of tags, and a list of bookmarks.
2893 a list of tags, and a list of bookmarks.
2894
2894
2895 When REV is not given, print a summary of the current state of the
2895 When REV is not given, print a summary of the current state of the
2896 repository.
2896 repository.
2897
2897
2898 Specifying a path to a repository root or Mercurial bundle will
2898 Specifying a path to a repository root or Mercurial bundle will
2899 cause lookup to operate on that repository/bundle.
2899 cause lookup to operate on that repository/bundle.
2900
2900
2901 Returns 0 if successful.
2901 Returns 0 if successful.
2902 """
2902 """
2903
2903
2904 if not repo and not source:
2904 if not repo and not source:
2905 raise util.Abort(_("there is no Mercurial repository here "
2905 raise util.Abort(_("there is no Mercurial repository here "
2906 "(.hg not found)"))
2906 "(.hg not found)"))
2907
2907
2908 hexfunc = ui.debugflag and hex or short
2908 hexfunc = ui.debugflag and hex or short
2909 default = not (num or id or branch or tags or bookmarks)
2909 default = not (num or id or branch or tags or bookmarks)
2910 output = []
2910 output = []
2911 revs = []
2911 revs = []
2912
2912
2913 if source:
2913 if source:
2914 source, branches = hg.parseurl(ui.expandpath(source))
2914 source, branches = hg.parseurl(ui.expandpath(source))
2915 repo = hg.repository(ui, source)
2915 repo = hg.repository(ui, source)
2916 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2916 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2917
2917
2918 if not repo.local():
2918 if not repo.local():
2919 if num or branch or tags:
2919 if num or branch or tags:
2920 raise util.Abort(
2920 raise util.Abort(
2921 _("can't query remote revision number, branch, or tags"))
2921 _("can't query remote revision number, branch, or tags"))
2922 if not rev and revs:
2922 if not rev and revs:
2923 rev = revs[0]
2923 rev = revs[0]
2924 if not rev:
2924 if not rev:
2925 rev = "tip"
2925 rev = "tip"
2926
2926
2927 remoterev = repo.lookup(rev)
2927 remoterev = repo.lookup(rev)
2928 if default or id:
2928 if default or id:
2929 output = [hexfunc(remoterev)]
2929 output = [hexfunc(remoterev)]
2930
2930
2931 def getbms():
2931 def getbms():
2932 bms = []
2932 bms = []
2933
2933
2934 if 'bookmarks' in repo.listkeys('namespaces'):
2934 if 'bookmarks' in repo.listkeys('namespaces'):
2935 hexremoterev = hex(remoterev)
2935 hexremoterev = hex(remoterev)
2936 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2936 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2937 if bmr == hexremoterev]
2937 if bmr == hexremoterev]
2938
2938
2939 return bms
2939 return bms
2940
2940
2941 if bookmarks:
2941 if bookmarks:
2942 output.extend(getbms())
2942 output.extend(getbms())
2943 elif default and not ui.quiet:
2943 elif default and not ui.quiet:
2944 # multiple bookmarks for a single parent separated by '/'
2944 # multiple bookmarks for a single parent separated by '/'
2945 bm = '/'.join(getbms())
2945 bm = '/'.join(getbms())
2946 if bm:
2946 if bm:
2947 output.append(bm)
2947 output.append(bm)
2948 else:
2948 else:
2949 if not rev:
2949 if not rev:
2950 ctx = repo[None]
2950 ctx = repo[None]
2951 parents = ctx.parents()
2951 parents = ctx.parents()
2952 changed = ""
2952 changed = ""
2953 if default or id or num:
2953 if default or id or num:
2954 changed = util.any(repo.status()) and "+" or ""
2954 changed = util.any(repo.status()) and "+" or ""
2955 if default or id:
2955 if default or id:
2956 output = ["%s%s" %
2956 output = ["%s%s" %
2957 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2957 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2958 if num:
2958 if num:
2959 output.append("%s%s" %
2959 output.append("%s%s" %
2960 ('+'.join([str(p.rev()) for p in parents]), changed))
2960 ('+'.join([str(p.rev()) for p in parents]), changed))
2961 else:
2961 else:
2962 ctx = scmutil.revsingle(repo, rev)
2962 ctx = scmutil.revsingle(repo, rev)
2963 if default or id:
2963 if default or id:
2964 output = [hexfunc(ctx.node())]
2964 output = [hexfunc(ctx.node())]
2965 if num:
2965 if num:
2966 output.append(str(ctx.rev()))
2966 output.append(str(ctx.rev()))
2967
2967
2968 if default and not ui.quiet:
2968 if default and not ui.quiet:
2969 b = ctx.branch()
2969 b = ctx.branch()
2970 if b != 'default':
2970 if b != 'default':
2971 output.append("(%s)" % b)
2971 output.append("(%s)" % b)
2972
2972
2973 # multiple tags for a single parent separated by '/'
2973 # multiple tags for a single parent separated by '/'
2974 t = '/'.join(ctx.tags())
2974 t = '/'.join(ctx.tags())
2975 if t:
2975 if t:
2976 output.append(t)
2976 output.append(t)
2977
2977
2978 # multiple bookmarks for a single parent separated by '/'
2978 # multiple bookmarks for a single parent separated by '/'
2979 bm = '/'.join(ctx.bookmarks())
2979 bm = '/'.join(ctx.bookmarks())
2980 if bm:
2980 if bm:
2981 output.append(bm)
2981 output.append(bm)
2982 else:
2982 else:
2983 if branch:
2983 if branch:
2984 output.append(ctx.branch())
2984 output.append(ctx.branch())
2985
2985
2986 if tags:
2986 if tags:
2987 output.extend(ctx.tags())
2987 output.extend(ctx.tags())
2988
2988
2989 if bookmarks:
2989 if bookmarks:
2990 output.extend(ctx.bookmarks())
2990 output.extend(ctx.bookmarks())
2991
2991
2992 ui.write("%s\n" % ' '.join(output))
2992 ui.write("%s\n" % ' '.join(output))
2993
2993
2994 @command('import|patch',
2994 @command('import|patch',
2995 [('p', 'strip', 1,
2995 [('p', 'strip', 1,
2996 _('directory strip option for patch. This has the same '
2996 _('directory strip option for patch. This has the same '
2997 'meaning as the corresponding patch option'), _('NUM')),
2997 'meaning as the corresponding patch option'), _('NUM')),
2998 ('b', 'base', '', _('base path'), _('PATH')),
2998 ('b', 'base', '', _('base path'), _('PATH')),
2999 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
2999 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3000 ('', 'no-commit', None,
3000 ('', 'no-commit', None,
3001 _("don't commit, just update the working directory")),
3001 _("don't commit, just update the working directory")),
3002 ('', 'exact', None,
3002 ('', 'exact', None,
3003 _('apply patch to the nodes from which it was generated')),
3003 _('apply patch to the nodes from which it was generated')),
3004 ('', 'import-branch', None,
3004 ('', 'import-branch', None,
3005 _('use any branch information in patch (implied by --exact)'))] +
3005 _('use any branch information in patch (implied by --exact)'))] +
3006 commitopts + commitopts2 + similarityopts,
3006 commitopts + commitopts2 + similarityopts,
3007 _('[OPTION]... PATCH...'))
3007 _('[OPTION]... PATCH...'))
3008 def import_(ui, repo, patch1, *patches, **opts):
3008 def import_(ui, repo, patch1, *patches, **opts):
3009 """import an ordered set of patches
3009 """import an ordered set of patches
3010
3010
3011 Import a list of patches and commit them individually (unless
3011 Import a list of patches and commit them individually (unless
3012 --no-commit is specified).
3012 --no-commit is specified).
3013
3013
3014 If there are outstanding changes in the working directory, import
3014 If there are outstanding changes in the working directory, import
3015 will abort unless given the -f/--force flag.
3015 will abort unless given the -f/--force flag.
3016
3016
3017 You can import a patch straight from a mail message. Even patches
3017 You can import a patch straight from a mail message. Even patches
3018 as attachments work (to use the body part, it must have type
3018 as attachments work (to use the body part, it must have type
3019 text/plain or text/x-patch). From and Subject headers of email
3019 text/plain or text/x-patch). From and Subject headers of email
3020 message are used as default committer and commit message. All
3020 message are used as default committer and commit message. All
3021 text/plain body parts before first diff are added to commit
3021 text/plain body parts before first diff are added to commit
3022 message.
3022 message.
3023
3023
3024 If the imported patch was generated by :hg:`export`, user and
3024 If the imported patch was generated by :hg:`export`, user and
3025 description from patch override values from message headers and
3025 description from patch override values from message headers and
3026 body. Values given on command line with -m/--message and -u/--user
3026 body. Values given on command line with -m/--message and -u/--user
3027 override these.
3027 override these.
3028
3028
3029 If --exact is specified, import will set the working directory to
3029 If --exact is specified, import will set the working directory to
3030 the parent of each patch before applying it, and will abort if the
3030 the parent of each patch before applying it, and will abort if the
3031 resulting changeset has a different ID than the one recorded in
3031 resulting changeset has a different ID than the one recorded in
3032 the patch. This may happen due to character set problems or other
3032 the patch. This may happen due to character set problems or other
3033 deficiencies in the text patch format.
3033 deficiencies in the text patch format.
3034
3034
3035 With -s/--similarity, hg will attempt to discover renames and
3035 With -s/--similarity, hg will attempt to discover renames and
3036 copies in the patch in the same way as 'addremove'.
3036 copies in the patch in the same way as 'addremove'.
3037
3037
3038 To read a patch from standard input, use "-" as the patch name. If
3038 To read a patch from standard input, use "-" as the patch name. If
3039 a URL is specified, the patch will be downloaded from it.
3039 a URL is specified, the patch will be downloaded from it.
3040 See :hg:`help dates` for a list of formats valid for -d/--date.
3040 See :hg:`help dates` for a list of formats valid for -d/--date.
3041
3041
3042 Returns 0 on success.
3042 Returns 0 on success.
3043 """
3043 """
3044 patches = (patch1,) + patches
3044 patches = (patch1,) + patches
3045
3045
3046 date = opts.get('date')
3046 date = opts.get('date')
3047 if date:
3047 if date:
3048 opts['date'] = util.parsedate(date)
3048 opts['date'] = util.parsedate(date)
3049
3049
3050 try:
3050 try:
3051 sim = float(opts.get('similarity') or 0)
3051 sim = float(opts.get('similarity') or 0)
3052 except ValueError:
3052 except ValueError:
3053 raise util.Abort(_('similarity must be a number'))
3053 raise util.Abort(_('similarity must be a number'))
3054 if sim < 0 or sim > 100:
3054 if sim < 0 or sim > 100:
3055 raise util.Abort(_('similarity must be between 0 and 100'))
3055 raise util.Abort(_('similarity must be between 0 and 100'))
3056
3056
3057 if opts.get('exact') or not opts.get('force'):
3057 if opts.get('exact') or not opts.get('force'):
3058 cmdutil.bailifchanged(repo)
3058 cmdutil.bailifchanged(repo)
3059
3059
3060 d = opts["base"]
3060 d = opts["base"]
3061 strip = opts["strip"]
3061 strip = opts["strip"]
3062 wlock = lock = None
3062 wlock = lock = None
3063 msgs = []
3063 msgs = []
3064
3064
3065 def tryone(ui, hunk):
3065 def tryone(ui, hunk):
3066 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3066 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3067 patch.extract(ui, hunk)
3067 patch.extract(ui, hunk)
3068
3068
3069 if not tmpname:
3069 if not tmpname:
3070 return None
3070 return None
3071 commitid = _('to working directory')
3071 commitid = _('to working directory')
3072
3072
3073 try:
3073 try:
3074 cmdline_message = cmdutil.logmessage(opts)
3074 cmdline_message = cmdutil.logmessage(opts)
3075 if cmdline_message:
3075 if cmdline_message:
3076 # pickup the cmdline msg
3076 # pickup the cmdline msg
3077 message = cmdline_message
3077 message = cmdline_message
3078 elif message:
3078 elif message:
3079 # pickup the patch msg
3079 # pickup the patch msg
3080 message = message.strip()
3080 message = message.strip()
3081 else:
3081 else:
3082 # launch the editor
3082 # launch the editor
3083 message = None
3083 message = None
3084 ui.debug('message:\n%s\n' % message)
3084 ui.debug('message:\n%s\n' % message)
3085
3085
3086 wp = repo.parents()
3086 wp = repo.parents()
3087 if opts.get('exact'):
3087 if opts.get('exact'):
3088 if not nodeid or not p1:
3088 if not nodeid or not p1:
3089 raise util.Abort(_('not a Mercurial patch'))
3089 raise util.Abort(_('not a Mercurial patch'))
3090 p1 = repo.lookup(p1)
3090 p1 = repo.lookup(p1)
3091 p2 = repo.lookup(p2 or hex(nullid))
3091 p2 = repo.lookup(p2 or hex(nullid))
3092
3092
3093 if p1 != wp[0].node():
3093 if p1 != wp[0].node():
3094 hg.clean(repo, p1)
3094 hg.clean(repo, p1)
3095 repo.dirstate.setparents(p1, p2)
3095 repo.dirstate.setparents(p1, p2)
3096 elif p2:
3096 elif p2:
3097 try:
3097 try:
3098 p1 = repo.lookup(p1)
3098 p1 = repo.lookup(p1)
3099 p2 = repo.lookup(p2)
3099 p2 = repo.lookup(p2)
3100 if p1 == wp[0].node():
3100 if p1 == wp[0].node():
3101 repo.dirstate.setparents(p1, p2)
3101 repo.dirstate.setparents(p1, p2)
3102 except error.RepoError:
3102 except error.RepoError:
3103 pass
3103 pass
3104 if opts.get('exact') or opts.get('import_branch'):
3104 if opts.get('exact') or opts.get('import_branch'):
3105 repo.dirstate.setbranch(branch or 'default')
3105 repo.dirstate.setbranch(branch or 'default')
3106
3106
3107 files = {}
3107 files = {}
3108 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3108 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3109 eolmode=None, similarity=sim / 100.0)
3109 eolmode=None, similarity=sim / 100.0)
3110 files = list(files)
3110 files = list(files)
3111 if opts.get('no_commit'):
3111 if opts.get('no_commit'):
3112 if message:
3112 if message:
3113 msgs.append(message)
3113 msgs.append(message)
3114 else:
3114 else:
3115 if opts.get('exact'):
3115 if opts.get('exact'):
3116 m = None
3116 m = None
3117 else:
3117 else:
3118 m = scmutil.matchfiles(repo, files or [])
3118 m = scmutil.matchfiles(repo, files or [])
3119 n = repo.commit(message, opts.get('user') or user,
3119 n = repo.commit(message, opts.get('user') or user,
3120 opts.get('date') or date, match=m,
3120 opts.get('date') or date, match=m,
3121 editor=cmdutil.commiteditor)
3121 editor=cmdutil.commiteditor)
3122 if opts.get('exact'):
3122 if opts.get('exact'):
3123 if hex(n) != nodeid:
3123 if hex(n) != nodeid:
3124 repo.rollback()
3124 repo.rollback()
3125 raise util.Abort(_('patch is damaged'
3125 raise util.Abort(_('patch is damaged'
3126 ' or loses information'))
3126 ' or loses information'))
3127 # Force a dirstate write so that the next transaction
3127 # Force a dirstate write so that the next transaction
3128 # backups an up-do-date file.
3128 # backups an up-do-date file.
3129 repo.dirstate.write()
3129 repo.dirstate.write()
3130 if n:
3130 if n:
3131 commitid = short(n)
3131 commitid = short(n)
3132
3132
3133 return commitid
3133 return commitid
3134 finally:
3134 finally:
3135 os.unlink(tmpname)
3135 os.unlink(tmpname)
3136
3136
3137 try:
3137 try:
3138 wlock = repo.wlock()
3138 wlock = repo.wlock()
3139 lock = repo.lock()
3139 lock = repo.lock()
3140 lastcommit = None
3140 lastcommit = None
3141 for p in patches:
3141 for p in patches:
3142 pf = os.path.join(d, p)
3142 pf = os.path.join(d, p)
3143
3143
3144 if pf == '-':
3144 if pf == '-':
3145 ui.status(_("applying patch from stdin\n"))
3145 ui.status(_("applying patch from stdin\n"))
3146 pf = sys.stdin
3146 pf = sys.stdin
3147 else:
3147 else:
3148 ui.status(_("applying %s\n") % p)
3148 ui.status(_("applying %s\n") % p)
3149 pf = url.open(ui, pf)
3149 pf = url.open(ui, pf)
3150
3150
3151 haspatch = False
3151 haspatch = False
3152 for hunk in patch.split(pf):
3152 for hunk in patch.split(pf):
3153 commitid = tryone(ui, hunk)
3153 commitid = tryone(ui, hunk)
3154 if commitid:
3154 if commitid:
3155 haspatch = True
3155 haspatch = True
3156 if lastcommit:
3156 if lastcommit:
3157 ui.status(_('applied %s\n') % lastcommit)
3157 ui.status(_('applied %s\n') % lastcommit)
3158 lastcommit = commitid
3158 lastcommit = commitid
3159
3159
3160 if not haspatch:
3160 if not haspatch:
3161 raise util.Abort(_('no diffs found'))
3161 raise util.Abort(_('no diffs found'))
3162
3162
3163 if msgs:
3163 if msgs:
3164 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
3164 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
3165 finally:
3165 finally:
3166 release(lock, wlock)
3166 release(lock, wlock)
3167
3167
3168 @command('incoming|in',
3168 @command('incoming|in',
3169 [('f', 'force', None,
3169 [('f', 'force', None,
3170 _('run even if remote repository is unrelated')),
3170 _('run even if remote repository is unrelated')),
3171 ('n', 'newest-first', None, _('show newest record first')),
3171 ('n', 'newest-first', None, _('show newest record first')),
3172 ('', 'bundle', '',
3172 ('', 'bundle', '',
3173 _('file to store the bundles into'), _('FILE')),
3173 _('file to store the bundles into'), _('FILE')),
3174 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3174 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3175 ('B', 'bookmarks', False, _("compare bookmarks")),
3175 ('B', 'bookmarks', False, _("compare bookmarks")),
3176 ('b', 'branch', [],
3176 ('b', 'branch', [],
3177 _('a specific branch you would like to pull'), _('BRANCH')),
3177 _('a specific branch you would like to pull'), _('BRANCH')),
3178 ] + logopts + remoteopts + subrepoopts,
3178 ] + logopts + remoteopts + subrepoopts,
3179 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3179 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3180 def incoming(ui, repo, source="default", **opts):
3180 def incoming(ui, repo, source="default", **opts):
3181 """show new changesets found in source
3181 """show new changesets found in source
3182
3182
3183 Show new changesets found in the specified path/URL or the default
3183 Show new changesets found in the specified path/URL or the default
3184 pull location. These are the changesets that would have been pulled
3184 pull location. These are the changesets that would have been pulled
3185 if a pull at the time you issued this command.
3185 if a pull at the time you issued this command.
3186
3186
3187 For remote repository, using --bundle avoids downloading the
3187 For remote repository, using --bundle avoids downloading the
3188 changesets twice if the incoming is followed by a pull.
3188 changesets twice if the incoming is followed by a pull.
3189
3189
3190 See pull for valid source format details.
3190 See pull for valid source format details.
3191
3191
3192 Returns 0 if there are incoming changes, 1 otherwise.
3192 Returns 0 if there are incoming changes, 1 otherwise.
3193 """
3193 """
3194 if opts.get('bundle') and opts.get('subrepos'):
3194 if opts.get('bundle') and opts.get('subrepos'):
3195 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3195 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3196
3196
3197 if opts.get('bookmarks'):
3197 if opts.get('bookmarks'):
3198 source, branches = hg.parseurl(ui.expandpath(source),
3198 source, branches = hg.parseurl(ui.expandpath(source),
3199 opts.get('branch'))
3199 opts.get('branch'))
3200 other = hg.repository(hg.remoteui(repo, opts), source)
3200 other = hg.repository(hg.remoteui(repo, opts), source)
3201 if 'bookmarks' not in other.listkeys('namespaces'):
3201 if 'bookmarks' not in other.listkeys('namespaces'):
3202 ui.warn(_("remote doesn't support bookmarks\n"))
3202 ui.warn(_("remote doesn't support bookmarks\n"))
3203 return 0
3203 return 0
3204 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3204 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3205 return bookmarks.diff(ui, repo, other)
3205 return bookmarks.diff(ui, repo, other)
3206
3206
3207 repo._subtoppath = ui.expandpath(source)
3207 repo._subtoppath = ui.expandpath(source)
3208 try:
3208 try:
3209 return hg.incoming(ui, repo, source, opts)
3209 return hg.incoming(ui, repo, source, opts)
3210 finally:
3210 finally:
3211 del repo._subtoppath
3211 del repo._subtoppath
3212
3212
3213
3213
3214 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3214 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3215 def init(ui, dest=".", **opts):
3215 def init(ui, dest=".", **opts):
3216 """create a new repository in the given directory
3216 """create a new repository in the given directory
3217
3217
3218 Initialize a new repository in the given directory. If the given
3218 Initialize a new repository in the given directory. If the given
3219 directory does not exist, it will be created.
3219 directory does not exist, it will be created.
3220
3220
3221 If no directory is given, the current directory is used.
3221 If no directory is given, the current directory is used.
3222
3222
3223 It is possible to specify an ``ssh://`` URL as the destination.
3223 It is possible to specify an ``ssh://`` URL as the destination.
3224 See :hg:`help urls` for more information.
3224 See :hg:`help urls` for more information.
3225
3225
3226 Returns 0 on success.
3226 Returns 0 on success.
3227 """
3227 """
3228 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=True)
3228 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=True)
3229
3229
3230 @command('locate',
3230 @command('locate',
3231 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3231 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3232 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3232 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3233 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3233 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3234 ] + walkopts,
3234 ] + walkopts,
3235 _('[OPTION]... [PATTERN]...'))
3235 _('[OPTION]... [PATTERN]...'))
3236 def locate(ui, repo, *pats, **opts):
3236 def locate(ui, repo, *pats, **opts):
3237 """locate files matching specific patterns
3237 """locate files matching specific patterns
3238
3238
3239 Print files under Mercurial control in the working directory whose
3239 Print files under Mercurial control in the working directory whose
3240 names match the given patterns.
3240 names match the given patterns.
3241
3241
3242 By default, this command searches all directories in the working
3242 By default, this command searches all directories in the working
3243 directory. To search just the current directory and its
3243 directory. To search just the current directory and its
3244 subdirectories, use "--include .".
3244 subdirectories, use "--include .".
3245
3245
3246 If no patterns are given to match, this command prints the names
3246 If no patterns are given to match, this command prints the names
3247 of all files under Mercurial control in the working directory.
3247 of all files under Mercurial control in the working directory.
3248
3248
3249 If you want to feed the output of this command into the "xargs"
3249 If you want to feed the output of this command into the "xargs"
3250 command, use the -0 option to both this command and "xargs". This
3250 command, use the -0 option to both this command and "xargs". This
3251 will avoid the problem of "xargs" treating single filenames that
3251 will avoid the problem of "xargs" treating single filenames that
3252 contain whitespace as multiple filenames.
3252 contain whitespace as multiple filenames.
3253
3253
3254 Returns 0 if a match is found, 1 otherwise.
3254 Returns 0 if a match is found, 1 otherwise.
3255 """
3255 """
3256 end = opts.get('print0') and '\0' or '\n'
3256 end = opts.get('print0') and '\0' or '\n'
3257 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3257 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3258
3258
3259 ret = 1
3259 ret = 1
3260 m = scmutil.match(repo, pats, opts, default='relglob')
3260 m = scmutil.match(repo, pats, opts, default='relglob')
3261 m.bad = lambda x, y: False
3261 m.bad = lambda x, y: False
3262 for abs in repo[rev].walk(m):
3262 for abs in repo[rev].walk(m):
3263 if not rev and abs not in repo.dirstate:
3263 if not rev and abs not in repo.dirstate:
3264 continue
3264 continue
3265 if opts.get('fullpath'):
3265 if opts.get('fullpath'):
3266 ui.write(repo.wjoin(abs), end)
3266 ui.write(repo.wjoin(abs), end)
3267 else:
3267 else:
3268 ui.write(((pats and m.rel(abs)) or abs), end)
3268 ui.write(((pats and m.rel(abs)) or abs), end)
3269 ret = 0
3269 ret = 0
3270
3270
3271 return ret
3271 return ret
3272
3272
3273 @command('^log|history',
3273 @command('^log|history',
3274 [('f', 'follow', None,
3274 [('f', 'follow', None,
3275 _('follow changeset history, or file history across copies and renames')),
3275 _('follow changeset history, or file history across copies and renames')),
3276 ('', 'follow-first', None,
3276 ('', 'follow-first', None,
3277 _('only follow the first parent of merge changesets')),
3277 _('only follow the first parent of merge changesets')),
3278 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3278 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3279 ('C', 'copies', None, _('show copied files')),
3279 ('C', 'copies', None, _('show copied files')),
3280 ('k', 'keyword', [],
3280 ('k', 'keyword', [],
3281 _('do case-insensitive search for a given text'), _('TEXT')),
3281 _('do case-insensitive search for a given text'), _('TEXT')),
3282 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3282 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3283 ('', 'removed', None, _('include revisions where files were removed')),
3283 ('', 'removed', None, _('include revisions where files were removed')),
3284 ('m', 'only-merges', None, _('show only merges')),
3284 ('m', 'only-merges', None, _('show only merges')),
3285 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3285 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3286 ('', 'only-branch', [],
3286 ('', 'only-branch', [],
3287 _('show only changesets within the given named branch (DEPRECATED)'),
3287 _('show only changesets within the given named branch (DEPRECATED)'),
3288 _('BRANCH')),
3288 _('BRANCH')),
3289 ('b', 'branch', [],
3289 ('b', 'branch', [],
3290 _('show changesets within the given named branch'), _('BRANCH')),
3290 _('show changesets within the given named branch'), _('BRANCH')),
3291 ('P', 'prune', [],
3291 ('P', 'prune', [],
3292 _('do not display revision or any of its ancestors'), _('REV')),
3292 _('do not display revision or any of its ancestors'), _('REV')),
3293 ] + logopts + walkopts,
3293 ] + logopts + walkopts,
3294 _('[OPTION]... [FILE]'))
3294 _('[OPTION]... [FILE]'))
3295 def log(ui, repo, *pats, **opts):
3295 def log(ui, repo, *pats, **opts):
3296 """show revision history of entire repository or files
3296 """show revision history of entire repository or files
3297
3297
3298 Print the revision history of the specified files or the entire
3298 Print the revision history of the specified files or the entire
3299 project.
3299 project.
3300
3300
3301 File history is shown without following rename or copy history of
3301 File history is shown without following rename or copy history of
3302 files. Use -f/--follow with a filename to follow history across
3302 files. Use -f/--follow with a filename to follow history across
3303 renames and copies. --follow without a filename will only show
3303 renames and copies. --follow without a filename will only show
3304 ancestors or descendants of the starting revision. --follow-first
3304 ancestors or descendants of the starting revision. --follow-first
3305 only follows the first parent of merge revisions.
3305 only follows the first parent of merge revisions.
3306
3306
3307 If no revision range is specified, the default is ``tip:0`` unless
3307 If no revision range is specified, the default is ``tip:0`` unless
3308 --follow is set, in which case the working directory parent is
3308 --follow is set, in which case the working directory parent is
3309 used as the starting revision. You can specify a revision set for
3309 used as the starting revision. You can specify a revision set for
3310 log, see :hg:`help revsets` for more information.
3310 log, see :hg:`help revsets` for more information.
3311
3311
3312 See :hg:`help dates` for a list of formats valid for -d/--date.
3312 See :hg:`help dates` for a list of formats valid for -d/--date.
3313
3313
3314 By default this command prints revision number and changeset id,
3314 By default this command prints revision number and changeset id,
3315 tags, non-trivial parents, user, date and time, and a summary for
3315 tags, non-trivial parents, user, date and time, and a summary for
3316 each commit. When the -v/--verbose switch is used, the list of
3316 each commit. When the -v/--verbose switch is used, the list of
3317 changed files and full commit message are shown.
3317 changed files and full commit message are shown.
3318
3318
3319 .. note::
3319 .. note::
3320 log -p/--patch may generate unexpected diff output for merge
3320 log -p/--patch may generate unexpected diff output for merge
3321 changesets, as it will only compare the merge changeset against
3321 changesets, as it will only compare the merge changeset against
3322 its first parent. Also, only files different from BOTH parents
3322 its first parent. Also, only files different from BOTH parents
3323 will appear in files:.
3323 will appear in files:.
3324
3324
3325 Returns 0 on success.
3325 Returns 0 on success.
3326 """
3326 """
3327
3327
3328 matchfn = scmutil.match(repo, pats, opts)
3328 matchfn = scmutil.match(repo, pats, opts)
3329 limit = cmdutil.loglimit(opts)
3329 limit = cmdutil.loglimit(opts)
3330 count = 0
3330 count = 0
3331
3331
3332 endrev = None
3332 endrev = None
3333 if opts.get('copies') and opts.get('rev'):
3333 if opts.get('copies') and opts.get('rev'):
3334 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3334 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3335
3335
3336 df = False
3336 df = False
3337 if opts["date"]:
3337 if opts["date"]:
3338 df = util.matchdate(opts["date"])
3338 df = util.matchdate(opts["date"])
3339
3339
3340 branches = opts.get('branch', []) + opts.get('only_branch', [])
3340 branches = opts.get('branch', []) + opts.get('only_branch', [])
3341 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3341 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3342
3342
3343 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3343 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3344 def prep(ctx, fns):
3344 def prep(ctx, fns):
3345 rev = ctx.rev()
3345 rev = ctx.rev()
3346 parents = [p for p in repo.changelog.parentrevs(rev)
3346 parents = [p for p in repo.changelog.parentrevs(rev)
3347 if p != nullrev]
3347 if p != nullrev]
3348 if opts.get('no_merges') and len(parents) == 2:
3348 if opts.get('no_merges') and len(parents) == 2:
3349 return
3349 return
3350 if opts.get('only_merges') and len(parents) != 2:
3350 if opts.get('only_merges') and len(parents) != 2:
3351 return
3351 return
3352 if opts.get('branch') and ctx.branch() not in opts['branch']:
3352 if opts.get('branch') and ctx.branch() not in opts['branch']:
3353 return
3353 return
3354 if df and not df(ctx.date()[0]):
3354 if df and not df(ctx.date()[0]):
3355 return
3355 return
3356 if opts['user'] and not [k for k in opts['user']
3356 if opts['user'] and not [k for k in opts['user']
3357 if k.lower() in ctx.user().lower()]:
3357 if k.lower() in ctx.user().lower()]:
3358 return
3358 return
3359 if opts.get('keyword'):
3359 if opts.get('keyword'):
3360 for k in [kw.lower() for kw in opts['keyword']]:
3360 for k in [kw.lower() for kw in opts['keyword']]:
3361 if (k in ctx.user().lower() or
3361 if (k in ctx.user().lower() or
3362 k in ctx.description().lower() or
3362 k in ctx.description().lower() or
3363 k in " ".join(ctx.files()).lower()):
3363 k in " ".join(ctx.files()).lower()):
3364 break
3364 break
3365 else:
3365 else:
3366 return
3366 return
3367
3367
3368 copies = None
3368 copies = None
3369 if opts.get('copies') and rev:
3369 if opts.get('copies') and rev:
3370 copies = []
3370 copies = []
3371 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3371 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3372 for fn in ctx.files():
3372 for fn in ctx.files():
3373 rename = getrenamed(fn, rev)
3373 rename = getrenamed(fn, rev)
3374 if rename:
3374 if rename:
3375 copies.append((fn, rename[0]))
3375 copies.append((fn, rename[0]))
3376
3376
3377 revmatchfn = None
3377 revmatchfn = None
3378 if opts.get('patch') or opts.get('stat'):
3378 if opts.get('patch') or opts.get('stat'):
3379 if opts.get('follow') or opts.get('follow_first'):
3379 if opts.get('follow') or opts.get('follow_first'):
3380 # note: this might be wrong when following through merges
3380 # note: this might be wrong when following through merges
3381 revmatchfn = scmutil.match(repo, fns, default='path')
3381 revmatchfn = scmutil.match(repo, fns, default='path')
3382 else:
3382 else:
3383 revmatchfn = matchfn
3383 revmatchfn = matchfn
3384
3384
3385 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3385 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3386
3386
3387 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3387 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3388 if count == limit:
3388 if count == limit:
3389 break
3389 break
3390 if displayer.flush(ctx.rev()):
3390 if displayer.flush(ctx.rev()):
3391 count += 1
3391 count += 1
3392 displayer.close()
3392 displayer.close()
3393
3393
3394 @command('manifest',
3394 @command('manifest',
3395 [('r', 'rev', '', _('revision to display'), _('REV')),
3395 [('r', 'rev', '', _('revision to display'), _('REV')),
3396 ('', 'all', False, _("list files from all revisions"))],
3396 ('', 'all', False, _("list files from all revisions"))],
3397 _('[-r REV]'))
3397 _('[-r REV]'))
3398 def manifest(ui, repo, node=None, rev=None, **opts):
3398 def manifest(ui, repo, node=None, rev=None, **opts):
3399 """output the current or given revision of the project manifest
3399 """output the current or given revision of the project manifest
3400
3400
3401 Print a list of version controlled files for the given revision.
3401 Print a list of version controlled files for the given revision.
3402 If no revision is given, the first parent of the working directory
3402 If no revision is given, the first parent of the working directory
3403 is used, or the null revision if no revision is checked out.
3403 is used, or the null revision if no revision is checked out.
3404
3404
3405 With -v, print file permissions, symlink and executable bits.
3405 With -v, print file permissions, symlink and executable bits.
3406 With --debug, print file revision hashes.
3406 With --debug, print file revision hashes.
3407
3407
3408 If option --all is specified, the list of all files from all revisions
3408 If option --all is specified, the list of all files from all revisions
3409 is printed. This includes deleted and renamed files.
3409 is printed. This includes deleted and renamed files.
3410
3410
3411 Returns 0 on success.
3411 Returns 0 on success.
3412 """
3412 """
3413 if opts.get('all'):
3413 if opts.get('all'):
3414 if rev or node:
3414 if rev or node:
3415 raise util.Abort(_("can't specify a revision with --all"))
3415 raise util.Abort(_("can't specify a revision with --all"))
3416
3416
3417 res = []
3417 res = []
3418 prefix = "data/"
3418 prefix = "data/"
3419 suffix = ".i"
3419 suffix = ".i"
3420 plen = len(prefix)
3420 plen = len(prefix)
3421 slen = len(suffix)
3421 slen = len(suffix)
3422 lock = repo.lock()
3422 lock = repo.lock()
3423 try:
3423 try:
3424 for fn, b, size in repo.store.datafiles():
3424 for fn, b, size in repo.store.datafiles():
3425 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3425 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3426 res.append(fn[plen:-slen])
3426 res.append(fn[plen:-slen])
3427 finally:
3427 finally:
3428 lock.release()
3428 lock.release()
3429 for f in sorted(res):
3429 for f in sorted(res):
3430 ui.write("%s\n" % f)
3430 ui.write("%s\n" % f)
3431 return
3431 return
3432
3432
3433 if rev and node:
3433 if rev and node:
3434 raise util.Abort(_("please specify just one revision"))
3434 raise util.Abort(_("please specify just one revision"))
3435
3435
3436 if not node:
3436 if not node:
3437 node = rev
3437 node = rev
3438
3438
3439 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3439 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3440 ctx = scmutil.revsingle(repo, node)
3440 ctx = scmutil.revsingle(repo, node)
3441 for f in ctx:
3441 for f in ctx:
3442 if ui.debugflag:
3442 if ui.debugflag:
3443 ui.write("%40s " % hex(ctx.manifest()[f]))
3443 ui.write("%40s " % hex(ctx.manifest()[f]))
3444 if ui.verbose:
3444 if ui.verbose:
3445 ui.write(decor[ctx.flags(f)])
3445 ui.write(decor[ctx.flags(f)])
3446 ui.write("%s\n" % f)
3446 ui.write("%s\n" % f)
3447
3447
3448 @command('^merge',
3448 @command('^merge',
3449 [('f', 'force', None, _('force a merge with outstanding changes')),
3449 [('f', 'force', None, _('force a merge with outstanding changes')),
3450 ('t', 'tool', '', _('specify merge tool')),
3450 ('t', 'tool', '', _('specify merge tool')),
3451 ('r', 'rev', '', _('revision to merge'), _('REV')),
3451 ('r', 'rev', '', _('revision to merge'), _('REV')),
3452 ('P', 'preview', None,
3452 ('P', 'preview', None,
3453 _('review revisions to merge (no merge is performed)'))],
3453 _('review revisions to merge (no merge is performed)'))],
3454 _('[-P] [-f] [[-r] REV]'))
3454 _('[-P] [-f] [[-r] REV]'))
3455 def merge(ui, repo, node=None, **opts):
3455 def merge(ui, repo, node=None, **opts):
3456 """merge working directory with another revision
3456 """merge working directory with another revision
3457
3457
3458 The current working directory is updated with all changes made in
3458 The current working directory is updated with all changes made in
3459 the requested revision since the last common predecessor revision.
3459 the requested revision since the last common predecessor revision.
3460
3460
3461 Files that changed between either parent are marked as changed for
3461 Files that changed between either parent are marked as changed for
3462 the next commit and a commit must be performed before any further
3462 the next commit and a commit must be performed before any further
3463 updates to the repository are allowed. The next commit will have
3463 updates to the repository are allowed. The next commit will have
3464 two parents.
3464 two parents.
3465
3465
3466 ``--tool`` can be used to specify the merge tool used for file
3466 ``--tool`` can be used to specify the merge tool used for file
3467 merges. It overrides the HGMERGE environment variable and your
3467 merges. It overrides the HGMERGE environment variable and your
3468 configuration files. See :hg:`help merge-tools` for options.
3468 configuration files. See :hg:`help merge-tools` for options.
3469
3469
3470 If no revision is specified, the working directory's parent is a
3470 If no revision is specified, the working directory's parent is a
3471 head revision, and the current branch contains exactly one other
3471 head revision, and the current branch contains exactly one other
3472 head, the other head is merged with by default. Otherwise, an
3472 head, the other head is merged with by default. Otherwise, an
3473 explicit revision with which to merge with must be provided.
3473 explicit revision with which to merge with must be provided.
3474
3474
3475 :hg:`resolve` must be used to resolve unresolved files.
3475 :hg:`resolve` must be used to resolve unresolved files.
3476
3476
3477 To undo an uncommitted merge, use :hg:`update --clean .` which
3477 To undo an uncommitted merge, use :hg:`update --clean .` which
3478 will check out a clean copy of the original merge parent, losing
3478 will check out a clean copy of the original merge parent, losing
3479 all changes.
3479 all changes.
3480
3480
3481 Returns 0 on success, 1 if there are unresolved files.
3481 Returns 0 on success, 1 if there are unresolved files.
3482 """
3482 """
3483
3483
3484 if opts.get('rev') and node:
3484 if opts.get('rev') and node:
3485 raise util.Abort(_("please specify just one revision"))
3485 raise util.Abort(_("please specify just one revision"))
3486 if not node:
3486 if not node:
3487 node = opts.get('rev')
3487 node = opts.get('rev')
3488
3488
3489 if not node:
3489 if not node:
3490 branch = repo[None].branch()
3490 branch = repo[None].branch()
3491 bheads = repo.branchheads(branch)
3491 bheads = repo.branchheads(branch)
3492 if len(bheads) > 2:
3492 if len(bheads) > 2:
3493 raise util.Abort(_("branch '%s' has %d heads - "
3493 raise util.Abort(_("branch '%s' has %d heads - "
3494 "please merge with an explicit rev")
3494 "please merge with an explicit rev")
3495 % (branch, len(bheads)),
3495 % (branch, len(bheads)),
3496 hint=_("run 'hg heads .' to see heads"))
3496 hint=_("run 'hg heads .' to see heads"))
3497
3497
3498 parent = repo.dirstate.p1()
3498 parent = repo.dirstate.p1()
3499 if len(bheads) == 1:
3499 if len(bheads) == 1:
3500 if len(repo.heads()) > 1:
3500 if len(repo.heads()) > 1:
3501 raise util.Abort(_("branch '%s' has one head - "
3501 raise util.Abort(_("branch '%s' has one head - "
3502 "please merge with an explicit rev")
3502 "please merge with an explicit rev")
3503 % branch,
3503 % branch,
3504 hint=_("run 'hg heads' to see all heads"))
3504 hint=_("run 'hg heads' to see all heads"))
3505 msg = _('there is nothing to merge')
3505 msg = _('there is nothing to merge')
3506 if parent != repo.lookup(repo[None].branch()):
3506 if parent != repo.lookup(repo[None].branch()):
3507 msg = _('%s - use "hg update" instead') % msg
3507 msg = _('%s - use "hg update" instead') % msg
3508 raise util.Abort(msg)
3508 raise util.Abort(msg)
3509
3509
3510 if parent not in bheads:
3510 if parent not in bheads:
3511 raise util.Abort(_('working directory not at a head revision'),
3511 raise util.Abort(_('working directory not at a head revision'),
3512 hint=_("use 'hg update' or merge with an "
3512 hint=_("use 'hg update' or merge with an "
3513 "explicit revision"))
3513 "explicit revision"))
3514 node = parent == bheads[0] and bheads[-1] or bheads[0]
3514 node = parent == bheads[0] and bheads[-1] or bheads[0]
3515 else:
3515 else:
3516 node = scmutil.revsingle(repo, node).node()
3516 node = scmutil.revsingle(repo, node).node()
3517
3517
3518 if opts.get('preview'):
3518 if opts.get('preview'):
3519 # find nodes that are ancestors of p2 but not of p1
3519 # find nodes that are ancestors of p2 but not of p1
3520 p1 = repo.lookup('.')
3520 p1 = repo.lookup('.')
3521 p2 = repo.lookup(node)
3521 p2 = repo.lookup(node)
3522 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3522 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3523
3523
3524 displayer = cmdutil.show_changeset(ui, repo, opts)
3524 displayer = cmdutil.show_changeset(ui, repo, opts)
3525 for node in nodes:
3525 for node in nodes:
3526 displayer.show(repo[node])
3526 displayer.show(repo[node])
3527 displayer.close()
3527 displayer.close()
3528 return 0
3528 return 0
3529
3529
3530 try:
3530 try:
3531 # ui.forcemerge is an internal variable, do not document
3531 # ui.forcemerge is an internal variable, do not document
3532 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3532 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3533 return hg.merge(repo, node, force=opts.get('force'))
3533 return hg.merge(repo, node, force=opts.get('force'))
3534 finally:
3534 finally:
3535 ui.setconfig('ui', 'forcemerge', '')
3535 ui.setconfig('ui', 'forcemerge', '')
3536
3536
3537 @command('outgoing|out',
3537 @command('outgoing|out',
3538 [('f', 'force', None, _('run even when the destination is unrelated')),
3538 [('f', 'force', None, _('run even when the destination is unrelated')),
3539 ('r', 'rev', [],
3539 ('r', 'rev', [],
3540 _('a changeset intended to be included in the destination'), _('REV')),
3540 _('a changeset intended to be included in the destination'), _('REV')),
3541 ('n', 'newest-first', None, _('show newest record first')),
3541 ('n', 'newest-first', None, _('show newest record first')),
3542 ('B', 'bookmarks', False, _('compare bookmarks')),
3542 ('B', 'bookmarks', False, _('compare bookmarks')),
3543 ('b', 'branch', [], _('a specific branch you would like to push'),
3543 ('b', 'branch', [], _('a specific branch you would like to push'),
3544 _('BRANCH')),
3544 _('BRANCH')),
3545 ] + logopts + remoteopts + subrepoopts,
3545 ] + logopts + remoteopts + subrepoopts,
3546 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3546 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3547 def outgoing(ui, repo, dest=None, **opts):
3547 def outgoing(ui, repo, dest=None, **opts):
3548 """show changesets not found in the destination
3548 """show changesets not found in the destination
3549
3549
3550 Show changesets not found in the specified destination repository
3550 Show changesets not found in the specified destination repository
3551 or the default push location. These are the changesets that would
3551 or the default push location. These are the changesets that would
3552 be pushed if a push was requested.
3552 be pushed if a push was requested.
3553
3553
3554 See pull for details of valid destination formats.
3554 See pull for details of valid destination formats.
3555
3555
3556 Returns 0 if there are outgoing changes, 1 otherwise.
3556 Returns 0 if there are outgoing changes, 1 otherwise.
3557 """
3557 """
3558
3558
3559 if opts.get('bookmarks'):
3559 if opts.get('bookmarks'):
3560 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3560 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3561 dest, branches = hg.parseurl(dest, opts.get('branch'))
3561 dest, branches = hg.parseurl(dest, opts.get('branch'))
3562 other = hg.repository(hg.remoteui(repo, opts), dest)
3562 other = hg.repository(hg.remoteui(repo, opts), dest)
3563 if 'bookmarks' not in other.listkeys('namespaces'):
3563 if 'bookmarks' not in other.listkeys('namespaces'):
3564 ui.warn(_("remote doesn't support bookmarks\n"))
3564 ui.warn(_("remote doesn't support bookmarks\n"))
3565 return 0
3565 return 0
3566 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3566 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3567 return bookmarks.diff(ui, other, repo)
3567 return bookmarks.diff(ui, other, repo)
3568
3568
3569 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3569 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3570 try:
3570 try:
3571 return hg.outgoing(ui, repo, dest, opts)
3571 return hg.outgoing(ui, repo, dest, opts)
3572 finally:
3572 finally:
3573 del repo._subtoppath
3573 del repo._subtoppath
3574
3574
3575 @command('parents',
3575 @command('parents',
3576 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3576 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3577 ] + templateopts,
3577 ] + templateopts,
3578 _('[-r REV] [FILE]'))
3578 _('[-r REV] [FILE]'))
3579 def parents(ui, repo, file_=None, **opts):
3579 def parents(ui, repo, file_=None, **opts):
3580 """show the parents of the working directory or revision
3580 """show the parents of the working directory or revision
3581
3581
3582 Print the working directory's parent revisions. If a revision is
3582 Print the working directory's parent revisions. If a revision is
3583 given via -r/--rev, the parent of that revision will be printed.
3583 given via -r/--rev, the parent of that revision will be printed.
3584 If a file argument is given, the revision in which the file was
3584 If a file argument is given, the revision in which the file was
3585 last changed (before the working directory revision or the
3585 last changed (before the working directory revision or the
3586 argument to --rev if given) is printed.
3586 argument to --rev if given) is printed.
3587
3587
3588 Returns 0 on success.
3588 Returns 0 on success.
3589 """
3589 """
3590
3590
3591 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3591 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3592
3592
3593 if file_:
3593 if file_:
3594 m = scmutil.match(repo, (file_,), opts)
3594 m = scmutil.match(repo, (file_,), opts)
3595 if m.anypats() or len(m.files()) != 1:
3595 if m.anypats() or len(m.files()) != 1:
3596 raise util.Abort(_('can only specify an explicit filename'))
3596 raise util.Abort(_('can only specify an explicit filename'))
3597 file_ = m.files()[0]
3597 file_ = m.files()[0]
3598 filenodes = []
3598 filenodes = []
3599 for cp in ctx.parents():
3599 for cp in ctx.parents():
3600 if not cp:
3600 if not cp:
3601 continue
3601 continue
3602 try:
3602 try:
3603 filenodes.append(cp.filenode(file_))
3603 filenodes.append(cp.filenode(file_))
3604 except error.LookupError:
3604 except error.LookupError:
3605 pass
3605 pass
3606 if not filenodes:
3606 if not filenodes:
3607 raise util.Abort(_("'%s' not found in manifest!") % file_)
3607 raise util.Abort(_("'%s' not found in manifest!") % file_)
3608 fl = repo.file(file_)
3608 fl = repo.file(file_)
3609 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3609 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3610 else:
3610 else:
3611 p = [cp.node() for cp in ctx.parents()]
3611 p = [cp.node() for cp in ctx.parents()]
3612
3612
3613 displayer = cmdutil.show_changeset(ui, repo, opts)
3613 displayer = cmdutil.show_changeset(ui, repo, opts)
3614 for n in p:
3614 for n in p:
3615 if n != nullid:
3615 if n != nullid:
3616 displayer.show(repo[n])
3616 displayer.show(repo[n])
3617 displayer.close()
3617 displayer.close()
3618
3618
3619 @command('paths', [], _('[NAME]'))
3619 @command('paths', [], _('[NAME]'))
3620 def paths(ui, repo, search=None):
3620 def paths(ui, repo, search=None):
3621 """show aliases for remote repositories
3621 """show aliases for remote repositories
3622
3622
3623 Show definition of symbolic path name NAME. If no name is given,
3623 Show definition of symbolic path name NAME. If no name is given,
3624 show definition of all available names.
3624 show definition of all available names.
3625
3625
3626 Option -q/--quiet suppresses all output when searching for NAME
3626 Option -q/--quiet suppresses all output when searching for NAME
3627 and shows only the path names when listing all definitions.
3627 and shows only the path names when listing all definitions.
3628
3628
3629 Path names are defined in the [paths] section of your
3629 Path names are defined in the [paths] section of your
3630 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3630 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3631 repository, ``.hg/hgrc`` is used, too.
3631 repository, ``.hg/hgrc`` is used, too.
3632
3632
3633 The path names ``default`` and ``default-push`` have a special
3633 The path names ``default`` and ``default-push`` have a special
3634 meaning. When performing a push or pull operation, they are used
3634 meaning. When performing a push or pull operation, they are used
3635 as fallbacks if no location is specified on the command-line.
3635 as fallbacks if no location is specified on the command-line.
3636 When ``default-push`` is set, it will be used for push and
3636 When ``default-push`` is set, it will be used for push and
3637 ``default`` will be used for pull; otherwise ``default`` is used
3637 ``default`` will be used for pull; otherwise ``default`` is used
3638 as the fallback for both. When cloning a repository, the clone
3638 as the fallback for both. When cloning a repository, the clone
3639 source is written as ``default`` in ``.hg/hgrc``. Note that
3639 source is written as ``default`` in ``.hg/hgrc``. Note that
3640 ``default`` and ``default-push`` apply to all inbound (e.g.
3640 ``default`` and ``default-push`` apply to all inbound (e.g.
3641 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3641 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3642 :hg:`bundle`) operations.
3642 :hg:`bundle`) operations.
3643
3643
3644 See :hg:`help urls` for more information.
3644 See :hg:`help urls` for more information.
3645
3645
3646 Returns 0 on success.
3646 Returns 0 on success.
3647 """
3647 """
3648 if search:
3648 if search:
3649 for name, path in ui.configitems("paths"):
3649 for name, path in ui.configitems("paths"):
3650 if name == search:
3650 if name == search:
3651 ui.status("%s\n" % util.hidepassword(path))
3651 ui.status("%s\n" % util.hidepassword(path))
3652 return
3652 return
3653 if not ui.quiet:
3653 if not ui.quiet:
3654 ui.warn(_("not found!\n"))
3654 ui.warn(_("not found!\n"))
3655 return 1
3655 return 1
3656 else:
3656 else:
3657 for name, path in ui.configitems("paths"):
3657 for name, path in ui.configitems("paths"):
3658 if ui.quiet:
3658 if ui.quiet:
3659 ui.write("%s\n" % name)
3659 ui.write("%s\n" % name)
3660 else:
3660 else:
3661 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3661 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3662
3662
3663 def postincoming(ui, repo, modheads, optupdate, checkout):
3663 def postincoming(ui, repo, modheads, optupdate, checkout):
3664 if modheads == 0:
3664 if modheads == 0:
3665 return
3665 return
3666 if optupdate:
3666 if optupdate:
3667 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
3667 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
3668 return hg.update(repo, checkout)
3668 return hg.update(repo, checkout)
3669 else:
3669 else:
3670 ui.status(_("not updating, since new heads added\n"))
3670 ui.status(_("not updating, since new heads added\n"))
3671 if modheads > 1:
3671 if modheads > 1:
3672 currentbranchheads = len(repo.branchheads())
3672 currentbranchheads = len(repo.branchheads())
3673 if currentbranchheads == modheads:
3673 if currentbranchheads == modheads:
3674 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3674 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3675 elif currentbranchheads > 1:
3675 elif currentbranchheads > 1:
3676 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3676 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3677 else:
3677 else:
3678 ui.status(_("(run 'hg heads' to see heads)\n"))
3678 ui.status(_("(run 'hg heads' to see heads)\n"))
3679 else:
3679 else:
3680 ui.status(_("(run 'hg update' to get a working copy)\n"))
3680 ui.status(_("(run 'hg update' to get a working copy)\n"))
3681
3681
3682 @command('^pull',
3682 @command('^pull',
3683 [('u', 'update', None,
3683 [('u', 'update', None,
3684 _('update to new branch head if changesets were pulled')),
3684 _('update to new branch head if changesets were pulled')),
3685 ('f', 'force', None, _('run even when remote repository is unrelated')),
3685 ('f', 'force', None, _('run even when remote repository is unrelated')),
3686 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3686 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3687 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3687 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3688 ('b', 'branch', [], _('a specific branch you would like to pull'),
3688 ('b', 'branch', [], _('a specific branch you would like to pull'),
3689 _('BRANCH')),
3689 _('BRANCH')),
3690 ] + remoteopts,
3690 ] + remoteopts,
3691 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3691 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3692 def pull(ui, repo, source="default", **opts):
3692 def pull(ui, repo, source="default", **opts):
3693 """pull changes from the specified source
3693 """pull changes from the specified source
3694
3694
3695 Pull changes from a remote repository to a local one.
3695 Pull changes from a remote repository to a local one.
3696
3696
3697 This finds all changes from the repository at the specified path
3697 This finds all changes from the repository at the specified path
3698 or URL and adds them to a local repository (the current one unless
3698 or URL and adds them to a local repository (the current one unless
3699 -R is specified). By default, this does not update the copy of the
3699 -R is specified). By default, this does not update the copy of the
3700 project in the working directory.
3700 project in the working directory.
3701
3701
3702 Use :hg:`incoming` if you want to see what would have been added
3702 Use :hg:`incoming` if you want to see what would have been added
3703 by a pull at the time you issued this command. If you then decide
3703 by a pull at the time you issued this command. If you then decide
3704 to add those changes to the repository, you should use :hg:`pull
3704 to add those changes to the repository, you should use :hg:`pull
3705 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3705 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3706
3706
3707 If SOURCE is omitted, the 'default' path will be used.
3707 If SOURCE is omitted, the 'default' path will be used.
3708 See :hg:`help urls` for more information.
3708 See :hg:`help urls` for more information.
3709
3709
3710 Returns 0 on success, 1 if an update had unresolved files.
3710 Returns 0 on success, 1 if an update had unresolved files.
3711 """
3711 """
3712 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3712 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3713 other = hg.repository(hg.remoteui(repo, opts), source)
3713 other = hg.repository(hg.remoteui(repo, opts), source)
3714 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3714 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3715 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3715 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3716
3716
3717 if opts.get('bookmark'):
3717 if opts.get('bookmark'):
3718 if not revs:
3718 if not revs:
3719 revs = []
3719 revs = []
3720 rb = other.listkeys('bookmarks')
3720 rb = other.listkeys('bookmarks')
3721 for b in opts['bookmark']:
3721 for b in opts['bookmark']:
3722 if b not in rb:
3722 if b not in rb:
3723 raise util.Abort(_('remote bookmark %s not found!') % b)
3723 raise util.Abort(_('remote bookmark %s not found!') % b)
3724 revs.append(rb[b])
3724 revs.append(rb[b])
3725
3725
3726 if revs:
3726 if revs:
3727 try:
3727 try:
3728 revs = [other.lookup(rev) for rev in revs]
3728 revs = [other.lookup(rev) for rev in revs]
3729 except error.CapabilityError:
3729 except error.CapabilityError:
3730 err = _("other repository doesn't support revision lookup, "
3730 err = _("other repository doesn't support revision lookup, "
3731 "so a rev cannot be specified.")
3731 "so a rev cannot be specified.")
3732 raise util.Abort(err)
3732 raise util.Abort(err)
3733
3733
3734 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3734 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3735 bookmarks.updatefromremote(ui, repo, other)
3735 bookmarks.updatefromremote(ui, repo, other)
3736 if checkout:
3736 if checkout:
3737 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3737 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3738 repo._subtoppath = source
3738 repo._subtoppath = source
3739 try:
3739 try:
3740 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3740 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3741
3741
3742 finally:
3742 finally:
3743 del repo._subtoppath
3743 del repo._subtoppath
3744
3744
3745 # update specified bookmarks
3745 # update specified bookmarks
3746 if opts.get('bookmark'):
3746 if opts.get('bookmark'):
3747 for b in opts['bookmark']:
3747 for b in opts['bookmark']:
3748 # explicit pull overrides local bookmark if any
3748 # explicit pull overrides local bookmark if any
3749 ui.status(_("importing bookmark %s\n") % b)
3749 ui.status(_("importing bookmark %s\n") % b)
3750 repo._bookmarks[b] = repo[rb[b]].node()
3750 repo._bookmarks[b] = repo[rb[b]].node()
3751 bookmarks.write(repo)
3751 bookmarks.write(repo)
3752
3752
3753 return ret
3753 return ret
3754
3754
3755 @command('^push',
3755 @command('^push',
3756 [('f', 'force', None, _('force push')),
3756 [('f', 'force', None, _('force push')),
3757 ('r', 'rev', [],
3757 ('r', 'rev', [],
3758 _('a changeset intended to be included in the destination'),
3758 _('a changeset intended to be included in the destination'),
3759 _('REV')),
3759 _('REV')),
3760 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3760 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3761 ('b', 'branch', [],
3761 ('b', 'branch', [],
3762 _('a specific branch you would like to push'), _('BRANCH')),
3762 _('a specific branch you would like to push'), _('BRANCH')),
3763 ('', 'new-branch', False, _('allow pushing a new branch')),
3763 ('', 'new-branch', False, _('allow pushing a new branch')),
3764 ] + remoteopts,
3764 ] + remoteopts,
3765 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3765 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3766 def push(ui, repo, dest=None, **opts):
3766 def push(ui, repo, dest=None, **opts):
3767 """push changes to the specified destination
3767 """push changes to the specified destination
3768
3768
3769 Push changesets from the local repository to the specified
3769 Push changesets from the local repository to the specified
3770 destination.
3770 destination.
3771
3771
3772 This operation is symmetrical to pull: it is identical to a pull
3772 This operation is symmetrical to pull: it is identical to a pull
3773 in the destination repository from the current one.
3773 in the destination repository from the current one.
3774
3774
3775 By default, push will not allow creation of new heads at the
3775 By default, push will not allow creation of new heads at the
3776 destination, since multiple heads would make it unclear which head
3776 destination, since multiple heads would make it unclear which head
3777 to use. In this situation, it is recommended to pull and merge
3777 to use. In this situation, it is recommended to pull and merge
3778 before pushing.
3778 before pushing.
3779
3779
3780 Use --new-branch if you want to allow push to create a new named
3780 Use --new-branch if you want to allow push to create a new named
3781 branch that is not present at the destination. This allows you to
3781 branch that is not present at the destination. This allows you to
3782 only create a new branch without forcing other changes.
3782 only create a new branch without forcing other changes.
3783
3783
3784 Use -f/--force to override the default behavior and push all
3784 Use -f/--force to override the default behavior and push all
3785 changesets on all branches.
3785 changesets on all branches.
3786
3786
3787 If -r/--rev is used, the specified revision and all its ancestors
3787 If -r/--rev is used, the specified revision and all its ancestors
3788 will be pushed to the remote repository.
3788 will be pushed to the remote repository.
3789
3789
3790 Please see :hg:`help urls` for important details about ``ssh://``
3790 Please see :hg:`help urls` for important details about ``ssh://``
3791 URLs. If DESTINATION is omitted, a default path will be used.
3791 URLs. If DESTINATION is omitted, a default path will be used.
3792
3792
3793 Returns 0 if push was successful, 1 if nothing to push.
3793 Returns 0 if push was successful, 1 if nothing to push.
3794 """
3794 """
3795
3795
3796 if opts.get('bookmark'):
3796 if opts.get('bookmark'):
3797 for b in opts['bookmark']:
3797 for b in opts['bookmark']:
3798 # translate -B options to -r so changesets get pushed
3798 # translate -B options to -r so changesets get pushed
3799 if b in repo._bookmarks:
3799 if b in repo._bookmarks:
3800 opts.setdefault('rev', []).append(b)
3800 opts.setdefault('rev', []).append(b)
3801 else:
3801 else:
3802 # if we try to push a deleted bookmark, translate it to null
3802 # if we try to push a deleted bookmark, translate it to null
3803 # this lets simultaneous -r, -b options continue working
3803 # this lets simultaneous -r, -b options continue working
3804 opts.setdefault('rev', []).append("null")
3804 opts.setdefault('rev', []).append("null")
3805
3805
3806 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3806 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3807 dest, branches = hg.parseurl(dest, opts.get('branch'))
3807 dest, branches = hg.parseurl(dest, opts.get('branch'))
3808 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3808 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3809 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3809 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3810 other = hg.repository(hg.remoteui(repo, opts), dest)
3810 other = hg.repository(hg.remoteui(repo, opts), dest)
3811 if revs:
3811 if revs:
3812 revs = [repo.lookup(rev) for rev in revs]
3812 revs = [repo.lookup(rev) for rev in revs]
3813
3813
3814 repo._subtoppath = dest
3814 repo._subtoppath = dest
3815 try:
3815 try:
3816 # push subrepos depth-first for coherent ordering
3816 # push subrepos depth-first for coherent ordering
3817 c = repo['']
3817 c = repo['']
3818 subs = c.substate # only repos that are committed
3818 subs = c.substate # only repos that are committed
3819 for s in sorted(subs):
3819 for s in sorted(subs):
3820 if not c.sub(s).push(opts.get('force')):
3820 if not c.sub(s).push(opts.get('force')):
3821 return False
3821 return False
3822 finally:
3822 finally:
3823 del repo._subtoppath
3823 del repo._subtoppath
3824 result = repo.push(other, opts.get('force'), revs=revs,
3824 result = repo.push(other, opts.get('force'), revs=revs,
3825 newbranch=opts.get('new_branch'))
3825 newbranch=opts.get('new_branch'))
3826
3826
3827 result = (result == 0)
3827 result = (result == 0)
3828
3828
3829 if opts.get('bookmark'):
3829 if opts.get('bookmark'):
3830 rb = other.listkeys('bookmarks')
3830 rb = other.listkeys('bookmarks')
3831 for b in opts['bookmark']:
3831 for b in opts['bookmark']:
3832 # explicit push overrides remote bookmark if any
3832 # explicit push overrides remote bookmark if any
3833 if b in repo._bookmarks:
3833 if b in repo._bookmarks:
3834 ui.status(_("exporting bookmark %s\n") % b)
3834 ui.status(_("exporting bookmark %s\n") % b)
3835 new = repo[b].hex()
3835 new = repo[b].hex()
3836 elif b in rb:
3836 elif b in rb:
3837 ui.status(_("deleting remote bookmark %s\n") % b)
3837 ui.status(_("deleting remote bookmark %s\n") % b)
3838 new = '' # delete
3838 new = '' # delete
3839 else:
3839 else:
3840 ui.warn(_('bookmark %s does not exist on the local '
3840 ui.warn(_('bookmark %s does not exist on the local '
3841 'or remote repository!\n') % b)
3841 'or remote repository!\n') % b)
3842 return 2
3842 return 2
3843 old = rb.get(b, '')
3843 old = rb.get(b, '')
3844 r = other.pushkey('bookmarks', b, old, new)
3844 r = other.pushkey('bookmarks', b, old, new)
3845 if not r:
3845 if not r:
3846 ui.warn(_('updating bookmark %s failed!\n') % b)
3846 ui.warn(_('updating bookmark %s failed!\n') % b)
3847 if not result:
3847 if not result:
3848 result = 2
3848 result = 2
3849
3849
3850 return result
3850 return result
3851
3851
3852 @command('recover', [])
3852 @command('recover', [])
3853 def recover(ui, repo):
3853 def recover(ui, repo):
3854 """roll back an interrupted transaction
3854 """roll back an interrupted transaction
3855
3855
3856 Recover from an interrupted commit or pull.
3856 Recover from an interrupted commit or pull.
3857
3857
3858 This command tries to fix the repository status after an
3858 This command tries to fix the repository status after an
3859 interrupted operation. It should only be necessary when Mercurial
3859 interrupted operation. It should only be necessary when Mercurial
3860 suggests it.
3860 suggests it.
3861
3861
3862 Returns 0 if successful, 1 if nothing to recover or verify fails.
3862 Returns 0 if successful, 1 if nothing to recover or verify fails.
3863 """
3863 """
3864 if repo.recover():
3864 if repo.recover():
3865 return hg.verify(repo)
3865 return hg.verify(repo)
3866 return 1
3866 return 1
3867
3867
3868 @command('^remove|rm',
3868 @command('^remove|rm',
3869 [('A', 'after', None, _('record delete for missing files')),
3869 [('A', 'after', None, _('record delete for missing files')),
3870 ('f', 'force', None,
3870 ('f', 'force', None,
3871 _('remove (and delete) file even if added or modified')),
3871 _('remove (and delete) file even if added or modified')),
3872 ] + walkopts,
3872 ] + walkopts,
3873 _('[OPTION]... FILE...'))
3873 _('[OPTION]... FILE...'))
3874 def remove(ui, repo, *pats, **opts):
3874 def remove(ui, repo, *pats, **opts):
3875 """remove the specified files on the next commit
3875 """remove the specified files on the next commit
3876
3876
3877 Schedule the indicated files for removal from the repository.
3877 Schedule the indicated files for removal from the repository.
3878
3878
3879 This only removes files from the current branch, not from the
3879 This only removes files from the current branch, not from the
3880 entire project history. -A/--after can be used to remove only
3880 entire project history. -A/--after can be used to remove only
3881 files that have already been deleted, -f/--force can be used to
3881 files that have already been deleted, -f/--force can be used to
3882 force deletion, and -Af can be used to remove files from the next
3882 force deletion, and -Af can be used to remove files from the next
3883 revision without deleting them from the working directory.
3883 revision without deleting them from the working directory.
3884
3884
3885 The following table details the behavior of remove for different
3885 The following table details the behavior of remove for different
3886 file states (columns) and option combinations (rows). The file
3886 file states (columns) and option combinations (rows). The file
3887 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3887 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3888 reported by :hg:`status`). The actions are Warn, Remove (from
3888 reported by :hg:`status`). The actions are Warn, Remove (from
3889 branch) and Delete (from disk)::
3889 branch) and Delete (from disk)::
3890
3890
3891 A C M !
3891 A C M !
3892 none W RD W R
3892 none W RD W R
3893 -f R RD RD R
3893 -f R RD RD R
3894 -A W W W R
3894 -A W W W R
3895 -Af R R R R
3895 -Af R R R R
3896
3896
3897 Note that remove never deletes files in Added [A] state from the
3897 Note that remove never deletes files in Added [A] state from the
3898 working directory, not even if option --force is specified.
3898 working directory, not even if option --force is specified.
3899
3899
3900 This command schedules the files to be removed at the next commit.
3900 This command schedules the files to be removed at the next commit.
3901 To undo a remove before that, see :hg:`revert`.
3901 To undo a remove before that, see :hg:`revert`.
3902
3902
3903 Returns 0 on success, 1 if any warnings encountered.
3903 Returns 0 on success, 1 if any warnings encountered.
3904 """
3904 """
3905
3905
3906 ret = 0
3906 ret = 0
3907 after, force = opts.get('after'), opts.get('force')
3907 after, force = opts.get('after'), opts.get('force')
3908 if not pats and not after:
3908 if not pats and not after:
3909 raise util.Abort(_('no files specified'))
3909 raise util.Abort(_('no files specified'))
3910
3910
3911 m = scmutil.match(repo, pats, opts)
3911 m = scmutil.match(repo, pats, opts)
3912 s = repo.status(match=m, clean=True)
3912 s = repo.status(match=m, clean=True)
3913 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3913 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3914
3914
3915 for f in m.files():
3915 for f in m.files():
3916 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3916 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3917 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3917 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3918 ret = 1
3918 ret = 1
3919
3919
3920 if force:
3920 if force:
3921 remove, forget = modified + deleted + clean, added
3921 remove, forget = modified + deleted + clean, added
3922 elif after:
3922 elif after:
3923 remove, forget = deleted, []
3923 remove, forget = deleted, []
3924 for f in modified + added + clean:
3924 for f in modified + added + clean:
3925 ui.warn(_('not removing %s: file still exists (use -f'
3925 ui.warn(_('not removing %s: file still exists (use -f'
3926 ' to force removal)\n') % m.rel(f))
3926 ' to force removal)\n') % m.rel(f))
3927 ret = 1
3927 ret = 1
3928 else:
3928 else:
3929 remove, forget = deleted + clean, []
3929 remove, forget = deleted + clean, []
3930 for f in modified:
3930 for f in modified:
3931 ui.warn(_('not removing %s: file is modified (use -f'
3931 ui.warn(_('not removing %s: file is modified (use -f'
3932 ' to force removal)\n') % m.rel(f))
3932 ' to force removal)\n') % m.rel(f))
3933 ret = 1
3933 ret = 1
3934 for f in added:
3934 for f in added:
3935 ui.warn(_('not removing %s: file has been marked for add (use -f'
3935 ui.warn(_('not removing %s: file has been marked for add (use -f'
3936 ' to force removal)\n') % m.rel(f))
3936 ' to force removal)\n') % m.rel(f))
3937 ret = 1
3937 ret = 1
3938
3938
3939 for f in sorted(remove + forget):
3939 for f in sorted(remove + forget):
3940 if ui.verbose or not m.exact(f):
3940 if ui.verbose or not m.exact(f):
3941 ui.status(_('removing %s\n') % m.rel(f))
3941 ui.status(_('removing %s\n') % m.rel(f))
3942
3942
3943 repo[None].forget(forget)
3943 repo[None].forget(forget)
3944 repo[None].remove(remove, unlink=not after)
3944 repo[None].remove(remove, unlink=not after)
3945 return ret
3945 return ret
3946
3946
3947 @command('rename|move|mv',
3947 @command('rename|move|mv',
3948 [('A', 'after', None, _('record a rename that has already occurred')),
3948 [('A', 'after', None, _('record a rename that has already occurred')),
3949 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3949 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3950 ] + walkopts + dryrunopts,
3950 ] + walkopts + dryrunopts,
3951 _('[OPTION]... SOURCE... DEST'))
3951 _('[OPTION]... SOURCE... DEST'))
3952 def rename(ui, repo, *pats, **opts):
3952 def rename(ui, repo, *pats, **opts):
3953 """rename files; equivalent of copy + remove
3953 """rename files; equivalent of copy + remove
3954
3954
3955 Mark dest as copies of sources; mark sources for deletion. If dest
3955 Mark dest as copies of sources; mark sources for deletion. If dest
3956 is a directory, copies are put in that directory. If dest is a
3956 is a directory, copies are put in that directory. If dest is a
3957 file, there can only be one source.
3957 file, there can only be one source.
3958
3958
3959 By default, this command copies the contents of files as they
3959 By default, this command copies the contents of files as they
3960 exist in the working directory. If invoked with -A/--after, the
3960 exist in the working directory. If invoked with -A/--after, the
3961 operation is recorded, but no copying is performed.
3961 operation is recorded, but no copying is performed.
3962
3962
3963 This command takes effect at the next commit. To undo a rename
3963 This command takes effect at the next commit. To undo a rename
3964 before that, see :hg:`revert`.
3964 before that, see :hg:`revert`.
3965
3965
3966 Returns 0 on success, 1 if errors are encountered.
3966 Returns 0 on success, 1 if errors are encountered.
3967 """
3967 """
3968 wlock = repo.wlock(False)
3968 wlock = repo.wlock(False)
3969 try:
3969 try:
3970 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3970 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3971 finally:
3971 finally:
3972 wlock.release()
3972 wlock.release()
3973
3973
3974 @command('resolve',
3974 @command('resolve',
3975 [('a', 'all', None, _('select all unresolved files')),
3975 [('a', 'all', None, _('select all unresolved files')),
3976 ('l', 'list', None, _('list state of files needing merge')),
3976 ('l', 'list', None, _('list state of files needing merge')),
3977 ('m', 'mark', None, _('mark files as resolved')),
3977 ('m', 'mark', None, _('mark files as resolved')),
3978 ('u', 'unmark', None, _('mark files as unresolved')),
3978 ('u', 'unmark', None, _('mark files as unresolved')),
3979 ('t', 'tool', '', _('specify merge tool')),
3979 ('t', 'tool', '', _('specify merge tool')),
3980 ('n', 'no-status', None, _('hide status prefix'))]
3980 ('n', 'no-status', None, _('hide status prefix'))]
3981 + walkopts,
3981 + walkopts,
3982 _('[OPTION]... [FILE]...'))
3982 _('[OPTION]... [FILE]...'))
3983 def resolve(ui, repo, *pats, **opts):
3983 def resolve(ui, repo, *pats, **opts):
3984 """redo merges or set/view the merge status of files
3984 """redo merges or set/view the merge status of files
3985
3985
3986 Merges with unresolved conflicts are often the result of
3986 Merges with unresolved conflicts are often the result of
3987 non-interactive merging using the ``internal:merge`` configuration
3987 non-interactive merging using the ``internal:merge`` configuration
3988 setting, or a command-line merge tool like ``diff3``. The resolve
3988 setting, or a command-line merge tool like ``diff3``. The resolve
3989 command is used to manage the files involved in a merge, after
3989 command is used to manage the files involved in a merge, after
3990 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
3990 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
3991 working directory must have two parents).
3991 working directory must have two parents).
3992
3992
3993 The resolve command can be used in the following ways:
3993 The resolve command can be used in the following ways:
3994
3994
3995 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
3995 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
3996 files, discarding any previous merge attempts. Re-merging is not
3996 files, discarding any previous merge attempts. Re-merging is not
3997 performed for files already marked as resolved. Use ``--all/-a``
3997 performed for files already marked as resolved. Use ``--all/-a``
3998 to selects all unresolved files. ``--tool`` can be used to specify
3998 to selects all unresolved files. ``--tool`` can be used to specify
3999 the merge tool used for the given files. It overrides the HGMERGE
3999 the merge tool used for the given files. It overrides the HGMERGE
4000 environment variable and your configuration files.
4000 environment variable and your configuration files.
4001
4001
4002 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4002 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4003 (e.g. after having manually fixed-up the files). The default is
4003 (e.g. after having manually fixed-up the files). The default is
4004 to mark all unresolved files.
4004 to mark all unresolved files.
4005
4005
4006 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4006 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4007 default is to mark all resolved files.
4007 default is to mark all resolved files.
4008
4008
4009 - :hg:`resolve -l`: list files which had or still have conflicts.
4009 - :hg:`resolve -l`: list files which had or still have conflicts.
4010 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4010 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4011
4011
4012 Note that Mercurial will not let you commit files with unresolved
4012 Note that Mercurial will not let you commit files with unresolved
4013 merge conflicts. You must use :hg:`resolve -m ...` before you can
4013 merge conflicts. You must use :hg:`resolve -m ...` before you can
4014 commit after a conflicting merge.
4014 commit after a conflicting merge.
4015
4015
4016 Returns 0 on success, 1 if any files fail a resolve attempt.
4016 Returns 0 on success, 1 if any files fail a resolve attempt.
4017 """
4017 """
4018
4018
4019 all, mark, unmark, show, nostatus = \
4019 all, mark, unmark, show, nostatus = \
4020 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4020 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4021
4021
4022 if (show and (mark or unmark)) or (mark and unmark):
4022 if (show and (mark or unmark)) or (mark and unmark):
4023 raise util.Abort(_("too many options specified"))
4023 raise util.Abort(_("too many options specified"))
4024 if pats and all:
4024 if pats and all:
4025 raise util.Abort(_("can't specify --all and patterns"))
4025 raise util.Abort(_("can't specify --all and patterns"))
4026 if not (all or pats or show or mark or unmark):
4026 if not (all or pats or show or mark or unmark):
4027 raise util.Abort(_('no files or directories specified; '
4027 raise util.Abort(_('no files or directories specified; '
4028 'use --all to remerge all files'))
4028 'use --all to remerge all files'))
4029
4029
4030 ms = mergemod.mergestate(repo)
4030 ms = mergemod.mergestate(repo)
4031 m = scmutil.match(repo, pats, opts)
4031 m = scmutil.match(repo, pats, opts)
4032 ret = 0
4032 ret = 0
4033
4033
4034 for f in ms:
4034 for f in ms:
4035 if m(f):
4035 if m(f):
4036 if show:
4036 if show:
4037 if nostatus:
4037 if nostatus:
4038 ui.write("%s\n" % f)
4038 ui.write("%s\n" % f)
4039 else:
4039 else:
4040 ui.write("%s %s\n" % (ms[f].upper(), f),
4040 ui.write("%s %s\n" % (ms[f].upper(), f),
4041 label='resolve.' +
4041 label='resolve.' +
4042 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4042 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4043 elif mark:
4043 elif mark:
4044 ms.mark(f, "r")
4044 ms.mark(f, "r")
4045 elif unmark:
4045 elif unmark:
4046 ms.mark(f, "u")
4046 ms.mark(f, "u")
4047 else:
4047 else:
4048 wctx = repo[None]
4048 wctx = repo[None]
4049 mctx = wctx.parents()[-1]
4049 mctx = wctx.parents()[-1]
4050
4050
4051 # backup pre-resolve (merge uses .orig for its own purposes)
4051 # backup pre-resolve (merge uses .orig for its own purposes)
4052 a = repo.wjoin(f)
4052 a = repo.wjoin(f)
4053 util.copyfile(a, a + ".resolve")
4053 util.copyfile(a, a + ".resolve")
4054
4054
4055 try:
4055 try:
4056 # resolve file
4056 # resolve file
4057 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4057 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4058 if ms.resolve(f, wctx, mctx):
4058 if ms.resolve(f, wctx, mctx):
4059 ret = 1
4059 ret = 1
4060 finally:
4060 finally:
4061 ui.setconfig('ui', 'forcemerge', '')
4061 ui.setconfig('ui', 'forcemerge', '')
4062
4062
4063 # replace filemerge's .orig file with our resolve file
4063 # replace filemerge's .orig file with our resolve file
4064 util.rename(a + ".resolve", a + ".orig")
4064 util.rename(a + ".resolve", a + ".orig")
4065
4065
4066 ms.commit()
4066 ms.commit()
4067 return ret
4067 return ret
4068
4068
4069 @command('revert',
4069 @command('revert',
4070 [('a', 'all', None, _('revert all changes when no arguments given')),
4070 [('a', 'all', None, _('revert all changes when no arguments given')),
4071 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4071 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4072 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4072 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4073 ('', 'no-backup', None, _('do not save backup copies of files')),
4073 ('', 'no-backup', None, _('do not save backup copies of files')),
4074 ] + walkopts + dryrunopts,
4074 ] + walkopts + dryrunopts,
4075 _('[OPTION]... [-r REV] [NAME]...'))
4075 _('[OPTION]... [-r REV] [NAME]...'))
4076 def revert(ui, repo, *pats, **opts):
4076 def revert(ui, repo, *pats, **opts):
4077 """restore individual files or directories to an earlier state
4077 """restore individual files or directories to an earlier state
4078
4078
4079 .. note::
4079 .. note::
4080 This command is most likely not what you are looking for.
4080 This command is most likely not what you are looking for.
4081 Revert will partially overwrite content in the working
4081 Revert will partially overwrite content in the working
4082 directory without changing the working directory parents. Use
4082 directory without changing the working directory parents. Use
4083 :hg:`update -r rev` to check out earlier revisions, or
4083 :hg:`update -r rev` to check out earlier revisions, or
4084 :hg:`update --clean .` to undo a merge which has added another
4084 :hg:`update --clean .` to undo a merge which has added another
4085 parent.
4085 parent.
4086
4086
4087 With no revision specified, revert the named files or directories
4087 With no revision specified, revert the named files or directories
4088 to the contents they had in the parent of the working directory.
4088 to the contents they had in the parent of the working directory.
4089 This restores the contents of the affected files to an unmodified
4089 This restores the contents of the affected files to an unmodified
4090 state and unschedules adds, removes, copies, and renames. If the
4090 state and unschedules adds, removes, copies, and renames. If the
4091 working directory has two parents, you must explicitly specify a
4091 working directory has two parents, you must explicitly specify a
4092 revision.
4092 revision.
4093
4093
4094 Using the -r/--rev option, revert the given files or directories
4094 Using the -r/--rev option, revert the given files or directories
4095 to their contents as of a specific revision. This can be helpful
4095 to their contents as of a specific revision. This can be helpful
4096 to "roll back" some or all of an earlier change. See :hg:`help
4096 to "roll back" some or all of an earlier change. See :hg:`help
4097 dates` for a list of formats valid for -d/--date.
4097 dates` for a list of formats valid for -d/--date.
4098
4098
4099 Revert modifies the working directory. It does not commit any
4099 Revert modifies the working directory. It does not commit any
4100 changes, or change the parent of the working directory. If you
4100 changes, or change the parent of the working directory. If you
4101 revert to a revision other than the parent of the working
4101 revert to a revision other than the parent of the working
4102 directory, the reverted files will thus appear modified
4102 directory, the reverted files will thus appear modified
4103 afterwards.
4103 afterwards.
4104
4104
4105 If a file has been deleted, it is restored. Files scheduled for
4105 If a file has been deleted, it is restored. Files scheduled for
4106 addition are just unscheduled and left as they are. If the
4106 addition are just unscheduled and left as they are. If the
4107 executable mode of a file was changed, it is reset.
4107 executable mode of a file was changed, it is reset.
4108
4108
4109 If names are given, all files matching the names are reverted.
4109 If names are given, all files matching the names are reverted.
4110 If no arguments are given, no files are reverted.
4110 If no arguments are given, no files are reverted.
4111
4111
4112 Modified files are saved with a .orig suffix before reverting.
4112 Modified files are saved with a .orig suffix before reverting.
4113 To disable these backups, use --no-backup.
4113 To disable these backups, use --no-backup.
4114
4114
4115 Returns 0 on success.
4115 Returns 0 on success.
4116 """
4116 """
4117
4117
4118 if opts.get("date"):
4118 if opts.get("date"):
4119 if opts.get("rev"):
4119 if opts.get("rev"):
4120 raise util.Abort(_("you can't specify a revision and a date"))
4120 raise util.Abort(_("you can't specify a revision and a date"))
4121 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4121 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4122
4122
4123 parent, p2 = repo.dirstate.parents()
4123 parent, p2 = repo.dirstate.parents()
4124 if not opts.get('rev') and p2 != nullid:
4124 if not opts.get('rev') and p2 != nullid:
4125 raise util.Abort(_('uncommitted merge - '
4125 raise util.Abort(_('uncommitted merge - '
4126 'use "hg update", see "hg help revert"'))
4126 'use "hg update", see "hg help revert"'))
4127
4127
4128 if not pats and not opts.get('all'):
4128 if not pats and not opts.get('all'):
4129 raise util.Abort(_('no files or directories specified; '
4129 raise util.Abort(_('no files or directories specified; '
4130 'use --all to revert the whole repo'))
4130 'use --all to revert the whole repo'))
4131
4131
4132 ctx = scmutil.revsingle(repo, opts.get('rev'))
4132 ctx = scmutil.revsingle(repo, opts.get('rev'))
4133 node = ctx.node()
4133 node = ctx.node()
4134 mf = ctx.manifest()
4134 mf = ctx.manifest()
4135 if node == parent:
4135 if node == parent:
4136 pmf = mf
4136 pmf = mf
4137 else:
4137 else:
4138 pmf = None
4138 pmf = None
4139
4139
4140 # need all matching names in dirstate and manifest of target rev,
4140 # need all matching names in dirstate and manifest of target rev,
4141 # so have to walk both. do not print errors if files exist in one
4141 # so have to walk both. do not print errors if files exist in one
4142 # but not other.
4142 # but not other.
4143
4143
4144 names = {}
4144 names = {}
4145
4145
4146 wlock = repo.wlock()
4146 wlock = repo.wlock()
4147 try:
4147 try:
4148 # walk dirstate.
4148 # walk dirstate.
4149
4149
4150 m = scmutil.match(repo, pats, opts)
4150 m = scmutil.match(repo, pats, opts)
4151 m.bad = lambda x, y: False
4151 m.bad = lambda x, y: False
4152 for abs in repo.walk(m):
4152 for abs in repo.walk(m):
4153 names[abs] = m.rel(abs), m.exact(abs)
4153 names[abs] = m.rel(abs), m.exact(abs)
4154
4154
4155 # walk target manifest.
4155 # walk target manifest.
4156
4156
4157 def badfn(path, msg):
4157 def badfn(path, msg):
4158 if path in names:
4158 if path in names:
4159 return
4159 return
4160 path_ = path + '/'
4160 path_ = path + '/'
4161 for f in names:
4161 for f in names:
4162 if f.startswith(path_):
4162 if f.startswith(path_):
4163 return
4163 return
4164 ui.warn("%s: %s\n" % (m.rel(path), msg))
4164 ui.warn("%s: %s\n" % (m.rel(path), msg))
4165
4165
4166 m = scmutil.match(repo, pats, opts)
4166 m = scmutil.match(repo, pats, opts)
4167 m.bad = badfn
4167 m.bad = badfn
4168 for abs in repo[node].walk(m):
4168 for abs in repo[node].walk(m):
4169 if abs not in names:
4169 if abs not in names:
4170 names[abs] = m.rel(abs), m.exact(abs)
4170 names[abs] = m.rel(abs), m.exact(abs)
4171
4171
4172 m = scmutil.matchfiles(repo, names)
4172 m = scmutil.matchfiles(repo, names)
4173 changes = repo.status(match=m)[:4]
4173 changes = repo.status(match=m)[:4]
4174 modified, added, removed, deleted = map(set, changes)
4174 modified, added, removed, deleted = map(set, changes)
4175
4175
4176 # if f is a rename, also revert the source
4176 # if f is a rename, also revert the source
4177 cwd = repo.getcwd()
4177 cwd = repo.getcwd()
4178 for f in added:
4178 for f in added:
4179 src = repo.dirstate.copied(f)
4179 src = repo.dirstate.copied(f)
4180 if src and src not in names and repo.dirstate[src] == 'r':
4180 if src and src not in names and repo.dirstate[src] == 'r':
4181 removed.add(src)
4181 removed.add(src)
4182 names[src] = (repo.pathto(src, cwd), True)
4182 names[src] = (repo.pathto(src, cwd), True)
4183
4183
4184 def removeforget(abs):
4184 def removeforget(abs):
4185 if repo.dirstate[abs] == 'a':
4185 if repo.dirstate[abs] == 'a':
4186 return _('forgetting %s\n')
4186 return _('forgetting %s\n')
4187 return _('removing %s\n')
4187 return _('removing %s\n')
4188
4188
4189 revert = ([], _('reverting %s\n'))
4189 revert = ([], _('reverting %s\n'))
4190 add = ([], _('adding %s\n'))
4190 add = ([], _('adding %s\n'))
4191 remove = ([], removeforget)
4191 remove = ([], removeforget)
4192 undelete = ([], _('undeleting %s\n'))
4192 undelete = ([], _('undeleting %s\n'))
4193
4193
4194 disptable = (
4194 disptable = (
4195 # dispatch table:
4195 # dispatch table:
4196 # file state
4196 # file state
4197 # action if in target manifest
4197 # action if in target manifest
4198 # action if not in target manifest
4198 # action if not in target manifest
4199 # make backup if in target manifest
4199 # make backup if in target manifest
4200 # make backup if not in target manifest
4200 # make backup if not in target manifest
4201 (modified, revert, remove, True, True),
4201 (modified, revert, remove, True, True),
4202 (added, revert, remove, True, False),
4202 (added, revert, remove, True, False),
4203 (removed, undelete, None, False, False),
4203 (removed, undelete, None, False, False),
4204 (deleted, revert, remove, False, False),
4204 (deleted, revert, remove, False, False),
4205 )
4205 )
4206
4206
4207 for abs, (rel, exact) in sorted(names.items()):
4207 for abs, (rel, exact) in sorted(names.items()):
4208 mfentry = mf.get(abs)
4208 mfentry = mf.get(abs)
4209 target = repo.wjoin(abs)
4209 target = repo.wjoin(abs)
4210 def handle(xlist, dobackup):
4210 def handle(xlist, dobackup):
4211 xlist[0].append(abs)
4211 xlist[0].append(abs)
4212 if (dobackup and not opts.get('no_backup') and
4212 if (dobackup and not opts.get('no_backup') and
4213 os.path.lexists(target)):
4213 os.path.lexists(target)):
4214 bakname = "%s.orig" % rel
4214 bakname = "%s.orig" % rel
4215 ui.note(_('saving current version of %s as %s\n') %
4215 ui.note(_('saving current version of %s as %s\n') %
4216 (rel, bakname))
4216 (rel, bakname))
4217 if not opts.get('dry_run'):
4217 if not opts.get('dry_run'):
4218 util.rename(target, bakname)
4218 util.rename(target, bakname)
4219 if ui.verbose or not exact:
4219 if ui.verbose or not exact:
4220 msg = xlist[1]
4220 msg = xlist[1]
4221 if not isinstance(msg, basestring):
4221 if not isinstance(msg, basestring):
4222 msg = msg(abs)
4222 msg = msg(abs)
4223 ui.status(msg % rel)
4223 ui.status(msg % rel)
4224 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4224 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4225 if abs not in table:
4225 if abs not in table:
4226 continue
4226 continue
4227 # file has changed in dirstate
4227 # file has changed in dirstate
4228 if mfentry:
4228 if mfentry:
4229 handle(hitlist, backuphit)
4229 handle(hitlist, backuphit)
4230 elif misslist is not None:
4230 elif misslist is not None:
4231 handle(misslist, backupmiss)
4231 handle(misslist, backupmiss)
4232 break
4232 break
4233 else:
4233 else:
4234 if abs not in repo.dirstate:
4234 if abs not in repo.dirstate:
4235 if mfentry:
4235 if mfentry:
4236 handle(add, True)
4236 handle(add, True)
4237 elif exact:
4237 elif exact:
4238 ui.warn(_('file not managed: %s\n') % rel)
4238 ui.warn(_('file not managed: %s\n') % rel)
4239 continue
4239 continue
4240 # file has not changed in dirstate
4240 # file has not changed in dirstate
4241 if node == parent:
4241 if node == parent:
4242 if exact:
4242 if exact:
4243 ui.warn(_('no changes needed to %s\n') % rel)
4243 ui.warn(_('no changes needed to %s\n') % rel)
4244 continue
4244 continue
4245 if pmf is None:
4245 if pmf is None:
4246 # only need parent manifest in this unlikely case,
4246 # only need parent manifest in this unlikely case,
4247 # so do not read by default
4247 # so do not read by default
4248 pmf = repo[parent].manifest()
4248 pmf = repo[parent].manifest()
4249 if abs in pmf:
4249 if abs in pmf:
4250 if mfentry:
4250 if mfentry:
4251 # if version of file is same in parent and target
4251 # if version of file is same in parent and target
4252 # manifests, do nothing
4252 # manifests, do nothing
4253 if (pmf[abs] != mfentry or
4253 if (pmf[abs] != mfentry or
4254 pmf.flags(abs) != mf.flags(abs)):
4254 pmf.flags(abs) != mf.flags(abs)):
4255 handle(revert, False)
4255 handle(revert, False)
4256 else:
4256 else:
4257 handle(remove, False)
4257 handle(remove, False)
4258
4258
4259 if not opts.get('dry_run'):
4259 if not opts.get('dry_run'):
4260 def checkout(f):
4260 def checkout(f):
4261 fc = ctx[f]
4261 fc = ctx[f]
4262 repo.wwrite(f, fc.data(), fc.flags())
4262 repo.wwrite(f, fc.data(), fc.flags())
4263
4263
4264 audit_path = scmutil.pathauditor(repo.root)
4264 audit_path = scmutil.pathauditor(repo.root)
4265 for f in remove[0]:
4265 for f in remove[0]:
4266 if repo.dirstate[f] == 'a':
4266 if repo.dirstate[f] == 'a':
4267 repo.dirstate.drop(f)
4267 repo.dirstate.drop(f)
4268 continue
4268 continue
4269 audit_path(f)
4269 audit_path(f)
4270 try:
4270 try:
4271 util.unlinkpath(repo.wjoin(f))
4271 util.unlinkpath(repo.wjoin(f))
4272 except OSError:
4272 except OSError:
4273 pass
4273 pass
4274 repo.dirstate.remove(f)
4274 repo.dirstate.remove(f)
4275
4275
4276 normal = None
4276 normal = None
4277 if node == parent:
4277 if node == parent:
4278 # We're reverting to our parent. If possible, we'd like status
4278 # We're reverting to our parent. If possible, we'd like status
4279 # to report the file as clean. We have to use normallookup for
4279 # to report the file as clean. We have to use normallookup for
4280 # merges to avoid losing information about merged/dirty files.
4280 # merges to avoid losing information about merged/dirty files.
4281 if p2 != nullid:
4281 if p2 != nullid:
4282 normal = repo.dirstate.normallookup
4282 normal = repo.dirstate.normallookup
4283 else:
4283 else:
4284 normal = repo.dirstate.normal
4284 normal = repo.dirstate.normal
4285 for f in revert[0]:
4285 for f in revert[0]:
4286 checkout(f)
4286 checkout(f)
4287 if normal:
4287 if normal:
4288 normal(f)
4288 normal(f)
4289
4289
4290 for f in add[0]:
4290 for f in add[0]:
4291 checkout(f)
4291 checkout(f)
4292 repo.dirstate.add(f)
4292 repo.dirstate.add(f)
4293
4293
4294 normal = repo.dirstate.normallookup
4294 normal = repo.dirstate.normallookup
4295 if node == parent and p2 == nullid:
4295 if node == parent and p2 == nullid:
4296 normal = repo.dirstate.normal
4296 normal = repo.dirstate.normal
4297 for f in undelete[0]:
4297 for f in undelete[0]:
4298 checkout(f)
4298 checkout(f)
4299 normal(f)
4299 normal(f)
4300
4300
4301 finally:
4301 finally:
4302 wlock.release()
4302 wlock.release()
4303
4303
4304 @command('rollback', dryrunopts)
4304 @command('rollback', dryrunopts)
4305 def rollback(ui, repo, **opts):
4305 def rollback(ui, repo, **opts):
4306 """roll back the last transaction (dangerous)
4306 """roll back the last transaction (dangerous)
4307
4307
4308 This command should be used with care. There is only one level of
4308 This command should be used with care. There is only one level of
4309 rollback, and there is no way to undo a rollback. It will also
4309 rollback, and there is no way to undo a rollback. It will also
4310 restore the dirstate at the time of the last transaction, losing
4310 restore the dirstate at the time of the last transaction, losing
4311 any dirstate changes since that time. This command does not alter
4311 any dirstate changes since that time. This command does not alter
4312 the working directory.
4312 the working directory.
4313
4313
4314 Transactions are used to encapsulate the effects of all commands
4314 Transactions are used to encapsulate the effects of all commands
4315 that create new changesets or propagate existing changesets into a
4315 that create new changesets or propagate existing changesets into a
4316 repository. For example, the following commands are transactional,
4316 repository. For example, the following commands are transactional,
4317 and their effects can be rolled back:
4317 and their effects can be rolled back:
4318
4318
4319 - commit
4319 - commit
4320 - import
4320 - import
4321 - pull
4321 - pull
4322 - push (with this repository as the destination)
4322 - push (with this repository as the destination)
4323 - unbundle
4323 - unbundle
4324
4324
4325 This command is not intended for use on public repositories. Once
4325 This command is not intended for use on public repositories. Once
4326 changes are visible for pull by other users, rolling a transaction
4326 changes are visible for pull by other users, rolling a transaction
4327 back locally is ineffective (someone else may already have pulled
4327 back locally is ineffective (someone else may already have pulled
4328 the changes). Furthermore, a race is possible with readers of the
4328 the changes). Furthermore, a race is possible with readers of the
4329 repository; for example an in-progress pull from the repository
4329 repository; for example an in-progress pull from the repository
4330 may fail if a rollback is performed.
4330 may fail if a rollback is performed.
4331
4331
4332 Returns 0 on success, 1 if no rollback data is available.
4332 Returns 0 on success, 1 if no rollback data is available.
4333 """
4333 """
4334 return repo.rollback(opts.get('dry_run'))
4334 return repo.rollback(opts.get('dry_run'))
4335
4335
4336 @command('root', [])
4336 @command('root', [])
4337 def root(ui, repo):
4337 def root(ui, repo):
4338 """print the root (top) of the current working directory
4338 """print the root (top) of the current working directory
4339
4339
4340 Print the root directory of the current repository.
4340 Print the root directory of the current repository.
4341
4341
4342 Returns 0 on success.
4342 Returns 0 on success.
4343 """
4343 """
4344 ui.write(repo.root + "\n")
4344 ui.write(repo.root + "\n")
4345
4345
4346 @command('^serve',
4346 @command('^serve',
4347 [('A', 'accesslog', '', _('name of access log file to write to'),
4347 [('A', 'accesslog', '', _('name of access log file to write to'),
4348 _('FILE')),
4348 _('FILE')),
4349 ('d', 'daemon', None, _('run server in background')),
4349 ('d', 'daemon', None, _('run server in background')),
4350 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4350 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4351 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4351 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4352 # use string type, then we can check if something was passed
4352 # use string type, then we can check if something was passed
4353 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4353 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4354 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4354 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4355 _('ADDR')),
4355 _('ADDR')),
4356 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4356 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4357 _('PREFIX')),
4357 _('PREFIX')),
4358 ('n', 'name', '',
4358 ('n', 'name', '',
4359 _('name to show in web pages (default: working directory)'), _('NAME')),
4359 _('name to show in web pages (default: working directory)'), _('NAME')),
4360 ('', 'web-conf', '',
4360 ('', 'web-conf', '',
4361 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4361 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4362 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4362 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4363 _('FILE')),
4363 _('FILE')),
4364 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4364 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4365 ('', 'stdio', None, _('for remote clients')),
4365 ('', 'stdio', None, _('for remote clients')),
4366 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4366 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4367 ('', 'style', '', _('template style to use'), _('STYLE')),
4367 ('', 'style', '', _('template style to use'), _('STYLE')),
4368 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4368 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4369 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4369 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4370 _('[OPTION]...'))
4370 _('[OPTION]...'))
4371 def serve(ui, repo, **opts):
4371 def serve(ui, repo, **opts):
4372 """start stand-alone webserver
4372 """start stand-alone webserver
4373
4373
4374 Start a local HTTP repository browser and pull server. You can use
4374 Start a local HTTP repository browser and pull server. You can use
4375 this for ad-hoc sharing and browsing of repositories. It is
4375 this for ad-hoc sharing and browsing of repositories. It is
4376 recommended to use a real web server to serve a repository for
4376 recommended to use a real web server to serve a repository for
4377 longer periods of time.
4377 longer periods of time.
4378
4378
4379 Please note that the server does not implement access control.
4379 Please note that the server does not implement access control.
4380 This means that, by default, anybody can read from the server and
4380 This means that, by default, anybody can read from the server and
4381 nobody can write to it by default. Set the ``web.allow_push``
4381 nobody can write to it by default. Set the ``web.allow_push``
4382 option to ``*`` to allow everybody to push to the server. You
4382 option to ``*`` to allow everybody to push to the server. You
4383 should use a real web server if you need to authenticate users.
4383 should use a real web server if you need to authenticate users.
4384
4384
4385 By default, the server logs accesses to stdout and errors to
4385 By default, the server logs accesses to stdout and errors to
4386 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4386 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4387 files.
4387 files.
4388
4388
4389 To have the server choose a free port number to listen on, specify
4389 To have the server choose a free port number to listen on, specify
4390 a port number of 0; in this case, the server will print the port
4390 a port number of 0; in this case, the server will print the port
4391 number it uses.
4391 number it uses.
4392
4392
4393 Returns 0 on success.
4393 Returns 0 on success.
4394 """
4394 """
4395
4395
4396 if opts["stdio"]:
4396 if opts["stdio"]:
4397 if repo is None:
4397 if repo is None:
4398 raise error.RepoError(_("There is no Mercurial repository here"
4398 raise error.RepoError(_("There is no Mercurial repository here"
4399 " (.hg not found)"))
4399 " (.hg not found)"))
4400 s = sshserver.sshserver(ui, repo)
4400 s = sshserver.sshserver(ui, repo)
4401 s.serve_forever()
4401 s.serve_forever()
4402
4402
4403 # this way we can check if something was given in the command-line
4403 # this way we can check if something was given in the command-line
4404 if opts.get('port'):
4404 if opts.get('port'):
4405 opts['port'] = util.getport(opts.get('port'))
4405 opts['port'] = util.getport(opts.get('port'))
4406
4406
4407 baseui = repo and repo.baseui or ui
4407 baseui = repo and repo.baseui or ui
4408 optlist = ("name templates style address port prefix ipv6"
4408 optlist = ("name templates style address port prefix ipv6"
4409 " accesslog errorlog certificate encoding")
4409 " accesslog errorlog certificate encoding")
4410 for o in optlist.split():
4410 for o in optlist.split():
4411 val = opts.get(o, '')
4411 val = opts.get(o, '')
4412 if val in (None, ''): # should check against default options instead
4412 if val in (None, ''): # should check against default options instead
4413 continue
4413 continue
4414 baseui.setconfig("web", o, val)
4414 baseui.setconfig("web", o, val)
4415 if repo and repo.ui != baseui:
4415 if repo and repo.ui != baseui:
4416 repo.ui.setconfig("web", o, val)
4416 repo.ui.setconfig("web", o, val)
4417
4417
4418 o = opts.get('web_conf') or opts.get('webdir_conf')
4418 o = opts.get('web_conf') or opts.get('webdir_conf')
4419 if not o:
4419 if not o:
4420 if not repo:
4420 if not repo:
4421 raise error.RepoError(_("There is no Mercurial repository"
4421 raise error.RepoError(_("There is no Mercurial repository"
4422 " here (.hg not found)"))
4422 " here (.hg not found)"))
4423 o = repo.root
4423 o = repo.root
4424
4424
4425 app = hgweb.hgweb(o, baseui=ui)
4425 app = hgweb.hgweb(o, baseui=ui)
4426
4426
4427 class service(object):
4427 class service(object):
4428 def init(self):
4428 def init(self):
4429 util.setsignalhandler()
4429 util.setsignalhandler()
4430 self.httpd = hgweb.server.create_server(ui, app)
4430 self.httpd = hgweb.server.create_server(ui, app)
4431
4431
4432 if opts['port'] and not ui.verbose:
4432 if opts['port'] and not ui.verbose:
4433 return
4433 return
4434
4434
4435 if self.httpd.prefix:
4435 if self.httpd.prefix:
4436 prefix = self.httpd.prefix.strip('/') + '/'
4436 prefix = self.httpd.prefix.strip('/') + '/'
4437 else:
4437 else:
4438 prefix = ''
4438 prefix = ''
4439
4439
4440 port = ':%d' % self.httpd.port
4440 port = ':%d' % self.httpd.port
4441 if port == ':80':
4441 if port == ':80':
4442 port = ''
4442 port = ''
4443
4443
4444 bindaddr = self.httpd.addr
4444 bindaddr = self.httpd.addr
4445 if bindaddr == '0.0.0.0':
4445 if bindaddr == '0.0.0.0':
4446 bindaddr = '*'
4446 bindaddr = '*'
4447 elif ':' in bindaddr: # IPv6
4447 elif ':' in bindaddr: # IPv6
4448 bindaddr = '[%s]' % bindaddr
4448 bindaddr = '[%s]' % bindaddr
4449
4449
4450 fqaddr = self.httpd.fqaddr
4450 fqaddr = self.httpd.fqaddr
4451 if ':' in fqaddr:
4451 if ':' in fqaddr:
4452 fqaddr = '[%s]' % fqaddr
4452 fqaddr = '[%s]' % fqaddr
4453 if opts['port']:
4453 if opts['port']:
4454 write = ui.status
4454 write = ui.status
4455 else:
4455 else:
4456 write = ui.write
4456 write = ui.write
4457 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4457 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4458 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4458 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4459
4459
4460 def run(self):
4460 def run(self):
4461 self.httpd.serve_forever()
4461 self.httpd.serve_forever()
4462
4462
4463 service = service()
4463 service = service()
4464
4464
4465 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4465 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4466
4466
4467 @command('showconfig|debugconfig',
4467 @command('showconfig|debugconfig',
4468 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4468 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4469 _('[-u] [NAME]...'))
4469 _('[-u] [NAME]...'))
4470 def showconfig(ui, repo, *values, **opts):
4470 def showconfig(ui, repo, *values, **opts):
4471 """show combined config settings from all hgrc files
4471 """show combined config settings from all hgrc files
4472
4472
4473 With no arguments, print names and values of all config items.
4473 With no arguments, print names and values of all config items.
4474
4474
4475 With one argument of the form section.name, print just the value
4475 With one argument of the form section.name, print just the value
4476 of that config item.
4476 of that config item.
4477
4477
4478 With multiple arguments, print names and values of all config
4478 With multiple arguments, print names and values of all config
4479 items with matching section names.
4479 items with matching section names.
4480
4480
4481 With --debug, the source (filename and line number) is printed
4481 With --debug, the source (filename and line number) is printed
4482 for each config item.
4482 for each config item.
4483
4483
4484 Returns 0 on success.
4484 Returns 0 on success.
4485 """
4485 """
4486
4486
4487 for f in scmutil.rcpath():
4487 for f in scmutil.rcpath():
4488 ui.debug(_('read config from: %s\n') % f)
4488 ui.debug(_('read config from: %s\n') % f)
4489 untrusted = bool(opts.get('untrusted'))
4489 untrusted = bool(opts.get('untrusted'))
4490 if values:
4490 if values:
4491 sections = [v for v in values if '.' not in v]
4491 sections = [v for v in values if '.' not in v]
4492 items = [v for v in values if '.' in v]
4492 items = [v for v in values if '.' in v]
4493 if len(items) > 1 or items and sections:
4493 if len(items) > 1 or items and sections:
4494 raise util.Abort(_('only one config item permitted'))
4494 raise util.Abort(_('only one config item permitted'))
4495 for section, name, value in ui.walkconfig(untrusted=untrusted):
4495 for section, name, value in ui.walkconfig(untrusted=untrusted):
4496 value = str(value).replace('\n', '\\n')
4496 value = str(value).replace('\n', '\\n')
4497 sectname = section + '.' + name
4497 sectname = section + '.' + name
4498 if values:
4498 if values:
4499 for v in values:
4499 for v in values:
4500 if v == section:
4500 if v == section:
4501 ui.debug('%s: ' %
4501 ui.debug('%s: ' %
4502 ui.configsource(section, name, untrusted))
4502 ui.configsource(section, name, untrusted))
4503 ui.write('%s=%s\n' % (sectname, value))
4503 ui.write('%s=%s\n' % (sectname, value))
4504 elif v == sectname:
4504 elif v == sectname:
4505 ui.debug('%s: ' %
4505 ui.debug('%s: ' %
4506 ui.configsource(section, name, untrusted))
4506 ui.configsource(section, name, untrusted))
4507 ui.write(value, '\n')
4507 ui.write(value, '\n')
4508 else:
4508 else:
4509 ui.debug('%s: ' %
4509 ui.debug('%s: ' %
4510 ui.configsource(section, name, untrusted))
4510 ui.configsource(section, name, untrusted))
4511 ui.write('%s=%s\n' % (sectname, value))
4511 ui.write('%s=%s\n' % (sectname, value))
4512
4512
4513 @command('^status|st',
4513 @command('^status|st',
4514 [('A', 'all', None, _('show status of all files')),
4514 [('A', 'all', None, _('show status of all files')),
4515 ('m', 'modified', None, _('show only modified files')),
4515 ('m', 'modified', None, _('show only modified files')),
4516 ('a', 'added', None, _('show only added files')),
4516 ('a', 'added', None, _('show only added files')),
4517 ('r', 'removed', None, _('show only removed files')),
4517 ('r', 'removed', None, _('show only removed files')),
4518 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4518 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4519 ('c', 'clean', None, _('show only files without changes')),
4519 ('c', 'clean', None, _('show only files without changes')),
4520 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4520 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4521 ('i', 'ignored', None, _('show only ignored files')),
4521 ('i', 'ignored', None, _('show only ignored files')),
4522 ('n', 'no-status', None, _('hide status prefix')),
4522 ('n', 'no-status', None, _('hide status prefix')),
4523 ('C', 'copies', None, _('show source of copied files')),
4523 ('C', 'copies', None, _('show source of copied files')),
4524 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4524 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4525 ('', 'rev', [], _('show difference from revision'), _('REV')),
4525 ('', 'rev', [], _('show difference from revision'), _('REV')),
4526 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4526 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4527 ] + walkopts + subrepoopts,
4527 ] + walkopts + subrepoopts,
4528 _('[OPTION]... [FILE]...'))
4528 _('[OPTION]... [FILE]...'))
4529 def status(ui, repo, *pats, **opts):
4529 def status(ui, repo, *pats, **opts):
4530 """show changed files in the working directory
4530 """show changed files in the working directory
4531
4531
4532 Show status of files in the repository. If names are given, only
4532 Show status of files in the repository. If names are given, only
4533 files that match are shown. Files that are clean or ignored or
4533 files that match are shown. Files that are clean or ignored or
4534 the source of a copy/move operation, are not listed unless
4534 the source of a copy/move operation, are not listed unless
4535 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4535 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4536 Unless options described with "show only ..." are given, the
4536 Unless options described with "show only ..." are given, the
4537 options -mardu are used.
4537 options -mardu are used.
4538
4538
4539 Option -q/--quiet hides untracked (unknown and ignored) files
4539 Option -q/--quiet hides untracked (unknown and ignored) files
4540 unless explicitly requested with -u/--unknown or -i/--ignored.
4540 unless explicitly requested with -u/--unknown or -i/--ignored.
4541
4541
4542 .. note::
4542 .. note::
4543 status may appear to disagree with diff if permissions have
4543 status may appear to disagree with diff if permissions have
4544 changed or a merge has occurred. The standard diff format does
4544 changed or a merge has occurred. The standard diff format does
4545 not report permission changes and diff only reports changes
4545 not report permission changes and diff only reports changes
4546 relative to one merge parent.
4546 relative to one merge parent.
4547
4547
4548 If one revision is given, it is used as the base revision.
4548 If one revision is given, it is used as the base revision.
4549 If two revisions are given, the differences between them are
4549 If two revisions are given, the differences between them are
4550 shown. The --change option can also be used as a shortcut to list
4550 shown. The --change option can also be used as a shortcut to list
4551 the changed files of a revision from its first parent.
4551 the changed files of a revision from its first parent.
4552
4552
4553 The codes used to show the status of files are::
4553 The codes used to show the status of files are::
4554
4554
4555 M = modified
4555 M = modified
4556 A = added
4556 A = added
4557 R = removed
4557 R = removed
4558 C = clean
4558 C = clean
4559 ! = missing (deleted by non-hg command, but still tracked)
4559 ! = missing (deleted by non-hg command, but still tracked)
4560 ? = not tracked
4560 ? = not tracked
4561 I = ignored
4561 I = ignored
4562 = origin of the previous file listed as A (added)
4562 = origin of the previous file listed as A (added)
4563
4563
4564 Returns 0 on success.
4564 Returns 0 on success.
4565 """
4565 """
4566
4566
4567 revs = opts.get('rev')
4567 revs = opts.get('rev')
4568 change = opts.get('change')
4568 change = opts.get('change')
4569
4569
4570 if revs and change:
4570 if revs and change:
4571 msg = _('cannot specify --rev and --change at the same time')
4571 msg = _('cannot specify --rev and --change at the same time')
4572 raise util.Abort(msg)
4572 raise util.Abort(msg)
4573 elif change:
4573 elif change:
4574 node2 = repo.lookup(change)
4574 node2 = repo.lookup(change)
4575 node1 = repo[node2].p1().node()
4575 node1 = repo[node2].p1().node()
4576 else:
4576 else:
4577 node1, node2 = scmutil.revpair(repo, revs)
4577 node1, node2 = scmutil.revpair(repo, revs)
4578
4578
4579 cwd = (pats and repo.getcwd()) or ''
4579 cwd = (pats and repo.getcwd()) or ''
4580 end = opts.get('print0') and '\0' or '\n'
4580 end = opts.get('print0') and '\0' or '\n'
4581 copy = {}
4581 copy = {}
4582 states = 'modified added removed deleted unknown ignored clean'.split()
4582 states = 'modified added removed deleted unknown ignored clean'.split()
4583 show = [k for k in states if opts.get(k)]
4583 show = [k for k in states if opts.get(k)]
4584 if opts.get('all'):
4584 if opts.get('all'):
4585 show += ui.quiet and (states[:4] + ['clean']) or states
4585 show += ui.quiet and (states[:4] + ['clean']) or states
4586 if not show:
4586 if not show:
4587 show = ui.quiet and states[:4] or states[:5]
4587 show = ui.quiet and states[:4] or states[:5]
4588
4588
4589 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4589 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4590 'ignored' in show, 'clean' in show, 'unknown' in show,
4590 'ignored' in show, 'clean' in show, 'unknown' in show,
4591 opts.get('subrepos'))
4591 opts.get('subrepos'))
4592 changestates = zip(states, 'MAR!?IC', stat)
4592 changestates = zip(states, 'MAR!?IC', stat)
4593
4593
4594 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4594 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4595 ctxn = repo[nullid]
4595 ctxn = repo[nullid]
4596 ctx1 = repo[node1]
4596 ctx1 = repo[node1]
4597 ctx2 = repo[node2]
4597 ctx2 = repo[node2]
4598 added = stat[1]
4598 added = stat[1]
4599 if node2 is None:
4599 if node2 is None:
4600 added = stat[0] + stat[1] # merged?
4600 added = stat[0] + stat[1] # merged?
4601
4601
4602 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4602 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4603 if k in added:
4603 if k in added:
4604 copy[k] = v
4604 copy[k] = v
4605 elif v in added:
4605 elif v in added:
4606 copy[v] = k
4606 copy[v] = k
4607
4607
4608 for state, char, files in changestates:
4608 for state, char, files in changestates:
4609 if state in show:
4609 if state in show:
4610 format = "%s %%s%s" % (char, end)
4610 format = "%s %%s%s" % (char, end)
4611 if opts.get('no_status'):
4611 if opts.get('no_status'):
4612 format = "%%s%s" % end
4612 format = "%%s%s" % end
4613
4613
4614 for f in files:
4614 for f in files:
4615 ui.write(format % repo.pathto(f, cwd),
4615 ui.write(format % repo.pathto(f, cwd),
4616 label='status.' + state)
4616 label='status.' + state)
4617 if f in copy:
4617 if f in copy:
4618 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4618 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4619 label='status.copied')
4619 label='status.copied')
4620
4620
4621 @command('^summary|sum',
4621 @command('^summary|sum',
4622 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4622 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4623 def summary(ui, repo, **opts):
4623 def summary(ui, repo, **opts):
4624 """summarize working directory state
4624 """summarize working directory state
4625
4625
4626 This generates a brief summary of the working directory state,
4626 This generates a brief summary of the working directory state,
4627 including parents, branch, commit status, and available updates.
4627 including parents, branch, commit status, and available updates.
4628
4628
4629 With the --remote option, this will check the default paths for
4629 With the --remote option, this will check the default paths for
4630 incoming and outgoing changes. This can be time-consuming.
4630 incoming and outgoing changes. This can be time-consuming.
4631
4631
4632 Returns 0 on success.
4632 Returns 0 on success.
4633 """
4633 """
4634
4634
4635 ctx = repo[None]
4635 ctx = repo[None]
4636 parents = ctx.parents()
4636 parents = ctx.parents()
4637 pnode = parents[0].node()
4637 pnode = parents[0].node()
4638
4638
4639 for p in parents:
4639 for p in parents:
4640 # label with log.changeset (instead of log.parent) since this
4640 # label with log.changeset (instead of log.parent) since this
4641 # shows a working directory parent *changeset*:
4641 # shows a working directory parent *changeset*:
4642 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4642 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4643 label='log.changeset')
4643 label='log.changeset')
4644 ui.write(' '.join(p.tags()), label='log.tag')
4644 ui.write(' '.join(p.tags()), label='log.tag')
4645 if p.bookmarks():
4645 if p.bookmarks():
4646 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4646 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4647 if p.rev() == -1:
4647 if p.rev() == -1:
4648 if not len(repo):
4648 if not len(repo):
4649 ui.write(_(' (empty repository)'))
4649 ui.write(_(' (empty repository)'))
4650 else:
4650 else:
4651 ui.write(_(' (no revision checked out)'))
4651 ui.write(_(' (no revision checked out)'))
4652 ui.write('\n')
4652 ui.write('\n')
4653 if p.description():
4653 if p.description():
4654 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4654 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4655 label='log.summary')
4655 label='log.summary')
4656
4656
4657 branch = ctx.branch()
4657 branch = ctx.branch()
4658 bheads = repo.branchheads(branch)
4658 bheads = repo.branchheads(branch)
4659 m = _('branch: %s\n') % branch
4659 m = _('branch: %s\n') % branch
4660 if branch != 'default':
4660 if branch != 'default':
4661 ui.write(m, label='log.branch')
4661 ui.write(m, label='log.branch')
4662 else:
4662 else:
4663 ui.status(m, label='log.branch')
4663 ui.status(m, label='log.branch')
4664
4664
4665 st = list(repo.status(unknown=True))[:6]
4665 st = list(repo.status(unknown=True))[:6]
4666
4666
4667 c = repo.dirstate.copies()
4667 c = repo.dirstate.copies()
4668 copied, renamed = [], []
4668 copied, renamed = [], []
4669 for d, s in c.iteritems():
4669 for d, s in c.iteritems():
4670 if s in st[2]:
4670 if s in st[2]:
4671 st[2].remove(s)
4671 st[2].remove(s)
4672 renamed.append(d)
4672 renamed.append(d)
4673 else:
4673 else:
4674 copied.append(d)
4674 copied.append(d)
4675 if d in st[1]:
4675 if d in st[1]:
4676 st[1].remove(d)
4676 st[1].remove(d)
4677 st.insert(3, renamed)
4677 st.insert(3, renamed)
4678 st.insert(4, copied)
4678 st.insert(4, copied)
4679
4679
4680 ms = mergemod.mergestate(repo)
4680 ms = mergemod.mergestate(repo)
4681 st.append([f for f in ms if ms[f] == 'u'])
4681 st.append([f for f in ms if ms[f] == 'u'])
4682
4682
4683 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4683 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4684 st.append(subs)
4684 st.append(subs)
4685
4685
4686 labels = [ui.label(_('%d modified'), 'status.modified'),
4686 labels = [ui.label(_('%d modified'), 'status.modified'),
4687 ui.label(_('%d added'), 'status.added'),
4687 ui.label(_('%d added'), 'status.added'),
4688 ui.label(_('%d removed'), 'status.removed'),
4688 ui.label(_('%d removed'), 'status.removed'),
4689 ui.label(_('%d renamed'), 'status.copied'),
4689 ui.label(_('%d renamed'), 'status.copied'),
4690 ui.label(_('%d copied'), 'status.copied'),
4690 ui.label(_('%d copied'), 'status.copied'),
4691 ui.label(_('%d deleted'), 'status.deleted'),
4691 ui.label(_('%d deleted'), 'status.deleted'),
4692 ui.label(_('%d unknown'), 'status.unknown'),
4692 ui.label(_('%d unknown'), 'status.unknown'),
4693 ui.label(_('%d ignored'), 'status.ignored'),
4693 ui.label(_('%d ignored'), 'status.ignored'),
4694 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4694 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4695 ui.label(_('%d subrepos'), 'status.modified')]
4695 ui.label(_('%d subrepos'), 'status.modified')]
4696 t = []
4696 t = []
4697 for s, l in zip(st, labels):
4697 for s, l in zip(st, labels):
4698 if s:
4698 if s:
4699 t.append(l % len(s))
4699 t.append(l % len(s))
4700
4700
4701 t = ', '.join(t)
4701 t = ', '.join(t)
4702 cleanworkdir = False
4702 cleanworkdir = False
4703
4703
4704 if len(parents) > 1:
4704 if len(parents) > 1:
4705 t += _(' (merge)')
4705 t += _(' (merge)')
4706 elif branch != parents[0].branch():
4706 elif branch != parents[0].branch():
4707 t += _(' (new branch)')
4707 t += _(' (new branch)')
4708 elif (parents[0].extra().get('close') and
4708 elif (parents[0].extra().get('close') and
4709 pnode in repo.branchheads(branch, closed=True)):
4709 pnode in repo.branchheads(branch, closed=True)):
4710 t += _(' (head closed)')
4710 t += _(' (head closed)')
4711 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4711 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4712 t += _(' (clean)')
4712 t += _(' (clean)')
4713 cleanworkdir = True
4713 cleanworkdir = True
4714 elif pnode not in bheads:
4714 elif pnode not in bheads:
4715 t += _(' (new branch head)')
4715 t += _(' (new branch head)')
4716
4716
4717 if cleanworkdir:
4717 if cleanworkdir:
4718 ui.status(_('commit: %s\n') % t.strip())
4718 ui.status(_('commit: %s\n') % t.strip())
4719 else:
4719 else:
4720 ui.write(_('commit: %s\n') % t.strip())
4720 ui.write(_('commit: %s\n') % t.strip())
4721
4721
4722 # all ancestors of branch heads - all ancestors of parent = new csets
4722 # all ancestors of branch heads - all ancestors of parent = new csets
4723 new = [0] * len(repo)
4723 new = [0] * len(repo)
4724 cl = repo.changelog
4724 cl = repo.changelog
4725 for a in [cl.rev(n) for n in bheads]:
4725 for a in [cl.rev(n) for n in bheads]:
4726 new[a] = 1
4726 new[a] = 1
4727 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4727 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4728 new[a] = 1
4728 new[a] = 1
4729 for a in [p.rev() for p in parents]:
4729 for a in [p.rev() for p in parents]:
4730 if a >= 0:
4730 if a >= 0:
4731 new[a] = 0
4731 new[a] = 0
4732 for a in cl.ancestors(*[p.rev() for p in parents]):
4732 for a in cl.ancestors(*[p.rev() for p in parents]):
4733 new[a] = 0
4733 new[a] = 0
4734 new = sum(new)
4734 new = sum(new)
4735
4735
4736 if new == 0:
4736 if new == 0:
4737 ui.status(_('update: (current)\n'))
4737 ui.status(_('update: (current)\n'))
4738 elif pnode not in bheads:
4738 elif pnode not in bheads:
4739 ui.write(_('update: %d new changesets (update)\n') % new)
4739 ui.write(_('update: %d new changesets (update)\n') % new)
4740 else:
4740 else:
4741 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4741 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4742 (new, len(bheads)))
4742 (new, len(bheads)))
4743
4743
4744 if opts.get('remote'):
4744 if opts.get('remote'):
4745 t = []
4745 t = []
4746 source, branches = hg.parseurl(ui.expandpath('default'))
4746 source, branches = hg.parseurl(ui.expandpath('default'))
4747 other = hg.repository(hg.remoteui(repo, {}), source)
4747 other = hg.repository(hg.remoteui(repo, {}), source)
4748 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4748 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4749 ui.debug('comparing with %s\n' % util.hidepassword(source))
4749 ui.debug('comparing with %s\n' % util.hidepassword(source))
4750 repo.ui.pushbuffer()
4750 repo.ui.pushbuffer()
4751 commoninc = discovery.findcommonincoming(repo, other)
4751 commoninc = discovery.findcommonincoming(repo, other)
4752 _common, incoming, _rheads = commoninc
4752 _common, incoming, _rheads = commoninc
4753 repo.ui.popbuffer()
4753 repo.ui.popbuffer()
4754 if incoming:
4754 if incoming:
4755 t.append(_('1 or more incoming'))
4755 t.append(_('1 or more incoming'))
4756
4756
4757 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4757 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4758 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4758 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4759 if source != dest:
4759 if source != dest:
4760 other = hg.repository(hg.remoteui(repo, {}), dest)
4760 other = hg.repository(hg.remoteui(repo, {}), dest)
4761 commoninc = None
4761 commoninc = None
4762 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4762 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4763 repo.ui.pushbuffer()
4763 repo.ui.pushbuffer()
4764 common, outheads = discovery.findcommonoutgoing(repo, other,
4764 common, outheads = discovery.findcommonoutgoing(repo, other,
4765 commoninc=commoninc)
4765 commoninc=commoninc)
4766 repo.ui.popbuffer()
4766 repo.ui.popbuffer()
4767 o = repo.changelog.findmissing(common=common, heads=outheads)
4767 o = repo.changelog.findmissing(common=common, heads=outheads)
4768 if o:
4768 if o:
4769 t.append(_('%d outgoing') % len(o))
4769 t.append(_('%d outgoing') % len(o))
4770 if 'bookmarks' in other.listkeys('namespaces'):
4770 if 'bookmarks' in other.listkeys('namespaces'):
4771 lmarks = repo.listkeys('bookmarks')
4771 lmarks = repo.listkeys('bookmarks')
4772 rmarks = other.listkeys('bookmarks')
4772 rmarks = other.listkeys('bookmarks')
4773 diff = set(rmarks) - set(lmarks)
4773 diff = set(rmarks) - set(lmarks)
4774 if len(diff) > 0:
4774 if len(diff) > 0:
4775 t.append(_('%d incoming bookmarks') % len(diff))
4775 t.append(_('%d incoming bookmarks') % len(diff))
4776 diff = set(lmarks) - set(rmarks)
4776 diff = set(lmarks) - set(rmarks)
4777 if len(diff) > 0:
4777 if len(diff) > 0:
4778 t.append(_('%d outgoing bookmarks') % len(diff))
4778 t.append(_('%d outgoing bookmarks') % len(diff))
4779
4779
4780 if t:
4780 if t:
4781 ui.write(_('remote: %s\n') % (', '.join(t)))
4781 ui.write(_('remote: %s\n') % (', '.join(t)))
4782 else:
4782 else:
4783 ui.status(_('remote: (synced)\n'))
4783 ui.status(_('remote: (synced)\n'))
4784
4784
4785 @command('tag',
4785 @command('tag',
4786 [('f', 'force', None, _('force tag')),
4786 [('f', 'force', None, _('force tag')),
4787 ('l', 'local', None, _('make the tag local')),
4787 ('l', 'local', None, _('make the tag local')),
4788 ('r', 'rev', '', _('revision to tag'), _('REV')),
4788 ('r', 'rev', '', _('revision to tag'), _('REV')),
4789 ('', 'remove', None, _('remove a tag')),
4789 ('', 'remove', None, _('remove a tag')),
4790 # -l/--local is already there, commitopts cannot be used
4790 # -l/--local is already there, commitopts cannot be used
4791 ('e', 'edit', None, _('edit commit message')),
4791 ('e', 'edit', None, _('edit commit message')),
4792 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4792 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4793 ] + commitopts2,
4793 ] + commitopts2,
4794 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4794 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4795 def tag(ui, repo, name1, *names, **opts):
4795 def tag(ui, repo, name1, *names, **opts):
4796 """add one or more tags for the current or given revision
4796 """add one or more tags for the current or given revision
4797
4797
4798 Name a particular revision using <name>.
4798 Name a particular revision using <name>.
4799
4799
4800 Tags are used to name particular revisions of the repository and are
4800 Tags are used to name particular revisions of the repository and are
4801 very useful to compare different revisions, to go back to significant
4801 very useful to compare different revisions, to go back to significant
4802 earlier versions or to mark branch points as releases, etc. Changing
4802 earlier versions or to mark branch points as releases, etc. Changing
4803 an existing tag is normally disallowed; use -f/--force to override.
4803 an existing tag is normally disallowed; use -f/--force to override.
4804
4804
4805 If no revision is given, the parent of the working directory is
4805 If no revision is given, the parent of the working directory is
4806 used, or tip if no revision is checked out.
4806 used, or tip if no revision is checked out.
4807
4807
4808 To facilitate version control, distribution, and merging of tags,
4808 To facilitate version control, distribution, and merging of tags,
4809 they are stored as a file named ".hgtags" which is managed similarly
4809 they are stored as a file named ".hgtags" which is managed similarly
4810 to other project files and can be hand-edited if necessary. This
4810 to other project files and can be hand-edited if necessary. This
4811 also means that tagging creates a new commit. The file
4811 also means that tagging creates a new commit. The file
4812 ".hg/localtags" is used for local tags (not shared among
4812 ".hg/localtags" is used for local tags (not shared among
4813 repositories).
4813 repositories).
4814
4814
4815 Tag commits are usually made at the head of a branch. If the parent
4815 Tag commits are usually made at the head of a branch. If the parent
4816 of the working directory is not a branch head, :hg:`tag` aborts; use
4816 of the working directory is not a branch head, :hg:`tag` aborts; use
4817 -f/--force to force the tag commit to be based on a non-head
4817 -f/--force to force the tag commit to be based on a non-head
4818 changeset.
4818 changeset.
4819
4819
4820 See :hg:`help dates` for a list of formats valid for -d/--date.
4820 See :hg:`help dates` for a list of formats valid for -d/--date.
4821
4821
4822 Since tag names have priority over branch names during revision
4822 Since tag names have priority over branch names during revision
4823 lookup, using an existing branch name as a tag name is discouraged.
4823 lookup, using an existing branch name as a tag name is discouraged.
4824
4824
4825 Returns 0 on success.
4825 Returns 0 on success.
4826 """
4826 """
4827
4827
4828 rev_ = "."
4828 rev_ = "."
4829 names = [t.strip() for t in (name1,) + names]
4829 names = [t.strip() for t in (name1,) + names]
4830 if len(names) != len(set(names)):
4830 if len(names) != len(set(names)):
4831 raise util.Abort(_('tag names must be unique'))
4831 raise util.Abort(_('tag names must be unique'))
4832 for n in names:
4832 for n in names:
4833 if n in ['tip', '.', 'null']:
4833 if n in ['tip', '.', 'null']:
4834 raise util.Abort(_("the name '%s' is reserved") % n)
4834 raise util.Abort(_("the name '%s' is reserved") % n)
4835 if not n:
4835 if not n:
4836 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4836 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4837 if opts.get('rev') and opts.get('remove'):
4837 if opts.get('rev') and opts.get('remove'):
4838 raise util.Abort(_("--rev and --remove are incompatible"))
4838 raise util.Abort(_("--rev and --remove are incompatible"))
4839 if opts.get('rev'):
4839 if opts.get('rev'):
4840 rev_ = opts['rev']
4840 rev_ = opts['rev']
4841 message = opts.get('message')
4841 message = opts.get('message')
4842 if opts.get('remove'):
4842 if opts.get('remove'):
4843 expectedtype = opts.get('local') and 'local' or 'global'
4843 expectedtype = opts.get('local') and 'local' or 'global'
4844 for n in names:
4844 for n in names:
4845 if not repo.tagtype(n):
4845 if not repo.tagtype(n):
4846 raise util.Abort(_("tag '%s' does not exist") % n)
4846 raise util.Abort(_("tag '%s' does not exist") % n)
4847 if repo.tagtype(n) != expectedtype:
4847 if repo.tagtype(n) != expectedtype:
4848 if expectedtype == 'global':
4848 if expectedtype == 'global':
4849 raise util.Abort(_("tag '%s' is not a global tag") % n)
4849 raise util.Abort(_("tag '%s' is not a global tag") % n)
4850 else:
4850 else:
4851 raise util.Abort(_("tag '%s' is not a local tag") % n)
4851 raise util.Abort(_("tag '%s' is not a local tag") % n)
4852 rev_ = nullid
4852 rev_ = nullid
4853 if not message:
4853 if not message:
4854 # we don't translate commit messages
4854 # we don't translate commit messages
4855 message = 'Removed tag %s' % ', '.join(names)
4855 message = 'Removed tag %s' % ', '.join(names)
4856 elif not opts.get('force'):
4856 elif not opts.get('force'):
4857 for n in names:
4857 for n in names:
4858 if n in repo.tags():
4858 if n in repo.tags():
4859 raise util.Abort(_("tag '%s' already exists "
4859 raise util.Abort(_("tag '%s' already exists "
4860 "(use -f to force)") % n)
4860 "(use -f to force)") % n)
4861 if not opts.get('local'):
4861 if not opts.get('local'):
4862 p1, p2 = repo.dirstate.parents()
4862 p1, p2 = repo.dirstate.parents()
4863 if p2 != nullid:
4863 if p2 != nullid:
4864 raise util.Abort(_('uncommitted merge'))
4864 raise util.Abort(_('uncommitted merge'))
4865 bheads = repo.branchheads()
4865 bheads = repo.branchheads()
4866 if not opts.get('force') and bheads and p1 not in bheads:
4866 if not opts.get('force') and bheads and p1 not in bheads:
4867 raise util.Abort(_('not at a branch head (use -f to force)'))
4867 raise util.Abort(_('not at a branch head (use -f to force)'))
4868 r = scmutil.revsingle(repo, rev_).node()
4868 r = scmutil.revsingle(repo, rev_).node()
4869
4869
4870 if not message:
4870 if not message:
4871 # we don't translate commit messages
4871 # we don't translate commit messages
4872 message = ('Added tag %s for changeset %s' %
4872 message = ('Added tag %s for changeset %s' %
4873 (', '.join(names), short(r)))
4873 (', '.join(names), short(r)))
4874
4874
4875 date = opts.get('date')
4875 date = opts.get('date')
4876 if date:
4876 if date:
4877 date = util.parsedate(date)
4877 date = util.parsedate(date)
4878
4878
4879 if opts.get('edit'):
4879 if opts.get('edit'):
4880 message = ui.edit(message, ui.username())
4880 message = ui.edit(message, ui.username())
4881
4881
4882 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4882 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4883
4883
4884 @command('tags', [], '')
4884 @command('tags', [], '')
4885 def tags(ui, repo):
4885 def tags(ui, repo):
4886 """list repository tags
4886 """list repository tags
4887
4887
4888 This lists both regular and local tags. When the -v/--verbose
4888 This lists both regular and local tags. When the -v/--verbose
4889 switch is used, a third column "local" is printed for local tags.
4889 switch is used, a third column "local" is printed for local tags.
4890
4890
4891 Returns 0 on success.
4891 Returns 0 on success.
4892 """
4892 """
4893
4893
4894 hexfunc = ui.debugflag and hex or short
4894 hexfunc = ui.debugflag and hex or short
4895 tagtype = ""
4895 tagtype = ""
4896
4896
4897 for t, n in reversed(repo.tagslist()):
4897 for t, n in reversed(repo.tagslist()):
4898 if ui.quiet:
4898 if ui.quiet:
4899 ui.write("%s\n" % t)
4899 ui.write("%s\n" % t)
4900 continue
4900 continue
4901
4901
4902 hn = hexfunc(n)
4902 hn = hexfunc(n)
4903 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4903 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4904 spaces = " " * (30 - encoding.colwidth(t))
4904 spaces = " " * (30 - encoding.colwidth(t))
4905
4905
4906 if ui.verbose:
4906 if ui.verbose:
4907 if repo.tagtype(t) == 'local':
4907 if repo.tagtype(t) == 'local':
4908 tagtype = " local"
4908 tagtype = " local"
4909 else:
4909 else:
4910 tagtype = ""
4910 tagtype = ""
4911 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4911 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4912
4912
4913 @command('tip',
4913 @command('tip',
4914 [('p', 'patch', None, _('show patch')),
4914 [('p', 'patch', None, _('show patch')),
4915 ('g', 'git', None, _('use git extended diff format')),
4915 ('g', 'git', None, _('use git extended diff format')),
4916 ] + templateopts,
4916 ] + templateopts,
4917 _('[-p] [-g]'))
4917 _('[-p] [-g]'))
4918 def tip(ui, repo, **opts):
4918 def tip(ui, repo, **opts):
4919 """show the tip revision
4919 """show the tip revision
4920
4920
4921 The tip revision (usually just called the tip) is the changeset
4921 The tip revision (usually just called the tip) is the changeset
4922 most recently added to the repository (and therefore the most
4922 most recently added to the repository (and therefore the most
4923 recently changed head).
4923 recently changed head).
4924
4924
4925 If you have just made a commit, that commit will be the tip. If
4925 If you have just made a commit, that commit will be the tip. If
4926 you have just pulled changes from another repository, the tip of
4926 you have just pulled changes from another repository, the tip of
4927 that repository becomes the current tip. The "tip" tag is special
4927 that repository becomes the current tip. The "tip" tag is special
4928 and cannot be renamed or assigned to a different changeset.
4928 and cannot be renamed or assigned to a different changeset.
4929
4929
4930 Returns 0 on success.
4930 Returns 0 on success.
4931 """
4931 """
4932 displayer = cmdutil.show_changeset(ui, repo, opts)
4932 displayer = cmdutil.show_changeset(ui, repo, opts)
4933 displayer.show(repo[len(repo) - 1])
4933 displayer.show(repo[len(repo) - 1])
4934 displayer.close()
4934 displayer.close()
4935
4935
4936 @command('unbundle',
4936 @command('unbundle',
4937 [('u', 'update', None,
4937 [('u', 'update', None,
4938 _('update to new branch head if changesets were unbundled'))],
4938 _('update to new branch head if changesets were unbundled'))],
4939 _('[-u] FILE...'))
4939 _('[-u] FILE...'))
4940 def unbundle(ui, repo, fname1, *fnames, **opts):
4940 def unbundle(ui, repo, fname1, *fnames, **opts):
4941 """apply one or more changegroup files
4941 """apply one or more changegroup files
4942
4942
4943 Apply one or more compressed changegroup files generated by the
4943 Apply one or more compressed changegroup files generated by the
4944 bundle command.
4944 bundle command.
4945
4945
4946 Returns 0 on success, 1 if an update has unresolved files.
4946 Returns 0 on success, 1 if an update has unresolved files.
4947 """
4947 """
4948 fnames = (fname1,) + fnames
4948 fnames = (fname1,) + fnames
4949
4949
4950 lock = repo.lock()
4950 lock = repo.lock()
4951 wc = repo['.']
4951 wc = repo['.']
4952 try:
4952 try:
4953 for fname in fnames:
4953 for fname in fnames:
4954 f = url.open(ui, fname)
4954 f = url.open(ui, fname)
4955 gen = changegroup.readbundle(f, fname)
4955 gen = changegroup.readbundle(f, fname)
4956 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4956 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4957 lock=lock)
4957 lock=lock)
4958 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4958 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4959 finally:
4959 finally:
4960 lock.release()
4960 lock.release()
4961 return postincoming(ui, repo, modheads, opts.get('update'), None)
4961 return postincoming(ui, repo, modheads, opts.get('update'), None)
4962
4962
4963 @command('^update|up|checkout|co',
4963 @command('^update|up|checkout|co',
4964 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4964 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4965 ('c', 'check', None,
4965 ('c', 'check', None,
4966 _('update across branches if no uncommitted changes')),
4966 _('update across branches if no uncommitted changes')),
4967 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4967 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4968 ('r', 'rev', '', _('revision'), _('REV'))],
4968 ('r', 'rev', '', _('revision'), _('REV'))],
4969 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4969 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4970 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4970 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4971 """update working directory (or switch revisions)
4971 """update working directory (or switch revisions)
4972
4972
4973 Update the repository's working directory to the specified
4973 Update the repository's working directory to the specified
4974 changeset. If no changeset is specified, update to the tip of the
4974 changeset. If no changeset is specified, update to the tip of the
4975 current named branch.
4975 current named branch.
4976
4976
4977 If the changeset is not a descendant of the working directory's
4977 If the changeset is not a descendant of the working directory's
4978 parent, the update is aborted. With the -c/--check option, the
4978 parent, the update is aborted. With the -c/--check option, the
4979 working directory is checked for uncommitted changes; if none are
4979 working directory is checked for uncommitted changes; if none are
4980 found, the working directory is updated to the specified
4980 found, the working directory is updated to the specified
4981 changeset.
4981 changeset.
4982
4982
4983 The following rules apply when the working directory contains
4983 The following rules apply when the working directory contains
4984 uncommitted changes:
4984 uncommitted changes:
4985
4985
4986 1. If neither -c/--check nor -C/--clean is specified, and if
4986 1. If neither -c/--check nor -C/--clean is specified, and if
4987 the requested changeset is an ancestor or descendant of
4987 the requested changeset is an ancestor or descendant of
4988 the working directory's parent, the uncommitted changes
4988 the working directory's parent, the uncommitted changes
4989 are merged into the requested changeset and the merged
4989 are merged into the requested changeset and the merged
4990 result is left uncommitted. If the requested changeset is
4990 result is left uncommitted. If the requested changeset is
4991 not an ancestor or descendant (that is, it is on another
4991 not an ancestor or descendant (that is, it is on another
4992 branch), the update is aborted and the uncommitted changes
4992 branch), the update is aborted and the uncommitted changes
4993 are preserved.
4993 are preserved.
4994
4994
4995 2. With the -c/--check option, the update is aborted and the
4995 2. With the -c/--check option, the update is aborted and the
4996 uncommitted changes are preserved.
4996 uncommitted changes are preserved.
4997
4997
4998 3. With the -C/--clean option, uncommitted changes are discarded and
4998 3. With the -C/--clean option, uncommitted changes are discarded and
4999 the working directory is updated to the requested changeset.
4999 the working directory is updated to the requested changeset.
5000
5000
5001 Use null as the changeset to remove the working directory (like
5001 Use null as the changeset to remove the working directory (like
5002 :hg:`clone -U`).
5002 :hg:`clone -U`).
5003
5003
5004 If you want to update just one file to an older changeset, use
5004 If you want to update just one file to an older changeset, use
5005 :hg:`revert`.
5005 :hg:`revert`.
5006
5006
5007 See :hg:`help dates` for a list of formats valid for -d/--date.
5007 See :hg:`help dates` for a list of formats valid for -d/--date.
5008
5008
5009 Returns 0 on success, 1 if there are unresolved files.
5009 Returns 0 on success, 1 if there are unresolved files.
5010 """
5010 """
5011 if rev and node:
5011 if rev and node:
5012 raise util.Abort(_("please specify just one revision"))
5012 raise util.Abort(_("please specify just one revision"))
5013
5013
5014 if rev is None or rev == '':
5014 if rev is None or rev == '':
5015 rev = node
5015 rev = node
5016
5016
5017 # if we defined a bookmark, we have to remember the original bookmark name
5017 # if we defined a bookmark, we have to remember the original bookmark name
5018 brev = rev
5018 brev = rev
5019 rev = scmutil.revsingle(repo, rev, rev).rev()
5019 rev = scmutil.revsingle(repo, rev, rev).rev()
5020
5020
5021 if check and clean:
5021 if check and clean:
5022 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5022 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5023
5023
5024 if check:
5024 if check:
5025 # we could use dirty() but we can ignore merge and branch trivia
5025 # we could use dirty() but we can ignore merge and branch trivia
5026 c = repo[None]
5026 c = repo[None]
5027 if c.modified() or c.added() or c.removed():
5027 if c.modified() or c.added() or c.removed():
5028 raise util.Abort(_("uncommitted local changes"))
5028 raise util.Abort(_("uncommitted local changes"))
5029
5029
5030 if date:
5030 if date:
5031 if rev is not None:
5031 if rev is not None:
5032 raise util.Abort(_("you can't specify a revision and a date"))
5032 raise util.Abort(_("you can't specify a revision and a date"))
5033 rev = cmdutil.finddate(ui, repo, date)
5033 rev = cmdutil.finddate(ui, repo, date)
5034
5034
5035 if clean or check:
5035 if clean or check:
5036 ret = hg.clean(repo, rev)
5036 ret = hg.clean(repo, rev)
5037 else:
5037 else:
5038 ret = hg.update(repo, rev)
5038 ret = hg.update(repo, rev)
5039
5039
5040 if brev in repo._bookmarks:
5040 if brev in repo._bookmarks:
5041 bookmarks.setcurrent(repo, brev)
5041 bookmarks.setcurrent(repo, brev)
5042
5042
5043 return ret
5043 return ret
5044
5044
5045 @command('verify', [])
5045 @command('verify', [])
5046 def verify(ui, repo):
5046 def verify(ui, repo):
5047 """verify the integrity of the repository
5047 """verify the integrity of the repository
5048
5048
5049 Verify the integrity of the current repository.
5049 Verify the integrity of the current repository.
5050
5050
5051 This will perform an extensive check of the repository's
5051 This will perform an extensive check of the repository's
5052 integrity, validating the hashes and checksums of each entry in
5052 integrity, validating the hashes and checksums of each entry in
5053 the changelog, manifest, and tracked files, as well as the
5053 the changelog, manifest, and tracked files, as well as the
5054 integrity of their crosslinks and indices.
5054 integrity of their crosslinks and indices.
5055
5055
5056 Returns 0 on success, 1 if errors are encountered.
5056 Returns 0 on success, 1 if errors are encountered.
5057 """
5057 """
5058 return hg.verify(repo)
5058 return hg.verify(repo)
5059
5059
5060 @command('version', [])
5060 @command('version', [])
5061 def version_(ui):
5061 def version_(ui):
5062 """output version and copyright information"""
5062 """output version and copyright information"""
5063 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5063 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5064 % util.version())
5064 % util.version())
5065 ui.status(_(
5065 ui.status(_(
5066 "(see http://mercurial.selenic.com for more information)\n"
5066 "(see http://mercurial.selenic.com for more information)\n"
5067 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5067 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5068 "This is free software; see the source for copying conditions. "
5068 "This is free software; see the source for copying conditions. "
5069 "There is NO\nwarranty; "
5069 "There is NO\nwarranty; "
5070 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5070 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5071 ))
5071 ))
5072
5072
5073 norepo = ("clone init version help debugcommands debugcomplete"
5073 norepo = ("clone init version help debugcommands debugcomplete"
5074 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5074 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5075 " debugknown debuggetbundle debugbundle")
5075 " debugknown debuggetbundle debugbundle")
5076 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5076 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5077 " debugdata debugindex debugindexdot debugrevlog")
5077 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1127 +1,1129 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import nullid, nullrev, short, hex
8 from node import nullid, nullrev, short, hex
9 from i18n import _
9 from i18n import _
10 import ancestor, bdiff, error, util, scmutil, subrepo, patch, encoding
10 import ancestor, bdiff, error, util, scmutil, subrepo, patch, encoding
11 import os, errno, stat
11 import os, errno, stat
12
12
13 propertycache = util.propertycache
13 propertycache = util.propertycache
14
14
15 class changectx(object):
15 class changectx(object):
16 """A changecontext object makes access to data related to a particular
16 """A changecontext object makes access to data related to a particular
17 changeset convenient."""
17 changeset convenient."""
18 def __init__(self, repo, changeid=''):
18 def __init__(self, repo, changeid=''):
19 """changeid is a revision number, node, or tag"""
19 """changeid is a revision number, node, or tag"""
20 if changeid == '':
20 if changeid == '':
21 changeid = '.'
21 changeid = '.'
22 self._repo = repo
22 self._repo = repo
23 if isinstance(changeid, (long, int)):
23 if isinstance(changeid, (long, int)):
24 self._rev = changeid
24 self._rev = changeid
25 self._node = self._repo.changelog.node(changeid)
25 self._node = self._repo.changelog.node(changeid)
26 else:
26 else:
27 self._node = self._repo.lookup(changeid)
27 self._node = self._repo.lookup(changeid)
28 self._rev = self._repo.changelog.rev(self._node)
28 self._rev = self._repo.changelog.rev(self._node)
29
29
30 def __str__(self):
30 def __str__(self):
31 return short(self.node())
31 return short(self.node())
32
32
33 def __int__(self):
33 def __int__(self):
34 return self.rev()
34 return self.rev()
35
35
36 def __repr__(self):
36 def __repr__(self):
37 return "<changectx %s>" % str(self)
37 return "<changectx %s>" % str(self)
38
38
39 def __hash__(self):
39 def __hash__(self):
40 try:
40 try:
41 return hash(self._rev)
41 return hash(self._rev)
42 except AttributeError:
42 except AttributeError:
43 return id(self)
43 return id(self)
44
44
45 def __eq__(self, other):
45 def __eq__(self, other):
46 try:
46 try:
47 return self._rev == other._rev
47 return self._rev == other._rev
48 except AttributeError:
48 except AttributeError:
49 return False
49 return False
50
50
51 def __ne__(self, other):
51 def __ne__(self, other):
52 return not (self == other)
52 return not (self == other)
53
53
54 def __nonzero__(self):
54 def __nonzero__(self):
55 return self._rev != nullrev
55 return self._rev != nullrev
56
56
57 @propertycache
57 @propertycache
58 def _changeset(self):
58 def _changeset(self):
59 return self._repo.changelog.read(self.node())
59 return self._repo.changelog.read(self.node())
60
60
61 @propertycache
61 @propertycache
62 def _manifest(self):
62 def _manifest(self):
63 return self._repo.manifest.read(self._changeset[0])
63 return self._repo.manifest.read(self._changeset[0])
64
64
65 @propertycache
65 @propertycache
66 def _manifestdelta(self):
66 def _manifestdelta(self):
67 return self._repo.manifest.readdelta(self._changeset[0])
67 return self._repo.manifest.readdelta(self._changeset[0])
68
68
69 @propertycache
69 @propertycache
70 def _parents(self):
70 def _parents(self):
71 p = self._repo.changelog.parentrevs(self._rev)
71 p = self._repo.changelog.parentrevs(self._rev)
72 if p[1] == nullrev:
72 if p[1] == nullrev:
73 p = p[:-1]
73 p = p[:-1]
74 return [changectx(self._repo, x) for x in p]
74 return [changectx(self._repo, x) for x in p]
75
75
76 @propertycache
76 @propertycache
77 def substate(self):
77 def substate(self):
78 return subrepo.state(self, self._repo.ui)
78 return subrepo.state(self, self._repo.ui)
79
79
80 def __contains__(self, key):
80 def __contains__(self, key):
81 return key in self._manifest
81 return key in self._manifest
82
82
83 def __getitem__(self, key):
83 def __getitem__(self, key):
84 return self.filectx(key)
84 return self.filectx(key)
85
85
86 def __iter__(self):
86 def __iter__(self):
87 for f in sorted(self._manifest):
87 for f in sorted(self._manifest):
88 yield f
88 yield f
89
89
90 def changeset(self):
90 def changeset(self):
91 return self._changeset
91 return self._changeset
92 def manifest(self):
92 def manifest(self):
93 return self._manifest
93 return self._manifest
94 def manifestnode(self):
94 def manifestnode(self):
95 return self._changeset[0]
95 return self._changeset[0]
96
96
97 def rev(self):
97 def rev(self):
98 return self._rev
98 return self._rev
99 def node(self):
99 def node(self):
100 return self._node
100 return self._node
101 def hex(self):
101 def hex(self):
102 return hex(self._node)
102 return hex(self._node)
103 def user(self):
103 def user(self):
104 return self._changeset[1]
104 return self._changeset[1]
105 def date(self):
105 def date(self):
106 return self._changeset[2]
106 return self._changeset[2]
107 def files(self):
107 def files(self):
108 return self._changeset[3]
108 return self._changeset[3]
109 def description(self):
109 def description(self):
110 return self._changeset[4]
110 return self._changeset[4]
111 def branch(self):
111 def branch(self):
112 return encoding.tolocal(self._changeset[5].get("branch"))
112 return encoding.tolocal(self._changeset[5].get("branch"))
113 def extra(self):
113 def extra(self):
114 return self._changeset[5]
114 return self._changeset[5]
115 def tags(self):
115 def tags(self):
116 return self._repo.nodetags(self._node)
116 return self._repo.nodetags(self._node)
117 def bookmarks(self):
117 def bookmarks(self):
118 return self._repo.nodebookmarks(self._node)
118 return self._repo.nodebookmarks(self._node)
119
119
120 def parents(self):
120 def parents(self):
121 """return contexts for each parent changeset"""
121 """return contexts for each parent changeset"""
122 return self._parents
122 return self._parents
123
123
124 def p1(self):
124 def p1(self):
125 return self._parents[0]
125 return self._parents[0]
126
126
127 def p2(self):
127 def p2(self):
128 if len(self._parents) == 2:
128 if len(self._parents) == 2:
129 return self._parents[1]
129 return self._parents[1]
130 return changectx(self._repo, -1)
130 return changectx(self._repo, -1)
131
131
132 def children(self):
132 def children(self):
133 """return contexts for each child changeset"""
133 """return contexts for each child changeset"""
134 c = self._repo.changelog.children(self._node)
134 c = self._repo.changelog.children(self._node)
135 return [changectx(self._repo, x) for x in c]
135 return [changectx(self._repo, x) for x in c]
136
136
137 def ancestors(self):
137 def ancestors(self):
138 for a in self._repo.changelog.ancestors(self._rev):
138 for a in self._repo.changelog.ancestors(self._rev):
139 yield changectx(self._repo, a)
139 yield changectx(self._repo, a)
140
140
141 def descendants(self):
141 def descendants(self):
142 for d in self._repo.changelog.descendants(self._rev):
142 for d in self._repo.changelog.descendants(self._rev):
143 yield changectx(self._repo, d)
143 yield changectx(self._repo, d)
144
144
145 def _fileinfo(self, path):
145 def _fileinfo(self, path):
146 if '_manifest' in self.__dict__:
146 if '_manifest' in self.__dict__:
147 try:
147 try:
148 return self._manifest[path], self._manifest.flags(path)
148 return self._manifest[path], self._manifest.flags(path)
149 except KeyError:
149 except KeyError:
150 raise error.LookupError(self._node, path,
150 raise error.LookupError(self._node, path,
151 _('not found in manifest'))
151 _('not found in manifest'))
152 if '_manifestdelta' in self.__dict__ or path in self.files():
152 if '_manifestdelta' in self.__dict__ or path in self.files():
153 if path in self._manifestdelta:
153 if path in self._manifestdelta:
154 return self._manifestdelta[path], self._manifestdelta.flags(path)
154 return self._manifestdelta[path], self._manifestdelta.flags(path)
155 node, flag = self._repo.manifest.find(self._changeset[0], path)
155 node, flag = self._repo.manifest.find(self._changeset[0], path)
156 if not node:
156 if not node:
157 raise error.LookupError(self._node, path,
157 raise error.LookupError(self._node, path,
158 _('not found in manifest'))
158 _('not found in manifest'))
159
159
160 return node, flag
160 return node, flag
161
161
162 def filenode(self, path):
162 def filenode(self, path):
163 return self._fileinfo(path)[0]
163 return self._fileinfo(path)[0]
164
164
165 def flags(self, path):
165 def flags(self, path):
166 try:
166 try:
167 return self._fileinfo(path)[1]
167 return self._fileinfo(path)[1]
168 except error.LookupError:
168 except error.LookupError:
169 return ''
169 return ''
170
170
171 def filectx(self, path, fileid=None, filelog=None):
171 def filectx(self, path, fileid=None, filelog=None):
172 """get a file context from this changeset"""
172 """get a file context from this changeset"""
173 if fileid is None:
173 if fileid is None:
174 fileid = self.filenode(path)
174 fileid = self.filenode(path)
175 return filectx(self._repo, path, fileid=fileid,
175 return filectx(self._repo, path, fileid=fileid,
176 changectx=self, filelog=filelog)
176 changectx=self, filelog=filelog)
177
177
178 def ancestor(self, c2):
178 def ancestor(self, c2):
179 """
179 """
180 return the ancestor context of self and c2
180 return the ancestor context of self and c2
181 """
181 """
182 # deal with workingctxs
182 # deal with workingctxs
183 n2 = c2._node
183 n2 = c2._node
184 if n2 is None:
184 if n2 is None:
185 n2 = c2._parents[0]._node
185 n2 = c2._parents[0]._node
186 n = self._repo.changelog.ancestor(self._node, n2)
186 n = self._repo.changelog.ancestor(self._node, n2)
187 return changectx(self._repo, n)
187 return changectx(self._repo, n)
188
188
189 def walk(self, match):
189 def walk(self, match):
190 fset = set(match.files())
190 fset = set(match.files())
191 # for dirstate.walk, files=['.'] means "walk the whole tree".
191 # for dirstate.walk, files=['.'] means "walk the whole tree".
192 # follow that here, too
192 # follow that here, too
193 fset.discard('.')
193 fset.discard('.')
194 for fn in self:
194 for fn in self:
195 for ffn in fset:
195 for ffn in fset:
196 # match if the file is the exact name or a directory
196 # match if the file is the exact name or a directory
197 if ffn == fn or fn.startswith("%s/" % ffn):
197 if ffn == fn or fn.startswith("%s/" % ffn):
198 fset.remove(ffn)
198 fset.remove(ffn)
199 break
199 break
200 if match(fn):
200 if match(fn):
201 yield fn
201 yield fn
202 for fn in sorted(fset):
202 for fn in sorted(fset):
203 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
203 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
204 yield fn
204 yield fn
205
205
206 def sub(self, path):
206 def sub(self, path):
207 return subrepo.subrepo(self, path)
207 return subrepo.subrepo(self, path)
208
208
209 def diff(self, ctx2=None, match=None, **opts):
209 def diff(self, ctx2=None, match=None, **opts):
210 """Returns a diff generator for the given contexts and matcher"""
210 """Returns a diff generator for the given contexts and matcher"""
211 if ctx2 is None:
211 if ctx2 is None:
212 ctx2 = self.p1()
212 ctx2 = self.p1()
213 if ctx2 is not None and not isinstance(ctx2, changectx):
213 if ctx2 is not None and not isinstance(ctx2, changectx):
214 ctx2 = self._repo[ctx2]
214 ctx2 = self._repo[ctx2]
215 diffopts = patch.diffopts(self._repo.ui, opts)
215 diffopts = patch.diffopts(self._repo.ui, opts)
216 return patch.diff(self._repo, ctx2.node(), self.node(),
216 return patch.diff(self._repo, ctx2.node(), self.node(),
217 match=match, opts=diffopts)
217 match=match, opts=diffopts)
218
218
219 class filectx(object):
219 class filectx(object):
220 """A filecontext object makes access to data related to a particular
220 """A filecontext object makes access to data related to a particular
221 filerevision convenient."""
221 filerevision convenient."""
222 def __init__(self, repo, path, changeid=None, fileid=None,
222 def __init__(self, repo, path, changeid=None, fileid=None,
223 filelog=None, changectx=None):
223 filelog=None, changectx=None):
224 """changeid can be a changeset revision, node, or tag.
224 """changeid can be a changeset revision, node, or tag.
225 fileid can be a file revision or node."""
225 fileid can be a file revision or node."""
226 self._repo = repo
226 self._repo = repo
227 self._path = path
227 self._path = path
228
228
229 assert (changeid is not None
229 assert (changeid is not None
230 or fileid is not None
230 or fileid is not None
231 or changectx is not None), \
231 or changectx is not None), \
232 ("bad args: changeid=%r, fileid=%r, changectx=%r"
232 ("bad args: changeid=%r, fileid=%r, changectx=%r"
233 % (changeid, fileid, changectx))
233 % (changeid, fileid, changectx))
234
234
235 if filelog:
235 if filelog:
236 self._filelog = filelog
236 self._filelog = filelog
237
237
238 if changeid is not None:
238 if changeid is not None:
239 self._changeid = changeid
239 self._changeid = changeid
240 if changectx is not None:
240 if changectx is not None:
241 self._changectx = changectx
241 self._changectx = changectx
242 if fileid is not None:
242 if fileid is not None:
243 self._fileid = fileid
243 self._fileid = fileid
244
244
245 @propertycache
245 @propertycache
246 def _changectx(self):
246 def _changectx(self):
247 return changectx(self._repo, self._changeid)
247 return changectx(self._repo, self._changeid)
248
248
249 @propertycache
249 @propertycache
250 def _filelog(self):
250 def _filelog(self):
251 return self._repo.file(self._path)
251 return self._repo.file(self._path)
252
252
253 @propertycache
253 @propertycache
254 def _changeid(self):
254 def _changeid(self):
255 if '_changectx' in self.__dict__:
255 if '_changectx' in self.__dict__:
256 return self._changectx.rev()
256 return self._changectx.rev()
257 else:
257 else:
258 return self._filelog.linkrev(self._filerev)
258 return self._filelog.linkrev(self._filerev)
259
259
260 @propertycache
260 @propertycache
261 def _filenode(self):
261 def _filenode(self):
262 if '_fileid' in self.__dict__:
262 if '_fileid' in self.__dict__:
263 return self._filelog.lookup(self._fileid)
263 return self._filelog.lookup(self._fileid)
264 else:
264 else:
265 return self._changectx.filenode(self._path)
265 return self._changectx.filenode(self._path)
266
266
267 @propertycache
267 @propertycache
268 def _filerev(self):
268 def _filerev(self):
269 return self._filelog.rev(self._filenode)
269 return self._filelog.rev(self._filenode)
270
270
271 @propertycache
271 @propertycache
272 def _repopath(self):
272 def _repopath(self):
273 return self._path
273 return self._path
274
274
275 def __nonzero__(self):
275 def __nonzero__(self):
276 try:
276 try:
277 self._filenode
277 self._filenode
278 return True
278 return True
279 except error.LookupError:
279 except error.LookupError:
280 # file is missing
280 # file is missing
281 return False
281 return False
282
282
283 def __str__(self):
283 def __str__(self):
284 return "%s@%s" % (self.path(), short(self.node()))
284 return "%s@%s" % (self.path(), short(self.node()))
285
285
286 def __repr__(self):
286 def __repr__(self):
287 return "<filectx %s>" % str(self)
287 return "<filectx %s>" % str(self)
288
288
289 def __hash__(self):
289 def __hash__(self):
290 try:
290 try:
291 return hash((self._path, self._filenode))
291 return hash((self._path, self._filenode))
292 except AttributeError:
292 except AttributeError:
293 return id(self)
293 return id(self)
294
294
295 def __eq__(self, other):
295 def __eq__(self, other):
296 try:
296 try:
297 return (self._path == other._path
297 return (self._path == other._path
298 and self._filenode == other._filenode)
298 and self._filenode == other._filenode)
299 except AttributeError:
299 except AttributeError:
300 return False
300 return False
301
301
302 def __ne__(self, other):
302 def __ne__(self, other):
303 return not (self == other)
303 return not (self == other)
304
304
305 def filectx(self, fileid):
305 def filectx(self, fileid):
306 '''opens an arbitrary revision of the file without
306 '''opens an arbitrary revision of the file without
307 opening a new filelog'''
307 opening a new filelog'''
308 return filectx(self._repo, self._path, fileid=fileid,
308 return filectx(self._repo, self._path, fileid=fileid,
309 filelog=self._filelog)
309 filelog=self._filelog)
310
310
311 def filerev(self):
311 def filerev(self):
312 return self._filerev
312 return self._filerev
313 def filenode(self):
313 def filenode(self):
314 return self._filenode
314 return self._filenode
315 def flags(self):
315 def flags(self):
316 return self._changectx.flags(self._path)
316 return self._changectx.flags(self._path)
317 def filelog(self):
317 def filelog(self):
318 return self._filelog
318 return self._filelog
319
319
320 def rev(self):
320 def rev(self):
321 if '_changectx' in self.__dict__:
321 if '_changectx' in self.__dict__:
322 return self._changectx.rev()
322 return self._changectx.rev()
323 if '_changeid' in self.__dict__:
323 if '_changeid' in self.__dict__:
324 return self._changectx.rev()
324 return self._changectx.rev()
325 return self._filelog.linkrev(self._filerev)
325 return self._filelog.linkrev(self._filerev)
326
326
327 def linkrev(self):
327 def linkrev(self):
328 return self._filelog.linkrev(self._filerev)
328 return self._filelog.linkrev(self._filerev)
329 def node(self):
329 def node(self):
330 return self._changectx.node()
330 return self._changectx.node()
331 def hex(self):
331 def hex(self):
332 return hex(self.node())
332 return hex(self.node())
333 def user(self):
333 def user(self):
334 return self._changectx.user()
334 return self._changectx.user()
335 def date(self):
335 def date(self):
336 return self._changectx.date()
336 return self._changectx.date()
337 def files(self):
337 def files(self):
338 return self._changectx.files()
338 return self._changectx.files()
339 def description(self):
339 def description(self):
340 return self._changectx.description()
340 return self._changectx.description()
341 def branch(self):
341 def branch(self):
342 return self._changectx.branch()
342 return self._changectx.branch()
343 def extra(self):
343 def extra(self):
344 return self._changectx.extra()
344 return self._changectx.extra()
345 def manifest(self):
345 def manifest(self):
346 return self._changectx.manifest()
346 return self._changectx.manifest()
347 def changectx(self):
347 def changectx(self):
348 return self._changectx
348 return self._changectx
349
349
350 def data(self):
350 def data(self):
351 return self._filelog.read(self._filenode)
351 return self._filelog.read(self._filenode)
352 def path(self):
352 def path(self):
353 return self._path
353 return self._path
354 def size(self):
354 def size(self):
355 return self._filelog.size(self._filerev)
355 return self._filelog.size(self._filerev)
356
356
357 def cmp(self, fctx):
357 def cmp(self, fctx):
358 """compare with other file context
358 """compare with other file context
359
359
360 returns True if different than fctx.
360 returns True if different than fctx.
361 """
361 """
362 if (fctx._filerev is None and self._repo._encodefilterpats
362 if (fctx._filerev is None and self._repo._encodefilterpats
363 or self.size() == fctx.size()):
363 or self.size() == fctx.size()):
364 return self._filelog.cmp(self._filenode, fctx.data())
364 return self._filelog.cmp(self._filenode, fctx.data())
365
365
366 return True
366 return True
367
367
368 def renamed(self):
368 def renamed(self):
369 """check if file was actually renamed in this changeset revision
369 """check if file was actually renamed in this changeset revision
370
370
371 If rename logged in file revision, we report copy for changeset only
371 If rename logged in file revision, we report copy for changeset only
372 if file revisions linkrev points back to the changeset in question
372 if file revisions linkrev points back to the changeset in question
373 or both changeset parents contain different file revisions.
373 or both changeset parents contain different file revisions.
374 """
374 """
375
375
376 renamed = self._filelog.renamed(self._filenode)
376 renamed = self._filelog.renamed(self._filenode)
377 if not renamed:
377 if not renamed:
378 return renamed
378 return renamed
379
379
380 if self.rev() == self.linkrev():
380 if self.rev() == self.linkrev():
381 return renamed
381 return renamed
382
382
383 name = self.path()
383 name = self.path()
384 fnode = self._filenode
384 fnode = self._filenode
385 for p in self._changectx.parents():
385 for p in self._changectx.parents():
386 try:
386 try:
387 if fnode == p.filenode(name):
387 if fnode == p.filenode(name):
388 return None
388 return None
389 except error.LookupError:
389 except error.LookupError:
390 pass
390 pass
391 return renamed
391 return renamed
392
392
393 def parents(self):
393 def parents(self):
394 p = self._path
394 p = self._path
395 fl = self._filelog
395 fl = self._filelog
396 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
396 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
397
397
398 r = self._filelog.renamed(self._filenode)
398 r = self._filelog.renamed(self._filenode)
399 if r:
399 if r:
400 pl[0] = (r[0], r[1], None)
400 pl[0] = (r[0], r[1], None)
401
401
402 return [filectx(self._repo, p, fileid=n, filelog=l)
402 return [filectx(self._repo, p, fileid=n, filelog=l)
403 for p, n, l in pl if n != nullid]
403 for p, n, l in pl if n != nullid]
404
404
405 def p1(self):
405 def p1(self):
406 return self.parents()[0]
406 return self.parents()[0]
407
407
408 def p2(self):
408 def p2(self):
409 p = self.parents()
409 p = self.parents()
410 if len(p) == 2:
410 if len(p) == 2:
411 return p[1]
411 return p[1]
412 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
412 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
413
413
414 def children(self):
414 def children(self):
415 # hard for renames
415 # hard for renames
416 c = self._filelog.children(self._filenode)
416 c = self._filelog.children(self._filenode)
417 return [filectx(self._repo, self._path, fileid=x,
417 return [filectx(self._repo, self._path, fileid=x,
418 filelog=self._filelog) for x in c]
418 filelog=self._filelog) for x in c]
419
419
420 def annotate(self, follow=False, linenumber=None):
420 def annotate(self, follow=False, linenumber=None):
421 '''returns a list of tuples of (ctx, line) for each line
421 '''returns a list of tuples of (ctx, line) for each line
422 in the file, where ctx is the filectx of the node where
422 in the file, where ctx is the filectx of the node where
423 that line was last changed.
423 that line was last changed.
424 This returns tuples of ((ctx, linenumber), line) for each line,
424 This returns tuples of ((ctx, linenumber), line) for each line,
425 if "linenumber" parameter is NOT "None".
425 if "linenumber" parameter is NOT "None".
426 In such tuples, linenumber means one at the first appearance
426 In such tuples, linenumber means one at the first appearance
427 in the managed file.
427 in the managed file.
428 To reduce annotation cost,
428 To reduce annotation cost,
429 this returns fixed value(False is used) as linenumber,
429 this returns fixed value(False is used) as linenumber,
430 if "linenumber" parameter is "False".'''
430 if "linenumber" parameter is "False".'''
431
431
432 def decorate_compat(text, rev):
432 def decorate_compat(text, rev):
433 return ([rev] * len(text.splitlines()), text)
433 return ([rev] * len(text.splitlines()), text)
434
434
435 def without_linenumber(text, rev):
435 def without_linenumber(text, rev):
436 return ([(rev, False)] * len(text.splitlines()), text)
436 return ([(rev, False)] * len(text.splitlines()), text)
437
437
438 def with_linenumber(text, rev):
438 def with_linenumber(text, rev):
439 size = len(text.splitlines())
439 size = len(text.splitlines())
440 return ([(rev, i) for i in xrange(1, size + 1)], text)
440 return ([(rev, i) for i in xrange(1, size + 1)], text)
441
441
442 decorate = (((linenumber is None) and decorate_compat) or
442 decorate = (((linenumber is None) and decorate_compat) or
443 (linenumber and with_linenumber) or
443 (linenumber and with_linenumber) or
444 without_linenumber)
444 without_linenumber)
445
445
446 def pair(parent, child):
446 def pair(parent, child):
447 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
447 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
448 child[0][b1:b2] = parent[0][a1:a2]
448 child[0][b1:b2] = parent[0][a1:a2]
449 return child
449 return child
450
450
451 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
451 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
452 def getctx(path, fileid):
452 def getctx(path, fileid):
453 log = path == self._path and self._filelog or getlog(path)
453 log = path == self._path and self._filelog or getlog(path)
454 return filectx(self._repo, path, fileid=fileid, filelog=log)
454 return filectx(self._repo, path, fileid=fileid, filelog=log)
455 getctx = util.lrucachefunc(getctx)
455 getctx = util.lrucachefunc(getctx)
456
456
457 def parents(f):
457 def parents(f):
458 # we want to reuse filectx objects as much as possible
458 # we want to reuse filectx objects as much as possible
459 p = f._path
459 p = f._path
460 if f._filerev is None: # working dir
460 if f._filerev is None: # working dir
461 pl = [(n.path(), n.filerev()) for n in f.parents()]
461 pl = [(n.path(), n.filerev()) for n in f.parents()]
462 else:
462 else:
463 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
463 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
464
464
465 if follow:
465 if follow:
466 r = f.renamed()
466 r = f.renamed()
467 if r:
467 if r:
468 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
468 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
469
469
470 return [getctx(p, n) for p, n in pl if n != nullrev]
470 return [getctx(p, n) for p, n in pl if n != nullrev]
471
471
472 # use linkrev to find the first changeset where self appeared
472 # use linkrev to find the first changeset where self appeared
473 if self.rev() != self.linkrev():
473 if self.rev() != self.linkrev():
474 base = self.filectx(self.filerev())
474 base = self.filectx(self.filerev())
475 else:
475 else:
476 base = self
476 base = self
477
477
478 # This algorithm would prefer to be recursive, but Python is a
478 # This algorithm would prefer to be recursive, but Python is a
479 # bit recursion-hostile. Instead we do an iterative
479 # bit recursion-hostile. Instead we do an iterative
480 # depth-first search.
480 # depth-first search.
481
481
482 visit = [base]
482 visit = [base]
483 hist = {}
483 hist = {}
484 pcache = {}
484 pcache = {}
485 needed = {base: 1}
485 needed = {base: 1}
486 while visit:
486 while visit:
487 f = visit[-1]
487 f = visit[-1]
488 if f not in pcache:
488 if f not in pcache:
489 pcache[f] = parents(f)
489 pcache[f] = parents(f)
490
490
491 ready = True
491 ready = True
492 pl = pcache[f]
492 pl = pcache[f]
493 for p in pl:
493 for p in pl:
494 if p not in hist:
494 if p not in hist:
495 ready = False
495 ready = False
496 visit.append(p)
496 visit.append(p)
497 needed[p] = needed.get(p, 0) + 1
497 needed[p] = needed.get(p, 0) + 1
498 if ready:
498 if ready:
499 visit.pop()
499 visit.pop()
500 curr = decorate(f.data(), f)
500 curr = decorate(f.data(), f)
501 for p in pl:
501 for p in pl:
502 curr = pair(hist[p], curr)
502 curr = pair(hist[p], curr)
503 if needed[p] == 1:
503 if needed[p] == 1:
504 del hist[p]
504 del hist[p]
505 else:
505 else:
506 needed[p] -= 1
506 needed[p] -= 1
507
507
508 hist[f] = curr
508 hist[f] = curr
509 pcache[f] = []
509 pcache[f] = []
510
510
511 return zip(hist[base][0], hist[base][1].splitlines(True))
511 return zip(hist[base][0], hist[base][1].splitlines(True))
512
512
513 def ancestor(self, fc2, actx=None):
513 def ancestor(self, fc2, actx=None):
514 """
514 """
515 find the common ancestor file context, if any, of self, and fc2
515 find the common ancestor file context, if any, of self, and fc2
516
516
517 If actx is given, it must be the changectx of the common ancestor
517 If actx is given, it must be the changectx of the common ancestor
518 of self's and fc2's respective changesets.
518 of self's and fc2's respective changesets.
519 """
519 """
520
520
521 if actx is None:
521 if actx is None:
522 actx = self.changectx().ancestor(fc2.changectx())
522 actx = self.changectx().ancestor(fc2.changectx())
523
523
524 # the trivial case: changesets are unrelated, files must be too
524 # the trivial case: changesets are unrelated, files must be too
525 if not actx:
525 if not actx:
526 return None
526 return None
527
527
528 # the easy case: no (relevant) renames
528 # the easy case: no (relevant) renames
529 if fc2.path() == self.path() and self.path() in actx:
529 if fc2.path() == self.path() and self.path() in actx:
530 return actx[self.path()]
530 return actx[self.path()]
531 acache = {}
531 acache = {}
532
532
533 # prime the ancestor cache for the working directory
533 # prime the ancestor cache for the working directory
534 for c in (self, fc2):
534 for c in (self, fc2):
535 if c._filerev is None:
535 if c._filerev is None:
536 pl = [(n.path(), n.filenode()) for n in c.parents()]
536 pl = [(n.path(), n.filenode()) for n in c.parents()]
537 acache[(c._path, None)] = pl
537 acache[(c._path, None)] = pl
538
538
539 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
539 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
540 def parents(vertex):
540 def parents(vertex):
541 if vertex in acache:
541 if vertex in acache:
542 return acache[vertex]
542 return acache[vertex]
543 f, n = vertex
543 f, n = vertex
544 if f not in flcache:
544 if f not in flcache:
545 flcache[f] = self._repo.file(f)
545 flcache[f] = self._repo.file(f)
546 fl = flcache[f]
546 fl = flcache[f]
547 pl = [(f, p) for p in fl.parents(n) if p != nullid]
547 pl = [(f, p) for p in fl.parents(n) if p != nullid]
548 re = fl.renamed(n)
548 re = fl.renamed(n)
549 if re:
549 if re:
550 pl.append(re)
550 pl.append(re)
551 acache[vertex] = pl
551 acache[vertex] = pl
552 return pl
552 return pl
553
553
554 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
554 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
555 v = ancestor.ancestor(a, b, parents)
555 v = ancestor.ancestor(a, b, parents)
556 if v:
556 if v:
557 f, n = v
557 f, n = v
558 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
558 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
559
559
560 return None
560 return None
561
561
562 def ancestors(self):
562 def ancestors(self):
563 visit = {}
563 visit = {}
564 c = self
564 c = self
565 while True:
565 while True:
566 for parent in c.parents():
566 for parent in c.parents():
567 visit[(parent.rev(), parent.node())] = parent
567 visit[(parent.rev(), parent.node())] = parent
568 if not visit:
568 if not visit:
569 break
569 break
570 c = visit.pop(max(visit))
570 c = visit.pop(max(visit))
571 yield c
571 yield c
572
572
573 class workingctx(changectx):
573 class workingctx(changectx):
574 """A workingctx object makes access to data related to
574 """A workingctx object makes access to data related to
575 the current working directory convenient.
575 the current working directory convenient.
576 date - any valid date string or (unixtime, offset), or None.
576 date - any valid date string or (unixtime, offset), or None.
577 user - username string, or None.
577 user - username string, or None.
578 extra - a dictionary of extra values, or None.
578 extra - a dictionary of extra values, or None.
579 changes - a list of file lists as returned by localrepo.status()
579 changes - a list of file lists as returned by localrepo.status()
580 or None to use the repository status.
580 or None to use the repository status.
581 """
581 """
582 def __init__(self, repo, text="", user=None, date=None, extra=None,
582 def __init__(self, repo, text="", user=None, date=None, extra=None,
583 changes=None):
583 changes=None):
584 self._repo = repo
584 self._repo = repo
585 self._rev = None
585 self._rev = None
586 self._node = None
586 self._node = None
587 self._text = text
587 self._text = text
588 if date:
588 if date:
589 self._date = util.parsedate(date)
589 self._date = util.parsedate(date)
590 if user:
590 if user:
591 self._user = user
591 self._user = user
592 if changes:
592 if changes:
593 self._status = list(changes[:4])
593 self._status = list(changes[:4])
594 self._unknown = changes[4]
594 self._unknown = changes[4]
595 self._ignored = changes[5]
595 self._ignored = changes[5]
596 self._clean = changes[6]
596 self._clean = changes[6]
597 else:
597 else:
598 self._unknown = None
598 self._unknown = None
599 self._ignored = None
599 self._ignored = None
600 self._clean = None
600 self._clean = None
601
601
602 self._extra = {}
602 self._extra = {}
603 if extra:
603 if extra:
604 self._extra = extra.copy()
604 self._extra = extra.copy()
605 if 'branch' not in self._extra:
605 if 'branch' not in self._extra:
606 try:
606 try:
607 branch = encoding.fromlocal(self._repo.dirstate.branch())
607 branch = encoding.fromlocal(self._repo.dirstate.branch())
608 except UnicodeDecodeError:
608 except UnicodeDecodeError:
609 raise util.Abort(_('branch name not in UTF-8!'))
609 raise util.Abort(_('branch name not in UTF-8!'))
610 self._extra['branch'] = branch
610 self._extra['branch'] = branch
611 if self._extra['branch'] == '':
611 if self._extra['branch'] == '':
612 self._extra['branch'] = 'default'
612 self._extra['branch'] = 'default'
613
613
614 def __str__(self):
614 def __str__(self):
615 return str(self._parents[0]) + "+"
615 return str(self._parents[0]) + "+"
616
616
617 def __repr__(self):
617 def __repr__(self):
618 return "<workingctx %s>" % str(self)
618 return "<workingctx %s>" % str(self)
619
619
620 def __nonzero__(self):
620 def __nonzero__(self):
621 return True
621 return True
622
622
623 def __contains__(self, key):
623 def __contains__(self, key):
624 return self._repo.dirstate[key] not in "?r"
624 return self._repo.dirstate[key] not in "?r"
625
625
626 @propertycache
626 @propertycache
627 def _manifest(self):
627 def _manifest(self):
628 """generate a manifest corresponding to the working directory"""
628 """generate a manifest corresponding to the working directory"""
629
629
630 if self._unknown is None:
630 if self._unknown is None:
631 self.status(unknown=True)
631 self.status(unknown=True)
632
632
633 man = self._parents[0].manifest().copy()
633 man = self._parents[0].manifest().copy()
634 copied = self._repo.dirstate.copies()
634 copied = self._repo.dirstate.copies()
635 if len(self._parents) > 1:
635 if len(self._parents) > 1:
636 man2 = self.p2().manifest()
636 man2 = self.p2().manifest()
637 def getman(f):
637 def getman(f):
638 if f in man:
638 if f in man:
639 return man
639 return man
640 return man2
640 return man2
641 else:
641 else:
642 getman = lambda f: man
642 getman = lambda f: man
643 def cf(f):
643 def cf(f):
644 f = copied.get(f, f)
644 f = copied.get(f, f)
645 return getman(f).flags(f)
645 return getman(f).flags(f)
646 ff = self._repo.dirstate.flagfunc(cf)
646 ff = self._repo.dirstate.flagfunc(cf)
647 modified, added, removed, deleted = self._status
647 modified, added, removed, deleted = self._status
648 unknown = self._unknown
648 unknown = self._unknown
649 for i, l in (("a", added), ("m", modified), ("u", unknown)):
649 for i, l in (("a", added), ("m", modified), ("u", unknown)):
650 for f in l:
650 for f in l:
651 orig = copied.get(f, f)
651 orig = copied.get(f, f)
652 man[f] = getman(orig).get(orig, nullid) + i
652 man[f] = getman(orig).get(orig, nullid) + i
653 try:
653 try:
654 man.set(f, ff(f))
654 man.set(f, ff(f))
655 except OSError:
655 except OSError:
656 pass
656 pass
657
657
658 for f in deleted + removed:
658 for f in deleted + removed:
659 if f in man:
659 if f in man:
660 del man[f]
660 del man[f]
661
661
662 return man
662 return man
663
663
664 def __iter__(self):
664 def __iter__(self):
665 d = self._repo.dirstate
665 d = self._repo.dirstate
666 for f in d:
666 for f in d:
667 if d[f] != 'r':
667 if d[f] != 'r':
668 yield f
668 yield f
669
669
670 @propertycache
670 @propertycache
671 def _status(self):
671 def _status(self):
672 return self._repo.status()[:4]
672 return self._repo.status()[:4]
673
673
674 @propertycache
674 @propertycache
675 def _user(self):
675 def _user(self):
676 return self._repo.ui.username()
676 return self._repo.ui.username()
677
677
678 @propertycache
678 @propertycache
679 def _date(self):
679 def _date(self):
680 return util.makedate()
680 return util.makedate()
681
681
682 @propertycache
682 @propertycache
683 def _parents(self):
683 def _parents(self):
684 p = self._repo.dirstate.parents()
684 p = self._repo.dirstate.parents()
685 if p[1] == nullid:
685 if p[1] == nullid:
686 p = p[:-1]
686 p = p[:-1]
687 self._parents = [changectx(self._repo, x) for x in p]
687 self._parents = [changectx(self._repo, x) for x in p]
688 return self._parents
688 return self._parents
689
689
690 def status(self, ignored=False, clean=False, unknown=False):
690 def status(self, ignored=False, clean=False, unknown=False):
691 """Explicit status query
691 """Explicit status query
692 Unless this method is used to query the working copy status, the
692 Unless this method is used to query the working copy status, the
693 _status property will implicitly read the status using its default
693 _status property will implicitly read the status using its default
694 arguments."""
694 arguments."""
695 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
695 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
696 self._unknown = self._ignored = self._clean = None
696 self._unknown = self._ignored = self._clean = None
697 if unknown:
697 if unknown:
698 self._unknown = stat[4]
698 self._unknown = stat[4]
699 if ignored:
699 if ignored:
700 self._ignored = stat[5]
700 self._ignored = stat[5]
701 if clean:
701 if clean:
702 self._clean = stat[6]
702 self._clean = stat[6]
703 self._status = stat[:4]
703 self._status = stat[:4]
704 return stat
704 return stat
705
705
706 def manifest(self):
706 def manifest(self):
707 return self._manifest
707 return self._manifest
708 def user(self):
708 def user(self):
709 return self._user or self._repo.ui.username()
709 return self._user or self._repo.ui.username()
710 def date(self):
710 def date(self):
711 return self._date
711 return self._date
712 def description(self):
712 def description(self):
713 return self._text
713 return self._text
714 def files(self):
714 def files(self):
715 return sorted(self._status[0] + self._status[1] + self._status[2])
715 return sorted(self._status[0] + self._status[1] + self._status[2])
716
716
717 def modified(self):
717 def modified(self):
718 return self._status[0]
718 return self._status[0]
719 def added(self):
719 def added(self):
720 return self._status[1]
720 return self._status[1]
721 def removed(self):
721 def removed(self):
722 return self._status[2]
722 return self._status[2]
723 def deleted(self):
723 def deleted(self):
724 return self._status[3]
724 return self._status[3]
725 def unknown(self):
725 def unknown(self):
726 assert self._unknown is not None # must call status first
726 assert self._unknown is not None # must call status first
727 return self._unknown
727 return self._unknown
728 def ignored(self):
728 def ignored(self):
729 assert self._ignored is not None # must call status first
729 assert self._ignored is not None # must call status first
730 return self._ignored
730 return self._ignored
731 def clean(self):
731 def clean(self):
732 assert self._clean is not None # must call status first
732 assert self._clean is not None # must call status first
733 return self._clean
733 return self._clean
734 def branch(self):
734 def branch(self):
735 return encoding.tolocal(self._extra['branch'])
735 return encoding.tolocal(self._extra['branch'])
736 def extra(self):
736 def extra(self):
737 return self._extra
737 return self._extra
738
738
739 def tags(self):
739 def tags(self):
740 t = []
740 t = []
741 for p in self.parents():
741 for p in self.parents():
742 t.extend(p.tags())
742 t.extend(p.tags())
743 return t
743 return t
744
744
745 def bookmarks(self):
745 def bookmarks(self):
746 b = []
746 b = []
747 for p in self.parents():
747 for p in self.parents():
748 b.extend(p.bookmarks())
748 b.extend(p.bookmarks())
749 return b
749 return b
750
750
751 def children(self):
751 def children(self):
752 return []
752 return []
753
753
754 def flags(self, path):
754 def flags(self, path):
755 if '_manifest' in self.__dict__:
755 if '_manifest' in self.__dict__:
756 try:
756 try:
757 return self._manifest.flags(path)
757 return self._manifest.flags(path)
758 except KeyError:
758 except KeyError:
759 return ''
759 return ''
760
760
761 orig = self._repo.dirstate.copies().get(path, path)
761 orig = self._repo.dirstate.copies().get(path, path)
762
762
763 def findflag(ctx):
763 def findflag(ctx):
764 mnode = ctx.changeset()[0]
764 mnode = ctx.changeset()[0]
765 node, flag = self._repo.manifest.find(mnode, orig)
765 node, flag = self._repo.manifest.find(mnode, orig)
766 ff = self._repo.dirstate.flagfunc(lambda x: flag or '')
766 ff = self._repo.dirstate.flagfunc(lambda x: flag or '')
767 try:
767 try:
768 return ff(path)
768 return ff(path)
769 except OSError:
769 except OSError:
770 pass
770 pass
771
771
772 flag = findflag(self._parents[0])
772 flag = findflag(self._parents[0])
773 if flag is None and len(self.parents()) > 1:
773 if flag is None and len(self.parents()) > 1:
774 flag = findflag(self._parents[1])
774 flag = findflag(self._parents[1])
775 if flag is None or self._repo.dirstate[path] == 'r':
775 if flag is None or self._repo.dirstate[path] == 'r':
776 return ''
776 return ''
777 return flag
777 return flag
778
778
779 def filectx(self, path, filelog=None):
779 def filectx(self, path, filelog=None):
780 """get a file context from the working directory"""
780 """get a file context from the working directory"""
781 return workingfilectx(self._repo, path, workingctx=self,
781 return workingfilectx(self._repo, path, workingctx=self,
782 filelog=filelog)
782 filelog=filelog)
783
783
784 def ancestor(self, c2):
784 def ancestor(self, c2):
785 """return the ancestor context of self and c2"""
785 """return the ancestor context of self and c2"""
786 return self._parents[0].ancestor(c2) # punt on two parents for now
786 return self._parents[0].ancestor(c2) # punt on two parents for now
787
787
788 def walk(self, match):
788 def walk(self, match):
789 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
789 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
790 True, False))
790 True, False))
791
791
792 def dirty(self, missing=False):
792 def dirty(self, missing=False):
793 "check whether a working directory is modified"
793 "check whether a working directory is modified"
794 # check subrepos first
794 # check subrepos first
795 for s in self.substate:
795 for s in self.substate:
796 if self.sub(s).dirty():
796 if self.sub(s).dirty():
797 return True
797 return True
798 # check current working dir
798 # check current working dir
799 return (self.p2() or self.branch() != self.p1().branch() or
799 return (self.p2() or self.branch() != self.p1().branch() or
800 self.modified() or self.added() or self.removed() or
800 self.modified() or self.added() or self.removed() or
801 (missing and self.deleted()))
801 (missing and self.deleted()))
802
802
803 def add(self, list, prefix=""):
803 def add(self, list, prefix=""):
804 join = lambda f: os.path.join(prefix, f)
804 join = lambda f: os.path.join(prefix, f)
805 wlock = self._repo.wlock()
805 wlock = self._repo.wlock()
806 ui, ds = self._repo.ui, self._repo.dirstate
806 ui, ds = self._repo.ui, self._repo.dirstate
807 try:
807 try:
808 rejected = []
808 rejected = []
809 for f in list:
809 for f in list:
810 scmutil.checkportable(ui, join(f))
810 scmutil.checkportable(ui, join(f))
811 p = self._repo.wjoin(f)
811 p = self._repo.wjoin(f)
812 try:
812 try:
813 st = os.lstat(p)
813 st = os.lstat(p)
814 except OSError:
814 except OSError:
815 ui.warn(_("%s does not exist!\n") % join(f))
815 ui.warn(_("%s does not exist!\n") % join(f))
816 rejected.append(f)
816 rejected.append(f)
817 continue
817 continue
818 if st.st_size > 10000000:
818 if st.st_size > 10000000:
819 ui.warn(_("%s: up to %d MB of RAM may be required "
819 ui.warn(_("%s: up to %d MB of RAM may be required "
820 "to manage this file\n"
820 "to manage this file\n"
821 "(use 'hg revert %s' to cancel the "
821 "(use 'hg revert %s' to cancel the "
822 "pending addition)\n")
822 "pending addition)\n")
823 % (f, 3 * st.st_size // 1000000, join(f)))
823 % (f, 3 * st.st_size // 1000000, join(f)))
824 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
824 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
825 ui.warn(_("%s not added: only files and symlinks "
825 ui.warn(_("%s not added: only files and symlinks "
826 "supported currently\n") % join(f))
826 "supported currently\n") % join(f))
827 rejected.append(p)
827 rejected.append(p)
828 elif ds[f] in 'amn':
828 elif ds[f] in 'amn':
829 ui.warn(_("%s already tracked!\n") % join(f))
829 ui.warn(_("%s already tracked!\n") % join(f))
830 elif ds[f] == 'r':
830 elif ds[f] == 'r':
831 ds.normallookup(f)
831 ds.normallookup(f)
832 else:
832 else:
833 ds.add(f)
833 ds.add(f)
834 return rejected
834 return rejected
835 finally:
835 finally:
836 wlock.release()
836 wlock.release()
837
837
838 def forget(self, list):
838 def forget(self, files):
839 wlock = self._repo.wlock()
839 wlock = self._repo.wlock()
840 try:
840 try:
841 for f in list:
841 for f in files:
842 if self._repo.dirstate[f] != 'a':
842 if self._repo.dirstate[f] != 'a':
843 self._repo.ui.warn(_("%s not added!\n") % f)
843 self._repo.dirstate.remove(f)
844 elif f not in self._repo.dirstate:
845 self._repo.ui.warn(_("%s not tracked!\n") % f)
844 else:
846 else:
845 self._repo.dirstate.drop(f)
847 self._repo.dirstate.drop(f)
846 finally:
848 finally:
847 wlock.release()
849 wlock.release()
848
850
849 def ancestors(self):
851 def ancestors(self):
850 for a in self._repo.changelog.ancestors(
852 for a in self._repo.changelog.ancestors(
851 *[p.rev() for p in self._parents]):
853 *[p.rev() for p in self._parents]):
852 yield changectx(self._repo, a)
854 yield changectx(self._repo, a)
853
855
854 def remove(self, list, unlink=False):
856 def remove(self, list, unlink=False):
855 wlock = self._repo.wlock()
857 wlock = self._repo.wlock()
856 try:
858 try:
857 if unlink:
859 if unlink:
858 for f in list:
860 for f in list:
859 try:
861 try:
860 util.unlinkpath(self._repo.wjoin(f))
862 util.unlinkpath(self._repo.wjoin(f))
861 except OSError, inst:
863 except OSError, inst:
862 if inst.errno != errno.ENOENT:
864 if inst.errno != errno.ENOENT:
863 raise
865 raise
864 for f in list:
866 for f in list:
865 if self._repo.dirstate[f] == 'a':
867 if self._repo.dirstate[f] == 'a':
866 self._repo.dirstate.drop(f)
868 self._repo.dirstate.drop(f)
867 elif f not in self._repo.dirstate:
869 elif f not in self._repo.dirstate:
868 self._repo.ui.warn(_("%s not tracked!\n") % f)
870 self._repo.ui.warn(_("%s not tracked!\n") % f)
869 else:
871 else:
870 self._repo.dirstate.remove(f)
872 self._repo.dirstate.remove(f)
871 finally:
873 finally:
872 wlock.release()
874 wlock.release()
873
875
874 def undelete(self, list):
876 def undelete(self, list):
875 pctxs = self.parents()
877 pctxs = self.parents()
876 wlock = self._repo.wlock()
878 wlock = self._repo.wlock()
877 try:
879 try:
878 for f in list:
880 for f in list:
879 if self._repo.dirstate[f] != 'r':
881 if self._repo.dirstate[f] != 'r':
880 self._repo.ui.warn(_("%s not removed!\n") % f)
882 self._repo.ui.warn(_("%s not removed!\n") % f)
881 else:
883 else:
882 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
884 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
883 t = fctx.data()
885 t = fctx.data()
884 self._repo.wwrite(f, t, fctx.flags())
886 self._repo.wwrite(f, t, fctx.flags())
885 self._repo.dirstate.normal(f)
887 self._repo.dirstate.normal(f)
886 finally:
888 finally:
887 wlock.release()
889 wlock.release()
888
890
889 def copy(self, source, dest):
891 def copy(self, source, dest):
890 p = self._repo.wjoin(dest)
892 p = self._repo.wjoin(dest)
891 if not os.path.lexists(p):
893 if not os.path.lexists(p):
892 self._repo.ui.warn(_("%s does not exist!\n") % dest)
894 self._repo.ui.warn(_("%s does not exist!\n") % dest)
893 elif not (os.path.isfile(p) or os.path.islink(p)):
895 elif not (os.path.isfile(p) or os.path.islink(p)):
894 self._repo.ui.warn(_("copy failed: %s is not a file or a "
896 self._repo.ui.warn(_("copy failed: %s is not a file or a "
895 "symbolic link\n") % dest)
897 "symbolic link\n") % dest)
896 else:
898 else:
897 wlock = self._repo.wlock()
899 wlock = self._repo.wlock()
898 try:
900 try:
899 if self._repo.dirstate[dest] in '?r':
901 if self._repo.dirstate[dest] in '?r':
900 self._repo.dirstate.add(dest)
902 self._repo.dirstate.add(dest)
901 self._repo.dirstate.copy(source, dest)
903 self._repo.dirstate.copy(source, dest)
902 finally:
904 finally:
903 wlock.release()
905 wlock.release()
904
906
905 class workingfilectx(filectx):
907 class workingfilectx(filectx):
906 """A workingfilectx object makes access to data related to a particular
908 """A workingfilectx object makes access to data related to a particular
907 file in the working directory convenient."""
909 file in the working directory convenient."""
908 def __init__(self, repo, path, filelog=None, workingctx=None):
910 def __init__(self, repo, path, filelog=None, workingctx=None):
909 """changeid can be a changeset revision, node, or tag.
911 """changeid can be a changeset revision, node, or tag.
910 fileid can be a file revision or node."""
912 fileid can be a file revision or node."""
911 self._repo = repo
913 self._repo = repo
912 self._path = path
914 self._path = path
913 self._changeid = None
915 self._changeid = None
914 self._filerev = self._filenode = None
916 self._filerev = self._filenode = None
915
917
916 if filelog:
918 if filelog:
917 self._filelog = filelog
919 self._filelog = filelog
918 if workingctx:
920 if workingctx:
919 self._changectx = workingctx
921 self._changectx = workingctx
920
922
921 @propertycache
923 @propertycache
922 def _changectx(self):
924 def _changectx(self):
923 return workingctx(self._repo)
925 return workingctx(self._repo)
924
926
925 def __nonzero__(self):
927 def __nonzero__(self):
926 return True
928 return True
927
929
928 def __str__(self):
930 def __str__(self):
929 return "%s@%s" % (self.path(), self._changectx)
931 return "%s@%s" % (self.path(), self._changectx)
930
932
931 def __repr__(self):
933 def __repr__(self):
932 return "<workingfilectx %s>" % str(self)
934 return "<workingfilectx %s>" % str(self)
933
935
934 def data(self):
936 def data(self):
935 return self._repo.wread(self._path)
937 return self._repo.wread(self._path)
936 def renamed(self):
938 def renamed(self):
937 rp = self._repo.dirstate.copied(self._path)
939 rp = self._repo.dirstate.copied(self._path)
938 if not rp:
940 if not rp:
939 return None
941 return None
940 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
942 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
941
943
942 def parents(self):
944 def parents(self):
943 '''return parent filectxs, following copies if necessary'''
945 '''return parent filectxs, following copies if necessary'''
944 def filenode(ctx, path):
946 def filenode(ctx, path):
945 return ctx._manifest.get(path, nullid)
947 return ctx._manifest.get(path, nullid)
946
948
947 path = self._path
949 path = self._path
948 fl = self._filelog
950 fl = self._filelog
949 pcl = self._changectx._parents
951 pcl = self._changectx._parents
950 renamed = self.renamed()
952 renamed = self.renamed()
951
953
952 if renamed:
954 if renamed:
953 pl = [renamed + (None,)]
955 pl = [renamed + (None,)]
954 else:
956 else:
955 pl = [(path, filenode(pcl[0], path), fl)]
957 pl = [(path, filenode(pcl[0], path), fl)]
956
958
957 for pc in pcl[1:]:
959 for pc in pcl[1:]:
958 pl.append((path, filenode(pc, path), fl))
960 pl.append((path, filenode(pc, path), fl))
959
961
960 return [filectx(self._repo, p, fileid=n, filelog=l)
962 return [filectx(self._repo, p, fileid=n, filelog=l)
961 for p, n, l in pl if n != nullid]
963 for p, n, l in pl if n != nullid]
962
964
963 def children(self):
965 def children(self):
964 return []
966 return []
965
967
966 def size(self):
968 def size(self):
967 return os.lstat(self._repo.wjoin(self._path)).st_size
969 return os.lstat(self._repo.wjoin(self._path)).st_size
968 def date(self):
970 def date(self):
969 t, tz = self._changectx.date()
971 t, tz = self._changectx.date()
970 try:
972 try:
971 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
973 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
972 except OSError, err:
974 except OSError, err:
973 if err.errno != errno.ENOENT:
975 if err.errno != errno.ENOENT:
974 raise
976 raise
975 return (t, tz)
977 return (t, tz)
976
978
977 def cmp(self, fctx):
979 def cmp(self, fctx):
978 """compare with other file context
980 """compare with other file context
979
981
980 returns True if different than fctx.
982 returns True if different than fctx.
981 """
983 """
982 # fctx should be a filectx (not a wfctx)
984 # fctx should be a filectx (not a wfctx)
983 # invert comparison to reuse the same code path
985 # invert comparison to reuse the same code path
984 return fctx.cmp(self)
986 return fctx.cmp(self)
985
987
986 class memctx(object):
988 class memctx(object):
987 """Use memctx to perform in-memory commits via localrepo.commitctx().
989 """Use memctx to perform in-memory commits via localrepo.commitctx().
988
990
989 Revision information is supplied at initialization time while
991 Revision information is supplied at initialization time while
990 related files data and is made available through a callback
992 related files data and is made available through a callback
991 mechanism. 'repo' is the current localrepo, 'parents' is a
993 mechanism. 'repo' is the current localrepo, 'parents' is a
992 sequence of two parent revisions identifiers (pass None for every
994 sequence of two parent revisions identifiers (pass None for every
993 missing parent), 'text' is the commit message and 'files' lists
995 missing parent), 'text' is the commit message and 'files' lists
994 names of files touched by the revision (normalized and relative to
996 names of files touched by the revision (normalized and relative to
995 repository root).
997 repository root).
996
998
997 filectxfn(repo, memctx, path) is a callable receiving the
999 filectxfn(repo, memctx, path) is a callable receiving the
998 repository, the current memctx object and the normalized path of
1000 repository, the current memctx object and the normalized path of
999 requested file, relative to repository root. It is fired by the
1001 requested file, relative to repository root. It is fired by the
1000 commit function for every file in 'files', but calls order is
1002 commit function for every file in 'files', but calls order is
1001 undefined. If the file is available in the revision being
1003 undefined. If the file is available in the revision being
1002 committed (updated or added), filectxfn returns a memfilectx
1004 committed (updated or added), filectxfn returns a memfilectx
1003 object. If the file was removed, filectxfn raises an
1005 object. If the file was removed, filectxfn raises an
1004 IOError. Moved files are represented by marking the source file
1006 IOError. Moved files are represented by marking the source file
1005 removed and the new file added with copy information (see
1007 removed and the new file added with copy information (see
1006 memfilectx).
1008 memfilectx).
1007
1009
1008 user receives the committer name and defaults to current
1010 user receives the committer name and defaults to current
1009 repository username, date is the commit date in any format
1011 repository username, date is the commit date in any format
1010 supported by util.parsedate() and defaults to current date, extra
1012 supported by util.parsedate() and defaults to current date, extra
1011 is a dictionary of metadata or is left empty.
1013 is a dictionary of metadata or is left empty.
1012 """
1014 """
1013 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1015 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1014 date=None, extra=None):
1016 date=None, extra=None):
1015 self._repo = repo
1017 self._repo = repo
1016 self._rev = None
1018 self._rev = None
1017 self._node = None
1019 self._node = None
1018 self._text = text
1020 self._text = text
1019 self._date = date and util.parsedate(date) or util.makedate()
1021 self._date = date and util.parsedate(date) or util.makedate()
1020 self._user = user
1022 self._user = user
1021 parents = [(p or nullid) for p in parents]
1023 parents = [(p or nullid) for p in parents]
1022 p1, p2 = parents
1024 p1, p2 = parents
1023 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1025 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1024 files = sorted(set(files))
1026 files = sorted(set(files))
1025 self._status = [files, [], [], [], []]
1027 self._status = [files, [], [], [], []]
1026 self._filectxfn = filectxfn
1028 self._filectxfn = filectxfn
1027
1029
1028 self._extra = extra and extra.copy() or {}
1030 self._extra = extra and extra.copy() or {}
1029 if 'branch' not in self._extra:
1031 if 'branch' not in self._extra:
1030 self._extra['branch'] = 'default'
1032 self._extra['branch'] = 'default'
1031 elif self._extra.get('branch') == '':
1033 elif self._extra.get('branch') == '':
1032 self._extra['branch'] = 'default'
1034 self._extra['branch'] = 'default'
1033
1035
1034 def __str__(self):
1036 def __str__(self):
1035 return str(self._parents[0]) + "+"
1037 return str(self._parents[0]) + "+"
1036
1038
1037 def __int__(self):
1039 def __int__(self):
1038 return self._rev
1040 return self._rev
1039
1041
1040 def __nonzero__(self):
1042 def __nonzero__(self):
1041 return True
1043 return True
1042
1044
1043 def __getitem__(self, key):
1045 def __getitem__(self, key):
1044 return self.filectx(key)
1046 return self.filectx(key)
1045
1047
1046 def p1(self):
1048 def p1(self):
1047 return self._parents[0]
1049 return self._parents[0]
1048 def p2(self):
1050 def p2(self):
1049 return self._parents[1]
1051 return self._parents[1]
1050
1052
1051 def user(self):
1053 def user(self):
1052 return self._user or self._repo.ui.username()
1054 return self._user or self._repo.ui.username()
1053 def date(self):
1055 def date(self):
1054 return self._date
1056 return self._date
1055 def description(self):
1057 def description(self):
1056 return self._text
1058 return self._text
1057 def files(self):
1059 def files(self):
1058 return self.modified()
1060 return self.modified()
1059 def modified(self):
1061 def modified(self):
1060 return self._status[0]
1062 return self._status[0]
1061 def added(self):
1063 def added(self):
1062 return self._status[1]
1064 return self._status[1]
1063 def removed(self):
1065 def removed(self):
1064 return self._status[2]
1066 return self._status[2]
1065 def deleted(self):
1067 def deleted(self):
1066 return self._status[3]
1068 return self._status[3]
1067 def unknown(self):
1069 def unknown(self):
1068 return self._status[4]
1070 return self._status[4]
1069 def ignored(self):
1071 def ignored(self):
1070 return self._status[5]
1072 return self._status[5]
1071 def clean(self):
1073 def clean(self):
1072 return self._status[6]
1074 return self._status[6]
1073 def branch(self):
1075 def branch(self):
1074 return encoding.tolocal(self._extra['branch'])
1076 return encoding.tolocal(self._extra['branch'])
1075 def extra(self):
1077 def extra(self):
1076 return self._extra
1078 return self._extra
1077 def flags(self, f):
1079 def flags(self, f):
1078 return self[f].flags()
1080 return self[f].flags()
1079
1081
1080 def parents(self):
1082 def parents(self):
1081 """return contexts for each parent changeset"""
1083 """return contexts for each parent changeset"""
1082 return self._parents
1084 return self._parents
1083
1085
1084 def filectx(self, path, filelog=None):
1086 def filectx(self, path, filelog=None):
1085 """get a file context from the working directory"""
1087 """get a file context from the working directory"""
1086 return self._filectxfn(self._repo, self, path)
1088 return self._filectxfn(self._repo, self, path)
1087
1089
1088 def commit(self):
1090 def commit(self):
1089 """commit context to the repo"""
1091 """commit context to the repo"""
1090 return self._repo.commitctx(self)
1092 return self._repo.commitctx(self)
1091
1093
1092 class memfilectx(object):
1094 class memfilectx(object):
1093 """memfilectx represents an in-memory file to commit.
1095 """memfilectx represents an in-memory file to commit.
1094
1096
1095 See memctx for more details.
1097 See memctx for more details.
1096 """
1098 """
1097 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1099 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1098 """
1100 """
1099 path is the normalized file path relative to repository root.
1101 path is the normalized file path relative to repository root.
1100 data is the file content as a string.
1102 data is the file content as a string.
1101 islink is True if the file is a symbolic link.
1103 islink is True if the file is a symbolic link.
1102 isexec is True if the file is executable.
1104 isexec is True if the file is executable.
1103 copied is the source file path if current file was copied in the
1105 copied is the source file path if current file was copied in the
1104 revision being committed, or None."""
1106 revision being committed, or None."""
1105 self._path = path
1107 self._path = path
1106 self._data = data
1108 self._data = data
1107 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1109 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1108 self._copied = None
1110 self._copied = None
1109 if copied:
1111 if copied:
1110 self._copied = (copied, nullid)
1112 self._copied = (copied, nullid)
1111
1113
1112 def __nonzero__(self):
1114 def __nonzero__(self):
1113 return True
1115 return True
1114 def __str__(self):
1116 def __str__(self):
1115 return "%s@%s" % (self.path(), self._changectx)
1117 return "%s@%s" % (self.path(), self._changectx)
1116 def path(self):
1118 def path(self):
1117 return self._path
1119 return self._path
1118 def data(self):
1120 def data(self):
1119 return self._data
1121 return self._data
1120 def flags(self):
1122 def flags(self):
1121 return self._flags
1123 return self._flags
1122 def isexec(self):
1124 def isexec(self):
1123 return 'x' in self._flags
1125 return 'x' in self._flags
1124 def islink(self):
1126 def islink(self):
1125 return 'l' in self._flags
1127 return 'l' in self._flags
1126 def renamed(self):
1128 def renamed(self):
1127 return self._copied
1129 return self._copied
@@ -1,1767 +1,1767 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
10 import tempfile, zlib
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 1:
349 while 1:
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):
365 def setfile(self, fname, data, mode):
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.
368 be left unchanged.
369 """
369 """
370 raise NotImplementedError
370 raise NotImplementedError
371
371
372 def unlink(self, fname):
372 def unlink(self, fname):
373 """Unlink target file."""
373 """Unlink target file."""
374 raise NotImplementedError
374 raise NotImplementedError
375
375
376 def writerej(self, fname, failed, total, lines):
376 def writerej(self, fname, failed, total, lines):
377 """Write rejected lines for fname. total is the number of hunks
377 """Write rejected lines for fname. total is the number of hunks
378 which failed to apply and total the total number of hunks for this
378 which failed to apply and total the total number of hunks for this
379 files.
379 files.
380 """
380 """
381 pass
381 pass
382
382
383 def copy(self, src, dst):
383 def copy(self, src, dst):
384 """Copy src file into dst file. Create intermediate directories if
384 """Copy src file into dst file. Create intermediate directories if
385 necessary. Files are specified relatively to the patching base
385 necessary. Files are specified relatively to the patching base
386 directory.
386 directory.
387 """
387 """
388 raise NotImplementedError
388 raise NotImplementedError
389
389
390 def exists(self, fname):
390 def exists(self, fname):
391 raise NotImplementedError
391 raise NotImplementedError
392
392
393 class fsbackend(abstractbackend):
393 class fsbackend(abstractbackend):
394 def __init__(self, ui, basedir):
394 def __init__(self, ui, basedir):
395 super(fsbackend, self).__init__(ui)
395 super(fsbackend, self).__init__(ui)
396 self.opener = scmutil.opener(basedir)
396 self.opener = scmutil.opener(basedir)
397
397
398 def _join(self, f):
398 def _join(self, f):
399 return os.path.join(self.opener.base, f)
399 return os.path.join(self.opener.base, f)
400
400
401 def getfile(self, fname):
401 def getfile(self, fname):
402 path = self._join(fname)
402 path = self._join(fname)
403 if os.path.islink(path):
403 if os.path.islink(path):
404 return (os.readlink(path), (True, False))
404 return (os.readlink(path), (True, False))
405 isexec, islink = False, False
405 isexec, islink = False, False
406 try:
406 try:
407 isexec = os.lstat(path).st_mode & 0100 != 0
407 isexec = os.lstat(path).st_mode & 0100 != 0
408 islink = os.path.islink(path)
408 islink = os.path.islink(path)
409 except OSError, e:
409 except OSError, e:
410 if e.errno != errno.ENOENT:
410 if e.errno != errno.ENOENT:
411 raise
411 raise
412 return (self.opener.read(fname), (islink, isexec))
412 return (self.opener.read(fname), (islink, isexec))
413
413
414 def setfile(self, fname, data, mode):
414 def setfile(self, fname, data, mode):
415 islink, isexec = mode
415 islink, isexec = mode
416 if data is None:
416 if data is None:
417 util.setflags(self._join(fname), islink, isexec)
417 util.setflags(self._join(fname), islink, isexec)
418 return
418 return
419 if islink:
419 if islink:
420 self.opener.symlink(data, fname)
420 self.opener.symlink(data, fname)
421 else:
421 else:
422 self.opener.write(fname, data)
422 self.opener.write(fname, data)
423 if isexec:
423 if isexec:
424 util.setflags(self._join(fname), False, True)
424 util.setflags(self._join(fname), False, True)
425
425
426 def unlink(self, fname):
426 def unlink(self, fname):
427 try:
427 try:
428 util.unlinkpath(self._join(fname))
428 util.unlinkpath(self._join(fname))
429 except OSError, inst:
429 except OSError, inst:
430 if inst.errno != errno.ENOENT:
430 if inst.errno != errno.ENOENT:
431 raise
431 raise
432
432
433 def writerej(self, fname, failed, total, lines):
433 def writerej(self, fname, failed, total, lines):
434 fname = fname + ".rej"
434 fname = fname + ".rej"
435 self.ui.warn(
435 self.ui.warn(
436 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
436 _("%d out of %d hunks FAILED -- saving rejects to file %s\n") %
437 (failed, total, fname))
437 (failed, total, fname))
438 fp = self.opener(fname, 'w')
438 fp = self.opener(fname, 'w')
439 fp.writelines(lines)
439 fp.writelines(lines)
440 fp.close()
440 fp.close()
441
441
442 def copy(self, src, dst):
442 def copy(self, src, dst):
443 basedir = self.opener.base
443 basedir = self.opener.base
444 abssrc, absdst = [scmutil.canonpath(basedir, basedir, x)
444 abssrc, absdst = [scmutil.canonpath(basedir, basedir, x)
445 for x in [src, dst]]
445 for x in [src, dst]]
446 if os.path.lexists(absdst):
446 if os.path.lexists(absdst):
447 raise util.Abort(_("cannot create %s: destination already exists")
447 raise util.Abort(_("cannot create %s: destination already exists")
448 % dst)
448 % dst)
449 dstdir = os.path.dirname(absdst)
449 dstdir = os.path.dirname(absdst)
450 if dstdir and not os.path.isdir(dstdir):
450 if dstdir and not os.path.isdir(dstdir):
451 try:
451 try:
452 os.makedirs(dstdir)
452 os.makedirs(dstdir)
453 except IOError:
453 except IOError:
454 raise util.Abort(
454 raise util.Abort(
455 _("cannot create %s: unable to create destination directory")
455 _("cannot create %s: unable to create destination directory")
456 % dst)
456 % dst)
457 util.copyfile(abssrc, absdst)
457 util.copyfile(abssrc, absdst)
458
458
459 def exists(self, fname):
459 def exists(self, fname):
460 return os.path.lexists(self._join(fname))
460 return os.path.lexists(self._join(fname))
461
461
462 class workingbackend(fsbackend):
462 class workingbackend(fsbackend):
463 def __init__(self, ui, repo, similarity):
463 def __init__(self, ui, repo, similarity):
464 super(workingbackend, self).__init__(ui, repo.root)
464 super(workingbackend, self).__init__(ui, repo.root)
465 self.repo = repo
465 self.repo = repo
466 self.similarity = similarity
466 self.similarity = similarity
467 self.removed = set()
467 self.removed = set()
468 self.changed = set()
468 self.changed = set()
469 self.copied = []
469 self.copied = []
470
470
471 def setfile(self, fname, data, mode):
471 def setfile(self, fname, data, mode):
472 super(workingbackend, self).setfile(fname, data, mode)
472 super(workingbackend, self).setfile(fname, data, mode)
473 self.changed.add(fname)
473 self.changed.add(fname)
474
474
475 def unlink(self, fname):
475 def unlink(self, fname):
476 super(workingbackend, self).unlink(fname)
476 super(workingbackend, self).unlink(fname)
477 self.removed.add(fname)
477 self.removed.add(fname)
478 self.changed.add(fname)
478 self.changed.add(fname)
479
479
480 def copy(self, src, dst):
480 def copy(self, src, dst):
481 super(workingbackend, self).copy(src, dst)
481 super(workingbackend, self).copy(src, dst)
482 self.copied.append((src, dst))
482 self.copied.append((src, dst))
483 self.changed.add(dst)
483 self.changed.add(dst)
484
484
485 def close(self):
485 def close(self):
486 wctx = self.repo[None]
486 wctx = self.repo[None]
487 addremoved = set(self.changed)
487 addremoved = set(self.changed)
488 for src, dst in self.copied:
488 for src, dst in self.copied:
489 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
489 scmutil.dirstatecopy(self.ui, self.repo, wctx, src, dst)
490 addremoved.discard(src)
490 addremoved.discard(src)
491 if (not self.similarity) and self.removed:
491 if (not self.similarity) and self.removed:
492 wctx.remove(sorted(self.removed))
492 wctx.forget(sorted(self.removed))
493 if addremoved:
493 if addremoved:
494 cwd = self.repo.getcwd()
494 cwd = self.repo.getcwd()
495 if cwd:
495 if cwd:
496 addremoved = [util.pathto(self.repo.root, cwd, f)
496 addremoved = [util.pathto(self.repo.root, cwd, f)
497 for f in addremoved]
497 for f in addremoved]
498 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
498 scmutil.addremove(self.repo, addremoved, similarity=self.similarity)
499 return sorted(self.changed)
499 return sorted(self.changed)
500
500
501 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
501 # @@ -start,len +start,len @@ or @@ -start +start @@ if len is 1
502 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
502 unidesc = re.compile('@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@')
503 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
503 contextdesc = re.compile('(---|\*\*\*) (\d+)(,(\d+))? (---|\*\*\*)')
504 eolmodes = ['strict', 'crlf', 'lf', 'auto']
504 eolmodes = ['strict', 'crlf', 'lf', 'auto']
505
505
506 class patchfile(object):
506 class patchfile(object):
507 def __init__(self, ui, fname, backend, mode, missing=False,
507 def __init__(self, ui, fname, backend, mode, missing=False,
508 eolmode='strict'):
508 eolmode='strict'):
509 self.fname = fname
509 self.fname = fname
510 self.eolmode = eolmode
510 self.eolmode = eolmode
511 self.eol = None
511 self.eol = None
512 self.backend = backend
512 self.backend = backend
513 self.ui = ui
513 self.ui = ui
514 self.lines = []
514 self.lines = []
515 self.exists = False
515 self.exists = False
516 self.missing = missing
516 self.missing = missing
517 self.mode = mode
517 self.mode = mode
518 if not missing:
518 if not missing:
519 try:
519 try:
520 data, mode = self.backend.getfile(fname)
520 data, mode = self.backend.getfile(fname)
521 if data:
521 if data:
522 self.lines = data.splitlines(True)
522 self.lines = data.splitlines(True)
523 if self.mode is None:
523 if self.mode is None:
524 self.mode = mode
524 self.mode = mode
525 if self.lines:
525 if self.lines:
526 # Normalize line endings
526 # Normalize line endings
527 if self.lines[0].endswith('\r\n'):
527 if self.lines[0].endswith('\r\n'):
528 self.eol = '\r\n'
528 self.eol = '\r\n'
529 elif self.lines[0].endswith('\n'):
529 elif self.lines[0].endswith('\n'):
530 self.eol = '\n'
530 self.eol = '\n'
531 if eolmode != 'strict':
531 if eolmode != 'strict':
532 nlines = []
532 nlines = []
533 for l in self.lines:
533 for l in self.lines:
534 if l.endswith('\r\n'):
534 if l.endswith('\r\n'):
535 l = l[:-2] + '\n'
535 l = l[:-2] + '\n'
536 nlines.append(l)
536 nlines.append(l)
537 self.lines = nlines
537 self.lines = nlines
538 self.exists = True
538 self.exists = True
539 except IOError:
539 except IOError:
540 if self.mode is None:
540 if self.mode is None:
541 self.mode = (False, False)
541 self.mode = (False, False)
542 else:
542 else:
543 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
543 self.ui.warn(_("unable to find '%s' for patching\n") % self.fname)
544
544
545 self.hash = {}
545 self.hash = {}
546 self.dirty = 0
546 self.dirty = 0
547 self.offset = 0
547 self.offset = 0
548 self.skew = 0
548 self.skew = 0
549 self.rej = []
549 self.rej = []
550 self.fileprinted = False
550 self.fileprinted = False
551 self.printfile(False)
551 self.printfile(False)
552 self.hunks = 0
552 self.hunks = 0
553
553
554 def writelines(self, fname, lines, mode):
554 def writelines(self, fname, lines, mode):
555 if self.eolmode == 'auto':
555 if self.eolmode == 'auto':
556 eol = self.eol
556 eol = self.eol
557 elif self.eolmode == 'crlf':
557 elif self.eolmode == 'crlf':
558 eol = '\r\n'
558 eol = '\r\n'
559 else:
559 else:
560 eol = '\n'
560 eol = '\n'
561
561
562 if self.eolmode != 'strict' and eol and eol != '\n':
562 if self.eolmode != 'strict' and eol and eol != '\n':
563 rawlines = []
563 rawlines = []
564 for l in lines:
564 for l in lines:
565 if l and l[-1] == '\n':
565 if l and l[-1] == '\n':
566 l = l[:-1] + eol
566 l = l[:-1] + eol
567 rawlines.append(l)
567 rawlines.append(l)
568 lines = rawlines
568 lines = rawlines
569
569
570 self.backend.setfile(fname, ''.join(lines), mode)
570 self.backend.setfile(fname, ''.join(lines), mode)
571
571
572 def printfile(self, warn):
572 def printfile(self, warn):
573 if self.fileprinted:
573 if self.fileprinted:
574 return
574 return
575 if warn or self.ui.verbose:
575 if warn or self.ui.verbose:
576 self.fileprinted = True
576 self.fileprinted = True
577 s = _("patching file %s\n") % self.fname
577 s = _("patching file %s\n") % self.fname
578 if warn:
578 if warn:
579 self.ui.warn(s)
579 self.ui.warn(s)
580 else:
580 else:
581 self.ui.note(s)
581 self.ui.note(s)
582
582
583
583
584 def findlines(self, l, linenum):
584 def findlines(self, l, linenum):
585 # looks through the hash and finds candidate lines. The
585 # looks through the hash and finds candidate lines. The
586 # result is a list of line numbers sorted based on distance
586 # result is a list of line numbers sorted based on distance
587 # from linenum
587 # from linenum
588
588
589 cand = self.hash.get(l, [])
589 cand = self.hash.get(l, [])
590 if len(cand) > 1:
590 if len(cand) > 1:
591 # resort our list of potentials forward then back.
591 # resort our list of potentials forward then back.
592 cand.sort(key=lambda x: abs(x - linenum))
592 cand.sort(key=lambda x: abs(x - linenum))
593 return cand
593 return cand
594
594
595 def write_rej(self):
595 def write_rej(self):
596 # our rejects are a little different from patch(1). This always
596 # our rejects are a little different from patch(1). This always
597 # creates rejects in the same form as the original patch. A file
597 # creates rejects in the same form as the original patch. A file
598 # header is inserted so that you can run the reject through patch again
598 # header is inserted so that you can run the reject through patch again
599 # without having to type the filename.
599 # without having to type the filename.
600 if not self.rej:
600 if not self.rej:
601 return
601 return
602 base = os.path.basename(self.fname)
602 base = os.path.basename(self.fname)
603 lines = ["--- %s\n+++ %s\n" % (base, base)]
603 lines = ["--- %s\n+++ %s\n" % (base, base)]
604 for x in self.rej:
604 for x in self.rej:
605 for l in x.hunk:
605 for l in x.hunk:
606 lines.append(l)
606 lines.append(l)
607 if l[-1] != '\n':
607 if l[-1] != '\n':
608 lines.append("\n\ No newline at end of file\n")
608 lines.append("\n\ No newline at end of file\n")
609 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
609 self.backend.writerej(self.fname, len(self.rej), self.hunks, lines)
610
610
611 def apply(self, h):
611 def apply(self, h):
612 if not h.complete():
612 if not h.complete():
613 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
613 raise PatchError(_("bad hunk #%d %s (%d %d %d %d)") %
614 (h.number, h.desc, len(h.a), h.lena, len(h.b),
614 (h.number, h.desc, len(h.a), h.lena, len(h.b),
615 h.lenb))
615 h.lenb))
616
616
617 self.hunks += 1
617 self.hunks += 1
618
618
619 if self.missing:
619 if self.missing:
620 self.rej.append(h)
620 self.rej.append(h)
621 return -1
621 return -1
622
622
623 if self.exists and h.createfile():
623 if self.exists and h.createfile():
624 self.ui.warn(_("file %s already exists\n") % self.fname)
624 self.ui.warn(_("file %s already exists\n") % self.fname)
625 self.rej.append(h)
625 self.rej.append(h)
626 return -1
626 return -1
627
627
628 if isinstance(h, binhunk):
628 if isinstance(h, binhunk):
629 if h.rmfile():
629 if h.rmfile():
630 self.backend.unlink(self.fname)
630 self.backend.unlink(self.fname)
631 else:
631 else:
632 self.lines[:] = h.new()
632 self.lines[:] = h.new()
633 self.offset += len(h.new())
633 self.offset += len(h.new())
634 self.dirty = True
634 self.dirty = True
635 return 0
635 return 0
636
636
637 horig = h
637 horig = h
638 if (self.eolmode in ('crlf', 'lf')
638 if (self.eolmode in ('crlf', 'lf')
639 or self.eolmode == 'auto' and self.eol):
639 or self.eolmode == 'auto' and self.eol):
640 # If new eols are going to be normalized, then normalize
640 # If new eols are going to be normalized, then normalize
641 # hunk data before patching. Otherwise, preserve input
641 # hunk data before patching. Otherwise, preserve input
642 # line-endings.
642 # line-endings.
643 h = h.getnormalized()
643 h = h.getnormalized()
644
644
645 # fast case first, no offsets, no fuzz
645 # fast case first, no offsets, no fuzz
646 old = h.old()
646 old = h.old()
647 # patch starts counting at 1 unless we are adding the file
647 # patch starts counting at 1 unless we are adding the file
648 if h.starta == 0:
648 if h.starta == 0:
649 start = 0
649 start = 0
650 else:
650 else:
651 start = h.starta + self.offset - 1
651 start = h.starta + self.offset - 1
652 orig_start = start
652 orig_start = start
653 # if there's skew we want to emit the "(offset %d lines)" even
653 # if there's skew we want to emit the "(offset %d lines)" even
654 # when the hunk cleanly applies at start + skew, so skip the
654 # when the hunk cleanly applies at start + skew, so skip the
655 # fast case code
655 # fast case code
656 if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0:
656 if self.skew == 0 and diffhelpers.testhunk(old, self.lines, start) == 0:
657 if h.rmfile():
657 if h.rmfile():
658 self.backend.unlink(self.fname)
658 self.backend.unlink(self.fname)
659 else:
659 else:
660 self.lines[start : start + h.lena] = h.new()
660 self.lines[start : start + h.lena] = h.new()
661 self.offset += h.lenb - h.lena
661 self.offset += h.lenb - h.lena
662 self.dirty = True
662 self.dirty = True
663 return 0
663 return 0
664
664
665 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
665 # ok, we couldn't match the hunk. Lets look for offsets and fuzz it
666 self.hash = {}
666 self.hash = {}
667 for x, s in enumerate(self.lines):
667 for x, s in enumerate(self.lines):
668 self.hash.setdefault(s, []).append(x)
668 self.hash.setdefault(s, []).append(x)
669 if h.hunk[-1][0] != ' ':
669 if h.hunk[-1][0] != ' ':
670 # if the hunk tried to put something at the bottom of the file
670 # if the hunk tried to put something at the bottom of the file
671 # override the start line and use eof here
671 # override the start line and use eof here
672 search_start = len(self.lines)
672 search_start = len(self.lines)
673 else:
673 else:
674 search_start = orig_start + self.skew
674 search_start = orig_start + self.skew
675
675
676 for fuzzlen in xrange(3):
676 for fuzzlen in xrange(3):
677 for toponly in [True, False]:
677 for toponly in [True, False]:
678 old = h.old(fuzzlen, toponly)
678 old = h.old(fuzzlen, toponly)
679
679
680 cand = self.findlines(old[0][1:], search_start)
680 cand = self.findlines(old[0][1:], search_start)
681 for l in cand:
681 for l in cand:
682 if diffhelpers.testhunk(old, self.lines, l) == 0:
682 if diffhelpers.testhunk(old, self.lines, l) == 0:
683 newlines = h.new(fuzzlen, toponly)
683 newlines = h.new(fuzzlen, toponly)
684 self.lines[l : l + len(old)] = newlines
684 self.lines[l : l + len(old)] = newlines
685 self.offset += len(newlines) - len(old)
685 self.offset += len(newlines) - len(old)
686 self.skew = l - orig_start
686 self.skew = l - orig_start
687 self.dirty = True
687 self.dirty = True
688 offset = l - orig_start - fuzzlen
688 offset = l - orig_start - fuzzlen
689 if fuzzlen:
689 if fuzzlen:
690 msg = _("Hunk #%d succeeded at %d "
690 msg = _("Hunk #%d succeeded at %d "
691 "with fuzz %d "
691 "with fuzz %d "
692 "(offset %d lines).\n")
692 "(offset %d lines).\n")
693 self.printfile(True)
693 self.printfile(True)
694 self.ui.warn(msg %
694 self.ui.warn(msg %
695 (h.number, l + 1, fuzzlen, offset))
695 (h.number, l + 1, fuzzlen, offset))
696 else:
696 else:
697 msg = _("Hunk #%d succeeded at %d "
697 msg = _("Hunk #%d succeeded at %d "
698 "(offset %d lines).\n")
698 "(offset %d lines).\n")
699 self.ui.note(msg % (h.number, l + 1, offset))
699 self.ui.note(msg % (h.number, l + 1, offset))
700 return fuzzlen
700 return fuzzlen
701 self.printfile(True)
701 self.printfile(True)
702 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
702 self.ui.warn(_("Hunk #%d FAILED at %d\n") % (h.number, orig_start))
703 self.rej.append(horig)
703 self.rej.append(horig)
704 return -1
704 return -1
705
705
706 def close(self):
706 def close(self):
707 if self.dirty:
707 if self.dirty:
708 self.writelines(self.fname, self.lines, self.mode)
708 self.writelines(self.fname, self.lines, self.mode)
709 self.write_rej()
709 self.write_rej()
710 return len(self.rej)
710 return len(self.rej)
711
711
712 class hunk(object):
712 class hunk(object):
713 def __init__(self, desc, num, lr, context, create=False, remove=False):
713 def __init__(self, desc, num, lr, context, create=False, remove=False):
714 self.number = num
714 self.number = num
715 self.desc = desc
715 self.desc = desc
716 self.hunk = [desc]
716 self.hunk = [desc]
717 self.a = []
717 self.a = []
718 self.b = []
718 self.b = []
719 self.starta = self.lena = None
719 self.starta = self.lena = None
720 self.startb = self.lenb = None
720 self.startb = self.lenb = None
721 if lr is not None:
721 if lr is not None:
722 if context:
722 if context:
723 self.read_context_hunk(lr)
723 self.read_context_hunk(lr)
724 else:
724 else:
725 self.read_unified_hunk(lr)
725 self.read_unified_hunk(lr)
726 self.create = create
726 self.create = create
727 self.remove = remove and not create
727 self.remove = remove and not create
728
728
729 def getnormalized(self):
729 def getnormalized(self):
730 """Return a copy with line endings normalized to LF."""
730 """Return a copy with line endings normalized to LF."""
731
731
732 def normalize(lines):
732 def normalize(lines):
733 nlines = []
733 nlines = []
734 for line in lines:
734 for line in lines:
735 if line.endswith('\r\n'):
735 if line.endswith('\r\n'):
736 line = line[:-2] + '\n'
736 line = line[:-2] + '\n'
737 nlines.append(line)
737 nlines.append(line)
738 return nlines
738 return nlines
739
739
740 # Dummy object, it is rebuilt manually
740 # Dummy object, it is rebuilt manually
741 nh = hunk(self.desc, self.number, None, None, False, False)
741 nh = hunk(self.desc, self.number, None, None, False, False)
742 nh.number = self.number
742 nh.number = self.number
743 nh.desc = self.desc
743 nh.desc = self.desc
744 nh.hunk = self.hunk
744 nh.hunk = self.hunk
745 nh.a = normalize(self.a)
745 nh.a = normalize(self.a)
746 nh.b = normalize(self.b)
746 nh.b = normalize(self.b)
747 nh.starta = self.starta
747 nh.starta = self.starta
748 nh.startb = self.startb
748 nh.startb = self.startb
749 nh.lena = self.lena
749 nh.lena = self.lena
750 nh.lenb = self.lenb
750 nh.lenb = self.lenb
751 nh.create = self.create
751 nh.create = self.create
752 nh.remove = self.remove
752 nh.remove = self.remove
753 return nh
753 return nh
754
754
755 def read_unified_hunk(self, lr):
755 def read_unified_hunk(self, lr):
756 m = unidesc.match(self.desc)
756 m = unidesc.match(self.desc)
757 if not m:
757 if not m:
758 raise PatchError(_("bad hunk #%d") % self.number)
758 raise PatchError(_("bad hunk #%d") % self.number)
759 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
759 self.starta, foo, self.lena, self.startb, foo2, self.lenb = m.groups()
760 if self.lena is None:
760 if self.lena is None:
761 self.lena = 1
761 self.lena = 1
762 else:
762 else:
763 self.lena = int(self.lena)
763 self.lena = int(self.lena)
764 if self.lenb is None:
764 if self.lenb is None:
765 self.lenb = 1
765 self.lenb = 1
766 else:
766 else:
767 self.lenb = int(self.lenb)
767 self.lenb = int(self.lenb)
768 self.starta = int(self.starta)
768 self.starta = int(self.starta)
769 self.startb = int(self.startb)
769 self.startb = int(self.startb)
770 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
770 diffhelpers.addlines(lr, self.hunk, self.lena, self.lenb, self.a, self.b)
771 # if we hit eof before finishing out the hunk, the last line will
771 # if we hit eof before finishing out the hunk, the last line will
772 # be zero length. Lets try to fix it up.
772 # be zero length. Lets try to fix it up.
773 while len(self.hunk[-1]) == 0:
773 while len(self.hunk[-1]) == 0:
774 del self.hunk[-1]
774 del self.hunk[-1]
775 del self.a[-1]
775 del self.a[-1]
776 del self.b[-1]
776 del self.b[-1]
777 self.lena -= 1
777 self.lena -= 1
778 self.lenb -= 1
778 self.lenb -= 1
779 self._fixnewline(lr)
779 self._fixnewline(lr)
780
780
781 def read_context_hunk(self, lr):
781 def read_context_hunk(self, lr):
782 self.desc = lr.readline()
782 self.desc = lr.readline()
783 m = contextdesc.match(self.desc)
783 m = contextdesc.match(self.desc)
784 if not m:
784 if not m:
785 raise PatchError(_("bad hunk #%d") % self.number)
785 raise PatchError(_("bad hunk #%d") % self.number)
786 foo, self.starta, foo2, aend, foo3 = m.groups()
786 foo, self.starta, foo2, aend, foo3 = m.groups()
787 self.starta = int(self.starta)
787 self.starta = int(self.starta)
788 if aend is None:
788 if aend is None:
789 aend = self.starta
789 aend = self.starta
790 self.lena = int(aend) - self.starta
790 self.lena = int(aend) - self.starta
791 if self.starta:
791 if self.starta:
792 self.lena += 1
792 self.lena += 1
793 for x in xrange(self.lena):
793 for x in xrange(self.lena):
794 l = lr.readline()
794 l = lr.readline()
795 if l.startswith('---'):
795 if l.startswith('---'):
796 # lines addition, old block is empty
796 # lines addition, old block is empty
797 lr.push(l)
797 lr.push(l)
798 break
798 break
799 s = l[2:]
799 s = l[2:]
800 if l.startswith('- ') or l.startswith('! '):
800 if l.startswith('- ') or l.startswith('! '):
801 u = '-' + s
801 u = '-' + s
802 elif l.startswith(' '):
802 elif l.startswith(' '):
803 u = ' ' + s
803 u = ' ' + s
804 else:
804 else:
805 raise PatchError(_("bad hunk #%d old text line %d") %
805 raise PatchError(_("bad hunk #%d old text line %d") %
806 (self.number, x))
806 (self.number, x))
807 self.a.append(u)
807 self.a.append(u)
808 self.hunk.append(u)
808 self.hunk.append(u)
809
809
810 l = lr.readline()
810 l = lr.readline()
811 if l.startswith('\ '):
811 if l.startswith('\ '):
812 s = self.a[-1][:-1]
812 s = self.a[-1][:-1]
813 self.a[-1] = s
813 self.a[-1] = s
814 self.hunk[-1] = s
814 self.hunk[-1] = s
815 l = lr.readline()
815 l = lr.readline()
816 m = contextdesc.match(l)
816 m = contextdesc.match(l)
817 if not m:
817 if not m:
818 raise PatchError(_("bad hunk #%d") % self.number)
818 raise PatchError(_("bad hunk #%d") % self.number)
819 foo, self.startb, foo2, bend, foo3 = m.groups()
819 foo, self.startb, foo2, bend, foo3 = m.groups()
820 self.startb = int(self.startb)
820 self.startb = int(self.startb)
821 if bend is None:
821 if bend is None:
822 bend = self.startb
822 bend = self.startb
823 self.lenb = int(bend) - self.startb
823 self.lenb = int(bend) - self.startb
824 if self.startb:
824 if self.startb:
825 self.lenb += 1
825 self.lenb += 1
826 hunki = 1
826 hunki = 1
827 for x in xrange(self.lenb):
827 for x in xrange(self.lenb):
828 l = lr.readline()
828 l = lr.readline()
829 if l.startswith('\ '):
829 if l.startswith('\ '):
830 # XXX: the only way to hit this is with an invalid line range.
830 # XXX: the only way to hit this is with an invalid line range.
831 # The no-eol marker is not counted in the line range, but I
831 # The no-eol marker is not counted in the line range, but I
832 # guess there are diff(1) out there which behave differently.
832 # guess there are diff(1) out there which behave differently.
833 s = self.b[-1][:-1]
833 s = self.b[-1][:-1]
834 self.b[-1] = s
834 self.b[-1] = s
835 self.hunk[hunki - 1] = s
835 self.hunk[hunki - 1] = s
836 continue
836 continue
837 if not l:
837 if not l:
838 # line deletions, new block is empty and we hit EOF
838 # line deletions, new block is empty and we hit EOF
839 lr.push(l)
839 lr.push(l)
840 break
840 break
841 s = l[2:]
841 s = l[2:]
842 if l.startswith('+ ') or l.startswith('! '):
842 if l.startswith('+ ') or l.startswith('! '):
843 u = '+' + s
843 u = '+' + s
844 elif l.startswith(' '):
844 elif l.startswith(' '):
845 u = ' ' + s
845 u = ' ' + s
846 elif len(self.b) == 0:
846 elif len(self.b) == 0:
847 # line deletions, new block is empty
847 # line deletions, new block is empty
848 lr.push(l)
848 lr.push(l)
849 break
849 break
850 else:
850 else:
851 raise PatchError(_("bad hunk #%d old text line %d") %
851 raise PatchError(_("bad hunk #%d old text line %d") %
852 (self.number, x))
852 (self.number, x))
853 self.b.append(s)
853 self.b.append(s)
854 while True:
854 while True:
855 if hunki >= len(self.hunk):
855 if hunki >= len(self.hunk):
856 h = ""
856 h = ""
857 else:
857 else:
858 h = self.hunk[hunki]
858 h = self.hunk[hunki]
859 hunki += 1
859 hunki += 1
860 if h == u:
860 if h == u:
861 break
861 break
862 elif h.startswith('-'):
862 elif h.startswith('-'):
863 continue
863 continue
864 else:
864 else:
865 self.hunk.insert(hunki - 1, u)
865 self.hunk.insert(hunki - 1, u)
866 break
866 break
867
867
868 if not self.a:
868 if not self.a:
869 # this happens when lines were only added to the hunk
869 # this happens when lines were only added to the hunk
870 for x in self.hunk:
870 for x in self.hunk:
871 if x.startswith('-') or x.startswith(' '):
871 if x.startswith('-') or x.startswith(' '):
872 self.a.append(x)
872 self.a.append(x)
873 if not self.b:
873 if not self.b:
874 # this happens when lines were only deleted from the hunk
874 # this happens when lines were only deleted from the hunk
875 for x in self.hunk:
875 for x in self.hunk:
876 if x.startswith('+') or x.startswith(' '):
876 if x.startswith('+') or x.startswith(' '):
877 self.b.append(x[1:])
877 self.b.append(x[1:])
878 # @@ -start,len +start,len @@
878 # @@ -start,len +start,len @@
879 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
879 self.desc = "@@ -%d,%d +%d,%d @@\n" % (self.starta, self.lena,
880 self.startb, self.lenb)
880 self.startb, self.lenb)
881 self.hunk[0] = self.desc
881 self.hunk[0] = self.desc
882 self._fixnewline(lr)
882 self._fixnewline(lr)
883
883
884 def _fixnewline(self, lr):
884 def _fixnewline(self, lr):
885 l = lr.readline()
885 l = lr.readline()
886 if l.startswith('\ '):
886 if l.startswith('\ '):
887 diffhelpers.fix_newline(self.hunk, self.a, self.b)
887 diffhelpers.fix_newline(self.hunk, self.a, self.b)
888 else:
888 else:
889 lr.push(l)
889 lr.push(l)
890
890
891 def complete(self):
891 def complete(self):
892 return len(self.a) == self.lena and len(self.b) == self.lenb
892 return len(self.a) == self.lena and len(self.b) == self.lenb
893
893
894 def createfile(self):
894 def createfile(self):
895 return self.starta == 0 and self.lena == 0 and self.create
895 return self.starta == 0 and self.lena == 0 and self.create
896
896
897 def rmfile(self):
897 def rmfile(self):
898 return self.startb == 0 and self.lenb == 0 and self.remove
898 return self.startb == 0 and self.lenb == 0 and self.remove
899
899
900 def fuzzit(self, l, fuzz, toponly):
900 def fuzzit(self, l, fuzz, toponly):
901 # this removes context lines from the top and bottom of list 'l'. It
901 # this removes context lines from the top and bottom of list 'l'. It
902 # checks the hunk to make sure only context lines are removed, and then
902 # checks the hunk to make sure only context lines are removed, and then
903 # returns a new shortened list of lines.
903 # returns a new shortened list of lines.
904 fuzz = min(fuzz, len(l)-1)
904 fuzz = min(fuzz, len(l)-1)
905 if fuzz:
905 if fuzz:
906 top = 0
906 top = 0
907 bot = 0
907 bot = 0
908 hlen = len(self.hunk)
908 hlen = len(self.hunk)
909 for x in xrange(hlen - 1):
909 for x in xrange(hlen - 1):
910 # the hunk starts with the @@ line, so use x+1
910 # the hunk starts with the @@ line, so use x+1
911 if self.hunk[x + 1][0] == ' ':
911 if self.hunk[x + 1][0] == ' ':
912 top += 1
912 top += 1
913 else:
913 else:
914 break
914 break
915 if not toponly:
915 if not toponly:
916 for x in xrange(hlen - 1):
916 for x in xrange(hlen - 1):
917 if self.hunk[hlen - bot - 1][0] == ' ':
917 if self.hunk[hlen - bot - 1][0] == ' ':
918 bot += 1
918 bot += 1
919 else:
919 else:
920 break
920 break
921
921
922 # top and bot now count context in the hunk
922 # top and bot now count context in the hunk
923 # adjust them if either one is short
923 # adjust them if either one is short
924 context = max(top, bot, 3)
924 context = max(top, bot, 3)
925 if bot < context:
925 if bot < context:
926 bot = max(0, fuzz - (context - bot))
926 bot = max(0, fuzz - (context - bot))
927 else:
927 else:
928 bot = min(fuzz, bot)
928 bot = min(fuzz, bot)
929 if top < context:
929 if top < context:
930 top = max(0, fuzz - (context - top))
930 top = max(0, fuzz - (context - top))
931 else:
931 else:
932 top = min(fuzz, top)
932 top = min(fuzz, top)
933
933
934 return l[top:len(l)-bot]
934 return l[top:len(l)-bot]
935 return l
935 return l
936
936
937 def old(self, fuzz=0, toponly=False):
937 def old(self, fuzz=0, toponly=False):
938 return self.fuzzit(self.a, fuzz, toponly)
938 return self.fuzzit(self.a, fuzz, toponly)
939
939
940 def new(self, fuzz=0, toponly=False):
940 def new(self, fuzz=0, toponly=False):
941 return self.fuzzit(self.b, fuzz, toponly)
941 return self.fuzzit(self.b, fuzz, toponly)
942
942
943 class binhunk:
943 class binhunk:
944 'A binary patch file. Only understands literals so far.'
944 'A binary patch file. Only understands literals so far.'
945 def __init__(self, gitpatch, lr):
945 def __init__(self, gitpatch, lr):
946 self.gitpatch = gitpatch
946 self.gitpatch = gitpatch
947 self.text = None
947 self.text = None
948 self.hunk = ['GIT binary patch\n']
948 self.hunk = ['GIT binary patch\n']
949 self._read(lr)
949 self._read(lr)
950
950
951 def createfile(self):
951 def createfile(self):
952 return self.gitpatch.op == 'ADD'
952 return self.gitpatch.op == 'ADD'
953
953
954 def rmfile(self):
954 def rmfile(self):
955 return self.gitpatch.op == 'DELETE'
955 return self.gitpatch.op == 'DELETE'
956
956
957 def complete(self):
957 def complete(self):
958 return self.text is not None
958 return self.text is not None
959
959
960 def new(self):
960 def new(self):
961 return [self.text]
961 return [self.text]
962
962
963 def _read(self, lr):
963 def _read(self, lr):
964 line = lr.readline()
964 line = lr.readline()
965 self.hunk.append(line)
965 self.hunk.append(line)
966 while line and not line.startswith('literal '):
966 while line and not line.startswith('literal '):
967 line = lr.readline()
967 line = lr.readline()
968 self.hunk.append(line)
968 self.hunk.append(line)
969 if not line:
969 if not line:
970 raise PatchError(_('could not extract binary patch'))
970 raise PatchError(_('could not extract binary patch'))
971 size = int(line[8:].rstrip())
971 size = int(line[8:].rstrip())
972 dec = []
972 dec = []
973 line = lr.readline()
973 line = lr.readline()
974 self.hunk.append(line)
974 self.hunk.append(line)
975 while len(line) > 1:
975 while len(line) > 1:
976 l = line[0]
976 l = line[0]
977 if l <= 'Z' and l >= 'A':
977 if l <= 'Z' and l >= 'A':
978 l = ord(l) - ord('A') + 1
978 l = ord(l) - ord('A') + 1
979 else:
979 else:
980 l = ord(l) - ord('a') + 27
980 l = ord(l) - ord('a') + 27
981 dec.append(base85.b85decode(line[1:-1])[:l])
981 dec.append(base85.b85decode(line[1:-1])[:l])
982 line = lr.readline()
982 line = lr.readline()
983 self.hunk.append(line)
983 self.hunk.append(line)
984 text = zlib.decompress(''.join(dec))
984 text = zlib.decompress(''.join(dec))
985 if len(text) != size:
985 if len(text) != size:
986 raise PatchError(_('binary patch is %d bytes, not %d') %
986 raise PatchError(_('binary patch is %d bytes, not %d') %
987 len(text), size)
987 len(text), size)
988 self.text = text
988 self.text = text
989
989
990 def parsefilename(str):
990 def parsefilename(str):
991 # --- filename \t|space stuff
991 # --- filename \t|space stuff
992 s = str[4:].rstrip('\r\n')
992 s = str[4:].rstrip('\r\n')
993 i = s.find('\t')
993 i = s.find('\t')
994 if i < 0:
994 if i < 0:
995 i = s.find(' ')
995 i = s.find(' ')
996 if i < 0:
996 if i < 0:
997 return s
997 return s
998 return s[:i]
998 return s[:i]
999
999
1000 def pathstrip(path, strip):
1000 def pathstrip(path, strip):
1001 pathlen = len(path)
1001 pathlen = len(path)
1002 i = 0
1002 i = 0
1003 if strip == 0:
1003 if strip == 0:
1004 return '', path.rstrip()
1004 return '', path.rstrip()
1005 count = strip
1005 count = strip
1006 while count > 0:
1006 while count > 0:
1007 i = path.find('/', i)
1007 i = path.find('/', i)
1008 if i == -1:
1008 if i == -1:
1009 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1009 raise PatchError(_("unable to strip away %d of %d dirs from %s") %
1010 (count, strip, path))
1010 (count, strip, path))
1011 i += 1
1011 i += 1
1012 # consume '//' in the path
1012 # consume '//' in the path
1013 while i < pathlen - 1 and path[i] == '/':
1013 while i < pathlen - 1 and path[i] == '/':
1014 i += 1
1014 i += 1
1015 count -= 1
1015 count -= 1
1016 return path[:i].lstrip(), path[i:].rstrip()
1016 return path[:i].lstrip(), path[i:].rstrip()
1017
1017
1018 def selectfile(backend, afile_orig, bfile_orig, hunk, strip, gp):
1018 def selectfile(backend, afile_orig, bfile_orig, hunk, strip, gp):
1019 if gp:
1019 if gp:
1020 # Git patches do not play games. Excluding copies from the
1020 # Git patches do not play games. Excluding copies from the
1021 # following heuristic avoids a lot of confusion
1021 # following heuristic avoids a lot of confusion
1022 fname = pathstrip(gp.path, strip - 1)[1]
1022 fname = pathstrip(gp.path, strip - 1)[1]
1023 missing = not hunk.createfile() and not backend.exists(fname)
1023 missing = not hunk.createfile() and not backend.exists(fname)
1024 return fname, missing
1024 return fname, missing
1025 nulla = afile_orig == "/dev/null"
1025 nulla = afile_orig == "/dev/null"
1026 nullb = bfile_orig == "/dev/null"
1026 nullb = bfile_orig == "/dev/null"
1027 abase, afile = pathstrip(afile_orig, strip)
1027 abase, afile = pathstrip(afile_orig, strip)
1028 gooda = not nulla and backend.exists(afile)
1028 gooda = not nulla and backend.exists(afile)
1029 bbase, bfile = pathstrip(bfile_orig, strip)
1029 bbase, bfile = pathstrip(bfile_orig, strip)
1030 if afile == bfile:
1030 if afile == bfile:
1031 goodb = gooda
1031 goodb = gooda
1032 else:
1032 else:
1033 goodb = not nullb and backend.exists(bfile)
1033 goodb = not nullb and backend.exists(bfile)
1034 createfunc = hunk.createfile
1034 createfunc = hunk.createfile
1035 missing = not goodb and not gooda and not createfunc()
1035 missing = not goodb and not gooda and not createfunc()
1036
1036
1037 # some diff programs apparently produce patches where the afile is
1037 # some diff programs apparently produce patches where the afile is
1038 # not /dev/null, but afile starts with bfile
1038 # not /dev/null, but afile starts with bfile
1039 abasedir = afile[:afile.rfind('/') + 1]
1039 abasedir = afile[:afile.rfind('/') + 1]
1040 bbasedir = bfile[:bfile.rfind('/') + 1]
1040 bbasedir = bfile[:bfile.rfind('/') + 1]
1041 if missing and abasedir == bbasedir and afile.startswith(bfile):
1041 if missing and abasedir == bbasedir and afile.startswith(bfile):
1042 # this isn't very pretty
1042 # this isn't very pretty
1043 hunk.create = True
1043 hunk.create = True
1044 if createfunc():
1044 if createfunc():
1045 missing = False
1045 missing = False
1046 else:
1046 else:
1047 hunk.create = False
1047 hunk.create = 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, missing
1068 return fname, missing
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 gitpatches[-1][0] == bfile:
1125 if gitpatches and gitpatches[-1][0] == bfile:
1126 gp = gitpatches.pop()[1]
1126 gp = gitpatches.pop()[1]
1127 if x.startswith('GIT binary patch'):
1127 if x.startswith('GIT binary patch'):
1128 h = binhunk(gp, lr)
1128 h = binhunk(gp, lr)
1129 else:
1129 else:
1130 if context is None and x.startswith('***************'):
1130 if context is None and x.startswith('***************'):
1131 context = True
1131 context = True
1132 create = afile == '/dev/null' or gp and gp.op == 'ADD'
1132 create = afile == '/dev/null' or gp and gp.op == 'ADD'
1133 remove = bfile == '/dev/null' or gp and gp.op == 'DELETE'
1133 remove = bfile == '/dev/null' or gp and gp.op == 'DELETE'
1134 h = hunk(x, hunknum + 1, lr, context, create, remove)
1134 h = hunk(x, hunknum + 1, lr, context, create, remove)
1135 hunknum += 1
1135 hunknum += 1
1136 if emitfile:
1136 if emitfile:
1137 emitfile = False
1137 emitfile = False
1138 yield 'file', (afile, bfile, h, gp)
1138 yield 'file', (afile, bfile, h, gp)
1139 yield 'hunk', h
1139 yield 'hunk', h
1140 elif x.startswith('diff --git'):
1140 elif x.startswith('diff --git'):
1141 m = gitre.match(x)
1141 m = gitre.match(x)
1142 if not m:
1142 if not m:
1143 continue
1143 continue
1144 if gitpatches is None:
1144 if gitpatches is None:
1145 # scan whole input for git metadata
1145 # scan whole input for git metadata
1146 gitpatches = [('b/' + gp.path, gp) for gp
1146 gitpatches = [('b/' + gp.path, gp) for gp
1147 in scangitpatch(lr, x)]
1147 in scangitpatch(lr, x)]
1148 yield 'git', [g[1] for g in gitpatches
1148 yield 'git', [g[1] for g in gitpatches
1149 if g[1].op in ('COPY', 'RENAME')]
1149 if g[1].op in ('COPY', 'RENAME')]
1150 gitpatches.reverse()
1150 gitpatches.reverse()
1151 afile = 'a/' + m.group(1)
1151 afile = 'a/' + m.group(1)
1152 bfile = 'b/' + m.group(2)
1152 bfile = 'b/' + m.group(2)
1153 while bfile != gitpatches[-1][0]:
1153 while bfile != gitpatches[-1][0]:
1154 gp = gitpatches.pop()[1]
1154 gp = gitpatches.pop()[1]
1155 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1155 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1156 gp = gitpatches[-1][1]
1156 gp = gitpatches[-1][1]
1157 # copy/rename + modify should modify target, not source
1157 # copy/rename + modify should modify target, not source
1158 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1158 if gp.op in ('COPY', 'DELETE', 'RENAME', 'ADD') or gp.mode:
1159 afile = bfile
1159 afile = bfile
1160 newfile = True
1160 newfile = True
1161 elif x.startswith('---'):
1161 elif x.startswith('---'):
1162 # check for a unified diff
1162 # check for a unified diff
1163 l2 = lr.readline()
1163 l2 = lr.readline()
1164 if not l2.startswith('+++'):
1164 if not l2.startswith('+++'):
1165 lr.push(l2)
1165 lr.push(l2)
1166 continue
1166 continue
1167 newfile = True
1167 newfile = True
1168 context = False
1168 context = False
1169 afile = parsefilename(x)
1169 afile = parsefilename(x)
1170 bfile = parsefilename(l2)
1170 bfile = parsefilename(l2)
1171 elif x.startswith('***'):
1171 elif x.startswith('***'):
1172 # check for a context diff
1172 # check for a context diff
1173 l2 = lr.readline()
1173 l2 = lr.readline()
1174 if not l2.startswith('---'):
1174 if not l2.startswith('---'):
1175 lr.push(l2)
1175 lr.push(l2)
1176 continue
1176 continue
1177 l3 = lr.readline()
1177 l3 = lr.readline()
1178 lr.push(l3)
1178 lr.push(l3)
1179 if not l3.startswith("***************"):
1179 if not l3.startswith("***************"):
1180 lr.push(l2)
1180 lr.push(l2)
1181 continue
1181 continue
1182 newfile = True
1182 newfile = True
1183 context = True
1183 context = True
1184 afile = parsefilename(x)
1184 afile = parsefilename(x)
1185 bfile = parsefilename(l2)
1185 bfile = parsefilename(l2)
1186
1186
1187 if newfile:
1187 if newfile:
1188 newfile = False
1188 newfile = False
1189 emitfile = True
1189 emitfile = True
1190 state = BFILE
1190 state = BFILE
1191 hunknum = 0
1191 hunknum = 0
1192
1192
1193 while gitpatches:
1193 while gitpatches:
1194 gp = gitpatches.pop()[1]
1194 gp = gitpatches.pop()[1]
1195 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1195 yield 'file', ('a/' + gp.path, 'b/' + gp.path, None, gp)
1196
1196
1197 def applydiff(ui, fp, changed, backend, strip=1, eolmode='strict'):
1197 def applydiff(ui, fp, changed, backend, strip=1, eolmode='strict'):
1198 """Reads a patch from fp and tries to apply it.
1198 """Reads a patch from fp and tries to apply it.
1199
1199
1200 The dict 'changed' is filled in with all of the filenames changed
1200 The dict 'changed' is filled in with all of the filenames changed
1201 by the patch. Returns 0 for a clean patch, -1 if any rejects were
1201 by the patch. Returns 0 for a clean patch, -1 if any rejects were
1202 found and 1 if there was any fuzz.
1202 found and 1 if there was any fuzz.
1203
1203
1204 If 'eolmode' is 'strict', the patch content and patched file are
1204 If 'eolmode' is 'strict', the patch content and patched file are
1205 read in binary mode. Otherwise, line endings are ignored when
1205 read in binary mode. Otherwise, line endings are ignored when
1206 patching then normalized according to 'eolmode'.
1206 patching then normalized according to 'eolmode'.
1207 """
1207 """
1208 return _applydiff(ui, fp, patchfile, backend, changed, strip=strip,
1208 return _applydiff(ui, fp, patchfile, backend, changed, strip=strip,
1209 eolmode=eolmode)
1209 eolmode=eolmode)
1210
1210
1211 def _applydiff(ui, fp, patcher, backend, changed, strip=1, eolmode='strict'):
1211 def _applydiff(ui, fp, patcher, backend, changed, strip=1, 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.setdefault(current_file.fname, None)
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 if gp:
1234 if gp:
1235 path = pstrip(gp.path)
1235 path = pstrip(gp.path)
1236 changed[path] = gp
1236 changed[path] = gp
1237 if gp.op == 'DELETE':
1237 if gp.op == 'DELETE':
1238 backend.unlink(path)
1238 backend.unlink(path)
1239 continue
1239 continue
1240 if gp.op == 'RENAME':
1240 if gp.op == 'RENAME':
1241 backend.unlink(pstrip(gp.oldpath))
1241 backend.unlink(pstrip(gp.oldpath))
1242 if gp.mode and not first_hunk:
1242 if gp.mode and not first_hunk:
1243 data = None
1243 data = None
1244 if gp.op == 'ADD':
1244 if gp.op == 'ADD':
1245 # Added files without content have no hunk and
1245 # Added files without content have no hunk and
1246 # must be created
1246 # must be created
1247 data = ''
1247 data = ''
1248 backend.setfile(path, data, gp.mode)
1248 backend.setfile(path, data, gp.mode)
1249 if not first_hunk:
1249 if not first_hunk:
1250 continue
1250 continue
1251 try:
1251 try:
1252 mode = gp and gp.mode or None
1252 mode = gp and gp.mode or None
1253 current_file, missing = selectfile(backend, afile, bfile,
1253 current_file, missing = selectfile(backend, afile, bfile,
1254 first_hunk, strip, gp)
1254 first_hunk, strip, gp)
1255 current_file = patcher(ui, current_file, backend, mode,
1255 current_file = patcher(ui, current_file, backend, mode,
1256 missing=missing, eolmode=eolmode)
1256 missing=missing, eolmode=eolmode)
1257 except PatchError, inst:
1257 except PatchError, inst:
1258 ui.warn(str(inst) + '\n')
1258 ui.warn(str(inst) + '\n')
1259 current_file = None
1259 current_file = None
1260 rejects += 1
1260 rejects += 1
1261 continue
1261 continue
1262 elif state == 'git':
1262 elif state == 'git':
1263 for gp in values:
1263 for gp in values:
1264 backend.copy(pstrip(gp.oldpath), pstrip(gp.path))
1264 backend.copy(pstrip(gp.oldpath), pstrip(gp.path))
1265 else:
1265 else:
1266 raise util.Abort(_('unsupported parser state: %s') % state)
1266 raise util.Abort(_('unsupported parser state: %s') % state)
1267
1267
1268 if current_file:
1268 if current_file:
1269 rejects += current_file.close()
1269 rejects += current_file.close()
1270
1270
1271 if rejects:
1271 if rejects:
1272 return -1
1272 return -1
1273 return err
1273 return err
1274
1274
1275 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1275 def _externalpatch(ui, repo, patcher, patchname, strip, files,
1276 similarity):
1276 similarity):
1277 """use <patcher> to apply <patchname> to the working directory.
1277 """use <patcher> to apply <patchname> to the working directory.
1278 returns whether patch was applied with fuzz factor."""
1278 returns whether patch was applied with fuzz factor."""
1279
1279
1280 fuzz = False
1280 fuzz = False
1281 args = []
1281 args = []
1282 cwd = repo.root
1282 cwd = repo.root
1283 if cwd:
1283 if cwd:
1284 args.append('-d %s' % util.shellquote(cwd))
1284 args.append('-d %s' % util.shellquote(cwd))
1285 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1285 fp = util.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
1286 util.shellquote(patchname)))
1286 util.shellquote(patchname)))
1287 try:
1287 try:
1288 for line in fp:
1288 for line in fp:
1289 line = line.rstrip()
1289 line = line.rstrip()
1290 ui.note(line + '\n')
1290 ui.note(line + '\n')
1291 if line.startswith('patching file '):
1291 if line.startswith('patching file '):
1292 pf = util.parsepatchoutput(line)
1292 pf = util.parsepatchoutput(line)
1293 printed_file = False
1293 printed_file = False
1294 files.setdefault(pf, None)
1294 files.setdefault(pf, None)
1295 elif line.find('with fuzz') >= 0:
1295 elif line.find('with fuzz') >= 0:
1296 fuzz = True
1296 fuzz = True
1297 if not printed_file:
1297 if not printed_file:
1298 ui.warn(pf + '\n')
1298 ui.warn(pf + '\n')
1299 printed_file = True
1299 printed_file = True
1300 ui.warn(line + '\n')
1300 ui.warn(line + '\n')
1301 elif line.find('saving rejects to file') >= 0:
1301 elif line.find('saving rejects to file') >= 0:
1302 ui.warn(line + '\n')
1302 ui.warn(line + '\n')
1303 elif line.find('FAILED') >= 0:
1303 elif line.find('FAILED') >= 0:
1304 if not printed_file:
1304 if not printed_file:
1305 ui.warn(pf + '\n')
1305 ui.warn(pf + '\n')
1306 printed_file = True
1306 printed_file = True
1307 ui.warn(line + '\n')
1307 ui.warn(line + '\n')
1308 finally:
1308 finally:
1309 if files:
1309 if files:
1310 cfiles = list(files)
1310 cfiles = list(files)
1311 cwd = repo.getcwd()
1311 cwd = repo.getcwd()
1312 if cwd:
1312 if cwd:
1313 cfiles = [util.pathto(repo.root, cwd, f)
1313 cfiles = [util.pathto(repo.root, cwd, f)
1314 for f in cfile]
1314 for f in cfile]
1315 scmutil.addremove(repo, cfiles, similarity=similarity)
1315 scmutil.addremove(repo, cfiles, similarity=similarity)
1316 code = fp.close()
1316 code = fp.close()
1317 if code:
1317 if code:
1318 raise PatchError(_("patch command failed: %s") %
1318 raise PatchError(_("patch command failed: %s") %
1319 util.explainexit(code)[0])
1319 util.explainexit(code)[0])
1320 return fuzz
1320 return fuzz
1321
1321
1322 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1322 def internalpatch(ui, repo, patchobj, strip, files=None, eolmode='strict',
1323 similarity=0):
1323 similarity=0):
1324 """use builtin patch to apply <patchobj> to the working directory.
1324 """use builtin patch to apply <patchobj> to the working directory.
1325 returns whether patch was applied with fuzz factor."""
1325 returns whether patch was applied with fuzz factor."""
1326
1326
1327 if files is None:
1327 if files is None:
1328 files = {}
1328 files = {}
1329 if eolmode is None:
1329 if eolmode is None:
1330 eolmode = ui.config('patch', 'eol', 'strict')
1330 eolmode = ui.config('patch', 'eol', 'strict')
1331 if eolmode.lower() not in eolmodes:
1331 if eolmode.lower() not in eolmodes:
1332 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1332 raise util.Abort(_('unsupported line endings type: %s') % eolmode)
1333 eolmode = eolmode.lower()
1333 eolmode = eolmode.lower()
1334
1334
1335 backend = workingbackend(ui, repo, similarity)
1335 backend = workingbackend(ui, repo, similarity)
1336 try:
1336 try:
1337 fp = open(patchobj, 'rb')
1337 fp = open(patchobj, 'rb')
1338 except TypeError:
1338 except TypeError:
1339 fp = patchobj
1339 fp = patchobj
1340 try:
1340 try:
1341 ret = applydiff(ui, fp, files, backend, strip=strip, eolmode=eolmode)
1341 ret = applydiff(ui, fp, files, backend, strip=strip, eolmode=eolmode)
1342 finally:
1342 finally:
1343 if fp != patchobj:
1343 if fp != patchobj:
1344 fp.close()
1344 fp.close()
1345 files.update(dict.fromkeys(backend.close()))
1345 files.update(dict.fromkeys(backend.close()))
1346 if ret < 0:
1346 if ret < 0:
1347 raise PatchError(_('patch failed to apply'))
1347 raise PatchError(_('patch failed to apply'))
1348 return ret > 0
1348 return ret > 0
1349
1349
1350 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1350 def patch(ui, repo, patchname, strip=1, files=None, eolmode='strict',
1351 similarity=0):
1351 similarity=0):
1352 """Apply <patchname> to the working directory.
1352 """Apply <patchname> to the working directory.
1353
1353
1354 'eolmode' specifies how end of lines should be handled. It can be:
1354 'eolmode' specifies how end of lines should be handled. It can be:
1355 - 'strict': inputs are read in binary mode, EOLs are preserved
1355 - 'strict': inputs are read in binary mode, EOLs are preserved
1356 - 'crlf': EOLs are ignored when patching and reset to CRLF
1356 - 'crlf': EOLs are ignored when patching and reset to CRLF
1357 - 'lf': EOLs are ignored when patching and reset to LF
1357 - 'lf': EOLs are ignored when patching and reset to LF
1358 - None: get it from user settings, default to 'strict'
1358 - None: get it from user settings, default to 'strict'
1359 'eolmode' is ignored when using an external patcher program.
1359 'eolmode' is ignored when using an external patcher program.
1360
1360
1361 Returns whether patch was applied with fuzz factor.
1361 Returns whether patch was applied with fuzz factor.
1362 """
1362 """
1363 patcher = ui.config('ui', 'patch')
1363 patcher = ui.config('ui', 'patch')
1364 if files is None:
1364 if files is None:
1365 files = {}
1365 files = {}
1366 try:
1366 try:
1367 if patcher:
1367 if patcher:
1368 return _externalpatch(ui, repo, patcher, patchname, strip,
1368 return _externalpatch(ui, repo, patcher, patchname, strip,
1369 files, similarity)
1369 files, similarity)
1370 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1370 return internalpatch(ui, repo, patchname, strip, files, eolmode,
1371 similarity)
1371 similarity)
1372 except PatchError, err:
1372 except PatchError, err:
1373 raise util.Abort(str(err))
1373 raise util.Abort(str(err))
1374
1374
1375 def changedfiles(ui, repo, patchpath, strip=1):
1375 def changedfiles(ui, repo, patchpath, strip=1):
1376 backend = fsbackend(ui, repo.root)
1376 backend = fsbackend(ui, repo.root)
1377 fp = open(patchpath, 'rb')
1377 fp = open(patchpath, 'rb')
1378 try:
1378 try:
1379 changed = set()
1379 changed = set()
1380 for state, values in iterhunks(fp):
1380 for state, values in iterhunks(fp):
1381 if state == 'file':
1381 if state == 'file':
1382 afile, bfile, first_hunk, gp = values
1382 afile, bfile, first_hunk, gp = values
1383 if gp:
1383 if gp:
1384 changed.add(pathstrip(gp.path, strip - 1)[1])
1384 changed.add(pathstrip(gp.path, strip - 1)[1])
1385 if gp.op == 'RENAME':
1385 if gp.op == 'RENAME':
1386 changed.add(pathstrip(gp.oldpath, strip - 1)[1])
1386 changed.add(pathstrip(gp.oldpath, strip - 1)[1])
1387 if not first_hunk:
1387 if not first_hunk:
1388 continue
1388 continue
1389 current_file, missing = selectfile(backend, afile, bfile,
1389 current_file, missing = selectfile(backend, afile, bfile,
1390 first_hunk, strip, gp)
1390 first_hunk, strip, gp)
1391 changed.add(current_file)
1391 changed.add(current_file)
1392 elif state not in ('hunk', 'git'):
1392 elif state not in ('hunk', 'git'):
1393 raise util.Abort(_('unsupported parser state: %s') % state)
1393 raise util.Abort(_('unsupported parser state: %s') % state)
1394 return changed
1394 return changed
1395 finally:
1395 finally:
1396 fp.close()
1396 fp.close()
1397
1397
1398 def b85diff(to, tn):
1398 def b85diff(to, tn):
1399 '''print base85-encoded binary diff'''
1399 '''print base85-encoded binary diff'''
1400 def gitindex(text):
1400 def gitindex(text):
1401 if not text:
1401 if not text:
1402 return hex(nullid)
1402 return hex(nullid)
1403 l = len(text)
1403 l = len(text)
1404 s = util.sha1('blob %d\0' % l)
1404 s = util.sha1('blob %d\0' % l)
1405 s.update(text)
1405 s.update(text)
1406 return s.hexdigest()
1406 return s.hexdigest()
1407
1407
1408 def fmtline(line):
1408 def fmtline(line):
1409 l = len(line)
1409 l = len(line)
1410 if l <= 26:
1410 if l <= 26:
1411 l = chr(ord('A') + l - 1)
1411 l = chr(ord('A') + l - 1)
1412 else:
1412 else:
1413 l = chr(l - 26 + ord('a') - 1)
1413 l = chr(l - 26 + ord('a') - 1)
1414 return '%c%s\n' % (l, base85.b85encode(line, True))
1414 return '%c%s\n' % (l, base85.b85encode(line, True))
1415
1415
1416 def chunk(text, csize=52):
1416 def chunk(text, csize=52):
1417 l = len(text)
1417 l = len(text)
1418 i = 0
1418 i = 0
1419 while i < l:
1419 while i < l:
1420 yield text[i:i + csize]
1420 yield text[i:i + csize]
1421 i += csize
1421 i += csize
1422
1422
1423 tohash = gitindex(to)
1423 tohash = gitindex(to)
1424 tnhash = gitindex(tn)
1424 tnhash = gitindex(tn)
1425 if tohash == tnhash:
1425 if tohash == tnhash:
1426 return ""
1426 return ""
1427
1427
1428 # TODO: deltas
1428 # TODO: deltas
1429 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1429 ret = ['index %s..%s\nGIT binary patch\nliteral %s\n' %
1430 (tohash, tnhash, len(tn))]
1430 (tohash, tnhash, len(tn))]
1431 for l in chunk(zlib.compress(tn)):
1431 for l in chunk(zlib.compress(tn)):
1432 ret.append(fmtline(l))
1432 ret.append(fmtline(l))
1433 ret.append('\n')
1433 ret.append('\n')
1434 return ''.join(ret)
1434 return ''.join(ret)
1435
1435
1436 class GitDiffRequired(Exception):
1436 class GitDiffRequired(Exception):
1437 pass
1437 pass
1438
1438
1439 def diffopts(ui, opts=None, untrusted=False):
1439 def diffopts(ui, opts=None, untrusted=False):
1440 def get(key, name=None, getter=ui.configbool):
1440 def get(key, name=None, getter=ui.configbool):
1441 return ((opts and opts.get(key)) or
1441 return ((opts and opts.get(key)) or
1442 getter('diff', name or key, None, untrusted=untrusted))
1442 getter('diff', name or key, None, untrusted=untrusted))
1443 return mdiff.diffopts(
1443 return mdiff.diffopts(
1444 text=opts and opts.get('text'),
1444 text=opts and opts.get('text'),
1445 git=get('git'),
1445 git=get('git'),
1446 nodates=get('nodates'),
1446 nodates=get('nodates'),
1447 showfunc=get('show_function', 'showfunc'),
1447 showfunc=get('show_function', 'showfunc'),
1448 ignorews=get('ignore_all_space', 'ignorews'),
1448 ignorews=get('ignore_all_space', 'ignorews'),
1449 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1449 ignorewsamount=get('ignore_space_change', 'ignorewsamount'),
1450 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1450 ignoreblanklines=get('ignore_blank_lines', 'ignoreblanklines'),
1451 context=get('unified', getter=ui.config))
1451 context=get('unified', getter=ui.config))
1452
1452
1453 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1453 def diff(repo, node1=None, node2=None, match=None, changes=None, opts=None,
1454 losedatafn=None, prefix=''):
1454 losedatafn=None, prefix=''):
1455 '''yields diff of changes to files between two nodes, or node and
1455 '''yields diff of changes to files between two nodes, or node and
1456 working directory.
1456 working directory.
1457
1457
1458 if node1 is None, use first dirstate parent instead.
1458 if node1 is None, use first dirstate parent instead.
1459 if node2 is None, compare node1 with working directory.
1459 if node2 is None, compare node1 with working directory.
1460
1460
1461 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1461 losedatafn(**kwarg) is a callable run when opts.upgrade=True and
1462 every time some change cannot be represented with the current
1462 every time some change cannot be represented with the current
1463 patch format. Return False to upgrade to git patch format, True to
1463 patch format. Return False to upgrade to git patch format, True to
1464 accept the loss or raise an exception to abort the diff. It is
1464 accept the loss or raise an exception to abort the diff. It is
1465 called with the name of current file being diffed as 'fn'. If set
1465 called with the name of current file being diffed as 'fn'. If set
1466 to None, patches will always be upgraded to git format when
1466 to None, patches will always be upgraded to git format when
1467 necessary.
1467 necessary.
1468
1468
1469 prefix is a filename prefix that is prepended to all filenames on
1469 prefix is a filename prefix that is prepended to all filenames on
1470 display (used for subrepos).
1470 display (used for subrepos).
1471 '''
1471 '''
1472
1472
1473 if opts is None:
1473 if opts is None:
1474 opts = mdiff.defaultopts
1474 opts = mdiff.defaultopts
1475
1475
1476 if not node1 and not node2:
1476 if not node1 and not node2:
1477 node1 = repo.dirstate.p1()
1477 node1 = repo.dirstate.p1()
1478
1478
1479 def lrugetfilectx():
1479 def lrugetfilectx():
1480 cache = {}
1480 cache = {}
1481 order = []
1481 order = []
1482 def getfilectx(f, ctx):
1482 def getfilectx(f, ctx):
1483 fctx = ctx.filectx(f, filelog=cache.get(f))
1483 fctx = ctx.filectx(f, filelog=cache.get(f))
1484 if f not in cache:
1484 if f not in cache:
1485 if len(cache) > 20:
1485 if len(cache) > 20:
1486 del cache[order.pop(0)]
1486 del cache[order.pop(0)]
1487 cache[f] = fctx.filelog()
1487 cache[f] = fctx.filelog()
1488 else:
1488 else:
1489 order.remove(f)
1489 order.remove(f)
1490 order.append(f)
1490 order.append(f)
1491 return fctx
1491 return fctx
1492 return getfilectx
1492 return getfilectx
1493 getfilectx = lrugetfilectx()
1493 getfilectx = lrugetfilectx()
1494
1494
1495 ctx1 = repo[node1]
1495 ctx1 = repo[node1]
1496 ctx2 = repo[node2]
1496 ctx2 = repo[node2]
1497
1497
1498 if not changes:
1498 if not changes:
1499 changes = repo.status(ctx1, ctx2, match=match)
1499 changes = repo.status(ctx1, ctx2, match=match)
1500 modified, added, removed = changes[:3]
1500 modified, added, removed = changes[:3]
1501
1501
1502 if not modified and not added and not removed:
1502 if not modified and not added and not removed:
1503 return []
1503 return []
1504
1504
1505 revs = None
1505 revs = None
1506 if not repo.ui.quiet:
1506 if not repo.ui.quiet:
1507 hexfunc = repo.ui.debugflag and hex or short
1507 hexfunc = repo.ui.debugflag and hex or short
1508 revs = [hexfunc(node) for node in [node1, node2] if node]
1508 revs = [hexfunc(node) for node in [node1, node2] if node]
1509
1509
1510 copy = {}
1510 copy = {}
1511 if opts.git or opts.upgrade:
1511 if opts.git or opts.upgrade:
1512 copy = copies.copies(repo, ctx1, ctx2, repo[nullid])[0]
1512 copy = copies.copies(repo, ctx1, ctx2, repo[nullid])[0]
1513
1513
1514 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1514 difffn = lambda opts, losedata: trydiff(repo, revs, ctx1, ctx2,
1515 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1515 modified, added, removed, copy, getfilectx, opts, losedata, prefix)
1516 if opts.upgrade and not opts.git:
1516 if opts.upgrade and not opts.git:
1517 try:
1517 try:
1518 def losedata(fn):
1518 def losedata(fn):
1519 if not losedatafn or not losedatafn(fn=fn):
1519 if not losedatafn or not losedatafn(fn=fn):
1520 raise GitDiffRequired()
1520 raise GitDiffRequired()
1521 # Buffer the whole output until we are sure it can be generated
1521 # Buffer the whole output until we are sure it can be generated
1522 return list(difffn(opts.copy(git=False), losedata))
1522 return list(difffn(opts.copy(git=False), losedata))
1523 except GitDiffRequired:
1523 except GitDiffRequired:
1524 return difffn(opts.copy(git=True), None)
1524 return difffn(opts.copy(git=True), None)
1525 else:
1525 else:
1526 return difffn(opts, None)
1526 return difffn(opts, None)
1527
1527
1528 def difflabel(func, *args, **kw):
1528 def difflabel(func, *args, **kw):
1529 '''yields 2-tuples of (output, label) based on the output of func()'''
1529 '''yields 2-tuples of (output, label) based on the output of func()'''
1530 prefixes = [('diff', 'diff.diffline'),
1530 prefixes = [('diff', 'diff.diffline'),
1531 ('copy', 'diff.extended'),
1531 ('copy', 'diff.extended'),
1532 ('rename', 'diff.extended'),
1532 ('rename', 'diff.extended'),
1533 ('old', 'diff.extended'),
1533 ('old', 'diff.extended'),
1534 ('new', 'diff.extended'),
1534 ('new', 'diff.extended'),
1535 ('deleted', 'diff.extended'),
1535 ('deleted', 'diff.extended'),
1536 ('---', 'diff.file_a'),
1536 ('---', 'diff.file_a'),
1537 ('+++', 'diff.file_b'),
1537 ('+++', 'diff.file_b'),
1538 ('@@', 'diff.hunk'),
1538 ('@@', 'diff.hunk'),
1539 ('-', 'diff.deleted'),
1539 ('-', 'diff.deleted'),
1540 ('+', 'diff.inserted')]
1540 ('+', 'diff.inserted')]
1541
1541
1542 for chunk in func(*args, **kw):
1542 for chunk in func(*args, **kw):
1543 lines = chunk.split('\n')
1543 lines = chunk.split('\n')
1544 for i, line in enumerate(lines):
1544 for i, line in enumerate(lines):
1545 if i != 0:
1545 if i != 0:
1546 yield ('\n', '')
1546 yield ('\n', '')
1547 stripline = line
1547 stripline = line
1548 if line and line[0] in '+-':
1548 if line and line[0] in '+-':
1549 # highlight trailing whitespace, but only in changed lines
1549 # highlight trailing whitespace, but only in changed lines
1550 stripline = line.rstrip()
1550 stripline = line.rstrip()
1551 for prefix, label in prefixes:
1551 for prefix, label in prefixes:
1552 if stripline.startswith(prefix):
1552 if stripline.startswith(prefix):
1553 yield (stripline, label)
1553 yield (stripline, label)
1554 break
1554 break
1555 else:
1555 else:
1556 yield (line, '')
1556 yield (line, '')
1557 if line != stripline:
1557 if line != stripline:
1558 yield (line[len(stripline):], 'diff.trailingwhitespace')
1558 yield (line[len(stripline):], 'diff.trailingwhitespace')
1559
1559
1560 def diffui(*args, **kw):
1560 def diffui(*args, **kw):
1561 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1561 '''like diff(), but yields 2-tuples of (output, label) for ui.write()'''
1562 return difflabel(diff, *args, **kw)
1562 return difflabel(diff, *args, **kw)
1563
1563
1564
1564
1565 def _addmodehdr(header, omode, nmode):
1565 def _addmodehdr(header, omode, nmode):
1566 if omode != nmode:
1566 if omode != nmode:
1567 header.append('old mode %s\n' % omode)
1567 header.append('old mode %s\n' % omode)
1568 header.append('new mode %s\n' % nmode)
1568 header.append('new mode %s\n' % nmode)
1569
1569
1570 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1570 def trydiff(repo, revs, ctx1, ctx2, modified, added, removed,
1571 copy, getfilectx, opts, losedatafn, prefix):
1571 copy, getfilectx, opts, losedatafn, prefix):
1572
1572
1573 def join(f):
1573 def join(f):
1574 return os.path.join(prefix, f)
1574 return os.path.join(prefix, f)
1575
1575
1576 date1 = util.datestr(ctx1.date())
1576 date1 = util.datestr(ctx1.date())
1577 man1 = ctx1.manifest()
1577 man1 = ctx1.manifest()
1578
1578
1579 gone = set()
1579 gone = set()
1580 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1580 gitmode = {'l': '120000', 'x': '100755', '': '100644'}
1581
1581
1582 copyto = dict([(v, k) for k, v in copy.items()])
1582 copyto = dict([(v, k) for k, v in copy.items()])
1583
1583
1584 if opts.git:
1584 if opts.git:
1585 revs = None
1585 revs = None
1586
1586
1587 for f in sorted(modified + added + removed):
1587 for f in sorted(modified + added + removed):
1588 to = None
1588 to = None
1589 tn = None
1589 tn = None
1590 dodiff = True
1590 dodiff = True
1591 header = []
1591 header = []
1592 if f in man1:
1592 if f in man1:
1593 to = getfilectx(f, ctx1).data()
1593 to = getfilectx(f, ctx1).data()
1594 if f not in removed:
1594 if f not in removed:
1595 tn = getfilectx(f, ctx2).data()
1595 tn = getfilectx(f, ctx2).data()
1596 a, b = f, f
1596 a, b = f, f
1597 if opts.git or losedatafn:
1597 if opts.git or losedatafn:
1598 if f in added:
1598 if f in added:
1599 mode = gitmode[ctx2.flags(f)]
1599 mode = gitmode[ctx2.flags(f)]
1600 if f in copy or f in copyto:
1600 if f in copy or f in copyto:
1601 if opts.git:
1601 if opts.git:
1602 if f in copy:
1602 if f in copy:
1603 a = copy[f]
1603 a = copy[f]
1604 else:
1604 else:
1605 a = copyto[f]
1605 a = copyto[f]
1606 omode = gitmode[man1.flags(a)]
1606 omode = gitmode[man1.flags(a)]
1607 _addmodehdr(header, omode, mode)
1607 _addmodehdr(header, omode, mode)
1608 if a in removed and a not in gone:
1608 if a in removed and a not in gone:
1609 op = 'rename'
1609 op = 'rename'
1610 gone.add(a)
1610 gone.add(a)
1611 else:
1611 else:
1612 op = 'copy'
1612 op = 'copy'
1613 header.append('%s from %s\n' % (op, join(a)))
1613 header.append('%s from %s\n' % (op, join(a)))
1614 header.append('%s to %s\n' % (op, join(f)))
1614 header.append('%s to %s\n' % (op, join(f)))
1615 to = getfilectx(a, ctx1).data()
1615 to = getfilectx(a, ctx1).data()
1616 else:
1616 else:
1617 losedatafn(f)
1617 losedatafn(f)
1618 else:
1618 else:
1619 if opts.git:
1619 if opts.git:
1620 header.append('new file mode %s\n' % mode)
1620 header.append('new file mode %s\n' % mode)
1621 elif ctx2.flags(f):
1621 elif ctx2.flags(f):
1622 losedatafn(f)
1622 losedatafn(f)
1623 # In theory, if tn was copied or renamed we should check
1623 # In theory, if tn was copied or renamed we should check
1624 # if the source is binary too but the copy record already
1624 # if the source is binary too but the copy record already
1625 # forces git mode.
1625 # forces git mode.
1626 if util.binary(tn):
1626 if util.binary(tn):
1627 if opts.git:
1627 if opts.git:
1628 dodiff = 'binary'
1628 dodiff = 'binary'
1629 else:
1629 else:
1630 losedatafn(f)
1630 losedatafn(f)
1631 if not opts.git and not tn:
1631 if not opts.git and not tn:
1632 # regular diffs cannot represent new empty file
1632 # regular diffs cannot represent new empty file
1633 losedatafn(f)
1633 losedatafn(f)
1634 elif f in removed:
1634 elif f in removed:
1635 if opts.git:
1635 if opts.git:
1636 # have we already reported a copy above?
1636 # have we already reported a copy above?
1637 if ((f in copy and copy[f] in added
1637 if ((f in copy and copy[f] in added
1638 and copyto[copy[f]] == f) or
1638 and copyto[copy[f]] == f) or
1639 (f in copyto and copyto[f] in added
1639 (f in copyto and copyto[f] in added
1640 and copy[copyto[f]] == f)):
1640 and copy[copyto[f]] == f)):
1641 dodiff = False
1641 dodiff = False
1642 else:
1642 else:
1643 header.append('deleted file mode %s\n' %
1643 header.append('deleted file mode %s\n' %
1644 gitmode[man1.flags(f)])
1644 gitmode[man1.flags(f)])
1645 elif not to or util.binary(to):
1645 elif not to or util.binary(to):
1646 # regular diffs cannot represent empty file deletion
1646 # regular diffs cannot represent empty file deletion
1647 losedatafn(f)
1647 losedatafn(f)
1648 else:
1648 else:
1649 oflag = man1.flags(f)
1649 oflag = man1.flags(f)
1650 nflag = ctx2.flags(f)
1650 nflag = ctx2.flags(f)
1651 binary = util.binary(to) or util.binary(tn)
1651 binary = util.binary(to) or util.binary(tn)
1652 if opts.git:
1652 if opts.git:
1653 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1653 _addmodehdr(header, gitmode[oflag], gitmode[nflag])
1654 if binary:
1654 if binary:
1655 dodiff = 'binary'
1655 dodiff = 'binary'
1656 elif binary or nflag != oflag:
1656 elif binary or nflag != oflag:
1657 losedatafn(f)
1657 losedatafn(f)
1658 if opts.git:
1658 if opts.git:
1659 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1659 header.insert(0, mdiff.diffline(revs, join(a), join(b), opts))
1660
1660
1661 if dodiff:
1661 if dodiff:
1662 if dodiff == 'binary':
1662 if dodiff == 'binary':
1663 text = b85diff(to, tn)
1663 text = b85diff(to, tn)
1664 else:
1664 else:
1665 text = mdiff.unidiff(to, date1,
1665 text = mdiff.unidiff(to, date1,
1666 # ctx2 date may be dynamic
1666 # ctx2 date may be dynamic
1667 tn, util.datestr(ctx2.date()),
1667 tn, util.datestr(ctx2.date()),
1668 join(a), join(b), revs, opts=opts)
1668 join(a), join(b), revs, opts=opts)
1669 if header and (text or len(header) > 1):
1669 if header and (text or len(header) > 1):
1670 yield ''.join(header)
1670 yield ''.join(header)
1671 if text:
1671 if text:
1672 yield text
1672 yield text
1673
1673
1674 def diffstatsum(stats):
1674 def diffstatsum(stats):
1675 maxfile, addtotal, removetotal, binary = 0, 0, 0, False
1675 maxfile, addtotal, removetotal, binary = 0, 0, 0, False
1676 for f, a, r, b in stats:
1676 for f, a, r, b in stats:
1677 maxfile = max(maxfile, encoding.colwidth(f))
1677 maxfile = max(maxfile, encoding.colwidth(f))
1678 addtotal += a
1678 addtotal += a
1679 removetotal += r
1679 removetotal += r
1680 binary = binary or b
1680 binary = binary or b
1681
1681
1682 return maxfile, addtotal, removetotal, binary
1682 return maxfile, addtotal, removetotal, binary
1683
1683
1684 def diffstatdata(lines):
1684 def diffstatdata(lines):
1685 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1685 diffre = re.compile('^diff .*-r [a-z0-9]+\s(.*)$')
1686
1686
1687 results = []
1687 results = []
1688 filename, adds, removes = None, 0, 0
1688 filename, adds, removes = None, 0, 0
1689
1689
1690 def addresult():
1690 def addresult():
1691 if filename:
1691 if filename:
1692 isbinary = adds == 0 and removes == 0
1692 isbinary = adds == 0 and removes == 0
1693 results.append((filename, adds, removes, isbinary))
1693 results.append((filename, adds, removes, isbinary))
1694
1694
1695 for line in lines:
1695 for line in lines:
1696 if line.startswith('diff'):
1696 if line.startswith('diff'):
1697 addresult()
1697 addresult()
1698 # set numbers to 0 anyway when starting new file
1698 # set numbers to 0 anyway when starting new file
1699 adds, removes = 0, 0
1699 adds, removes = 0, 0
1700 if line.startswith('diff --git'):
1700 if line.startswith('diff --git'):
1701 filename = gitre.search(line).group(1)
1701 filename = gitre.search(line).group(1)
1702 elif line.startswith('diff -r'):
1702 elif line.startswith('diff -r'):
1703 # format: "diff -r ... -r ... filename"
1703 # format: "diff -r ... -r ... filename"
1704 filename = diffre.search(line).group(1)
1704 filename = diffre.search(line).group(1)
1705 elif line.startswith('+') and not line.startswith('+++'):
1705 elif line.startswith('+') and not line.startswith('+++'):
1706 adds += 1
1706 adds += 1
1707 elif line.startswith('-') and not line.startswith('---'):
1707 elif line.startswith('-') and not line.startswith('---'):
1708 removes += 1
1708 removes += 1
1709 addresult()
1709 addresult()
1710 return results
1710 return results
1711
1711
1712 def diffstat(lines, width=80, git=False):
1712 def diffstat(lines, width=80, git=False):
1713 output = []
1713 output = []
1714 stats = diffstatdata(lines)
1714 stats = diffstatdata(lines)
1715 maxname, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1715 maxname, totaladds, totalremoves, hasbinary = diffstatsum(stats)
1716 maxtotal = totaladds + totalremoves
1716 maxtotal = totaladds + totalremoves
1717
1717
1718 countwidth = len(str(maxtotal))
1718 countwidth = len(str(maxtotal))
1719 if hasbinary and countwidth < 3:
1719 if hasbinary and countwidth < 3:
1720 countwidth = 3
1720 countwidth = 3
1721 graphwidth = width - countwidth - maxname - 6
1721 graphwidth = width - countwidth - maxname - 6
1722 if graphwidth < 10:
1722 if graphwidth < 10:
1723 graphwidth = 10
1723 graphwidth = 10
1724
1724
1725 def scale(i):
1725 def scale(i):
1726 if maxtotal <= graphwidth:
1726 if maxtotal <= graphwidth:
1727 return i
1727 return i
1728 # If diffstat runs out of room it doesn't print anything,
1728 # If diffstat runs out of room it doesn't print anything,
1729 # which isn't very useful, so always print at least one + or -
1729 # which isn't very useful, so always print at least one + or -
1730 # if there were at least some changes.
1730 # if there were at least some changes.
1731 return max(i * graphwidth // maxtotal, int(bool(i)))
1731 return max(i * graphwidth // maxtotal, int(bool(i)))
1732
1732
1733 for filename, adds, removes, isbinary in stats:
1733 for filename, adds, removes, isbinary in stats:
1734 if git and isbinary:
1734 if git and isbinary:
1735 count = 'Bin'
1735 count = 'Bin'
1736 else:
1736 else:
1737 count = adds + removes
1737 count = adds + removes
1738 pluses = '+' * scale(adds)
1738 pluses = '+' * scale(adds)
1739 minuses = '-' * scale(removes)
1739 minuses = '-' * scale(removes)
1740 output.append(' %s%s | %*s %s%s\n' %
1740 output.append(' %s%s | %*s %s%s\n' %
1741 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1741 (filename, ' ' * (maxname - encoding.colwidth(filename)),
1742 countwidth, count, pluses, minuses))
1742 countwidth, count, pluses, minuses))
1743
1743
1744 if stats:
1744 if stats:
1745 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1745 output.append(_(' %d files changed, %d insertions(+), %d deletions(-)\n')
1746 % (len(stats), totaladds, totalremoves))
1746 % (len(stats), totaladds, totalremoves))
1747
1747
1748 return ''.join(output)
1748 return ''.join(output)
1749
1749
1750 def diffstatui(*args, **kw):
1750 def diffstatui(*args, **kw):
1751 '''like diffstat(), but yields 2-tuples of (output, label) for
1751 '''like diffstat(), but yields 2-tuples of (output, label) for
1752 ui.write()
1752 ui.write()
1753 '''
1753 '''
1754
1754
1755 for line in diffstat(*args, **kw).splitlines():
1755 for line in diffstat(*args, **kw).splitlines():
1756 if line and line[-1] in '+-':
1756 if line and line[-1] in '+-':
1757 name, graph = line.rsplit(' ', 1)
1757 name, graph = line.rsplit(' ', 1)
1758 yield (name + ' ', '')
1758 yield (name + ' ', '')
1759 m = re.search(r'\++', graph)
1759 m = re.search(r'\++', graph)
1760 if m:
1760 if m:
1761 yield (m.group(0), 'diffstat.inserted')
1761 yield (m.group(0), 'diffstat.inserted')
1762 m = re.search(r'-+', graph)
1762 m = re.search(r'-+', graph)
1763 if m:
1763 if m:
1764 yield (m.group(0), 'diffstat.deleted')
1764 yield (m.group(0), 'diffstat.deleted')
1765 else:
1765 else:
1766 yield (line, '')
1766 yield (line, '')
1767 yield ('\n', '')
1767 yield ('\n', '')
@@ -1,693 +1,693 b''
1 # scmutil.py - Mercurial core utility functions
1 # scmutil.py - Mercurial core utility functions
2 #
2 #
3 # Copyright Matt Mackall <mpm@selenic.com>
3 # Copyright 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 i18n import _
8 from i18n import _
9 import util, error, osutil, revset, similar
9 import util, error, osutil, revset, similar
10 import match as matchmod
10 import match as matchmod
11 import os, errno, stat, sys, glob
11 import os, errno, stat, sys, glob
12
12
13 def checkfilename(f):
13 def checkfilename(f):
14 '''Check that the filename f is an acceptable filename for a tracked file'''
14 '''Check that the filename f is an acceptable filename for a tracked file'''
15 if '\r' in f or '\n' in f:
15 if '\r' in f or '\n' in f:
16 raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
16 raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
17
17
18 def checkportable(ui, f):
18 def checkportable(ui, f):
19 '''Check if filename f is portable and warn or abort depending on config'''
19 '''Check if filename f is portable and warn or abort depending on config'''
20 checkfilename(f)
20 checkfilename(f)
21 abort, warn = checkportabilityalert(ui)
21 abort, warn = checkportabilityalert(ui)
22 if abort or warn:
22 if abort or warn:
23 msg = util.checkwinfilename(f)
23 msg = util.checkwinfilename(f)
24 if msg:
24 if msg:
25 msg = "%s: %r" % (msg, f)
25 msg = "%s: %r" % (msg, f)
26 if abort:
26 if abort:
27 raise util.Abort(msg)
27 raise util.Abort(msg)
28 ui.warn(_("warning: %s\n") % msg)
28 ui.warn(_("warning: %s\n") % msg)
29
29
30 def checkportabilityalert(ui):
30 def checkportabilityalert(ui):
31 '''check if the user's config requests nothing, a warning, or abort for
31 '''check if the user's config requests nothing, a warning, or abort for
32 non-portable filenames'''
32 non-portable filenames'''
33 val = ui.config('ui', 'portablefilenames', 'warn')
33 val = ui.config('ui', 'portablefilenames', 'warn')
34 lval = val.lower()
34 lval = val.lower()
35 bval = util.parsebool(val)
35 bval = util.parsebool(val)
36 abort = os.name == 'nt' or lval == 'abort'
36 abort = os.name == 'nt' or lval == 'abort'
37 warn = bval or lval == 'warn'
37 warn = bval or lval == 'warn'
38 if bval is None and not (warn or abort or lval == 'ignore'):
38 if bval is None and not (warn or abort or lval == 'ignore'):
39 raise error.ConfigError(
39 raise error.ConfigError(
40 _("ui.portablefilenames value is invalid ('%s')") % val)
40 _("ui.portablefilenames value is invalid ('%s')") % val)
41 return abort, warn
41 return abort, warn
42
42
43 class casecollisionauditor(object):
43 class casecollisionauditor(object):
44 def __init__(self, ui, abort, existingiter):
44 def __init__(self, ui, abort, existingiter):
45 self._ui = ui
45 self._ui = ui
46 self._abort = abort
46 self._abort = abort
47 self._map = {}
47 self._map = {}
48 for f in existingiter:
48 for f in existingiter:
49 self._map[f.lower()] = f
49 self._map[f.lower()] = f
50
50
51 def __call__(self, f):
51 def __call__(self, f):
52 fl = f.lower()
52 fl = f.lower()
53 map = self._map
53 map = self._map
54 if fl in map and map[fl] != f:
54 if fl in map and map[fl] != f:
55 msg = _('possible case-folding collision for %s') % f
55 msg = _('possible case-folding collision for %s') % f
56 if self._abort:
56 if self._abort:
57 raise util.Abort(msg)
57 raise util.Abort(msg)
58 self._ui.warn(_("warning: %s\n") % msg)
58 self._ui.warn(_("warning: %s\n") % msg)
59 map[fl] = f
59 map[fl] = f
60
60
61 class pathauditor(object):
61 class pathauditor(object):
62 '''ensure that a filesystem path contains no banned components.
62 '''ensure that a filesystem path contains no banned components.
63 the following properties of a path are checked:
63 the following properties of a path are checked:
64
64
65 - ends with a directory separator
65 - ends with a directory separator
66 - under top-level .hg
66 - under top-level .hg
67 - starts at the root of a windows drive
67 - starts at the root of a windows drive
68 - contains ".."
68 - contains ".."
69 - traverses a symlink (e.g. a/symlink_here/b)
69 - traverses a symlink (e.g. a/symlink_here/b)
70 - inside a nested repository (a callback can be used to approve
70 - inside a nested repository (a callback can be used to approve
71 some nested repositories, e.g., subrepositories)
71 some nested repositories, e.g., subrepositories)
72 '''
72 '''
73
73
74 def __init__(self, root, callback=None):
74 def __init__(self, root, callback=None):
75 self.audited = set()
75 self.audited = set()
76 self.auditeddir = set()
76 self.auditeddir = set()
77 self.root = root
77 self.root = root
78 self.callback = callback
78 self.callback = callback
79
79
80 def __call__(self, path):
80 def __call__(self, path):
81 '''Check the relative path.
81 '''Check the relative path.
82 path may contain a pattern (e.g. foodir/**.txt)'''
82 path may contain a pattern (e.g. foodir/**.txt)'''
83
83
84 if path in self.audited:
84 if path in self.audited:
85 return
85 return
86 # AIX ignores "/" at end of path, others raise EISDIR.
86 # AIX ignores "/" at end of path, others raise EISDIR.
87 if util.endswithsep(path):
87 if util.endswithsep(path):
88 raise util.Abort(_("path ends in directory separator: %s") % path)
88 raise util.Abort(_("path ends in directory separator: %s") % path)
89 normpath = os.path.normcase(path)
89 normpath = os.path.normcase(path)
90 parts = util.splitpath(normpath)
90 parts = util.splitpath(normpath)
91 if (os.path.splitdrive(path)[0]
91 if (os.path.splitdrive(path)[0]
92 or parts[0].lower() in ('.hg', '.hg.', '')
92 or parts[0].lower() in ('.hg', '.hg.', '')
93 or os.pardir in parts):
93 or os.pardir in parts):
94 raise util.Abort(_("path contains illegal component: %s") % path)
94 raise util.Abort(_("path contains illegal component: %s") % path)
95 if '.hg' in path.lower():
95 if '.hg' in path.lower():
96 lparts = [p.lower() for p in parts]
96 lparts = [p.lower() for p in parts]
97 for p in '.hg', '.hg.':
97 for p in '.hg', '.hg.':
98 if p in lparts[1:]:
98 if p in lparts[1:]:
99 pos = lparts.index(p)
99 pos = lparts.index(p)
100 base = os.path.join(*parts[:pos])
100 base = os.path.join(*parts[:pos])
101 raise util.Abort(_('path %r is inside nested repo %r')
101 raise util.Abort(_('path %r is inside nested repo %r')
102 % (path, base))
102 % (path, base))
103
103
104 parts.pop()
104 parts.pop()
105 prefixes = []
105 prefixes = []
106 while parts:
106 while parts:
107 prefix = os.sep.join(parts)
107 prefix = os.sep.join(parts)
108 if prefix in self.auditeddir:
108 if prefix in self.auditeddir:
109 break
109 break
110 curpath = os.path.join(self.root, prefix)
110 curpath = os.path.join(self.root, prefix)
111 try:
111 try:
112 st = os.lstat(curpath)
112 st = os.lstat(curpath)
113 except OSError, err:
113 except OSError, err:
114 # EINVAL can be raised as invalid path syntax under win32.
114 # EINVAL can be raised as invalid path syntax under win32.
115 # They must be ignored for patterns can be checked too.
115 # They must be ignored for patterns can be checked too.
116 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
116 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
117 raise
117 raise
118 else:
118 else:
119 if stat.S_ISLNK(st.st_mode):
119 if stat.S_ISLNK(st.st_mode):
120 raise util.Abort(
120 raise util.Abort(
121 _('path %r traverses symbolic link %r')
121 _('path %r traverses symbolic link %r')
122 % (path, prefix))
122 % (path, prefix))
123 elif (stat.S_ISDIR(st.st_mode) and
123 elif (stat.S_ISDIR(st.st_mode) and
124 os.path.isdir(os.path.join(curpath, '.hg'))):
124 os.path.isdir(os.path.join(curpath, '.hg'))):
125 if not self.callback or not self.callback(curpath):
125 if not self.callback or not self.callback(curpath):
126 raise util.Abort(_('path %r is inside nested repo %r') %
126 raise util.Abort(_('path %r is inside nested repo %r') %
127 (path, prefix))
127 (path, prefix))
128 prefixes.append(prefix)
128 prefixes.append(prefix)
129 parts.pop()
129 parts.pop()
130
130
131 self.audited.add(path)
131 self.audited.add(path)
132 # only add prefixes to the cache after checking everything: we don't
132 # only add prefixes to the cache after checking everything: we don't
133 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
133 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
134 self.auditeddir.update(prefixes)
134 self.auditeddir.update(prefixes)
135
135
136 class abstractopener(object):
136 class abstractopener(object):
137 """Abstract base class; cannot be instantiated"""
137 """Abstract base class; cannot be instantiated"""
138
138
139 def __init__(self, *args, **kwargs):
139 def __init__(self, *args, **kwargs):
140 '''Prevent instantiation; don't call this from subclasses.'''
140 '''Prevent instantiation; don't call this from subclasses.'''
141 raise NotImplementedError('attempted instantiating ' + str(type(self)))
141 raise NotImplementedError('attempted instantiating ' + str(type(self)))
142
142
143 def read(self, path):
143 def read(self, path):
144 fp = self(path, 'rb')
144 fp = self(path, 'rb')
145 try:
145 try:
146 return fp.read()
146 return fp.read()
147 finally:
147 finally:
148 fp.close()
148 fp.close()
149
149
150 def write(self, path, data):
150 def write(self, path, data):
151 fp = self(path, 'wb')
151 fp = self(path, 'wb')
152 try:
152 try:
153 return fp.write(data)
153 return fp.write(data)
154 finally:
154 finally:
155 fp.close()
155 fp.close()
156
156
157 def append(self, path, data):
157 def append(self, path, data):
158 fp = self(path, 'ab')
158 fp = self(path, 'ab')
159 try:
159 try:
160 return fp.write(data)
160 return fp.write(data)
161 finally:
161 finally:
162 fp.close()
162 fp.close()
163
163
164 class opener(abstractopener):
164 class opener(abstractopener):
165 '''Open files relative to a base directory
165 '''Open files relative to a base directory
166
166
167 This class is used to hide the details of COW semantics and
167 This class is used to hide the details of COW semantics and
168 remote file access from higher level code.
168 remote file access from higher level code.
169 '''
169 '''
170 def __init__(self, base, audit=True):
170 def __init__(self, base, audit=True):
171 self.base = base
171 self.base = base
172 if audit:
172 if audit:
173 self.auditor = pathauditor(base)
173 self.auditor = pathauditor(base)
174 else:
174 else:
175 self.auditor = util.always
175 self.auditor = util.always
176 self.createmode = None
176 self.createmode = None
177 self._trustnlink = None
177 self._trustnlink = None
178
178
179 @util.propertycache
179 @util.propertycache
180 def _cansymlink(self):
180 def _cansymlink(self):
181 return util.checklink(self.base)
181 return util.checklink(self.base)
182
182
183 def _fixfilemode(self, name):
183 def _fixfilemode(self, name):
184 if self.createmode is None:
184 if self.createmode is None:
185 return
185 return
186 os.chmod(name, self.createmode & 0666)
186 os.chmod(name, self.createmode & 0666)
187
187
188 def __call__(self, path, mode="r", text=False, atomictemp=False):
188 def __call__(self, path, mode="r", text=False, atomictemp=False):
189 r = util.checkosfilename(path)
189 r = util.checkosfilename(path)
190 if r:
190 if r:
191 raise util.Abort("%s: %r" % (r, path))
191 raise util.Abort("%s: %r" % (r, path))
192 self.auditor(path)
192 self.auditor(path)
193 f = os.path.join(self.base, path)
193 f = os.path.join(self.base, path)
194
194
195 if not text and "b" not in mode:
195 if not text and "b" not in mode:
196 mode += "b" # for that other OS
196 mode += "b" # for that other OS
197
197
198 nlink = -1
198 nlink = -1
199 dirname, basename = os.path.split(f)
199 dirname, basename = os.path.split(f)
200 # If basename is empty, then the path is malformed because it points
200 # If basename is empty, then the path is malformed because it points
201 # to a directory. Let the posixfile() call below raise IOError.
201 # to a directory. Let the posixfile() call below raise IOError.
202 if basename and mode not in ('r', 'rb'):
202 if basename and mode not in ('r', 'rb'):
203 if atomictemp:
203 if atomictemp:
204 if not os.path.isdir(dirname):
204 if not os.path.isdir(dirname):
205 util.makedirs(dirname, self.createmode)
205 util.makedirs(dirname, self.createmode)
206 return util.atomictempfile(f, mode, self.createmode)
206 return util.atomictempfile(f, mode, self.createmode)
207 try:
207 try:
208 if 'w' in mode:
208 if 'w' in mode:
209 util.unlink(f)
209 util.unlink(f)
210 nlink = 0
210 nlink = 0
211 else:
211 else:
212 # nlinks() may behave differently for files on Windows
212 # nlinks() may behave differently for files on Windows
213 # shares if the file is open.
213 # shares if the file is open.
214 fd = util.posixfile(f)
214 fd = util.posixfile(f)
215 nlink = util.nlinks(f)
215 nlink = util.nlinks(f)
216 if nlink < 1:
216 if nlink < 1:
217 nlink = 2 # force mktempcopy (issue1922)
217 nlink = 2 # force mktempcopy (issue1922)
218 fd.close()
218 fd.close()
219 except (OSError, IOError), e:
219 except (OSError, IOError), e:
220 if e.errno != errno.ENOENT:
220 if e.errno != errno.ENOENT:
221 raise
221 raise
222 nlink = 0
222 nlink = 0
223 if not os.path.isdir(dirname):
223 if not os.path.isdir(dirname):
224 util.makedirs(dirname, self.createmode)
224 util.makedirs(dirname, self.createmode)
225 if nlink > 0:
225 if nlink > 0:
226 if self._trustnlink is None:
226 if self._trustnlink is None:
227 self._trustnlink = nlink > 1 or util.checknlink(f)
227 self._trustnlink = nlink > 1 or util.checknlink(f)
228 if nlink > 1 or not self._trustnlink:
228 if nlink > 1 or not self._trustnlink:
229 util.rename(util.mktempcopy(f), f)
229 util.rename(util.mktempcopy(f), f)
230 fp = util.posixfile(f, mode)
230 fp = util.posixfile(f, mode)
231 if nlink == 0:
231 if nlink == 0:
232 self._fixfilemode(f)
232 self._fixfilemode(f)
233 return fp
233 return fp
234
234
235 def symlink(self, src, dst):
235 def symlink(self, src, dst):
236 self.auditor(dst)
236 self.auditor(dst)
237 linkname = os.path.join(self.base, dst)
237 linkname = os.path.join(self.base, dst)
238 try:
238 try:
239 os.unlink(linkname)
239 os.unlink(linkname)
240 except OSError:
240 except OSError:
241 pass
241 pass
242
242
243 dirname = os.path.dirname(linkname)
243 dirname = os.path.dirname(linkname)
244 if not os.path.exists(dirname):
244 if not os.path.exists(dirname):
245 util.makedirs(dirname, self.createmode)
245 util.makedirs(dirname, self.createmode)
246
246
247 if self._cansymlink:
247 if self._cansymlink:
248 try:
248 try:
249 os.symlink(src, linkname)
249 os.symlink(src, linkname)
250 except OSError, err:
250 except OSError, err:
251 raise OSError(err.errno, _('could not symlink to %r: %s') %
251 raise OSError(err.errno, _('could not symlink to %r: %s') %
252 (src, err.strerror), linkname)
252 (src, err.strerror), linkname)
253 else:
253 else:
254 f = self(dst, "w")
254 f = self(dst, "w")
255 f.write(src)
255 f.write(src)
256 f.close()
256 f.close()
257 self._fixfilemode(dst)
257 self._fixfilemode(dst)
258
258
259 def audit(self, path):
259 def audit(self, path):
260 self.auditor(path)
260 self.auditor(path)
261
261
262 class filteropener(abstractopener):
262 class filteropener(abstractopener):
263 '''Wrapper opener for filtering filenames with a function.'''
263 '''Wrapper opener for filtering filenames with a function.'''
264
264
265 def __init__(self, opener, filter):
265 def __init__(self, opener, filter):
266 self._filter = filter
266 self._filter = filter
267 self._orig = opener
267 self._orig = opener
268
268
269 def __call__(self, path, *args, **kwargs):
269 def __call__(self, path, *args, **kwargs):
270 return self._orig(self._filter(path), *args, **kwargs)
270 return self._orig(self._filter(path), *args, **kwargs)
271
271
272 def canonpath(root, cwd, myname, auditor=None):
272 def canonpath(root, cwd, myname, auditor=None):
273 '''return the canonical path of myname, given cwd and root'''
273 '''return the canonical path of myname, given cwd and root'''
274 if util.endswithsep(root):
274 if util.endswithsep(root):
275 rootsep = root
275 rootsep = root
276 else:
276 else:
277 rootsep = root + os.sep
277 rootsep = root + os.sep
278 name = myname
278 name = myname
279 if not os.path.isabs(name):
279 if not os.path.isabs(name):
280 name = os.path.join(root, cwd, name)
280 name = os.path.join(root, cwd, name)
281 name = os.path.normpath(name)
281 name = os.path.normpath(name)
282 if auditor is None:
282 if auditor is None:
283 auditor = pathauditor(root)
283 auditor = pathauditor(root)
284 if name != rootsep and name.startswith(rootsep):
284 if name != rootsep and name.startswith(rootsep):
285 name = name[len(rootsep):]
285 name = name[len(rootsep):]
286 auditor(name)
286 auditor(name)
287 return util.pconvert(name)
287 return util.pconvert(name)
288 elif name == root:
288 elif name == root:
289 return ''
289 return ''
290 else:
290 else:
291 # Determine whether `name' is in the hierarchy at or beneath `root',
291 # Determine whether `name' is in the hierarchy at or beneath `root',
292 # by iterating name=dirname(name) until that causes no change (can't
292 # by iterating name=dirname(name) until that causes no change (can't
293 # check name == '/', because that doesn't work on windows). For each
293 # check name == '/', because that doesn't work on windows). For each
294 # `name', compare dev/inode numbers. If they match, the list `rel'
294 # `name', compare dev/inode numbers. If they match, the list `rel'
295 # holds the reversed list of components making up the relative file
295 # holds the reversed list of components making up the relative file
296 # name we want.
296 # name we want.
297 root_st = os.stat(root)
297 root_st = os.stat(root)
298 rel = []
298 rel = []
299 while True:
299 while True:
300 try:
300 try:
301 name_st = os.stat(name)
301 name_st = os.stat(name)
302 except OSError:
302 except OSError:
303 break
303 break
304 if util.samestat(name_st, root_st):
304 if util.samestat(name_st, root_st):
305 if not rel:
305 if not rel:
306 # name was actually the same as root (maybe a symlink)
306 # name was actually the same as root (maybe a symlink)
307 return ''
307 return ''
308 rel.reverse()
308 rel.reverse()
309 name = os.path.join(*rel)
309 name = os.path.join(*rel)
310 auditor(name)
310 auditor(name)
311 return util.pconvert(name)
311 return util.pconvert(name)
312 dirname, basename = os.path.split(name)
312 dirname, basename = os.path.split(name)
313 rel.append(basename)
313 rel.append(basename)
314 if dirname == name:
314 if dirname == name:
315 break
315 break
316 name = dirname
316 name = dirname
317
317
318 raise util.Abort('%s not under root' % myname)
318 raise util.Abort('%s not under root' % myname)
319
319
320 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
320 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
321 '''yield every hg repository under path, recursively.'''
321 '''yield every hg repository under path, recursively.'''
322 def errhandler(err):
322 def errhandler(err):
323 if err.filename == path:
323 if err.filename == path:
324 raise err
324 raise err
325 if followsym and hasattr(os.path, 'samestat'):
325 if followsym and hasattr(os.path, 'samestat'):
326 def adddir(dirlst, dirname):
326 def adddir(dirlst, dirname):
327 match = False
327 match = False
328 samestat = os.path.samestat
328 samestat = os.path.samestat
329 dirstat = os.stat(dirname)
329 dirstat = os.stat(dirname)
330 for lstdirstat in dirlst:
330 for lstdirstat in dirlst:
331 if samestat(dirstat, lstdirstat):
331 if samestat(dirstat, lstdirstat):
332 match = True
332 match = True
333 break
333 break
334 if not match:
334 if not match:
335 dirlst.append(dirstat)
335 dirlst.append(dirstat)
336 return not match
336 return not match
337 else:
337 else:
338 followsym = False
338 followsym = False
339
339
340 if (seen_dirs is None) and followsym:
340 if (seen_dirs is None) and followsym:
341 seen_dirs = []
341 seen_dirs = []
342 adddir(seen_dirs, path)
342 adddir(seen_dirs, path)
343 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
343 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
344 dirs.sort()
344 dirs.sort()
345 if '.hg' in dirs:
345 if '.hg' in dirs:
346 yield root # found a repository
346 yield root # found a repository
347 qroot = os.path.join(root, '.hg', 'patches')
347 qroot = os.path.join(root, '.hg', 'patches')
348 if os.path.isdir(os.path.join(qroot, '.hg')):
348 if os.path.isdir(os.path.join(qroot, '.hg')):
349 yield qroot # we have a patch queue repo here
349 yield qroot # we have a patch queue repo here
350 if recurse:
350 if recurse:
351 # avoid recursing inside the .hg directory
351 # avoid recursing inside the .hg directory
352 dirs.remove('.hg')
352 dirs.remove('.hg')
353 else:
353 else:
354 dirs[:] = [] # don't descend further
354 dirs[:] = [] # don't descend further
355 elif followsym:
355 elif followsym:
356 newdirs = []
356 newdirs = []
357 for d in dirs:
357 for d in dirs:
358 fname = os.path.join(root, d)
358 fname = os.path.join(root, d)
359 if adddir(seen_dirs, fname):
359 if adddir(seen_dirs, fname):
360 if os.path.islink(fname):
360 if os.path.islink(fname):
361 for hgname in walkrepos(fname, True, seen_dirs):
361 for hgname in walkrepos(fname, True, seen_dirs):
362 yield hgname
362 yield hgname
363 else:
363 else:
364 newdirs.append(d)
364 newdirs.append(d)
365 dirs[:] = newdirs
365 dirs[:] = newdirs
366
366
367 def osrcpath():
367 def osrcpath():
368 '''return default os-specific hgrc search path'''
368 '''return default os-specific hgrc search path'''
369 path = systemrcpath()
369 path = systemrcpath()
370 path.extend(userrcpath())
370 path.extend(userrcpath())
371 path = [os.path.normpath(f) for f in path]
371 path = [os.path.normpath(f) for f in path]
372 return path
372 return path
373
373
374 _rcpath = None
374 _rcpath = None
375
375
376 def rcpath():
376 def rcpath():
377 '''return hgrc search path. if env var HGRCPATH is set, use it.
377 '''return hgrc search path. if env var HGRCPATH is set, use it.
378 for each item in path, if directory, use files ending in .rc,
378 for each item in path, if directory, use files ending in .rc,
379 else use item.
379 else use item.
380 make HGRCPATH empty to only look in .hg/hgrc of current repo.
380 make HGRCPATH empty to only look in .hg/hgrc of current repo.
381 if no HGRCPATH, use default os-specific path.'''
381 if no HGRCPATH, use default os-specific path.'''
382 global _rcpath
382 global _rcpath
383 if _rcpath is None:
383 if _rcpath is None:
384 if 'HGRCPATH' in os.environ:
384 if 'HGRCPATH' in os.environ:
385 _rcpath = []
385 _rcpath = []
386 for p in os.environ['HGRCPATH'].split(os.pathsep):
386 for p in os.environ['HGRCPATH'].split(os.pathsep):
387 if not p:
387 if not p:
388 continue
388 continue
389 p = util.expandpath(p)
389 p = util.expandpath(p)
390 if os.path.isdir(p):
390 if os.path.isdir(p):
391 for f, kind in osutil.listdir(p):
391 for f, kind in osutil.listdir(p):
392 if f.endswith('.rc'):
392 if f.endswith('.rc'):
393 _rcpath.append(os.path.join(p, f))
393 _rcpath.append(os.path.join(p, f))
394 else:
394 else:
395 _rcpath.append(p)
395 _rcpath.append(p)
396 else:
396 else:
397 _rcpath = osrcpath()
397 _rcpath = osrcpath()
398 return _rcpath
398 return _rcpath
399
399
400 if os.name != 'nt':
400 if os.name != 'nt':
401
401
402 def rcfiles(path):
402 def rcfiles(path):
403 rcs = [os.path.join(path, 'hgrc')]
403 rcs = [os.path.join(path, 'hgrc')]
404 rcdir = os.path.join(path, 'hgrc.d')
404 rcdir = os.path.join(path, 'hgrc.d')
405 try:
405 try:
406 rcs.extend([os.path.join(rcdir, f)
406 rcs.extend([os.path.join(rcdir, f)
407 for f, kind in osutil.listdir(rcdir)
407 for f, kind in osutil.listdir(rcdir)
408 if f.endswith(".rc")])
408 if f.endswith(".rc")])
409 except OSError:
409 except OSError:
410 pass
410 pass
411 return rcs
411 return rcs
412
412
413 def systemrcpath():
413 def systemrcpath():
414 path = []
414 path = []
415 # old mod_python does not set sys.argv
415 # old mod_python does not set sys.argv
416 if len(getattr(sys, 'argv', [])) > 0:
416 if len(getattr(sys, 'argv', [])) > 0:
417 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
417 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
418 '/../etc/mercurial'))
418 '/../etc/mercurial'))
419 path.extend(rcfiles('/etc/mercurial'))
419 path.extend(rcfiles('/etc/mercurial'))
420 return path
420 return path
421
421
422 def userrcpath():
422 def userrcpath():
423 return [os.path.expanduser('~/.hgrc')]
423 return [os.path.expanduser('~/.hgrc')]
424
424
425 else:
425 else:
426
426
427 _HKEY_LOCAL_MACHINE = 0x80000002L
427 _HKEY_LOCAL_MACHINE = 0x80000002L
428
428
429 def systemrcpath():
429 def systemrcpath():
430 '''return default os-specific hgrc search path'''
430 '''return default os-specific hgrc search path'''
431 rcpath = []
431 rcpath = []
432 filename = util.executablepath()
432 filename = util.executablepath()
433 # Use mercurial.ini found in directory with hg.exe
433 # Use mercurial.ini found in directory with hg.exe
434 progrc = os.path.join(os.path.dirname(filename), 'mercurial.ini')
434 progrc = os.path.join(os.path.dirname(filename), 'mercurial.ini')
435 if os.path.isfile(progrc):
435 if os.path.isfile(progrc):
436 rcpath.append(progrc)
436 rcpath.append(progrc)
437 return rcpath
437 return rcpath
438 # Use hgrc.d found in directory with hg.exe
438 # Use hgrc.d found in directory with hg.exe
439 progrcd = os.path.join(os.path.dirname(filename), 'hgrc.d')
439 progrcd = os.path.join(os.path.dirname(filename), 'hgrc.d')
440 if os.path.isdir(progrcd):
440 if os.path.isdir(progrcd):
441 for f, kind in osutil.listdir(progrcd):
441 for f, kind in osutil.listdir(progrcd):
442 if f.endswith('.rc'):
442 if f.endswith('.rc'):
443 rcpath.append(os.path.join(progrcd, f))
443 rcpath.append(os.path.join(progrcd, f))
444 return rcpath
444 return rcpath
445 # else look for a system rcpath in the registry
445 # else look for a system rcpath in the registry
446 value = util.lookupreg('SOFTWARE\\Mercurial', None,
446 value = util.lookupreg('SOFTWARE\\Mercurial', None,
447 _HKEY_LOCAL_MACHINE)
447 _HKEY_LOCAL_MACHINE)
448 if not isinstance(value, str) or not value:
448 if not isinstance(value, str) or not value:
449 return rcpath
449 return rcpath
450 value = value.replace('/', os.sep)
450 value = value.replace('/', os.sep)
451 for p in value.split(os.pathsep):
451 for p in value.split(os.pathsep):
452 if p.lower().endswith('mercurial.ini'):
452 if p.lower().endswith('mercurial.ini'):
453 rcpath.append(p)
453 rcpath.append(p)
454 elif os.path.isdir(p):
454 elif os.path.isdir(p):
455 for f, kind in osutil.listdir(p):
455 for f, kind in osutil.listdir(p):
456 if f.endswith('.rc'):
456 if f.endswith('.rc'):
457 rcpath.append(os.path.join(p, f))
457 rcpath.append(os.path.join(p, f))
458 return rcpath
458 return rcpath
459
459
460 def userrcpath():
460 def userrcpath():
461 '''return os-specific hgrc search path to the user dir'''
461 '''return os-specific hgrc search path to the user dir'''
462 home = os.path.expanduser('~')
462 home = os.path.expanduser('~')
463 path = [os.path.join(home, 'mercurial.ini'),
463 path = [os.path.join(home, 'mercurial.ini'),
464 os.path.join(home, '.hgrc')]
464 os.path.join(home, '.hgrc')]
465 userprofile = os.environ.get('USERPROFILE')
465 userprofile = os.environ.get('USERPROFILE')
466 if userprofile:
466 if userprofile:
467 path.append(os.path.join(userprofile, 'mercurial.ini'))
467 path.append(os.path.join(userprofile, 'mercurial.ini'))
468 path.append(os.path.join(userprofile, '.hgrc'))
468 path.append(os.path.join(userprofile, '.hgrc'))
469 return path
469 return path
470
470
471 def revsingle(repo, revspec, default='.'):
471 def revsingle(repo, revspec, default='.'):
472 if not revspec:
472 if not revspec:
473 return repo[default]
473 return repo[default]
474
474
475 l = revrange(repo, [revspec])
475 l = revrange(repo, [revspec])
476 if len(l) < 1:
476 if len(l) < 1:
477 raise util.Abort(_('empty revision set'))
477 raise util.Abort(_('empty revision set'))
478 return repo[l[-1]]
478 return repo[l[-1]]
479
479
480 def revpair(repo, revs):
480 def revpair(repo, revs):
481 if not revs:
481 if not revs:
482 return repo.dirstate.p1(), None
482 return repo.dirstate.p1(), None
483
483
484 l = revrange(repo, revs)
484 l = revrange(repo, revs)
485
485
486 if len(l) == 0:
486 if len(l) == 0:
487 return repo.dirstate.p1(), None
487 return repo.dirstate.p1(), None
488
488
489 if len(l) == 1:
489 if len(l) == 1:
490 return repo.lookup(l[0]), None
490 return repo.lookup(l[0]), None
491
491
492 return repo.lookup(l[0]), repo.lookup(l[-1])
492 return repo.lookup(l[0]), repo.lookup(l[-1])
493
493
494 _revrangesep = ':'
494 _revrangesep = ':'
495
495
496 def revrange(repo, revs):
496 def revrange(repo, revs):
497 """Yield revision as strings from a list of revision specifications."""
497 """Yield revision as strings from a list of revision specifications."""
498
498
499 def revfix(repo, val, defval):
499 def revfix(repo, val, defval):
500 if not val and val != 0 and defval is not None:
500 if not val and val != 0 and defval is not None:
501 return defval
501 return defval
502 return repo.changelog.rev(repo.lookup(val))
502 return repo.changelog.rev(repo.lookup(val))
503
503
504 seen, l = set(), []
504 seen, l = set(), []
505 for spec in revs:
505 for spec in revs:
506 # attempt to parse old-style ranges first to deal with
506 # attempt to parse old-style ranges first to deal with
507 # things like old-tag which contain query metacharacters
507 # things like old-tag which contain query metacharacters
508 try:
508 try:
509 if isinstance(spec, int):
509 if isinstance(spec, int):
510 seen.add(spec)
510 seen.add(spec)
511 l.append(spec)
511 l.append(spec)
512 continue
512 continue
513
513
514 if _revrangesep in spec:
514 if _revrangesep in spec:
515 start, end = spec.split(_revrangesep, 1)
515 start, end = spec.split(_revrangesep, 1)
516 start = revfix(repo, start, 0)
516 start = revfix(repo, start, 0)
517 end = revfix(repo, end, len(repo) - 1)
517 end = revfix(repo, end, len(repo) - 1)
518 step = start > end and -1 or 1
518 step = start > end and -1 or 1
519 for rev in xrange(start, end + step, step):
519 for rev in xrange(start, end + step, step):
520 if rev in seen:
520 if rev in seen:
521 continue
521 continue
522 seen.add(rev)
522 seen.add(rev)
523 l.append(rev)
523 l.append(rev)
524 continue
524 continue
525 elif spec and spec in repo: # single unquoted rev
525 elif spec and spec in repo: # single unquoted rev
526 rev = revfix(repo, spec, None)
526 rev = revfix(repo, spec, None)
527 if rev in seen:
527 if rev in seen:
528 continue
528 continue
529 seen.add(rev)
529 seen.add(rev)
530 l.append(rev)
530 l.append(rev)
531 continue
531 continue
532 except error.RepoLookupError:
532 except error.RepoLookupError:
533 pass
533 pass
534
534
535 # fall through to new-style queries if old-style fails
535 # fall through to new-style queries if old-style fails
536 m = revset.match(repo.ui, spec)
536 m = revset.match(repo.ui, spec)
537 for r in m(repo, range(len(repo))):
537 for r in m(repo, range(len(repo))):
538 if r not in seen:
538 if r not in seen:
539 l.append(r)
539 l.append(r)
540 seen.update(l)
540 seen.update(l)
541
541
542 return l
542 return l
543
543
544 def expandpats(pats):
544 def expandpats(pats):
545 if not util.expandglobs:
545 if not util.expandglobs:
546 return list(pats)
546 return list(pats)
547 ret = []
547 ret = []
548 for p in pats:
548 for p in pats:
549 kind, name = matchmod._patsplit(p, None)
549 kind, name = matchmod._patsplit(p, None)
550 if kind is None:
550 if kind is None:
551 try:
551 try:
552 globbed = glob.glob(name)
552 globbed = glob.glob(name)
553 except re.error:
553 except re.error:
554 globbed = [name]
554 globbed = [name]
555 if globbed:
555 if globbed:
556 ret.extend(globbed)
556 ret.extend(globbed)
557 continue
557 continue
558 ret.append(p)
558 ret.append(p)
559 return ret
559 return ret
560
560
561 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
561 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
562 if pats == ("",):
562 if pats == ("",):
563 pats = []
563 pats = []
564 if not globbed and default == 'relpath':
564 if not globbed and default == 'relpath':
565 pats = expandpats(pats or [])
565 pats = expandpats(pats or [])
566 m = matchmod.match(repo.root, repo.getcwd(), pats,
566 m = matchmod.match(repo.root, repo.getcwd(), pats,
567 opts.get('include'), opts.get('exclude'), default,
567 opts.get('include'), opts.get('exclude'), default,
568 auditor=repo.auditor)
568 auditor=repo.auditor)
569 def badfn(f, msg):
569 def badfn(f, msg):
570 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
570 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
571 m.bad = badfn
571 m.bad = badfn
572 return m
572 return m
573
573
574 def matchall(repo):
574 def matchall(repo):
575 return matchmod.always(repo.root, repo.getcwd())
575 return matchmod.always(repo.root, repo.getcwd())
576
576
577 def matchfiles(repo, files):
577 def matchfiles(repo, files):
578 return matchmod.exact(repo.root, repo.getcwd(), files)
578 return matchmod.exact(repo.root, repo.getcwd(), files)
579
579
580 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
580 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
581 if dry_run is None:
581 if dry_run is None:
582 dry_run = opts.get('dry_run')
582 dry_run = opts.get('dry_run')
583 if similarity is None:
583 if similarity is None:
584 similarity = float(opts.get('similarity') or 0)
584 similarity = float(opts.get('similarity') or 0)
585 # we'd use status here, except handling of symlinks and ignore is tricky
585 # we'd use status here, except handling of symlinks and ignore is tricky
586 added, unknown, deleted, removed = [], [], [], []
586 added, unknown, deleted, removed = [], [], [], []
587 audit_path = pathauditor(repo.root)
587 audit_path = pathauditor(repo.root)
588 m = match(repo, pats, opts)
588 m = match(repo, pats, opts)
589 for abs in repo.walk(m):
589 for abs in repo.walk(m):
590 target = repo.wjoin(abs)
590 target = repo.wjoin(abs)
591 good = True
591 good = True
592 try:
592 try:
593 audit_path(abs)
593 audit_path(abs)
594 except (OSError, util.Abort):
594 except (OSError, util.Abort):
595 good = False
595 good = False
596 rel = m.rel(abs)
596 rel = m.rel(abs)
597 exact = m.exact(abs)
597 exact = m.exact(abs)
598 if good and abs not in repo.dirstate:
598 if good and abs not in repo.dirstate:
599 unknown.append(abs)
599 unknown.append(abs)
600 if repo.ui.verbose or not exact:
600 if repo.ui.verbose or not exact:
601 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
601 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
602 elif repo.dirstate[abs] != 'r' and (not good or not os.path.lexists(target)
602 elif repo.dirstate[abs] != 'r' and (not good or not os.path.lexists(target)
603 or (os.path.isdir(target) and not os.path.islink(target))):
603 or (os.path.isdir(target) and not os.path.islink(target))):
604 deleted.append(abs)
604 deleted.append(abs)
605 if repo.ui.verbose or not exact:
605 if repo.ui.verbose or not exact:
606 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
606 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
607 # for finding renames
607 # for finding renames
608 elif repo.dirstate[abs] == 'r':
608 elif repo.dirstate[abs] == 'r':
609 removed.append(abs)
609 removed.append(abs)
610 elif repo.dirstate[abs] == 'a':
610 elif repo.dirstate[abs] == 'a':
611 added.append(abs)
611 added.append(abs)
612 copies = {}
612 copies = {}
613 if similarity > 0:
613 if similarity > 0:
614 for old, new, score in similar.findrenames(repo,
614 for old, new, score in similar.findrenames(repo,
615 added + unknown, removed + deleted, similarity):
615 added + unknown, removed + deleted, similarity):
616 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
616 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
617 repo.ui.status(_('recording removal of %s as rename to %s '
617 repo.ui.status(_('recording removal of %s as rename to %s '
618 '(%d%% similar)\n') %
618 '(%d%% similar)\n') %
619 (m.rel(old), m.rel(new), score * 100))
619 (m.rel(old), m.rel(new), score * 100))
620 copies[new] = old
620 copies[new] = old
621
621
622 if not dry_run:
622 if not dry_run:
623 wctx = repo[None]
623 wctx = repo[None]
624 wlock = repo.wlock()
624 wlock = repo.wlock()
625 try:
625 try:
626 wctx.remove(deleted)
626 wctx.forget(deleted)
627 wctx.add(unknown)
627 wctx.add(unknown)
628 for new, old in copies.iteritems():
628 for new, old in copies.iteritems():
629 wctx.copy(old, new)
629 wctx.copy(old, new)
630 finally:
630 finally:
631 wlock.release()
631 wlock.release()
632
632
633 def updatedir(ui, repo, patches, similarity=0):
633 def updatedir(ui, repo, patches, similarity=0):
634 '''Update dirstate after patch application according to metadata'''
634 '''Update dirstate after patch application according to metadata'''
635 if not patches:
635 if not patches:
636 return []
636 return []
637 copies = []
637 copies = []
638 removes = set()
638 removes = set()
639 cfiles = patches.keys()
639 cfiles = patches.keys()
640 cwd = repo.getcwd()
640 cwd = repo.getcwd()
641 if cwd:
641 if cwd:
642 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
642 cfiles = [util.pathto(repo.root, cwd, f) for f in patches.keys()]
643 for f in patches:
643 for f in patches:
644 gp = patches[f]
644 gp = patches[f]
645 if not gp:
645 if not gp:
646 continue
646 continue
647 if gp.op == 'RENAME':
647 if gp.op == 'RENAME':
648 copies.append((gp.oldpath, gp.path))
648 copies.append((gp.oldpath, gp.path))
649 removes.add(gp.oldpath)
649 removes.add(gp.oldpath)
650 elif gp.op == 'COPY':
650 elif gp.op == 'COPY':
651 copies.append((gp.oldpath, gp.path))
651 copies.append((gp.oldpath, gp.path))
652 elif gp.op == 'DELETE':
652 elif gp.op == 'DELETE':
653 removes.add(gp.path)
653 removes.add(gp.path)
654
654
655 wctx = repo[None]
655 wctx = repo[None]
656 for src, dst in copies:
656 for src, dst in copies:
657 dirstatecopy(ui, repo, wctx, src, dst, cwd=cwd)
657 dirstatecopy(ui, repo, wctx, src, dst, cwd=cwd)
658 if (not similarity) and removes:
658 if (not similarity) and removes:
659 wctx.remove(sorted(removes), True)
659 wctx.remove(sorted(removes), True)
660
660
661 for f in patches:
661 for f in patches:
662 gp = patches[f]
662 gp = patches[f]
663 if gp and gp.mode:
663 if gp and gp.mode:
664 islink, isexec = gp.mode
664 islink, isexec = gp.mode
665 dst = repo.wjoin(gp.path)
665 dst = repo.wjoin(gp.path)
666 # patch won't create empty files
666 # patch won't create empty files
667 if gp.op == 'ADD' and not os.path.lexists(dst):
667 if gp.op == 'ADD' and not os.path.lexists(dst):
668 flags = (isexec and 'x' or '') + (islink and 'l' or '')
668 flags = (isexec and 'x' or '') + (islink and 'l' or '')
669 repo.wwrite(gp.path, '', flags)
669 repo.wwrite(gp.path, '', flags)
670 util.setflags(dst, islink, isexec)
670 util.setflags(dst, islink, isexec)
671 addremove(repo, cfiles, similarity=similarity)
671 addremove(repo, cfiles, similarity=similarity)
672 files = patches.keys()
672 files = patches.keys()
673 files.extend([r for r in removes if r not in files])
673 files.extend([r for r in removes if r not in files])
674 return sorted(files)
674 return sorted(files)
675
675
676 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
676 def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None):
677 """Update the dirstate to reflect the intent of copying src to dst. For
677 """Update the dirstate to reflect the intent of copying src to dst. For
678 different reasons it might not end with dst being marked as copied from src.
678 different reasons it might not end with dst being marked as copied from src.
679 """
679 """
680 origsrc = repo.dirstate.copied(src) or src
680 origsrc = repo.dirstate.copied(src) or src
681 if dst == origsrc: # copying back a copy?
681 if dst == origsrc: # copying back a copy?
682 if repo.dirstate[dst] not in 'mn' and not dryrun:
682 if repo.dirstate[dst] not in 'mn' and not dryrun:
683 repo.dirstate.normallookup(dst)
683 repo.dirstate.normallookup(dst)
684 else:
684 else:
685 if repo.dirstate[origsrc] == 'a' and origsrc == src:
685 if repo.dirstate[origsrc] == 'a' and origsrc == src:
686 if not ui.quiet:
686 if not ui.quiet:
687 ui.warn(_("%s has not been committed yet, so no copy "
687 ui.warn(_("%s has not been committed yet, so no copy "
688 "data will be stored for %s.\n")
688 "data will be stored for %s.\n")
689 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
689 % (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
690 if repo.dirstate[dst] in '?r' and not dryrun:
690 if repo.dirstate[dst] in '?r' and not dryrun:
691 wctx.add([dst])
691 wctx.add([dst])
692 elif not dryrun:
692 elif not dryrun:
693 wctx.copy(origsrc, dst)
693 wctx.copy(origsrc, dst)
General Comments 0
You need to be logged in to leave comments. Login now