##// END OF EJS Templates
dirstate: rename forget to drop...
Matt Mackall -
r14434:cc8c0985 default
parent child Browse files
Show More
@@ -1,3296 +1,3296 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].remove(patches, True)
739 else:
739 else:
740 for p in patches:
740 for p in patches:
741 os.unlink(self.join(p))
741 os.unlink(self.join(p))
742
742
743 if numrevs:
743 if numrevs:
744 qfinished = self.applied[:numrevs]
744 qfinished = self.applied[:numrevs]
745 del self.applied[:numrevs]
745 del self.applied[:numrevs]
746 self.applied_dirty = 1
746 self.applied_dirty = 1
747
747
748 unknown = []
748 unknown = []
749
749
750 for (i, p) in sorted([(self.find_series(p), p) for p in patches],
750 for (i, p) in sorted([(self.find_series(p), p) for p in patches],
751 reverse=True):
751 reverse=True):
752 if i is not None:
752 if i is not None:
753 del self.full_series[i]
753 del self.full_series[i]
754 else:
754 else:
755 unknown.append(p)
755 unknown.append(p)
756
756
757 if unknown:
757 if unknown:
758 if numrevs:
758 if numrevs:
759 rev = dict((entry.name, entry.node) for entry in qfinished)
759 rev = dict((entry.name, entry.node) for entry in qfinished)
760 for p in unknown:
760 for p in unknown:
761 msg = _('revision %s refers to unknown patches: %s\n')
761 msg = _('revision %s refers to unknown patches: %s\n')
762 self.ui.warn(msg % (short(rev[p]), p))
762 self.ui.warn(msg % (short(rev[p]), p))
763 else:
763 else:
764 msg = _('unknown patches: %s\n')
764 msg = _('unknown patches: %s\n')
765 raise util.Abort(''.join(msg % p for p in unknown))
765 raise util.Abort(''.join(msg % p for p in unknown))
766
766
767 self.parse_series()
767 self.parse_series()
768 self.series_dirty = 1
768 self.series_dirty = 1
769
769
770 def _revpatches(self, repo, revs):
770 def _revpatches(self, repo, revs):
771 firstrev = repo[self.applied[0].node].rev()
771 firstrev = repo[self.applied[0].node].rev()
772 patches = []
772 patches = []
773 for i, rev in enumerate(revs):
773 for i, rev in enumerate(revs):
774
774
775 if rev < firstrev:
775 if rev < firstrev:
776 raise util.Abort(_('revision %d is not managed') % rev)
776 raise util.Abort(_('revision %d is not managed') % rev)
777
777
778 ctx = repo[rev]
778 ctx = repo[rev]
779 base = self.applied[i].node
779 base = self.applied[i].node
780 if ctx.node() != base:
780 if ctx.node() != base:
781 msg = _('cannot delete revision %d above applied patches')
781 msg = _('cannot delete revision %d above applied patches')
782 raise util.Abort(msg % rev)
782 raise util.Abort(msg % rev)
783
783
784 patch = self.applied[i].name
784 patch = self.applied[i].name
785 for fmt in ('[mq]: %s', 'imported patch %s'):
785 for fmt in ('[mq]: %s', 'imported patch %s'):
786 if ctx.description() == fmt % patch:
786 if ctx.description() == fmt % patch:
787 msg = _('patch %s finalized without changeset message\n')
787 msg = _('patch %s finalized without changeset message\n')
788 repo.ui.status(msg % patch)
788 repo.ui.status(msg % patch)
789 break
789 break
790
790
791 patches.append(patch)
791 patches.append(patch)
792 return patches
792 return patches
793
793
794 def finish(self, repo, revs):
794 def finish(self, repo, revs):
795 patches = self._revpatches(repo, sorted(revs))
795 patches = self._revpatches(repo, sorted(revs))
796 self._cleanup(patches, len(patches))
796 self._cleanup(patches, len(patches))
797
797
798 def delete(self, repo, patches, opts):
798 def delete(self, repo, patches, opts):
799 if not patches and not opts.get('rev'):
799 if not patches and not opts.get('rev'):
800 raise util.Abort(_('qdelete requires at least one revision or '
800 raise util.Abort(_('qdelete requires at least one revision or '
801 'patch name'))
801 'patch name'))
802
802
803 realpatches = []
803 realpatches = []
804 for patch in patches:
804 for patch in patches:
805 patch = self.lookup(patch, strict=True)
805 patch = self.lookup(patch, strict=True)
806 info = self.isapplied(patch)
806 info = self.isapplied(patch)
807 if info:
807 if info:
808 raise util.Abort(_("cannot delete applied patch %s") % patch)
808 raise util.Abort(_("cannot delete applied patch %s") % patch)
809 if patch not in self.series:
809 if patch not in self.series:
810 raise util.Abort(_("patch %s not in series file") % patch)
810 raise util.Abort(_("patch %s not in series file") % patch)
811 if patch not in realpatches:
811 if patch not in realpatches:
812 realpatches.append(patch)
812 realpatches.append(patch)
813
813
814 numrevs = 0
814 numrevs = 0
815 if opts.get('rev'):
815 if opts.get('rev'):
816 if not self.applied:
816 if not self.applied:
817 raise util.Abort(_('no patches applied'))
817 raise util.Abort(_('no patches applied'))
818 revs = scmutil.revrange(repo, opts.get('rev'))
818 revs = scmutil.revrange(repo, opts.get('rev'))
819 if len(revs) > 1 and revs[0] > revs[1]:
819 if len(revs) > 1 and revs[0] > revs[1]:
820 revs.reverse()
820 revs.reverse()
821 revpatches = self._revpatches(repo, revs)
821 revpatches = self._revpatches(repo, revs)
822 realpatches += revpatches
822 realpatches += revpatches
823 numrevs = len(revpatches)
823 numrevs = len(revpatches)
824
824
825 self._cleanup(realpatches, numrevs, opts.get('keep'))
825 self._cleanup(realpatches, numrevs, opts.get('keep'))
826
826
827 def check_toppatch(self, repo):
827 def check_toppatch(self, repo):
828 if self.applied:
828 if self.applied:
829 top = self.applied[-1].node
829 top = self.applied[-1].node
830 patch = self.applied[-1].name
830 patch = self.applied[-1].name
831 pp = repo.dirstate.parents()
831 pp = repo.dirstate.parents()
832 if top not in pp:
832 if top not in pp:
833 raise util.Abort(_("working directory revision is not qtip"))
833 raise util.Abort(_("working directory revision is not qtip"))
834 return top, patch
834 return top, patch
835 return None, None
835 return None, None
836
836
837 def check_substate(self, repo):
837 def check_substate(self, repo):
838 '''return list of subrepos at a different revision than substate.
838 '''return list of subrepos at a different revision than substate.
839 Abort if any subrepos have uncommitted changes.'''
839 Abort if any subrepos have uncommitted changes.'''
840 inclsubs = []
840 inclsubs = []
841 wctx = repo[None]
841 wctx = repo[None]
842 for s in wctx.substate:
842 for s in wctx.substate:
843 if wctx.sub(s).dirty(True):
843 if wctx.sub(s).dirty(True):
844 raise util.Abort(
844 raise util.Abort(
845 _("uncommitted changes in subrepository %s") % s)
845 _("uncommitted changes in subrepository %s") % s)
846 elif wctx.sub(s).dirty():
846 elif wctx.sub(s).dirty():
847 inclsubs.append(s)
847 inclsubs.append(s)
848 return inclsubs
848 return inclsubs
849
849
850 def localchangesfound(self, refresh=True):
850 def localchangesfound(self, refresh=True):
851 if refresh:
851 if refresh:
852 raise util.Abort(_("local changes found, refresh first"))
852 raise util.Abort(_("local changes found, refresh first"))
853 else:
853 else:
854 raise util.Abort(_("local changes found"))
854 raise util.Abort(_("local changes found"))
855
855
856 def check_localchanges(self, repo, force=False, refresh=True):
856 def check_localchanges(self, repo, force=False, refresh=True):
857 m, a, r, d = repo.status()[:4]
857 m, a, r, d = repo.status()[:4]
858 if (m or a or r or d) and not force:
858 if (m or a or r or d) and not force:
859 self.localchangesfound(refresh)
859 self.localchangesfound(refresh)
860 return m, a, r, d
860 return m, a, r, d
861
861
862 _reserved = ('series', 'status', 'guards', '.', '..')
862 _reserved = ('series', 'status', 'guards', '.', '..')
863 def check_reserved_name(self, name):
863 def check_reserved_name(self, name):
864 if name in self._reserved:
864 if name in self._reserved:
865 raise util.Abort(_('"%s" cannot be used as the name of a patch')
865 raise util.Abort(_('"%s" cannot be used as the name of a patch')
866 % name)
866 % name)
867 for prefix in ('.hg', '.mq'):
867 for prefix in ('.hg', '.mq'):
868 if name.startswith(prefix):
868 if name.startswith(prefix):
869 raise util.Abort(_('patch name cannot begin with "%s"')
869 raise util.Abort(_('patch name cannot begin with "%s"')
870 % prefix)
870 % prefix)
871 for c in ('#', ':'):
871 for c in ('#', ':'):
872 if c in name:
872 if c in name:
873 raise util.Abort(_('"%s" cannot be used in the name of a patch')
873 raise util.Abort(_('"%s" cannot be used in the name of a patch')
874 % c)
874 % c)
875
875
876 def checkpatchname(self, name, force=False):
876 def checkpatchname(self, name, force=False):
877 self.check_reserved_name(name)
877 self.check_reserved_name(name)
878 if not force and os.path.exists(self.join(name)):
878 if not force and os.path.exists(self.join(name)):
879 if os.path.isdir(self.join(name)):
879 if os.path.isdir(self.join(name)):
880 raise util.Abort(_('"%s" already exists as a directory')
880 raise util.Abort(_('"%s" already exists as a directory')
881 % name)
881 % name)
882 else:
882 else:
883 raise util.Abort(_('patch "%s" already exists') % name)
883 raise util.Abort(_('patch "%s" already exists') % name)
884
884
885 def new(self, repo, patchfn, *pats, **opts):
885 def new(self, repo, patchfn, *pats, **opts):
886 """options:
886 """options:
887 msg: a string or a no-argument function returning a string
887 msg: a string or a no-argument function returning a string
888 """
888 """
889 msg = opts.get('msg')
889 msg = opts.get('msg')
890 user = opts.get('user')
890 user = opts.get('user')
891 date = opts.get('date')
891 date = opts.get('date')
892 if date:
892 if date:
893 date = util.parsedate(date)
893 date = util.parsedate(date)
894 diffopts = self.diffopts({'git': opts.get('git')})
894 diffopts = self.diffopts({'git': opts.get('git')})
895 if opts.get('checkname', True):
895 if opts.get('checkname', True):
896 self.checkpatchname(patchfn)
896 self.checkpatchname(patchfn)
897 inclsubs = self.check_substate(repo)
897 inclsubs = self.check_substate(repo)
898 if inclsubs:
898 if inclsubs:
899 inclsubs.append('.hgsubstate')
899 inclsubs.append('.hgsubstate')
900 if opts.get('include') or opts.get('exclude') or pats:
900 if opts.get('include') or opts.get('exclude') or pats:
901 if inclsubs:
901 if inclsubs:
902 pats = list(pats or []) + inclsubs
902 pats = list(pats or []) + inclsubs
903 match = scmutil.match(repo, pats, opts)
903 match = scmutil.match(repo, pats, opts)
904 # detect missing files in pats
904 # detect missing files in pats
905 def badfn(f, msg):
905 def badfn(f, msg):
906 if f != '.hgsubstate': # .hgsubstate is auto-created
906 if f != '.hgsubstate': # .hgsubstate is auto-created
907 raise util.Abort('%s: %s' % (f, msg))
907 raise util.Abort('%s: %s' % (f, msg))
908 match.bad = badfn
908 match.bad = badfn
909 m, a, r, d = repo.status(match=match)[:4]
909 m, a, r, d = repo.status(match=match)[:4]
910 else:
910 else:
911 m, a, r, d = self.check_localchanges(repo, force=True)
911 m, a, r, d = self.check_localchanges(repo, force=True)
912 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
912 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
913 if len(repo[None].parents()) > 1:
913 if len(repo[None].parents()) > 1:
914 raise util.Abort(_('cannot manage merge changesets'))
914 raise util.Abort(_('cannot manage merge changesets'))
915 commitfiles = m + a + r
915 commitfiles = m + a + r
916 self.check_toppatch(repo)
916 self.check_toppatch(repo)
917 insert = self.full_series_end()
917 insert = self.full_series_end()
918 wlock = repo.wlock()
918 wlock = repo.wlock()
919 try:
919 try:
920 try:
920 try:
921 # if patch file write fails, abort early
921 # if patch file write fails, abort early
922 p = self.opener(patchfn, "w")
922 p = self.opener(patchfn, "w")
923 except IOError, e:
923 except IOError, e:
924 raise util.Abort(_('cannot write patch "%s": %s')
924 raise util.Abort(_('cannot write patch "%s": %s')
925 % (patchfn, e.strerror))
925 % (patchfn, e.strerror))
926 try:
926 try:
927 if self.plainmode:
927 if self.plainmode:
928 if user:
928 if user:
929 p.write("From: " + user + "\n")
929 p.write("From: " + user + "\n")
930 if not date:
930 if not date:
931 p.write("\n")
931 p.write("\n")
932 if date:
932 if date:
933 p.write("Date: %d %d\n\n" % date)
933 p.write("Date: %d %d\n\n" % date)
934 else:
934 else:
935 p.write("# HG changeset patch\n")
935 p.write("# HG changeset patch\n")
936 p.write("# Parent "
936 p.write("# Parent "
937 + hex(repo[None].p1().node()) + "\n")
937 + hex(repo[None].p1().node()) + "\n")
938 if user:
938 if user:
939 p.write("# User " + user + "\n")
939 p.write("# User " + user + "\n")
940 if date:
940 if date:
941 p.write("# Date %s %s\n\n" % date)
941 p.write("# Date %s %s\n\n" % date)
942 if hasattr(msg, '__call__'):
942 if hasattr(msg, '__call__'):
943 msg = msg()
943 msg = msg()
944 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
944 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
945 n = repo.commit(commitmsg, user, date, match=match, force=True)
945 n = repo.commit(commitmsg, user, date, match=match, force=True)
946 if n is None:
946 if n is None:
947 raise util.Abort(_("repo commit failed"))
947 raise util.Abort(_("repo commit failed"))
948 try:
948 try:
949 self.full_series[insert:insert] = [patchfn]
949 self.full_series[insert:insert] = [patchfn]
950 self.applied.append(statusentry(n, patchfn))
950 self.applied.append(statusentry(n, patchfn))
951 self.parse_series()
951 self.parse_series()
952 self.series_dirty = 1
952 self.series_dirty = 1
953 self.applied_dirty = 1
953 self.applied_dirty = 1
954 if msg:
954 if msg:
955 msg = msg + "\n\n"
955 msg = msg + "\n\n"
956 p.write(msg)
956 p.write(msg)
957 if commitfiles:
957 if commitfiles:
958 parent = self.qparents(repo, n)
958 parent = self.qparents(repo, n)
959 chunks = patchmod.diff(repo, node1=parent, node2=n,
959 chunks = patchmod.diff(repo, node1=parent, node2=n,
960 match=match, opts=diffopts)
960 match=match, opts=diffopts)
961 for chunk in chunks:
961 for chunk in chunks:
962 p.write(chunk)
962 p.write(chunk)
963 p.close()
963 p.close()
964 wlock.release()
964 wlock.release()
965 wlock = None
965 wlock = None
966 r = self.qrepo()
966 r = self.qrepo()
967 if r:
967 if r:
968 r[None].add([patchfn])
968 r[None].add([patchfn])
969 except:
969 except:
970 repo.rollback()
970 repo.rollback()
971 raise
971 raise
972 except Exception:
972 except Exception:
973 patchpath = self.join(patchfn)
973 patchpath = self.join(patchfn)
974 try:
974 try:
975 os.unlink(patchpath)
975 os.unlink(patchpath)
976 except:
976 except:
977 self.ui.warn(_('error unlinking %s\n') % patchpath)
977 self.ui.warn(_('error unlinking %s\n') % patchpath)
978 raise
978 raise
979 self.removeundo(repo)
979 self.removeundo(repo)
980 finally:
980 finally:
981 release(wlock)
981 release(wlock)
982
982
983 def strip(self, repo, revs, update=True, backup="all", force=None):
983 def strip(self, repo, revs, update=True, backup="all", force=None):
984 wlock = lock = None
984 wlock = lock = None
985 try:
985 try:
986 wlock = repo.wlock()
986 wlock = repo.wlock()
987 lock = repo.lock()
987 lock = repo.lock()
988
988
989 if update:
989 if update:
990 self.check_localchanges(repo, force=force, refresh=False)
990 self.check_localchanges(repo, force=force, refresh=False)
991 urev = self.qparents(repo, revs[0])
991 urev = self.qparents(repo, revs[0])
992 hg.clean(repo, urev)
992 hg.clean(repo, urev)
993 repo.dirstate.write()
993 repo.dirstate.write()
994
994
995 self.removeundo(repo)
995 self.removeundo(repo)
996 for rev in revs:
996 for rev in revs:
997 repair.strip(self.ui, repo, rev, backup)
997 repair.strip(self.ui, repo, rev, backup)
998 # strip may have unbundled a set of backed up revisions after
998 # strip may have unbundled a set of backed up revisions after
999 # the actual strip
999 # the actual strip
1000 self.removeundo(repo)
1000 self.removeundo(repo)
1001 finally:
1001 finally:
1002 release(lock, wlock)
1002 release(lock, wlock)
1003
1003
1004 def isapplied(self, patch):
1004 def isapplied(self, patch):
1005 """returns (index, rev, patch)"""
1005 """returns (index, rev, patch)"""
1006 for i, a in enumerate(self.applied):
1006 for i, a in enumerate(self.applied):
1007 if a.name == patch:
1007 if a.name == patch:
1008 return (i, a.node, a.name)
1008 return (i, a.node, a.name)
1009 return None
1009 return None
1010
1010
1011 # if the exact patch name does not exist, we try a few
1011 # if the exact patch name does not exist, we try a few
1012 # variations. If strict is passed, we try only #1
1012 # variations. If strict is passed, we try only #1
1013 #
1013 #
1014 # 1) a number to indicate an offset in the series file
1014 # 1) a number to indicate an offset in the series file
1015 # 2) a unique substring of the patch name was given
1015 # 2) a unique substring of the patch name was given
1016 # 3) patchname[-+]num to indicate an offset in the series file
1016 # 3) patchname[-+]num to indicate an offset in the series file
1017 def lookup(self, patch, strict=False):
1017 def lookup(self, patch, strict=False):
1018 patch = patch and str(patch)
1018 patch = patch and str(patch)
1019
1019
1020 def partial_name(s):
1020 def partial_name(s):
1021 if s in self.series:
1021 if s in self.series:
1022 return s
1022 return s
1023 matches = [x for x in self.series if s in x]
1023 matches = [x for x in self.series if s in x]
1024 if len(matches) > 1:
1024 if len(matches) > 1:
1025 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1025 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1026 for m in matches:
1026 for m in matches:
1027 self.ui.warn(' %s\n' % m)
1027 self.ui.warn(' %s\n' % m)
1028 return None
1028 return None
1029 if matches:
1029 if matches:
1030 return matches[0]
1030 return matches[0]
1031 if self.series and self.applied:
1031 if self.series and self.applied:
1032 if s == 'qtip':
1032 if s == 'qtip':
1033 return self.series[self.series_end(True)-1]
1033 return self.series[self.series_end(True)-1]
1034 if s == 'qbase':
1034 if s == 'qbase':
1035 return self.series[0]
1035 return self.series[0]
1036 return None
1036 return None
1037
1037
1038 if patch is None:
1038 if patch is None:
1039 return None
1039 return None
1040 if patch in self.series:
1040 if patch in self.series:
1041 return patch
1041 return patch
1042
1042
1043 if not os.path.isfile(self.join(patch)):
1043 if not os.path.isfile(self.join(patch)):
1044 try:
1044 try:
1045 sno = int(patch)
1045 sno = int(patch)
1046 except (ValueError, OverflowError):
1046 except (ValueError, OverflowError):
1047 pass
1047 pass
1048 else:
1048 else:
1049 if -len(self.series) <= sno < len(self.series):
1049 if -len(self.series) <= sno < len(self.series):
1050 return self.series[sno]
1050 return self.series[sno]
1051
1051
1052 if not strict:
1052 if not strict:
1053 res = partial_name(patch)
1053 res = partial_name(patch)
1054 if res:
1054 if res:
1055 return res
1055 return res
1056 minus = patch.rfind('-')
1056 minus = patch.rfind('-')
1057 if minus >= 0:
1057 if minus >= 0:
1058 res = partial_name(patch[:minus])
1058 res = partial_name(patch[:minus])
1059 if res:
1059 if res:
1060 i = self.series.index(res)
1060 i = self.series.index(res)
1061 try:
1061 try:
1062 off = int(patch[minus + 1:] or 1)
1062 off = int(patch[minus + 1:] or 1)
1063 except (ValueError, OverflowError):
1063 except (ValueError, OverflowError):
1064 pass
1064 pass
1065 else:
1065 else:
1066 if i - off >= 0:
1066 if i - off >= 0:
1067 return self.series[i - off]
1067 return self.series[i - off]
1068 plus = patch.rfind('+')
1068 plus = patch.rfind('+')
1069 if plus >= 0:
1069 if plus >= 0:
1070 res = partial_name(patch[:plus])
1070 res = partial_name(patch[:plus])
1071 if res:
1071 if res:
1072 i = self.series.index(res)
1072 i = self.series.index(res)
1073 try:
1073 try:
1074 off = int(patch[plus + 1:] or 1)
1074 off = int(patch[plus + 1:] or 1)
1075 except (ValueError, OverflowError):
1075 except (ValueError, OverflowError):
1076 pass
1076 pass
1077 else:
1077 else:
1078 if i + off < len(self.series):
1078 if i + off < len(self.series):
1079 return self.series[i + off]
1079 return self.series[i + off]
1080 raise util.Abort(_("patch %s not in series") % patch)
1080 raise util.Abort(_("patch %s not in series") % patch)
1081
1081
1082 def push(self, repo, patch=None, force=False, list=False,
1082 def push(self, repo, patch=None, force=False, list=False,
1083 mergeq=None, all=False, move=False, exact=False):
1083 mergeq=None, all=False, move=False, exact=False):
1084 diffopts = self.diffopts()
1084 diffopts = self.diffopts()
1085 wlock = repo.wlock()
1085 wlock = repo.wlock()
1086 try:
1086 try:
1087 heads = []
1087 heads = []
1088 for b, ls in repo.branchmap().iteritems():
1088 for b, ls in repo.branchmap().iteritems():
1089 heads += ls
1089 heads += ls
1090 if not heads:
1090 if not heads:
1091 heads = [nullid]
1091 heads = [nullid]
1092 if repo.dirstate.p1() not in heads and not exact:
1092 if repo.dirstate.p1() not in heads and not exact:
1093 self.ui.status(_("(working directory not at a head)\n"))
1093 self.ui.status(_("(working directory not at a head)\n"))
1094
1094
1095 if not self.series:
1095 if not self.series:
1096 self.ui.warn(_('no patches in series\n'))
1096 self.ui.warn(_('no patches in series\n'))
1097 return 0
1097 return 0
1098
1098
1099 patch = self.lookup(patch)
1099 patch = self.lookup(patch)
1100 # Suppose our series file is: A B C and the current 'top'
1100 # Suppose our series file is: A B C and the current 'top'
1101 # patch is B. qpush C should be performed (moving forward)
1101 # 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
1102 # qpush B is a NOP (no change) qpush A is an error (can't
1103 # go backwards with qpush)
1103 # go backwards with qpush)
1104 if patch:
1104 if patch:
1105 info = self.isapplied(patch)
1105 info = self.isapplied(patch)
1106 if info and info[0] >= len(self.applied) - 1:
1106 if info and info[0] >= len(self.applied) - 1:
1107 self.ui.warn(
1107 self.ui.warn(
1108 _('qpush: %s is already at the top\n') % patch)
1108 _('qpush: %s is already at the top\n') % patch)
1109 return 0
1109 return 0
1110
1110
1111 pushable, reason = self.pushable(patch)
1111 pushable, reason = self.pushable(patch)
1112 if pushable:
1112 if pushable:
1113 if self.series.index(patch) < self.series_end():
1113 if self.series.index(patch) < self.series_end():
1114 raise util.Abort(
1114 raise util.Abort(
1115 _("cannot push to a previous patch: %s") % patch)
1115 _("cannot push to a previous patch: %s") % patch)
1116 else:
1116 else:
1117 if reason:
1117 if reason:
1118 reason = _('guarded by %r') % reason
1118 reason = _('guarded by %r') % reason
1119 else:
1119 else:
1120 reason = _('no matching guards')
1120 reason = _('no matching guards')
1121 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1121 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1122 return 1
1122 return 1
1123 elif all:
1123 elif all:
1124 patch = self.series[-1]
1124 patch = self.series[-1]
1125 if self.isapplied(patch):
1125 if self.isapplied(patch):
1126 self.ui.warn(_('all patches are currently applied\n'))
1126 self.ui.warn(_('all patches are currently applied\n'))
1127 return 0
1127 return 0
1128
1128
1129 # Following the above example, starting at 'top' of B:
1129 # Following the above example, starting at 'top' of B:
1130 # qpush should be performed (pushes C), but a subsequent
1130 # qpush should be performed (pushes C), but a subsequent
1131 # qpush without an argument is an error (nothing to
1131 # qpush without an argument is an error (nothing to
1132 # apply). This allows a loop of "...while hg qpush..." to
1132 # apply). This allows a loop of "...while hg qpush..." to
1133 # work as it detects an error when done
1133 # work as it detects an error when done
1134 start = self.series_end()
1134 start = self.series_end()
1135 if start == len(self.series):
1135 if start == len(self.series):
1136 self.ui.warn(_('patch series already fully applied\n'))
1136 self.ui.warn(_('patch series already fully applied\n'))
1137 return 1
1137 return 1
1138
1138
1139 if exact:
1139 if exact:
1140 if move:
1140 if move:
1141 raise util.Abort(_("cannot use --exact and --move together"))
1141 raise util.Abort(_("cannot use --exact and --move together"))
1142 if self.applied:
1142 if self.applied:
1143 raise util.Abort(_("cannot push --exact with applied patches"))
1143 raise util.Abort(_("cannot push --exact with applied patches"))
1144 root = self.series[start]
1144 root = self.series[start]
1145 target = patchheader(self.join(root), self.plainmode).parent
1145 target = patchheader(self.join(root), self.plainmode).parent
1146 if not target:
1146 if not target:
1147 raise util.Abort(_("%s does not have a parent recorded" % root))
1147 raise util.Abort(_("%s does not have a parent recorded" % root))
1148 if not repo[target] == repo['.']:
1148 if not repo[target] == repo['.']:
1149 hg.update(repo, target)
1149 hg.update(repo, target)
1150
1150
1151 if move:
1151 if move:
1152 if not patch:
1152 if not patch:
1153 raise util.Abort(_("please specify the patch to move"))
1153 raise util.Abort(_("please specify the patch to move"))
1154 for i, rpn in enumerate(self.full_series[start:]):
1154 for i, rpn in enumerate(self.full_series[start:]):
1155 # strip markers for patch guards
1155 # strip markers for patch guards
1156 if self.guard_re.split(rpn, 1)[0] == patch:
1156 if self.guard_re.split(rpn, 1)[0] == patch:
1157 break
1157 break
1158 index = start + i
1158 index = start + i
1159 assert index < len(self.full_series)
1159 assert index < len(self.full_series)
1160 fullpatch = self.full_series[index]
1160 fullpatch = self.full_series[index]
1161 del self.full_series[index]
1161 del self.full_series[index]
1162 self.full_series.insert(start, fullpatch)
1162 self.full_series.insert(start, fullpatch)
1163 self.parse_series()
1163 self.parse_series()
1164 self.series_dirty = 1
1164 self.series_dirty = 1
1165
1165
1166 self.applied_dirty = 1
1166 self.applied_dirty = 1
1167 if start > 0:
1167 if start > 0:
1168 self.check_toppatch(repo)
1168 self.check_toppatch(repo)
1169 if not patch:
1169 if not patch:
1170 patch = self.series[start]
1170 patch = self.series[start]
1171 end = start + 1
1171 end = start + 1
1172 else:
1172 else:
1173 end = self.series.index(patch, start) + 1
1173 end = self.series.index(patch, start) + 1
1174
1174
1175 s = self.series[start:end]
1175 s = self.series[start:end]
1176
1176
1177 if not force:
1177 if not force:
1178 mm, aa, rr, dd = repo.status()[:4]
1178 mm, aa, rr, dd = repo.status()[:4]
1179 wcfiles = set(mm + aa + rr + dd)
1179 wcfiles = set(mm + aa + rr + dd)
1180 if wcfiles:
1180 if wcfiles:
1181 for patchname in s:
1181 for patchname in s:
1182 pf = os.path.join(self.path, patchname)
1182 pf = os.path.join(self.path, patchname)
1183 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1183 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1184 if wcfiles.intersection(patchfiles):
1184 if wcfiles.intersection(patchfiles):
1185 self.localchangesfound(self.applied)
1185 self.localchangesfound(self.applied)
1186 elif mergeq:
1186 elif mergeq:
1187 self.check_localchanges(refresh=self.applied)
1187 self.check_localchanges(refresh=self.applied)
1188
1188
1189 all_files = set()
1189 all_files = set()
1190 try:
1190 try:
1191 if mergeq:
1191 if mergeq:
1192 ret = self.mergepatch(repo, mergeq, s, diffopts)
1192 ret = self.mergepatch(repo, mergeq, s, diffopts)
1193 else:
1193 else:
1194 ret = self.apply(repo, s, list, all_files=all_files)
1194 ret = self.apply(repo, s, list, all_files=all_files)
1195 except:
1195 except:
1196 self.ui.warn(_('cleaning up working directory...'))
1196 self.ui.warn(_('cleaning up working directory...'))
1197 node = repo.dirstate.p1()
1197 node = repo.dirstate.p1()
1198 hg.revert(repo, node, None)
1198 hg.revert(repo, node, None)
1199 # only remove unknown files that we know we touched or
1199 # only remove unknown files that we know we touched or
1200 # created while patching
1200 # created while patching
1201 for f in all_files:
1201 for f in all_files:
1202 if f not in repo.dirstate:
1202 if f not in repo.dirstate:
1203 try:
1203 try:
1204 util.unlinkpath(repo.wjoin(f))
1204 util.unlinkpath(repo.wjoin(f))
1205 except OSError, inst:
1205 except OSError, inst:
1206 if inst.errno != errno.ENOENT:
1206 if inst.errno != errno.ENOENT:
1207 raise
1207 raise
1208 self.ui.warn(_('done\n'))
1208 self.ui.warn(_('done\n'))
1209 raise
1209 raise
1210
1210
1211 if not self.applied:
1211 if not self.applied:
1212 return ret[0]
1212 return ret[0]
1213 top = self.applied[-1].name
1213 top = self.applied[-1].name
1214 if ret[0] and ret[0] > 1:
1214 if ret[0] and ret[0] > 1:
1215 msg = _("errors during apply, please fix and refresh %s\n")
1215 msg = _("errors during apply, please fix and refresh %s\n")
1216 self.ui.write(msg % top)
1216 self.ui.write(msg % top)
1217 else:
1217 else:
1218 self.ui.write(_("now at: %s\n") % top)
1218 self.ui.write(_("now at: %s\n") % top)
1219 return ret[0]
1219 return ret[0]
1220
1220
1221 finally:
1221 finally:
1222 wlock.release()
1222 wlock.release()
1223
1223
1224 def pop(self, repo, patch=None, force=False, update=True, all=False):
1224 def pop(self, repo, patch=None, force=False, update=True, all=False):
1225 wlock = repo.wlock()
1225 wlock = repo.wlock()
1226 try:
1226 try:
1227 if patch:
1227 if patch:
1228 # index, rev, patch
1228 # index, rev, patch
1229 info = self.isapplied(patch)
1229 info = self.isapplied(patch)
1230 if not info:
1230 if not info:
1231 patch = self.lookup(patch)
1231 patch = self.lookup(patch)
1232 info = self.isapplied(patch)
1232 info = self.isapplied(patch)
1233 if not info:
1233 if not info:
1234 raise util.Abort(_("patch %s is not applied") % patch)
1234 raise util.Abort(_("patch %s is not applied") % patch)
1235
1235
1236 if not self.applied:
1236 if not self.applied:
1237 # Allow qpop -a to work repeatedly,
1237 # Allow qpop -a to work repeatedly,
1238 # but not qpop without an argument
1238 # but not qpop without an argument
1239 self.ui.warn(_("no patches applied\n"))
1239 self.ui.warn(_("no patches applied\n"))
1240 return not all
1240 return not all
1241
1241
1242 if all:
1242 if all:
1243 start = 0
1243 start = 0
1244 elif patch:
1244 elif patch:
1245 start = info[0] + 1
1245 start = info[0] + 1
1246 else:
1246 else:
1247 start = len(self.applied) - 1
1247 start = len(self.applied) - 1
1248
1248
1249 if start >= len(self.applied):
1249 if start >= len(self.applied):
1250 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1250 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1251 return
1251 return
1252
1252
1253 if not update:
1253 if not update:
1254 parents = repo.dirstate.parents()
1254 parents = repo.dirstate.parents()
1255 rr = [x.node for x in self.applied]
1255 rr = [x.node for x in self.applied]
1256 for p in parents:
1256 for p in parents:
1257 if p in rr:
1257 if p in rr:
1258 self.ui.warn(_("qpop: forcing dirstate update\n"))
1258 self.ui.warn(_("qpop: forcing dirstate update\n"))
1259 update = True
1259 update = True
1260 else:
1260 else:
1261 parents = [p.node() for p in repo[None].parents()]
1261 parents = [p.node() for p in repo[None].parents()]
1262 needupdate = False
1262 needupdate = False
1263 for entry in self.applied[start:]:
1263 for entry in self.applied[start:]:
1264 if entry.node in parents:
1264 if entry.node in parents:
1265 needupdate = True
1265 needupdate = True
1266 break
1266 break
1267 update = needupdate
1267 update = needupdate
1268
1268
1269 self.applied_dirty = 1
1269 self.applied_dirty = 1
1270 end = len(self.applied)
1270 end = len(self.applied)
1271 rev = self.applied[start].node
1271 rev = self.applied[start].node
1272 if update:
1272 if update:
1273 top = self.check_toppatch(repo)[0]
1273 top = self.check_toppatch(repo)[0]
1274
1274
1275 try:
1275 try:
1276 heads = repo.changelog.heads(rev)
1276 heads = repo.changelog.heads(rev)
1277 except error.LookupError:
1277 except error.LookupError:
1278 node = short(rev)
1278 node = short(rev)
1279 raise util.Abort(_('trying to pop unknown node %s') % node)
1279 raise util.Abort(_('trying to pop unknown node %s') % node)
1280
1280
1281 if heads != [self.applied[-1].node]:
1281 if heads != [self.applied[-1].node]:
1282 raise util.Abort(_("popping would remove a revision not "
1282 raise util.Abort(_("popping would remove a revision not "
1283 "managed by this patch queue"))
1283 "managed by this patch queue"))
1284
1284
1285 # we know there are no local changes, so we can make a simplified
1285 # we know there are no local changes, so we can make a simplified
1286 # form of hg.update.
1286 # form of hg.update.
1287 if update:
1287 if update:
1288 qp = self.qparents(repo, rev)
1288 qp = self.qparents(repo, rev)
1289 ctx = repo[qp]
1289 ctx = repo[qp]
1290 m, a, r, d = repo.status(qp, top)[:4]
1290 m, a, r, d = repo.status(qp, top)[:4]
1291 parentfiles = set(m + a + r + d)
1291 parentfiles = set(m + a + r + d)
1292 if not force and parentfiles:
1292 if not force and parentfiles:
1293 mm, aa, rr, dd = repo.status()[:4]
1293 mm, aa, rr, dd = repo.status()[:4]
1294 wcfiles = set(mm + aa + rr + dd)
1294 wcfiles = set(mm + aa + rr + dd)
1295 if wcfiles.intersection(parentfiles):
1295 if wcfiles.intersection(parentfiles):
1296 self.localchangesfound()
1296 self.localchangesfound()
1297 if d:
1297 if d:
1298 raise util.Abort(_("deletions found between repo revs"))
1298 raise util.Abort(_("deletions found between repo revs"))
1299 for f in a:
1299 for f in a:
1300 try:
1300 try:
1301 util.unlinkpath(repo.wjoin(f))
1301 util.unlinkpath(repo.wjoin(f))
1302 except OSError, e:
1302 except OSError, e:
1303 if e.errno != errno.ENOENT:
1303 if e.errno != errno.ENOENT:
1304 raise
1304 raise
1305 repo.dirstate.forget(f)
1305 repo.dirstate.drop(f)
1306 for f in m + r:
1306 for f in m + r:
1307 fctx = ctx[f]
1307 fctx = ctx[f]
1308 repo.wwrite(f, fctx.data(), fctx.flags())
1308 repo.wwrite(f, fctx.data(), fctx.flags())
1309 repo.dirstate.normal(f)
1309 repo.dirstate.normal(f)
1310 repo.dirstate.setparents(qp, nullid)
1310 repo.dirstate.setparents(qp, nullid)
1311 for patch in reversed(self.applied[start:end]):
1311 for patch in reversed(self.applied[start:end]):
1312 self.ui.status(_("popping %s\n") % patch.name)
1312 self.ui.status(_("popping %s\n") % patch.name)
1313 del self.applied[start:end]
1313 del self.applied[start:end]
1314 self.strip(repo, [rev], update=False, backup='strip')
1314 self.strip(repo, [rev], update=False, backup='strip')
1315 if self.applied:
1315 if self.applied:
1316 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1316 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1317 else:
1317 else:
1318 self.ui.write(_("patch queue now empty\n"))
1318 self.ui.write(_("patch queue now empty\n"))
1319 finally:
1319 finally:
1320 wlock.release()
1320 wlock.release()
1321
1321
1322 def diff(self, repo, pats, opts):
1322 def diff(self, repo, pats, opts):
1323 top, patch = self.check_toppatch(repo)
1323 top, patch = self.check_toppatch(repo)
1324 if not top:
1324 if not top:
1325 self.ui.write(_("no patches applied\n"))
1325 self.ui.write(_("no patches applied\n"))
1326 return
1326 return
1327 qp = self.qparents(repo, top)
1327 qp = self.qparents(repo, top)
1328 if opts.get('reverse'):
1328 if opts.get('reverse'):
1329 node1, node2 = None, qp
1329 node1, node2 = None, qp
1330 else:
1330 else:
1331 node1, node2 = qp, None
1331 node1, node2 = qp, None
1332 diffopts = self.diffopts(opts, patch)
1332 diffopts = self.diffopts(opts, patch)
1333 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1333 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1334
1334
1335 def refresh(self, repo, pats=None, **opts):
1335 def refresh(self, repo, pats=None, **opts):
1336 if not self.applied:
1336 if not self.applied:
1337 self.ui.write(_("no patches applied\n"))
1337 self.ui.write(_("no patches applied\n"))
1338 return 1
1338 return 1
1339 msg = opts.get('msg', '').rstrip()
1339 msg = opts.get('msg', '').rstrip()
1340 newuser = opts.get('user')
1340 newuser = opts.get('user')
1341 newdate = opts.get('date')
1341 newdate = opts.get('date')
1342 if newdate:
1342 if newdate:
1343 newdate = '%d %d' % util.parsedate(newdate)
1343 newdate = '%d %d' % util.parsedate(newdate)
1344 wlock = repo.wlock()
1344 wlock = repo.wlock()
1345
1345
1346 try:
1346 try:
1347 self.check_toppatch(repo)
1347 self.check_toppatch(repo)
1348 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1348 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1349 if repo.changelog.heads(top) != [top]:
1349 if repo.changelog.heads(top) != [top]:
1350 raise util.Abort(_("cannot refresh a revision with children"))
1350 raise util.Abort(_("cannot refresh a revision with children"))
1351
1351
1352 inclsubs = self.check_substate(repo)
1352 inclsubs = self.check_substate(repo)
1353
1353
1354 cparents = repo.changelog.parents(top)
1354 cparents = repo.changelog.parents(top)
1355 patchparent = self.qparents(repo, top)
1355 patchparent = self.qparents(repo, top)
1356 ph = patchheader(self.join(patchfn), self.plainmode)
1356 ph = patchheader(self.join(patchfn), self.plainmode)
1357 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1357 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1358 if msg:
1358 if msg:
1359 ph.setmessage(msg)
1359 ph.setmessage(msg)
1360 if newuser:
1360 if newuser:
1361 ph.setuser(newuser)
1361 ph.setuser(newuser)
1362 if newdate:
1362 if newdate:
1363 ph.setdate(newdate)
1363 ph.setdate(newdate)
1364 ph.setparent(hex(patchparent))
1364 ph.setparent(hex(patchparent))
1365
1365
1366 # only commit new patch when write is complete
1366 # only commit new patch when write is complete
1367 patchf = self.opener(patchfn, 'w', atomictemp=True)
1367 patchf = self.opener(patchfn, 'w', atomictemp=True)
1368
1368
1369 comments = str(ph)
1369 comments = str(ph)
1370 if comments:
1370 if comments:
1371 patchf.write(comments)
1371 patchf.write(comments)
1372
1372
1373 # update the dirstate in place, strip off the qtip commit
1373 # update the dirstate in place, strip off the qtip commit
1374 # and then commit.
1374 # and then commit.
1375 #
1375 #
1376 # this should really read:
1376 # this should really read:
1377 # mm, dd, aa = repo.status(top, patchparent)[:3]
1377 # mm, dd, aa = repo.status(top, patchparent)[:3]
1378 # but we do it backwards to take advantage of manifest/chlog
1378 # but we do it backwards to take advantage of manifest/chlog
1379 # caching against the next repo.status call
1379 # caching against the next repo.status call
1380 mm, aa, dd = repo.status(patchparent, top)[:3]
1380 mm, aa, dd = repo.status(patchparent, top)[:3]
1381 changes = repo.changelog.read(top)
1381 changes = repo.changelog.read(top)
1382 man = repo.manifest.read(changes[0])
1382 man = repo.manifest.read(changes[0])
1383 aaa = aa[:]
1383 aaa = aa[:]
1384 matchfn = scmutil.match(repo, pats, opts)
1384 matchfn = scmutil.match(repo, pats, opts)
1385 # in short mode, we only diff the files included in the
1385 # in short mode, we only diff the files included in the
1386 # patch already plus specified files
1386 # patch already plus specified files
1387 if opts.get('short'):
1387 if opts.get('short'):
1388 # if amending a patch, we start with existing
1388 # if amending a patch, we start with existing
1389 # files plus specified files - unfiltered
1389 # files plus specified files - unfiltered
1390 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1390 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1391 # filter with inc/exl options
1391 # filter with inc/exl options
1392 matchfn = scmutil.match(repo, opts=opts)
1392 matchfn = scmutil.match(repo, opts=opts)
1393 else:
1393 else:
1394 match = scmutil.matchall(repo)
1394 match = scmutil.matchall(repo)
1395 m, a, r, d = repo.status(match=match)[:4]
1395 m, a, r, d = repo.status(match=match)[:4]
1396 mm = set(mm)
1396 mm = set(mm)
1397 aa = set(aa)
1397 aa = set(aa)
1398 dd = set(dd)
1398 dd = set(dd)
1399
1399
1400 # we might end up with files that were added between
1400 # we might end up with files that were added between
1401 # qtip and the dirstate parent, but then changed in the
1401 # qtip and the dirstate parent, but then changed in the
1402 # local dirstate. in this case, we want them to only
1402 # local dirstate. in this case, we want them to only
1403 # show up in the added section
1403 # show up in the added section
1404 for x in m:
1404 for x in m:
1405 if x not in aa:
1405 if x not in aa:
1406 mm.add(x)
1406 mm.add(x)
1407 # we might end up with files added by the local dirstate that
1407 # we might end up with files added by the local dirstate that
1408 # were deleted by the patch. In this case, they should only
1408 # were deleted by the patch. In this case, they should only
1409 # show up in the changed section.
1409 # show up in the changed section.
1410 for x in a:
1410 for x in a:
1411 if x in dd:
1411 if x in dd:
1412 dd.remove(x)
1412 dd.remove(x)
1413 mm.add(x)
1413 mm.add(x)
1414 else:
1414 else:
1415 aa.add(x)
1415 aa.add(x)
1416 # make sure any files deleted in the local dirstate
1416 # make sure any files deleted in the local dirstate
1417 # are not in the add or change column of the patch
1417 # are not in the add or change column of the patch
1418 forget = []
1418 forget = []
1419 for x in d + r:
1419 for x in d + r:
1420 if x in aa:
1420 if x in aa:
1421 aa.remove(x)
1421 aa.remove(x)
1422 forget.append(x)
1422 forget.append(x)
1423 continue
1423 continue
1424 else:
1424 else:
1425 mm.discard(x)
1425 mm.discard(x)
1426 dd.add(x)
1426 dd.add(x)
1427
1427
1428 m = list(mm)
1428 m = list(mm)
1429 r = list(dd)
1429 r = list(dd)
1430 a = list(aa)
1430 a = list(aa)
1431 c = [filter(matchfn, l) for l in (m, a, r)]
1431 c = [filter(matchfn, l) for l in (m, a, r)]
1432 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1432 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1433 chunks = patchmod.diff(repo, patchparent, match=match,
1433 chunks = patchmod.diff(repo, patchparent, match=match,
1434 changes=c, opts=diffopts)
1434 changes=c, opts=diffopts)
1435 for chunk in chunks:
1435 for chunk in chunks:
1436 patchf.write(chunk)
1436 patchf.write(chunk)
1437
1437
1438 try:
1438 try:
1439 if diffopts.git or diffopts.upgrade:
1439 if diffopts.git or diffopts.upgrade:
1440 copies = {}
1440 copies = {}
1441 for dst in a:
1441 for dst in a:
1442 src = repo.dirstate.copied(dst)
1442 src = repo.dirstate.copied(dst)
1443 # during qfold, the source file for copies may
1443 # during qfold, the source file for copies may
1444 # be removed. Treat this as a simple add.
1444 # be removed. Treat this as a simple add.
1445 if src is not None and src in repo.dirstate:
1445 if src is not None and src in repo.dirstate:
1446 copies.setdefault(src, []).append(dst)
1446 copies.setdefault(src, []).append(dst)
1447 repo.dirstate.add(dst)
1447 repo.dirstate.add(dst)
1448 # remember the copies between patchparent and qtip
1448 # remember the copies between patchparent and qtip
1449 for dst in aaa:
1449 for dst in aaa:
1450 f = repo.file(dst)
1450 f = repo.file(dst)
1451 src = f.renamed(man[dst])
1451 src = f.renamed(man[dst])
1452 if src:
1452 if src:
1453 copies.setdefault(src[0], []).extend(
1453 copies.setdefault(src[0], []).extend(
1454 copies.get(dst, []))
1454 copies.get(dst, []))
1455 if dst in a:
1455 if dst in a:
1456 copies[src[0]].append(dst)
1456 copies[src[0]].append(dst)
1457 # we can't copy a file created by the patch itself
1457 # we can't copy a file created by the patch itself
1458 if dst in copies:
1458 if dst in copies:
1459 del copies[dst]
1459 del copies[dst]
1460 for src, dsts in copies.iteritems():
1460 for src, dsts in copies.iteritems():
1461 for dst in dsts:
1461 for dst in dsts:
1462 repo.dirstate.copy(src, dst)
1462 repo.dirstate.copy(src, dst)
1463 else:
1463 else:
1464 for dst in a:
1464 for dst in a:
1465 repo.dirstate.add(dst)
1465 repo.dirstate.add(dst)
1466 # Drop useless copy information
1466 # Drop useless copy information
1467 for f in list(repo.dirstate.copies()):
1467 for f in list(repo.dirstate.copies()):
1468 repo.dirstate.copy(None, f)
1468 repo.dirstate.copy(None, f)
1469 for f in r:
1469 for f in r:
1470 repo.dirstate.remove(f)
1470 repo.dirstate.remove(f)
1471 # if the patch excludes a modified file, mark that
1471 # if the patch excludes a modified file, mark that
1472 # file with mtime=0 so status can see it.
1472 # file with mtime=0 so status can see it.
1473 mm = []
1473 mm = []
1474 for i in xrange(len(m)-1, -1, -1):
1474 for i in xrange(len(m)-1, -1, -1):
1475 if not matchfn(m[i]):
1475 if not matchfn(m[i]):
1476 mm.append(m[i])
1476 mm.append(m[i])
1477 del m[i]
1477 del m[i]
1478 for f in m:
1478 for f in m:
1479 repo.dirstate.normal(f)
1479 repo.dirstate.normal(f)
1480 for f in mm:
1480 for f in mm:
1481 repo.dirstate.normallookup(f)
1481 repo.dirstate.normallookup(f)
1482 for f in forget:
1482 for f in forget:
1483 repo.dirstate.forget(f)
1483 repo.dirstate.drop(f)
1484
1484
1485 if not msg:
1485 if not msg:
1486 if not ph.message:
1486 if not ph.message:
1487 message = "[mq]: %s\n" % patchfn
1487 message = "[mq]: %s\n" % patchfn
1488 else:
1488 else:
1489 message = "\n".join(ph.message)
1489 message = "\n".join(ph.message)
1490 else:
1490 else:
1491 message = msg
1491 message = msg
1492
1492
1493 user = ph.user or changes[1]
1493 user = ph.user or changes[1]
1494
1494
1495 # assumes strip can roll itself back if interrupted
1495 # assumes strip can roll itself back if interrupted
1496 repo.dirstate.setparents(*cparents)
1496 repo.dirstate.setparents(*cparents)
1497 self.applied.pop()
1497 self.applied.pop()
1498 self.applied_dirty = 1
1498 self.applied_dirty = 1
1499 self.strip(repo, [top], update=False,
1499 self.strip(repo, [top], update=False,
1500 backup='strip')
1500 backup='strip')
1501 except:
1501 except:
1502 repo.dirstate.invalidate()
1502 repo.dirstate.invalidate()
1503 raise
1503 raise
1504
1504
1505 try:
1505 try:
1506 # might be nice to attempt to roll back strip after this
1506 # might be nice to attempt to roll back strip after this
1507 n = repo.commit(message, user, ph.date, match=match,
1507 n = repo.commit(message, user, ph.date, match=match,
1508 force=True)
1508 force=True)
1509 # only write patch after a successful commit
1509 # only write patch after a successful commit
1510 patchf.rename()
1510 patchf.rename()
1511 self.applied.append(statusentry(n, patchfn))
1511 self.applied.append(statusentry(n, patchfn))
1512 except:
1512 except:
1513 ctx = repo[cparents[0]]
1513 ctx = repo[cparents[0]]
1514 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1514 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1515 self.save_dirty()
1515 self.save_dirty()
1516 self.ui.warn(_('refresh interrupted while patch was popped! '
1516 self.ui.warn(_('refresh interrupted while patch was popped! '
1517 '(revert --all, qpush to recover)\n'))
1517 '(revert --all, qpush to recover)\n'))
1518 raise
1518 raise
1519 finally:
1519 finally:
1520 wlock.release()
1520 wlock.release()
1521 self.removeundo(repo)
1521 self.removeundo(repo)
1522
1522
1523 def init(self, repo, create=False):
1523 def init(self, repo, create=False):
1524 if not create and os.path.isdir(self.path):
1524 if not create and os.path.isdir(self.path):
1525 raise util.Abort(_("patch queue directory already exists"))
1525 raise util.Abort(_("patch queue directory already exists"))
1526 try:
1526 try:
1527 os.mkdir(self.path)
1527 os.mkdir(self.path)
1528 except OSError, inst:
1528 except OSError, inst:
1529 if inst.errno != errno.EEXIST or not create:
1529 if inst.errno != errno.EEXIST or not create:
1530 raise
1530 raise
1531 if create:
1531 if create:
1532 return self.qrepo(create=True)
1532 return self.qrepo(create=True)
1533
1533
1534 def unapplied(self, repo, patch=None):
1534 def unapplied(self, repo, patch=None):
1535 if patch and patch not in self.series:
1535 if patch and patch not in self.series:
1536 raise util.Abort(_("patch %s is not in series file") % patch)
1536 raise util.Abort(_("patch %s is not in series file") % patch)
1537 if not patch:
1537 if not patch:
1538 start = self.series_end()
1538 start = self.series_end()
1539 else:
1539 else:
1540 start = self.series.index(patch) + 1
1540 start = self.series.index(patch) + 1
1541 unapplied = []
1541 unapplied = []
1542 for i in xrange(start, len(self.series)):
1542 for i in xrange(start, len(self.series)):
1543 pushable, reason = self.pushable(i)
1543 pushable, reason = self.pushable(i)
1544 if pushable:
1544 if pushable:
1545 unapplied.append((i, self.series[i]))
1545 unapplied.append((i, self.series[i]))
1546 self.explain_pushable(i)
1546 self.explain_pushable(i)
1547 return unapplied
1547 return unapplied
1548
1548
1549 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1549 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1550 summary=False):
1550 summary=False):
1551 def displayname(pfx, patchname, state):
1551 def displayname(pfx, patchname, state):
1552 if pfx:
1552 if pfx:
1553 self.ui.write(pfx)
1553 self.ui.write(pfx)
1554 if summary:
1554 if summary:
1555 ph = patchheader(self.join(patchname), self.plainmode)
1555 ph = patchheader(self.join(patchname), self.plainmode)
1556 msg = ph.message and ph.message[0] or ''
1556 msg = ph.message and ph.message[0] or ''
1557 if self.ui.formatted():
1557 if self.ui.formatted():
1558 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1558 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1559 if width > 0:
1559 if width > 0:
1560 msg = util.ellipsis(msg, width)
1560 msg = util.ellipsis(msg, width)
1561 else:
1561 else:
1562 msg = ''
1562 msg = ''
1563 self.ui.write(patchname, label='qseries.' + state)
1563 self.ui.write(patchname, label='qseries.' + state)
1564 self.ui.write(': ')
1564 self.ui.write(': ')
1565 self.ui.write(msg, label='qseries.message.' + state)
1565 self.ui.write(msg, label='qseries.message.' + state)
1566 else:
1566 else:
1567 self.ui.write(patchname, label='qseries.' + state)
1567 self.ui.write(patchname, label='qseries.' + state)
1568 self.ui.write('\n')
1568 self.ui.write('\n')
1569
1569
1570 applied = set([p.name for p in self.applied])
1570 applied = set([p.name for p in self.applied])
1571 if length is None:
1571 if length is None:
1572 length = len(self.series) - start
1572 length = len(self.series) - start
1573 if not missing:
1573 if not missing:
1574 if self.ui.verbose:
1574 if self.ui.verbose:
1575 idxwidth = len(str(start + length - 1))
1575 idxwidth = len(str(start + length - 1))
1576 for i in xrange(start, start + length):
1576 for i in xrange(start, start + length):
1577 patch = self.series[i]
1577 patch = self.series[i]
1578 if patch in applied:
1578 if patch in applied:
1579 char, state = 'A', 'applied'
1579 char, state = 'A', 'applied'
1580 elif self.pushable(i)[0]:
1580 elif self.pushable(i)[0]:
1581 char, state = 'U', 'unapplied'
1581 char, state = 'U', 'unapplied'
1582 else:
1582 else:
1583 char, state = 'G', 'guarded'
1583 char, state = 'G', 'guarded'
1584 pfx = ''
1584 pfx = ''
1585 if self.ui.verbose:
1585 if self.ui.verbose:
1586 pfx = '%*d %s ' % (idxwidth, i, char)
1586 pfx = '%*d %s ' % (idxwidth, i, char)
1587 elif status and status != char:
1587 elif status and status != char:
1588 continue
1588 continue
1589 displayname(pfx, patch, state)
1589 displayname(pfx, patch, state)
1590 else:
1590 else:
1591 msng_list = []
1591 msng_list = []
1592 for root, dirs, files in os.walk(self.path):
1592 for root, dirs, files in os.walk(self.path):
1593 d = root[len(self.path) + 1:]
1593 d = root[len(self.path) + 1:]
1594 for f in files:
1594 for f in files:
1595 fl = os.path.join(d, f)
1595 fl = os.path.join(d, f)
1596 if (fl not in self.series and
1596 if (fl not in self.series and
1597 fl not in (self.status_path, self.series_path,
1597 fl not in (self.status_path, self.series_path,
1598 self.guards_path)
1598 self.guards_path)
1599 and not fl.startswith('.')):
1599 and not fl.startswith('.')):
1600 msng_list.append(fl)
1600 msng_list.append(fl)
1601 for x in sorted(msng_list):
1601 for x in sorted(msng_list):
1602 pfx = self.ui.verbose and ('D ') or ''
1602 pfx = self.ui.verbose and ('D ') or ''
1603 displayname(pfx, x, 'missing')
1603 displayname(pfx, x, 'missing')
1604
1604
1605 def issaveline(self, l):
1605 def issaveline(self, l):
1606 if l.name == '.hg.patches.save.line':
1606 if l.name == '.hg.patches.save.line':
1607 return True
1607 return True
1608
1608
1609 def qrepo(self, create=False):
1609 def qrepo(self, create=False):
1610 ui = self.ui.copy()
1610 ui = self.ui.copy()
1611 ui.setconfig('paths', 'default', '', overlay=False)
1611 ui.setconfig('paths', 'default', '', overlay=False)
1612 ui.setconfig('paths', 'default-push', '', overlay=False)
1612 ui.setconfig('paths', 'default-push', '', overlay=False)
1613 if create or os.path.isdir(self.join(".hg")):
1613 if create or os.path.isdir(self.join(".hg")):
1614 return hg.repository(ui, path=self.path, create=create)
1614 return hg.repository(ui, path=self.path, create=create)
1615
1615
1616 def restore(self, repo, rev, delete=None, qupdate=None):
1616 def restore(self, repo, rev, delete=None, qupdate=None):
1617 desc = repo[rev].description().strip()
1617 desc = repo[rev].description().strip()
1618 lines = desc.splitlines()
1618 lines = desc.splitlines()
1619 i = 0
1619 i = 0
1620 datastart = None
1620 datastart = None
1621 series = []
1621 series = []
1622 applied = []
1622 applied = []
1623 qpp = None
1623 qpp = None
1624 for i, line in enumerate(lines):
1624 for i, line in enumerate(lines):
1625 if line == 'Patch Data:':
1625 if line == 'Patch Data:':
1626 datastart = i + 1
1626 datastart = i + 1
1627 elif line.startswith('Dirstate:'):
1627 elif line.startswith('Dirstate:'):
1628 l = line.rstrip()
1628 l = line.rstrip()
1629 l = l[10:].split(' ')
1629 l = l[10:].split(' ')
1630 qpp = [bin(x) for x in l]
1630 qpp = [bin(x) for x in l]
1631 elif datastart is not None:
1631 elif datastart is not None:
1632 l = line.rstrip()
1632 l = line.rstrip()
1633 n, name = l.split(':', 1)
1633 n, name = l.split(':', 1)
1634 if n:
1634 if n:
1635 applied.append(statusentry(bin(n), name))
1635 applied.append(statusentry(bin(n), name))
1636 else:
1636 else:
1637 series.append(l)
1637 series.append(l)
1638 if datastart is None:
1638 if datastart is None:
1639 self.ui.warn(_("No saved patch data found\n"))
1639 self.ui.warn(_("No saved patch data found\n"))
1640 return 1
1640 return 1
1641 self.ui.warn(_("restoring status: %s\n") % lines[0])
1641 self.ui.warn(_("restoring status: %s\n") % lines[0])
1642 self.full_series = series
1642 self.full_series = series
1643 self.applied = applied
1643 self.applied = applied
1644 self.parse_series()
1644 self.parse_series()
1645 self.series_dirty = 1
1645 self.series_dirty = 1
1646 self.applied_dirty = 1
1646 self.applied_dirty = 1
1647 heads = repo.changelog.heads()
1647 heads = repo.changelog.heads()
1648 if delete:
1648 if delete:
1649 if rev not in heads:
1649 if rev not in heads:
1650 self.ui.warn(_("save entry has children, leaving it alone\n"))
1650 self.ui.warn(_("save entry has children, leaving it alone\n"))
1651 else:
1651 else:
1652 self.ui.warn(_("removing save entry %s\n") % short(rev))
1652 self.ui.warn(_("removing save entry %s\n") % short(rev))
1653 pp = repo.dirstate.parents()
1653 pp = repo.dirstate.parents()
1654 if rev in pp:
1654 if rev in pp:
1655 update = True
1655 update = True
1656 else:
1656 else:
1657 update = False
1657 update = False
1658 self.strip(repo, [rev], update=update, backup='strip')
1658 self.strip(repo, [rev], update=update, backup='strip')
1659 if qpp:
1659 if qpp:
1660 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1660 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1661 (short(qpp[0]), short(qpp[1])))
1661 (short(qpp[0]), short(qpp[1])))
1662 if qupdate:
1662 if qupdate:
1663 self.ui.status(_("updating queue directory\n"))
1663 self.ui.status(_("updating queue directory\n"))
1664 r = self.qrepo()
1664 r = self.qrepo()
1665 if not r:
1665 if not r:
1666 self.ui.warn(_("Unable to load queue repository\n"))
1666 self.ui.warn(_("Unable to load queue repository\n"))
1667 return 1
1667 return 1
1668 hg.clean(r, qpp[0])
1668 hg.clean(r, qpp[0])
1669
1669
1670 def save(self, repo, msg=None):
1670 def save(self, repo, msg=None):
1671 if not self.applied:
1671 if not self.applied:
1672 self.ui.warn(_("save: no patches applied, exiting\n"))
1672 self.ui.warn(_("save: no patches applied, exiting\n"))
1673 return 1
1673 return 1
1674 if self.issaveline(self.applied[-1]):
1674 if self.issaveline(self.applied[-1]):
1675 self.ui.warn(_("status is already saved\n"))
1675 self.ui.warn(_("status is already saved\n"))
1676 return 1
1676 return 1
1677
1677
1678 if not msg:
1678 if not msg:
1679 msg = _("hg patches saved state")
1679 msg = _("hg patches saved state")
1680 else:
1680 else:
1681 msg = "hg patches: " + msg.rstrip('\r\n')
1681 msg = "hg patches: " + msg.rstrip('\r\n')
1682 r = self.qrepo()
1682 r = self.qrepo()
1683 if r:
1683 if r:
1684 pp = r.dirstate.parents()
1684 pp = r.dirstate.parents()
1685 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1685 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1686 msg += "\n\nPatch Data:\n"
1686 msg += "\n\nPatch Data:\n"
1687 msg += ''.join('%s\n' % x for x in self.applied)
1687 msg += ''.join('%s\n' % x for x in self.applied)
1688 msg += ''.join(':%s\n' % x for x in self.full_series)
1688 msg += ''.join(':%s\n' % x for x in self.full_series)
1689 n = repo.commit(msg, force=True)
1689 n = repo.commit(msg, force=True)
1690 if not n:
1690 if not n:
1691 self.ui.warn(_("repo commit failed\n"))
1691 self.ui.warn(_("repo commit failed\n"))
1692 return 1
1692 return 1
1693 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1693 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1694 self.applied_dirty = 1
1694 self.applied_dirty = 1
1695 self.removeundo(repo)
1695 self.removeundo(repo)
1696
1696
1697 def full_series_end(self):
1697 def full_series_end(self):
1698 if self.applied:
1698 if self.applied:
1699 p = self.applied[-1].name
1699 p = self.applied[-1].name
1700 end = self.find_series(p)
1700 end = self.find_series(p)
1701 if end is None:
1701 if end is None:
1702 return len(self.full_series)
1702 return len(self.full_series)
1703 return end + 1
1703 return end + 1
1704 return 0
1704 return 0
1705
1705
1706 def series_end(self, all_patches=False):
1706 def series_end(self, all_patches=False):
1707 """If all_patches is False, return the index of the next pushable patch
1707 """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
1708 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.
1709 index of the first patch past the last applied one.
1710 """
1710 """
1711 end = 0
1711 end = 0
1712 def next(start):
1712 def next(start):
1713 if all_patches or start >= len(self.series):
1713 if all_patches or start >= len(self.series):
1714 return start
1714 return start
1715 for i in xrange(start, len(self.series)):
1715 for i in xrange(start, len(self.series)):
1716 p, reason = self.pushable(i)
1716 p, reason = self.pushable(i)
1717 if p:
1717 if p:
1718 break
1718 break
1719 self.explain_pushable(i)
1719 self.explain_pushable(i)
1720 return i
1720 return i
1721 if self.applied:
1721 if self.applied:
1722 p = self.applied[-1].name
1722 p = self.applied[-1].name
1723 try:
1723 try:
1724 end = self.series.index(p)
1724 end = self.series.index(p)
1725 except ValueError:
1725 except ValueError:
1726 return 0
1726 return 0
1727 return next(end + 1)
1727 return next(end + 1)
1728 return next(end)
1728 return next(end)
1729
1729
1730 def appliedname(self, index):
1730 def appliedname(self, index):
1731 pname = self.applied[index].name
1731 pname = self.applied[index].name
1732 if not self.ui.verbose:
1732 if not self.ui.verbose:
1733 p = pname
1733 p = pname
1734 else:
1734 else:
1735 p = str(self.series.index(pname)) + " " + pname
1735 p = str(self.series.index(pname)) + " " + pname
1736 return p
1736 return p
1737
1737
1738 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1738 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1739 force=None, git=False):
1739 force=None, git=False):
1740 def checkseries(patchname):
1740 def checkseries(patchname):
1741 if patchname in self.series:
1741 if patchname in self.series:
1742 raise util.Abort(_('patch %s is already in the series file')
1742 raise util.Abort(_('patch %s is already in the series file')
1743 % patchname)
1743 % patchname)
1744
1744
1745 if rev:
1745 if rev:
1746 if files:
1746 if files:
1747 raise util.Abort(_('option "-r" not valid when importing '
1747 raise util.Abort(_('option "-r" not valid when importing '
1748 'files'))
1748 'files'))
1749 rev = scmutil.revrange(repo, rev)
1749 rev = scmutil.revrange(repo, rev)
1750 rev.sort(reverse=True)
1750 rev.sort(reverse=True)
1751 if (len(files) > 1 or len(rev) > 1) and patchname:
1751 if (len(files) > 1 or len(rev) > 1) and patchname:
1752 raise util.Abort(_('option "-n" not valid when importing multiple '
1752 raise util.Abort(_('option "-n" not valid when importing multiple '
1753 'patches'))
1753 'patches'))
1754 if rev:
1754 if rev:
1755 # If mq patches are applied, we can only import revisions
1755 # If mq patches are applied, we can only import revisions
1756 # that form a linear path to qbase.
1756 # that form a linear path to qbase.
1757 # Otherwise, they should form a linear path to a head.
1757 # Otherwise, they should form a linear path to a head.
1758 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1758 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1759 if len(heads) > 1:
1759 if len(heads) > 1:
1760 raise util.Abort(_('revision %d is the root of more than one '
1760 raise util.Abort(_('revision %d is the root of more than one '
1761 'branch') % rev[-1])
1761 'branch') % rev[-1])
1762 if self.applied:
1762 if self.applied:
1763 base = repo.changelog.node(rev[0])
1763 base = repo.changelog.node(rev[0])
1764 if base in [n.node for n in self.applied]:
1764 if base in [n.node for n in self.applied]:
1765 raise util.Abort(_('revision %d is already managed')
1765 raise util.Abort(_('revision %d is already managed')
1766 % rev[0])
1766 % rev[0])
1767 if heads != [self.applied[-1].node]:
1767 if heads != [self.applied[-1].node]:
1768 raise util.Abort(_('revision %d is not the parent of '
1768 raise util.Abort(_('revision %d is not the parent of '
1769 'the queue') % rev[0])
1769 'the queue') % rev[0])
1770 base = repo.changelog.rev(self.applied[0].node)
1770 base = repo.changelog.rev(self.applied[0].node)
1771 lastparent = repo.changelog.parentrevs(base)[0]
1771 lastparent = repo.changelog.parentrevs(base)[0]
1772 else:
1772 else:
1773 if heads != [repo.changelog.node(rev[0])]:
1773 if heads != [repo.changelog.node(rev[0])]:
1774 raise util.Abort(_('revision %d has unmanaged children')
1774 raise util.Abort(_('revision %d has unmanaged children')
1775 % rev[0])
1775 % rev[0])
1776 lastparent = None
1776 lastparent = None
1777
1777
1778 diffopts = self.diffopts({'git': git})
1778 diffopts = self.diffopts({'git': git})
1779 for r in rev:
1779 for r in rev:
1780 p1, p2 = repo.changelog.parentrevs(r)
1780 p1, p2 = repo.changelog.parentrevs(r)
1781 n = repo.changelog.node(r)
1781 n = repo.changelog.node(r)
1782 if p2 != nullrev:
1782 if p2 != nullrev:
1783 raise util.Abort(_('cannot import merge revision %d') % r)
1783 raise util.Abort(_('cannot import merge revision %d') % r)
1784 if lastparent and lastparent != r:
1784 if lastparent and lastparent != r:
1785 raise util.Abort(_('revision %d is not the parent of %d')
1785 raise util.Abort(_('revision %d is not the parent of %d')
1786 % (r, lastparent))
1786 % (r, lastparent))
1787 lastparent = p1
1787 lastparent = p1
1788
1788
1789 if not patchname:
1789 if not patchname:
1790 patchname = normname('%d.diff' % r)
1790 patchname = normname('%d.diff' % r)
1791 checkseries(patchname)
1791 checkseries(patchname)
1792 self.checkpatchname(patchname, force)
1792 self.checkpatchname(patchname, force)
1793 self.full_series.insert(0, patchname)
1793 self.full_series.insert(0, patchname)
1794
1794
1795 patchf = self.opener(patchname, "w")
1795 patchf = self.opener(patchname, "w")
1796 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1796 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1797 patchf.close()
1797 patchf.close()
1798
1798
1799 se = statusentry(n, patchname)
1799 se = statusentry(n, patchname)
1800 self.applied.insert(0, se)
1800 self.applied.insert(0, se)
1801
1801
1802 self.added.append(patchname)
1802 self.added.append(patchname)
1803 patchname = None
1803 patchname = None
1804 self.parse_series()
1804 self.parse_series()
1805 self.applied_dirty = 1
1805 self.applied_dirty = 1
1806 self.series_dirty = True
1806 self.series_dirty = True
1807
1807
1808 for i, filename in enumerate(files):
1808 for i, filename in enumerate(files):
1809 if existing:
1809 if existing:
1810 if filename == '-':
1810 if filename == '-':
1811 raise util.Abort(_('-e is incompatible with import from -'))
1811 raise util.Abort(_('-e is incompatible with import from -'))
1812 filename = normname(filename)
1812 filename = normname(filename)
1813 self.check_reserved_name(filename)
1813 self.check_reserved_name(filename)
1814 originpath = self.join(filename)
1814 originpath = self.join(filename)
1815 if not os.path.isfile(originpath):
1815 if not os.path.isfile(originpath):
1816 raise util.Abort(_("patch %s does not exist") % filename)
1816 raise util.Abort(_("patch %s does not exist") % filename)
1817
1817
1818 if patchname:
1818 if patchname:
1819 self.checkpatchname(patchname, force)
1819 self.checkpatchname(patchname, force)
1820
1820
1821 self.ui.write(_('renaming %s to %s\n')
1821 self.ui.write(_('renaming %s to %s\n')
1822 % (filename, patchname))
1822 % (filename, patchname))
1823 util.rename(originpath, self.join(patchname))
1823 util.rename(originpath, self.join(patchname))
1824 else:
1824 else:
1825 patchname = filename
1825 patchname = filename
1826
1826
1827 else:
1827 else:
1828 if filename == '-' and not patchname:
1828 if filename == '-' and not patchname:
1829 raise util.Abort(_('need --name to import a patch from -'))
1829 raise util.Abort(_('need --name to import a patch from -'))
1830 elif not patchname:
1830 elif not patchname:
1831 patchname = normname(os.path.basename(filename.rstrip('/')))
1831 patchname = normname(os.path.basename(filename.rstrip('/')))
1832 self.checkpatchname(patchname, force)
1832 self.checkpatchname(patchname, force)
1833 try:
1833 try:
1834 if filename == '-':
1834 if filename == '-':
1835 text = sys.stdin.read()
1835 text = sys.stdin.read()
1836 else:
1836 else:
1837 fp = url.open(self.ui, filename)
1837 fp = url.open(self.ui, filename)
1838 text = fp.read()
1838 text = fp.read()
1839 fp.close()
1839 fp.close()
1840 except (OSError, IOError):
1840 except (OSError, IOError):
1841 raise util.Abort(_("unable to read file %s") % filename)
1841 raise util.Abort(_("unable to read file %s") % filename)
1842 patchf = self.opener(patchname, "w")
1842 patchf = self.opener(patchname, "w")
1843 patchf.write(text)
1843 patchf.write(text)
1844 patchf.close()
1844 patchf.close()
1845 if not force:
1845 if not force:
1846 checkseries(patchname)
1846 checkseries(patchname)
1847 if patchname not in self.series:
1847 if patchname not in self.series:
1848 index = self.full_series_end() + i
1848 index = self.full_series_end() + i
1849 self.full_series[index:index] = [patchname]
1849 self.full_series[index:index] = [patchname]
1850 self.parse_series()
1850 self.parse_series()
1851 self.series_dirty = True
1851 self.series_dirty = True
1852 self.ui.warn(_("adding %s to series file\n") % patchname)
1852 self.ui.warn(_("adding %s to series file\n") % patchname)
1853 self.added.append(patchname)
1853 self.added.append(patchname)
1854 patchname = None
1854 patchname = None
1855
1855
1856 self.removeundo(repo)
1856 self.removeundo(repo)
1857
1857
1858 @command("qdelete|qremove|qrm",
1858 @command("qdelete|qremove|qrm",
1859 [('k', 'keep', None, _('keep patch file')),
1859 [('k', 'keep', None, _('keep patch file')),
1860 ('r', 'rev', [],
1860 ('r', 'rev', [],
1861 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1861 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1862 _('hg qdelete [-k] [PATCH]...'))
1862 _('hg qdelete [-k] [PATCH]...'))
1863 def delete(ui, repo, *patches, **opts):
1863 def delete(ui, repo, *patches, **opts):
1864 """remove patches from queue
1864 """remove patches from queue
1865
1865
1866 The patches must not be applied, and at least one patch is required. With
1866 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.
1867 -k/--keep, the patch files are preserved in the patch directory.
1868
1868
1869 To stop managing a patch and move it into permanent history,
1869 To stop managing a patch and move it into permanent history,
1870 use the :hg:`qfinish` command."""
1870 use the :hg:`qfinish` command."""
1871 q = repo.mq
1871 q = repo.mq
1872 q.delete(repo, patches, opts)
1872 q.delete(repo, patches, opts)
1873 q.save_dirty()
1873 q.save_dirty()
1874 return 0
1874 return 0
1875
1875
1876 @command("qapplied",
1876 @command("qapplied",
1877 [('1', 'last', None, _('show only the last patch'))
1877 [('1', 'last', None, _('show only the last patch'))
1878 ] + seriesopts,
1878 ] + seriesopts,
1879 _('hg qapplied [-1] [-s] [PATCH]'))
1879 _('hg qapplied [-1] [-s] [PATCH]'))
1880 def applied(ui, repo, patch=None, **opts):
1880 def applied(ui, repo, patch=None, **opts):
1881 """print the patches already applied
1881 """print the patches already applied
1882
1882
1883 Returns 0 on success."""
1883 Returns 0 on success."""
1884
1884
1885 q = repo.mq
1885 q = repo.mq
1886
1886
1887 if patch:
1887 if patch:
1888 if patch not in q.series:
1888 if patch not in q.series:
1889 raise util.Abort(_("patch %s is not in series file") % patch)
1889 raise util.Abort(_("patch %s is not in series file") % patch)
1890 end = q.series.index(patch) + 1
1890 end = q.series.index(patch) + 1
1891 else:
1891 else:
1892 end = q.series_end(True)
1892 end = q.series_end(True)
1893
1893
1894 if opts.get('last') and not end:
1894 if opts.get('last') and not end:
1895 ui.write(_("no patches applied\n"))
1895 ui.write(_("no patches applied\n"))
1896 return 1
1896 return 1
1897 elif opts.get('last') and end == 1:
1897 elif opts.get('last') and end == 1:
1898 ui.write(_("only one patch applied\n"))
1898 ui.write(_("only one patch applied\n"))
1899 return 1
1899 return 1
1900 elif opts.get('last'):
1900 elif opts.get('last'):
1901 start = end - 2
1901 start = end - 2
1902 end = 1
1902 end = 1
1903 else:
1903 else:
1904 start = 0
1904 start = 0
1905
1905
1906 q.qseries(repo, length=end, start=start, status='A',
1906 q.qseries(repo, length=end, start=start, status='A',
1907 summary=opts.get('summary'))
1907 summary=opts.get('summary'))
1908
1908
1909
1909
1910 @command("qunapplied",
1910 @command("qunapplied",
1911 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1911 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1912 _('hg qunapplied [-1] [-s] [PATCH]'))
1912 _('hg qunapplied [-1] [-s] [PATCH]'))
1913 def unapplied(ui, repo, patch=None, **opts):
1913 def unapplied(ui, repo, patch=None, **opts):
1914 """print the patches not yet applied
1914 """print the patches not yet applied
1915
1915
1916 Returns 0 on success."""
1916 Returns 0 on success."""
1917
1917
1918 q = repo.mq
1918 q = repo.mq
1919 if patch:
1919 if patch:
1920 if patch not in q.series:
1920 if patch not in q.series:
1921 raise util.Abort(_("patch %s is not in series file") % patch)
1921 raise util.Abort(_("patch %s is not in series file") % patch)
1922 start = q.series.index(patch) + 1
1922 start = q.series.index(patch) + 1
1923 else:
1923 else:
1924 start = q.series_end(True)
1924 start = q.series_end(True)
1925
1925
1926 if start == len(q.series) and opts.get('first'):
1926 if start == len(q.series) and opts.get('first'):
1927 ui.write(_("all patches applied\n"))
1927 ui.write(_("all patches applied\n"))
1928 return 1
1928 return 1
1929
1929
1930 length = opts.get('first') and 1 or None
1930 length = opts.get('first') and 1 or None
1931 q.qseries(repo, start=start, length=length, status='U',
1931 q.qseries(repo, start=start, length=length, status='U',
1932 summary=opts.get('summary'))
1932 summary=opts.get('summary'))
1933
1933
1934 @command("qimport",
1934 @command("qimport",
1935 [('e', 'existing', None, _('import file in patch directory')),
1935 [('e', 'existing', None, _('import file in patch directory')),
1936 ('n', 'name', '',
1936 ('n', 'name', '',
1937 _('name of patch file'), _('NAME')),
1937 _('name of patch file'), _('NAME')),
1938 ('f', 'force', None, _('overwrite existing files')),
1938 ('f', 'force', None, _('overwrite existing files')),
1939 ('r', 'rev', [],
1939 ('r', 'rev', [],
1940 _('place existing revisions under mq control'), _('REV')),
1940 _('place existing revisions under mq control'), _('REV')),
1941 ('g', 'git', None, _('use git extended diff format')),
1941 ('g', 'git', None, _('use git extended diff format')),
1942 ('P', 'push', None, _('qpush after importing'))],
1942 ('P', 'push', None, _('qpush after importing'))],
1943 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1943 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1944 def qimport(ui, repo, *filename, **opts):
1944 def qimport(ui, repo, *filename, **opts):
1945 """import a patch
1945 """import a patch
1946
1946
1947 The patch is inserted into the series after the last applied
1947 The patch is inserted into the series after the last applied
1948 patch. If no patches have been applied, qimport prepends the patch
1948 patch. If no patches have been applied, qimport prepends the patch
1949 to the series.
1949 to the series.
1950
1950
1951 The patch will have the same name as its source file unless you
1951 The patch will have the same name as its source file unless you
1952 give it a new one with -n/--name.
1952 give it a new one with -n/--name.
1953
1953
1954 You can register an existing patch inside the patch directory with
1954 You can register an existing patch inside the patch directory with
1955 the -e/--existing flag.
1955 the -e/--existing flag.
1956
1956
1957 With -f/--force, an existing patch of the same name will be
1957 With -f/--force, an existing patch of the same name will be
1958 overwritten.
1958 overwritten.
1959
1959
1960 An existing changeset may be placed under mq control with -r/--rev
1960 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).
1961 (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
1962 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
1963 format. See the diffs help topic for information on why this is
1964 important for preserving rename/copy information and permission
1964 important for preserving rename/copy information and permission
1965 changes. Use :hg:`qfinish` to remove changesets from mq control.
1965 changes. Use :hg:`qfinish` to remove changesets from mq control.
1966
1966
1967 To import a patch from standard input, pass - as the patch file.
1967 To import a patch from standard input, pass - as the patch file.
1968 When importing from standard input, a patch name must be specified
1968 When importing from standard input, a patch name must be specified
1969 using the --name flag.
1969 using the --name flag.
1970
1970
1971 To import an existing patch while renaming it::
1971 To import an existing patch while renaming it::
1972
1972
1973 hg qimport -e existing-patch -n new-name
1973 hg qimport -e existing-patch -n new-name
1974
1974
1975 Returns 0 if import succeeded.
1975 Returns 0 if import succeeded.
1976 """
1976 """
1977 q = repo.mq
1977 q = repo.mq
1978 try:
1978 try:
1979 q.qimport(repo, filename, patchname=opts.get('name'),
1979 q.qimport(repo, filename, patchname=opts.get('name'),
1980 existing=opts.get('existing'), force=opts.get('force'),
1980 existing=opts.get('existing'), force=opts.get('force'),
1981 rev=opts.get('rev'), git=opts.get('git'))
1981 rev=opts.get('rev'), git=opts.get('git'))
1982 finally:
1982 finally:
1983 q.save_dirty()
1983 q.save_dirty()
1984
1984
1985 if opts.get('push') and not opts.get('rev'):
1985 if opts.get('push') and not opts.get('rev'):
1986 return q.push(repo, None)
1986 return q.push(repo, None)
1987 return 0
1987 return 0
1988
1988
1989 def qinit(ui, repo, create):
1989 def qinit(ui, repo, create):
1990 """initialize a new queue repository
1990 """initialize a new queue repository
1991
1991
1992 This command also creates a series file for ordering patches, and
1992 This command also creates a series file for ordering patches, and
1993 an mq-specific .hgignore file in the queue repository, to exclude
1993 an mq-specific .hgignore file in the queue repository, to exclude
1994 the status and guards files (these contain mostly transient state).
1994 the status and guards files (these contain mostly transient state).
1995
1995
1996 Returns 0 if initialization succeeded."""
1996 Returns 0 if initialization succeeded."""
1997 q = repo.mq
1997 q = repo.mq
1998 r = q.init(repo, create)
1998 r = q.init(repo, create)
1999 q.save_dirty()
1999 q.save_dirty()
2000 if r:
2000 if r:
2001 if not os.path.exists(r.wjoin('.hgignore')):
2001 if not os.path.exists(r.wjoin('.hgignore')):
2002 fp = r.wopener('.hgignore', 'w')
2002 fp = r.wopener('.hgignore', 'w')
2003 fp.write('^\\.hg\n')
2003 fp.write('^\\.hg\n')
2004 fp.write('^\\.mq\n')
2004 fp.write('^\\.mq\n')
2005 fp.write('syntax: glob\n')
2005 fp.write('syntax: glob\n')
2006 fp.write('status\n')
2006 fp.write('status\n')
2007 fp.write('guards\n')
2007 fp.write('guards\n')
2008 fp.close()
2008 fp.close()
2009 if not os.path.exists(r.wjoin('series')):
2009 if not os.path.exists(r.wjoin('series')):
2010 r.wopener('series', 'w').close()
2010 r.wopener('series', 'w').close()
2011 r[None].add(['.hgignore', 'series'])
2011 r[None].add(['.hgignore', 'series'])
2012 commands.add(ui, r)
2012 commands.add(ui, r)
2013 return 0
2013 return 0
2014
2014
2015 @command("^qinit",
2015 @command("^qinit",
2016 [('c', 'create-repo', None, _('create queue repository'))],
2016 [('c', 'create-repo', None, _('create queue repository'))],
2017 _('hg qinit [-c]'))
2017 _('hg qinit [-c]'))
2018 def init(ui, repo, **opts):
2018 def init(ui, repo, **opts):
2019 """init a new queue repository (DEPRECATED)
2019 """init a new queue repository (DEPRECATED)
2020
2020
2021 The queue repository is unversioned by default. If
2021 The queue repository is unversioned by default. If
2022 -c/--create-repo is specified, qinit will create a separate nested
2022 -c/--create-repo is specified, qinit will create a separate nested
2023 repository for patches (qinit -c may also be run later to convert
2023 repository for patches (qinit -c may also be run later to convert
2024 an unversioned patch repository into a versioned one). You can use
2024 an unversioned patch repository into a versioned one). You can use
2025 qcommit to commit changes to this queue repository.
2025 qcommit to commit changes to this queue repository.
2026
2026
2027 This command is deprecated. Without -c, it's implied by other relevant
2027 This command is deprecated. Without -c, it's implied by other relevant
2028 commands. With -c, use :hg:`init --mq` instead."""
2028 commands. With -c, use :hg:`init --mq` instead."""
2029 return qinit(ui, repo, create=opts.get('create_repo'))
2029 return qinit(ui, repo, create=opts.get('create_repo'))
2030
2030
2031 @command("qclone",
2031 @command("qclone",
2032 [('', 'pull', None, _('use pull protocol to copy metadata')),
2032 [('', 'pull', None, _('use pull protocol to copy metadata')),
2033 ('U', 'noupdate', None, _('do not update the new working directories')),
2033 ('U', 'noupdate', None, _('do not update the new working directories')),
2034 ('', 'uncompressed', None,
2034 ('', 'uncompressed', None,
2035 _('use uncompressed transfer (fast over LAN)')),
2035 _('use uncompressed transfer (fast over LAN)')),
2036 ('p', 'patches', '',
2036 ('p', 'patches', '',
2037 _('location of source patch repository'), _('REPO')),
2037 _('location of source patch repository'), _('REPO')),
2038 ] + commands.remoteopts,
2038 ] + commands.remoteopts,
2039 _('hg qclone [OPTION]... SOURCE [DEST]'))
2039 _('hg qclone [OPTION]... SOURCE [DEST]'))
2040 def clone(ui, source, dest=None, **opts):
2040 def clone(ui, source, dest=None, **opts):
2041 '''clone main and patch repository at same time
2041 '''clone main and patch repository at same time
2042
2042
2043 If source is local, destination will have no patches applied. If
2043 If source is local, destination will have no patches applied. If
2044 source is remote, this command can not check if patches are
2044 source is remote, this command can not check if patches are
2045 applied in source, so cannot guarantee that patches are not
2045 applied in source, so cannot guarantee that patches are not
2046 applied in destination. If you clone remote repository, be sure
2046 applied in destination. If you clone remote repository, be sure
2047 before that it has no patches applied.
2047 before that it has no patches applied.
2048
2048
2049 Source patch repository is looked for in <src>/.hg/patches by
2049 Source patch repository is looked for in <src>/.hg/patches by
2050 default. Use -p <url> to change.
2050 default. Use -p <url> to change.
2051
2051
2052 The patch directory must be a nested Mercurial repository, as
2052 The patch directory must be a nested Mercurial repository, as
2053 would be created by :hg:`init --mq`.
2053 would be created by :hg:`init --mq`.
2054
2054
2055 Return 0 on success.
2055 Return 0 on success.
2056 '''
2056 '''
2057 def patchdir(repo):
2057 def patchdir(repo):
2058 url = repo.url()
2058 url = repo.url()
2059 if url.endswith('/'):
2059 if url.endswith('/'):
2060 url = url[:-1]
2060 url = url[:-1]
2061 return url + '/.hg/patches'
2061 return url + '/.hg/patches'
2062 if dest is None:
2062 if dest is None:
2063 dest = hg.defaultdest(source)
2063 dest = hg.defaultdest(source)
2064 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2064 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2065 if opts.get('patches'):
2065 if opts.get('patches'):
2066 patchespath = ui.expandpath(opts.get('patches'))
2066 patchespath = ui.expandpath(opts.get('patches'))
2067 else:
2067 else:
2068 patchespath = patchdir(sr)
2068 patchespath = patchdir(sr)
2069 try:
2069 try:
2070 hg.repository(ui, patchespath)
2070 hg.repository(ui, patchespath)
2071 except error.RepoError:
2071 except error.RepoError:
2072 raise util.Abort(_('versioned patch repository not found'
2072 raise util.Abort(_('versioned patch repository not found'
2073 ' (see init --mq)'))
2073 ' (see init --mq)'))
2074 qbase, destrev = None, None
2074 qbase, destrev = None, None
2075 if sr.local():
2075 if sr.local():
2076 if sr.mq.applied:
2076 if sr.mq.applied:
2077 qbase = sr.mq.applied[0].node
2077 qbase = sr.mq.applied[0].node
2078 if not hg.islocal(dest):
2078 if not hg.islocal(dest):
2079 heads = set(sr.heads())
2079 heads = set(sr.heads())
2080 destrev = list(heads.difference(sr.heads(qbase)))
2080 destrev = list(heads.difference(sr.heads(qbase)))
2081 destrev.append(sr.changelog.parents(qbase)[0])
2081 destrev.append(sr.changelog.parents(qbase)[0])
2082 elif sr.capable('lookup'):
2082 elif sr.capable('lookup'):
2083 try:
2083 try:
2084 qbase = sr.lookup('qbase')
2084 qbase = sr.lookup('qbase')
2085 except error.RepoError:
2085 except error.RepoError:
2086 pass
2086 pass
2087 ui.note(_('cloning main repository\n'))
2087 ui.note(_('cloning main repository\n'))
2088 sr, dr = hg.clone(ui, sr.url(), dest,
2088 sr, dr = hg.clone(ui, sr.url(), dest,
2089 pull=opts.get('pull'),
2089 pull=opts.get('pull'),
2090 rev=destrev,
2090 rev=destrev,
2091 update=False,
2091 update=False,
2092 stream=opts.get('uncompressed'))
2092 stream=opts.get('uncompressed'))
2093 ui.note(_('cloning patch repository\n'))
2093 ui.note(_('cloning patch repository\n'))
2094 hg.clone(ui, opts.get('patches') or patchdir(sr), patchdir(dr),
2094 hg.clone(ui, opts.get('patches') or patchdir(sr), patchdir(dr),
2095 pull=opts.get('pull'), update=not opts.get('noupdate'),
2095 pull=opts.get('pull'), update=not opts.get('noupdate'),
2096 stream=opts.get('uncompressed'))
2096 stream=opts.get('uncompressed'))
2097 if dr.local():
2097 if dr.local():
2098 if qbase:
2098 if qbase:
2099 ui.note(_('stripping applied patches from destination '
2099 ui.note(_('stripping applied patches from destination '
2100 'repository\n'))
2100 'repository\n'))
2101 dr.mq.strip(dr, [qbase], update=False, backup=None)
2101 dr.mq.strip(dr, [qbase], update=False, backup=None)
2102 if not opts.get('noupdate'):
2102 if not opts.get('noupdate'):
2103 ui.note(_('updating destination repository\n'))
2103 ui.note(_('updating destination repository\n'))
2104 hg.update(dr, dr.changelog.tip())
2104 hg.update(dr, dr.changelog.tip())
2105
2105
2106 @command("qcommit|qci",
2106 @command("qcommit|qci",
2107 commands.table["^commit|ci"][1],
2107 commands.table["^commit|ci"][1],
2108 _('hg qcommit [OPTION]... [FILE]...'))
2108 _('hg qcommit [OPTION]... [FILE]...'))
2109 def commit(ui, repo, *pats, **opts):
2109 def commit(ui, repo, *pats, **opts):
2110 """commit changes in the queue repository (DEPRECATED)
2110 """commit changes in the queue repository (DEPRECATED)
2111
2111
2112 This command is deprecated; use :hg:`commit --mq` instead."""
2112 This command is deprecated; use :hg:`commit --mq` instead."""
2113 q = repo.mq
2113 q = repo.mq
2114 r = q.qrepo()
2114 r = q.qrepo()
2115 if not r:
2115 if not r:
2116 raise util.Abort('no queue repository')
2116 raise util.Abort('no queue repository')
2117 commands.commit(r.ui, r, *pats, **opts)
2117 commands.commit(r.ui, r, *pats, **opts)
2118
2118
2119 @command("qseries",
2119 @command("qseries",
2120 [('m', 'missing', None, _('print patches not in series')),
2120 [('m', 'missing', None, _('print patches not in series')),
2121 ] + seriesopts,
2121 ] + seriesopts,
2122 _('hg qseries [-ms]'))
2122 _('hg qseries [-ms]'))
2123 def series(ui, repo, **opts):
2123 def series(ui, repo, **opts):
2124 """print the entire series file
2124 """print the entire series file
2125
2125
2126 Returns 0 on success."""
2126 Returns 0 on success."""
2127 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2127 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2128 return 0
2128 return 0
2129
2129
2130 @command("qtop", [] + seriesopts, _('hg qtop [-s]'))
2130 @command("qtop", [] + seriesopts, _('hg qtop [-s]'))
2131 def top(ui, repo, **opts):
2131 def top(ui, repo, **opts):
2132 """print the name of the current patch
2132 """print the name of the current patch
2133
2133
2134 Returns 0 on success."""
2134 Returns 0 on success."""
2135 q = repo.mq
2135 q = repo.mq
2136 t = q.applied and q.series_end(True) or 0
2136 t = q.applied and q.series_end(True) or 0
2137 if t:
2137 if t:
2138 q.qseries(repo, start=t - 1, length=1, status='A',
2138 q.qseries(repo, start=t - 1, length=1, status='A',
2139 summary=opts.get('summary'))
2139 summary=opts.get('summary'))
2140 else:
2140 else:
2141 ui.write(_("no patches applied\n"))
2141 ui.write(_("no patches applied\n"))
2142 return 1
2142 return 1
2143
2143
2144 @command("qnext", [] + seriesopts, _('hg qnext [-s]'))
2144 @command("qnext", [] + seriesopts, _('hg qnext [-s]'))
2145 def next(ui, repo, **opts):
2145 def next(ui, repo, **opts):
2146 """print the name of the next patch
2146 """print the name of the next patch
2147
2147
2148 Returns 0 on success."""
2148 Returns 0 on success."""
2149 q = repo.mq
2149 q = repo.mq
2150 end = q.series_end()
2150 end = q.series_end()
2151 if end == len(q.series):
2151 if end == len(q.series):
2152 ui.write(_("all patches applied\n"))
2152 ui.write(_("all patches applied\n"))
2153 return 1
2153 return 1
2154 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2154 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2155
2155
2156 @command("qprev", [] + seriesopts, _('hg qprev [-s]'))
2156 @command("qprev", [] + seriesopts, _('hg qprev [-s]'))
2157 def prev(ui, repo, **opts):
2157 def prev(ui, repo, **opts):
2158 """print the name of the previous patch
2158 """print the name of the previous patch
2159
2159
2160 Returns 0 on success."""
2160 Returns 0 on success."""
2161 q = repo.mq
2161 q = repo.mq
2162 l = len(q.applied)
2162 l = len(q.applied)
2163 if l == 1:
2163 if l == 1:
2164 ui.write(_("only one patch applied\n"))
2164 ui.write(_("only one patch applied\n"))
2165 return 1
2165 return 1
2166 if not l:
2166 if not l:
2167 ui.write(_("no patches applied\n"))
2167 ui.write(_("no patches applied\n"))
2168 return 1
2168 return 1
2169 q.qseries(repo, start=l - 2, length=1, status='A',
2169 q.qseries(repo, start=l - 2, length=1, status='A',
2170 summary=opts.get('summary'))
2170 summary=opts.get('summary'))
2171
2171
2172 def setupheaderopts(ui, opts):
2172 def setupheaderopts(ui, opts):
2173 if not opts.get('user') and opts.get('currentuser'):
2173 if not opts.get('user') and opts.get('currentuser'):
2174 opts['user'] = ui.username()
2174 opts['user'] = ui.username()
2175 if not opts.get('date') and opts.get('currentdate'):
2175 if not opts.get('date') and opts.get('currentdate'):
2176 opts['date'] = "%d %d" % util.makedate()
2176 opts['date'] = "%d %d" % util.makedate()
2177
2177
2178 @command("^qnew",
2178 @command("^qnew",
2179 [('e', 'edit', None, _('edit commit message')),
2179 [('e', 'edit', None, _('edit commit message')),
2180 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2180 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2181 ('g', 'git', None, _('use git extended diff format')),
2181 ('g', 'git', None, _('use git extended diff format')),
2182 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2182 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2183 ('u', 'user', '',
2183 ('u', 'user', '',
2184 _('add "From: <USER>" to patch'), _('USER')),
2184 _('add "From: <USER>" to patch'), _('USER')),
2185 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2185 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2186 ('d', 'date', '',
2186 ('d', 'date', '',
2187 _('add "Date: <DATE>" to patch'), _('DATE'))
2187 _('add "Date: <DATE>" to patch'), _('DATE'))
2188 ] + commands.walkopts + commands.commitopts,
2188 ] + commands.walkopts + commands.commitopts,
2189 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2189 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2190 def new(ui, repo, patch, *args, **opts):
2190 def new(ui, repo, patch, *args, **opts):
2191 """create a new patch
2191 """create a new patch
2192
2192
2193 qnew creates a new patch on top of the currently-applied patch (if
2193 qnew creates a new patch on top of the currently-applied patch (if
2194 any). The patch will be initialized with any outstanding changes
2194 any). The patch will be initialized with any outstanding changes
2195 in the working directory. You may also use -I/--include,
2195 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
2196 -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
2197 only changes to matching files to the new patch, leaving the rest
2198 as uncommitted modifications.
2198 as uncommitted modifications.
2199
2199
2200 -u/--user and -d/--date can be used to set the (given) user and
2200 -u/--user and -d/--date can be used to set the (given) user and
2201 date, respectively. -U/--currentuser and -D/--currentdate set user
2201 date, respectively. -U/--currentuser and -D/--currentdate set user
2202 to current user and date to current date.
2202 to current user and date to current date.
2203
2203
2204 -e/--edit, -m/--message or -l/--logfile set the patch header as
2204 -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
2205 well as the commit message. If none is specified, the header is
2206 empty and the commit message is '[mq]: PATCH'.
2206 empty and the commit message is '[mq]: PATCH'.
2207
2207
2208 Use the -g/--git option to keep the patch in the git extended diff
2208 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
2209 format. Read the diffs help topic for more information on why this
2210 is important for preserving permission changes and copy/rename
2210 is important for preserving permission changes and copy/rename
2211 information.
2211 information.
2212
2212
2213 Returns 0 on successful creation of a new patch.
2213 Returns 0 on successful creation of a new patch.
2214 """
2214 """
2215 msg = cmdutil.logmessage(opts)
2215 msg = cmdutil.logmessage(opts)
2216 def getmsg():
2216 def getmsg():
2217 return ui.edit(msg, opts.get('user') or ui.username())
2217 return ui.edit(msg, opts.get('user') or ui.username())
2218 q = repo.mq
2218 q = repo.mq
2219 opts['msg'] = msg
2219 opts['msg'] = msg
2220 if opts.get('edit'):
2220 if opts.get('edit'):
2221 opts['msg'] = getmsg
2221 opts['msg'] = getmsg
2222 else:
2222 else:
2223 opts['msg'] = msg
2223 opts['msg'] = msg
2224 setupheaderopts(ui, opts)
2224 setupheaderopts(ui, opts)
2225 q.new(repo, patch, *args, **opts)
2225 q.new(repo, patch, *args, **opts)
2226 q.save_dirty()
2226 q.save_dirty()
2227 return 0
2227 return 0
2228
2228
2229 @command("^qrefresh",
2229 @command("^qrefresh",
2230 [('e', 'edit', None, _('edit commit message')),
2230 [('e', 'edit', None, _('edit commit message')),
2231 ('g', 'git', None, _('use git extended diff format')),
2231 ('g', 'git', None, _('use git extended diff format')),
2232 ('s', 'short', None,
2232 ('s', 'short', None,
2233 _('refresh only files already in the patch and specified files')),
2233 _('refresh only files already in the patch and specified files')),
2234 ('U', 'currentuser', None,
2234 ('U', 'currentuser', None,
2235 _('add/update author field in patch with current user')),
2235 _('add/update author field in patch with current user')),
2236 ('u', 'user', '',
2236 ('u', 'user', '',
2237 _('add/update author field in patch with given user'), _('USER')),
2237 _('add/update author field in patch with given user'), _('USER')),
2238 ('D', 'currentdate', None,
2238 ('D', 'currentdate', None,
2239 _('add/update date field in patch with current date')),
2239 _('add/update date field in patch with current date')),
2240 ('d', 'date', '',
2240 ('d', 'date', '',
2241 _('add/update date field in patch with given date'), _('DATE'))
2241 _('add/update date field in patch with given date'), _('DATE'))
2242 ] + commands.walkopts + commands.commitopts,
2242 ] + commands.walkopts + commands.commitopts,
2243 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2243 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2244 def refresh(ui, repo, *pats, **opts):
2244 def refresh(ui, repo, *pats, **opts):
2245 """update the current patch
2245 """update the current patch
2246
2246
2247 If any file patterns are provided, the refreshed patch will
2247 If any file patterns are provided, the refreshed patch will
2248 contain only the modifications that match those patterns; the
2248 contain only the modifications that match those patterns; the
2249 remaining modifications will remain in the working directory.
2249 remaining modifications will remain in the working directory.
2250
2250
2251 If -s/--short is specified, files currently included in the patch
2251 If -s/--short is specified, files currently included in the patch
2252 will be refreshed just like matched files and remain in the patch.
2252 will be refreshed just like matched files and remain in the patch.
2253
2253
2254 If -e/--edit is specified, Mercurial will start your configured editor for
2254 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
2255 you to enter a message. In case qrefresh fails, you will find a backup of
2256 your message in ``.hg/last-message.txt``.
2256 your message in ``.hg/last-message.txt``.
2257
2257
2258 hg add/remove/copy/rename work as usual, though you might want to
2258 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
2259 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
2260 and renames. See the diffs help topic for more information on the
2261 git diff format.
2261 git diff format.
2262
2262
2263 Returns 0 on success.
2263 Returns 0 on success.
2264 """
2264 """
2265 q = repo.mq
2265 q = repo.mq
2266 message = cmdutil.logmessage(opts)
2266 message = cmdutil.logmessage(opts)
2267 if opts.get('edit'):
2267 if opts.get('edit'):
2268 if not q.applied:
2268 if not q.applied:
2269 ui.write(_("no patches applied\n"))
2269 ui.write(_("no patches applied\n"))
2270 return 1
2270 return 1
2271 if message:
2271 if message:
2272 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2272 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2273 patch = q.applied[-1].name
2273 patch = q.applied[-1].name
2274 ph = patchheader(q.join(patch), q.plainmode)
2274 ph = patchheader(q.join(patch), q.plainmode)
2275 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2275 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)
2276 # We don't want to lose the patch message if qrefresh fails (issue2062)
2277 msgfile = repo.opener('last-message.txt', 'wb')
2277 msgfile = repo.opener('last-message.txt', 'wb')
2278 msgfile.write(message)
2278 msgfile.write(message)
2279 msgfile.close()
2279 msgfile.close()
2280 setupheaderopts(ui, opts)
2280 setupheaderopts(ui, opts)
2281 ret = q.refresh(repo, pats, msg=message, **opts)
2281 ret = q.refresh(repo, pats, msg=message, **opts)
2282 q.save_dirty()
2282 q.save_dirty()
2283 return ret
2283 return ret
2284
2284
2285 @command("^qdiff",
2285 @command("^qdiff",
2286 commands.diffopts + commands.diffopts2 + commands.walkopts,
2286 commands.diffopts + commands.diffopts2 + commands.walkopts,
2287 _('hg qdiff [OPTION]... [FILE]...'))
2287 _('hg qdiff [OPTION]... [FILE]...'))
2288 def diff(ui, repo, *pats, **opts):
2288 def diff(ui, repo, *pats, **opts):
2289 """diff of the current patch and subsequent modifications
2289 """diff of the current patch and subsequent modifications
2290
2290
2291 Shows a diff which includes the current patch as well as any
2291 Shows a diff which includes the current patch as well as any
2292 changes which have been made in the working directory since the
2292 changes which have been made in the working directory since the
2293 last refresh (thus showing what the current patch would become
2293 last refresh (thus showing what the current patch would become
2294 after a qrefresh).
2294 after a qrefresh).
2295
2295
2296 Use :hg:`diff` if you only want to see the changes made since the
2296 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
2297 last qrefresh, or :hg:`export qtip` if you want to see changes
2298 made by the current patch without including changes made since the
2298 made by the current patch without including changes made since the
2299 qrefresh.
2299 qrefresh.
2300
2300
2301 Returns 0 on success.
2301 Returns 0 on success.
2302 """
2302 """
2303 repo.mq.diff(repo, pats, opts)
2303 repo.mq.diff(repo, pats, opts)
2304 return 0
2304 return 0
2305
2305
2306 @command('qfold',
2306 @command('qfold',
2307 [('e', 'edit', None, _('edit patch header')),
2307 [('e', 'edit', None, _('edit patch header')),
2308 ('k', 'keep', None, _('keep folded patch files')),
2308 ('k', 'keep', None, _('keep folded patch files')),
2309 ] + commands.commitopts,
2309 ] + commands.commitopts,
2310 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2310 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2311 def fold(ui, repo, *files, **opts):
2311 def fold(ui, repo, *files, **opts):
2312 """fold the named patches into the current patch
2312 """fold the named patches into the current patch
2313
2313
2314 Patches must not yet be applied. Each patch will be successively
2314 Patches must not yet be applied. Each patch will be successively
2315 applied to the current patch in the order given. If all the
2315 applied to the current patch in the order given. If all the
2316 patches apply successfully, the current patch will be refreshed
2316 patches apply successfully, the current patch will be refreshed
2317 with the new cumulative patch, and the folded patches will be
2317 with the new cumulative patch, and the folded patches will be
2318 deleted. With -k/--keep, the folded patch files will not be
2318 deleted. With -k/--keep, the folded patch files will not be
2319 removed afterwards.
2319 removed afterwards.
2320
2320
2321 The header for each folded patch will be concatenated with the
2321 The header for each folded patch will be concatenated with the
2322 current patch header, separated by a line of ``* * *``.
2322 current patch header, separated by a line of ``* * *``.
2323
2323
2324 Returns 0 on success."""
2324 Returns 0 on success."""
2325
2325
2326 q = repo.mq
2326 q = repo.mq
2327
2327
2328 if not files:
2328 if not files:
2329 raise util.Abort(_('qfold requires at least one patch name'))
2329 raise util.Abort(_('qfold requires at least one patch name'))
2330 if not q.check_toppatch(repo)[0]:
2330 if not q.check_toppatch(repo)[0]:
2331 raise util.Abort(_('no patches applied'))
2331 raise util.Abort(_('no patches applied'))
2332 q.check_localchanges(repo)
2332 q.check_localchanges(repo)
2333
2333
2334 message = cmdutil.logmessage(opts)
2334 message = cmdutil.logmessage(opts)
2335 if opts.get('edit'):
2335 if opts.get('edit'):
2336 if message:
2336 if message:
2337 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2337 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2338
2338
2339 parent = q.lookup('qtip')
2339 parent = q.lookup('qtip')
2340 patches = []
2340 patches = []
2341 messages = []
2341 messages = []
2342 for f in files:
2342 for f in files:
2343 p = q.lookup(f)
2343 p = q.lookup(f)
2344 if p in patches or p == parent:
2344 if p in patches or p == parent:
2345 ui.warn(_('Skipping already folded patch %s\n') % p)
2345 ui.warn(_('Skipping already folded patch %s\n') % p)
2346 if q.isapplied(p):
2346 if q.isapplied(p):
2347 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2347 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2348 patches.append(p)
2348 patches.append(p)
2349
2349
2350 for p in patches:
2350 for p in patches:
2351 if not message:
2351 if not message:
2352 ph = patchheader(q.join(p), q.plainmode)
2352 ph = patchheader(q.join(p), q.plainmode)
2353 if ph.message:
2353 if ph.message:
2354 messages.append(ph.message)
2354 messages.append(ph.message)
2355 pf = q.join(p)
2355 pf = q.join(p)
2356 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2356 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2357 if not patchsuccess:
2357 if not patchsuccess:
2358 raise util.Abort(_('error folding patch %s') % p)
2358 raise util.Abort(_('error folding patch %s') % p)
2359
2359
2360 if not message:
2360 if not message:
2361 ph = patchheader(q.join(parent), q.plainmode)
2361 ph = patchheader(q.join(parent), q.plainmode)
2362 message, user = ph.message, ph.user
2362 message, user = ph.message, ph.user
2363 for msg in messages:
2363 for msg in messages:
2364 message.append('* * *')
2364 message.append('* * *')
2365 message.extend(msg)
2365 message.extend(msg)
2366 message = '\n'.join(message)
2366 message = '\n'.join(message)
2367
2367
2368 if opts.get('edit'):
2368 if opts.get('edit'):
2369 message = ui.edit(message, user or ui.username())
2369 message = ui.edit(message, user or ui.username())
2370
2370
2371 diffopts = q.patchopts(q.diffopts(), *patches)
2371 diffopts = q.patchopts(q.diffopts(), *patches)
2372 q.refresh(repo, msg=message, git=diffopts.git)
2372 q.refresh(repo, msg=message, git=diffopts.git)
2373 q.delete(repo, patches, opts)
2373 q.delete(repo, patches, opts)
2374 q.save_dirty()
2374 q.save_dirty()
2375
2375
2376 @command("qgoto",
2376 @command("qgoto",
2377 [('f', 'force', None, _('overwrite any local changes'))],
2377 [('f', 'force', None, _('overwrite any local changes'))],
2378 _('hg qgoto [OPTION]... PATCH'))
2378 _('hg qgoto [OPTION]... PATCH'))
2379 def goto(ui, repo, patch, **opts):
2379 def goto(ui, repo, patch, **opts):
2380 '''push or pop patches until named patch is at top of stack
2380 '''push or pop patches until named patch is at top of stack
2381
2381
2382 Returns 0 on success.'''
2382 Returns 0 on success.'''
2383 q = repo.mq
2383 q = repo.mq
2384 patch = q.lookup(patch)
2384 patch = q.lookup(patch)
2385 if q.isapplied(patch):
2385 if q.isapplied(patch):
2386 ret = q.pop(repo, patch, force=opts.get('force'))
2386 ret = q.pop(repo, patch, force=opts.get('force'))
2387 else:
2387 else:
2388 ret = q.push(repo, patch, force=opts.get('force'))
2388 ret = q.push(repo, patch, force=opts.get('force'))
2389 q.save_dirty()
2389 q.save_dirty()
2390 return ret
2390 return ret
2391
2391
2392 @command("qguard",
2392 @command("qguard",
2393 [('l', 'list', None, _('list all patches and guards')),
2393 [('l', 'list', None, _('list all patches and guards')),
2394 ('n', 'none', None, _('drop all guards'))],
2394 ('n', 'none', None, _('drop all guards'))],
2395 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2395 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2396 def guard(ui, repo, *args, **opts):
2396 def guard(ui, repo, *args, **opts):
2397 '''set or print guards for a patch
2397 '''set or print guards for a patch
2398
2398
2399 Guards control whether a patch can be pushed. A patch with no
2399 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
2400 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
2401 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
2402 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2403 has activated it.
2403 has activated it.
2404
2404
2405 With no arguments, print the currently active guards.
2405 With no arguments, print the currently active guards.
2406 With arguments, set guards for the named patch.
2406 With arguments, set guards for the named patch.
2407
2407
2408 .. note::
2408 .. note::
2409 Specifying negative guards now requires '--'.
2409 Specifying negative guards now requires '--'.
2410
2410
2411 To set guards on another patch::
2411 To set guards on another patch::
2412
2412
2413 hg qguard other.patch -- +2.6.17 -stable
2413 hg qguard other.patch -- +2.6.17 -stable
2414
2414
2415 Returns 0 on success.
2415 Returns 0 on success.
2416 '''
2416 '''
2417 def status(idx):
2417 def status(idx):
2418 guards = q.series_guards[idx] or ['unguarded']
2418 guards = q.series_guards[idx] or ['unguarded']
2419 if q.series[idx] in applied:
2419 if q.series[idx] in applied:
2420 state = 'applied'
2420 state = 'applied'
2421 elif q.pushable(idx)[0]:
2421 elif q.pushable(idx)[0]:
2422 state = 'unapplied'
2422 state = 'unapplied'
2423 else:
2423 else:
2424 state = 'guarded'
2424 state = 'guarded'
2425 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2425 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2426 ui.write('%s: ' % ui.label(q.series[idx], label))
2426 ui.write('%s: ' % ui.label(q.series[idx], label))
2427
2427
2428 for i, guard in enumerate(guards):
2428 for i, guard in enumerate(guards):
2429 if guard.startswith('+'):
2429 if guard.startswith('+'):
2430 ui.write(guard, label='qguard.positive')
2430 ui.write(guard, label='qguard.positive')
2431 elif guard.startswith('-'):
2431 elif guard.startswith('-'):
2432 ui.write(guard, label='qguard.negative')
2432 ui.write(guard, label='qguard.negative')
2433 else:
2433 else:
2434 ui.write(guard, label='qguard.unguarded')
2434 ui.write(guard, label='qguard.unguarded')
2435 if i != len(guards) - 1:
2435 if i != len(guards) - 1:
2436 ui.write(' ')
2436 ui.write(' ')
2437 ui.write('\n')
2437 ui.write('\n')
2438 q = repo.mq
2438 q = repo.mq
2439 applied = set(p.name for p in q.applied)
2439 applied = set(p.name for p in q.applied)
2440 patch = None
2440 patch = None
2441 args = list(args)
2441 args = list(args)
2442 if opts.get('list'):
2442 if opts.get('list'):
2443 if args or opts.get('none'):
2443 if args or opts.get('none'):
2444 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2444 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2445 for i in xrange(len(q.series)):
2445 for i in xrange(len(q.series)):
2446 status(i)
2446 status(i)
2447 return
2447 return
2448 if not args or args[0][0:1] in '-+':
2448 if not args or args[0][0:1] in '-+':
2449 if not q.applied:
2449 if not q.applied:
2450 raise util.Abort(_('no patches applied'))
2450 raise util.Abort(_('no patches applied'))
2451 patch = q.applied[-1].name
2451 patch = q.applied[-1].name
2452 if patch is None and args[0][0:1] not in '-+':
2452 if patch is None and args[0][0:1] not in '-+':
2453 patch = args.pop(0)
2453 patch = args.pop(0)
2454 if patch is None:
2454 if patch is None:
2455 raise util.Abort(_('no patch to work with'))
2455 raise util.Abort(_('no patch to work with'))
2456 if args or opts.get('none'):
2456 if args or opts.get('none'):
2457 idx = q.find_series(patch)
2457 idx = q.find_series(patch)
2458 if idx is None:
2458 if idx is None:
2459 raise util.Abort(_('no patch named %s') % patch)
2459 raise util.Abort(_('no patch named %s') % patch)
2460 q.set_guards(idx, args)
2460 q.set_guards(idx, args)
2461 q.save_dirty()
2461 q.save_dirty()
2462 else:
2462 else:
2463 status(q.series.index(q.lookup(patch)))
2463 status(q.series.index(q.lookup(patch)))
2464
2464
2465 @command("qheader", [], _('hg qheader [PATCH]'))
2465 @command("qheader", [], _('hg qheader [PATCH]'))
2466 def header(ui, repo, patch=None):
2466 def header(ui, repo, patch=None):
2467 """print the header of the topmost or specified patch
2467 """print the header of the topmost or specified patch
2468
2468
2469 Returns 0 on success."""
2469 Returns 0 on success."""
2470 q = repo.mq
2470 q = repo.mq
2471
2471
2472 if patch:
2472 if patch:
2473 patch = q.lookup(patch)
2473 patch = q.lookup(patch)
2474 else:
2474 else:
2475 if not q.applied:
2475 if not q.applied:
2476 ui.write(_('no patches applied\n'))
2476 ui.write(_('no patches applied\n'))
2477 return 1
2477 return 1
2478 patch = q.lookup('qtip')
2478 patch = q.lookup('qtip')
2479 ph = patchheader(q.join(patch), q.plainmode)
2479 ph = patchheader(q.join(patch), q.plainmode)
2480
2480
2481 ui.write('\n'.join(ph.message) + '\n')
2481 ui.write('\n'.join(ph.message) + '\n')
2482
2482
2483 def lastsavename(path):
2483 def lastsavename(path):
2484 (directory, base) = os.path.split(path)
2484 (directory, base) = os.path.split(path)
2485 names = os.listdir(directory)
2485 names = os.listdir(directory)
2486 namere = re.compile("%s.([0-9]+)" % base)
2486 namere = re.compile("%s.([0-9]+)" % base)
2487 maxindex = None
2487 maxindex = None
2488 maxname = None
2488 maxname = None
2489 for f in names:
2489 for f in names:
2490 m = namere.match(f)
2490 m = namere.match(f)
2491 if m:
2491 if m:
2492 index = int(m.group(1))
2492 index = int(m.group(1))
2493 if maxindex is None or index > maxindex:
2493 if maxindex is None or index > maxindex:
2494 maxindex = index
2494 maxindex = index
2495 maxname = f
2495 maxname = f
2496 if maxname:
2496 if maxname:
2497 return (os.path.join(directory, maxname), maxindex)
2497 return (os.path.join(directory, maxname), maxindex)
2498 return (None, None)
2498 return (None, None)
2499
2499
2500 def savename(path):
2500 def savename(path):
2501 (last, index) = lastsavename(path)
2501 (last, index) = lastsavename(path)
2502 if last is None:
2502 if last is None:
2503 index = 0
2503 index = 0
2504 newpath = path + ".%d" % (index + 1)
2504 newpath = path + ".%d" % (index + 1)
2505 return newpath
2505 return newpath
2506
2506
2507 @command("^qpush",
2507 @command("^qpush",
2508 [('f', 'force', None, _('apply on top of local changes')),
2508 [('f', 'force', None, _('apply on top of local changes')),
2509 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2509 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2510 ('l', 'list', None, _('list patch name in commit text')),
2510 ('l', 'list', None, _('list patch name in commit text')),
2511 ('a', 'all', None, _('apply all patches')),
2511 ('a', 'all', None, _('apply all patches')),
2512 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2512 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2513 ('n', 'name', '',
2513 ('n', 'name', '',
2514 _('merge queue name (DEPRECATED)'), _('NAME')),
2514 _('merge queue name (DEPRECATED)'), _('NAME')),
2515 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2515 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2516 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2516 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2517 def push(ui, repo, patch=None, **opts):
2517 def push(ui, repo, patch=None, **opts):
2518 """push the next patch onto the stack
2518 """push the next patch onto the stack
2519
2519
2520 When -f/--force is applied, all local changes in patched files
2520 When -f/--force is applied, all local changes in patched files
2521 will be lost.
2521 will be lost.
2522
2522
2523 Return 0 on success.
2523 Return 0 on success.
2524 """
2524 """
2525 q = repo.mq
2525 q = repo.mq
2526 mergeq = None
2526 mergeq = None
2527
2527
2528 if opts.get('merge'):
2528 if opts.get('merge'):
2529 if opts.get('name'):
2529 if opts.get('name'):
2530 newpath = repo.join(opts.get('name'))
2530 newpath = repo.join(opts.get('name'))
2531 else:
2531 else:
2532 newpath, i = lastsavename(q.path)
2532 newpath, i = lastsavename(q.path)
2533 if not newpath:
2533 if not newpath:
2534 ui.warn(_("no saved queues found, please use -n\n"))
2534 ui.warn(_("no saved queues found, please use -n\n"))
2535 return 1
2535 return 1
2536 mergeq = queue(ui, repo.join(""), newpath)
2536 mergeq = queue(ui, repo.join(""), newpath)
2537 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2537 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2538 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2538 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2539 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2539 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2540 exact=opts.get('exact'))
2540 exact=opts.get('exact'))
2541 return ret
2541 return ret
2542
2542
2543 @command("^qpop",
2543 @command("^qpop",
2544 [('a', 'all', None, _('pop all patches')),
2544 [('a', 'all', None, _('pop all patches')),
2545 ('n', 'name', '',
2545 ('n', 'name', '',
2546 _('queue name to pop (DEPRECATED)'), _('NAME')),
2546 _('queue name to pop (DEPRECATED)'), _('NAME')),
2547 ('f', 'force', None, _('forget any local changes to patched files'))],
2547 ('f', 'force', None, _('forget any local changes to patched files'))],
2548 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2548 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2549 def pop(ui, repo, patch=None, **opts):
2549 def pop(ui, repo, patch=None, **opts):
2550 """pop the current patch off the stack
2550 """pop the current patch off the stack
2551
2551
2552 By default, pops off the top of the patch stack. If given a patch
2552 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
2553 name, keeps popping off patches until the named patch is at the
2554 top of the stack.
2554 top of the stack.
2555
2555
2556 Return 0 on success.
2556 Return 0 on success.
2557 """
2557 """
2558 localupdate = True
2558 localupdate = True
2559 if opts.get('name'):
2559 if opts.get('name'):
2560 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2560 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2561 ui.warn(_('using patch queue: %s\n') % q.path)
2561 ui.warn(_('using patch queue: %s\n') % q.path)
2562 localupdate = False
2562 localupdate = False
2563 else:
2563 else:
2564 q = repo.mq
2564 q = repo.mq
2565 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2565 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2566 all=opts.get('all'))
2566 all=opts.get('all'))
2567 q.save_dirty()
2567 q.save_dirty()
2568 return ret
2568 return ret
2569
2569
2570 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2570 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2571 def rename(ui, repo, patch, name=None, **opts):
2571 def rename(ui, repo, patch, name=None, **opts):
2572 """rename a patch
2572 """rename a patch
2573
2573
2574 With one argument, renames the current patch to PATCH1.
2574 With one argument, renames the current patch to PATCH1.
2575 With two arguments, renames PATCH1 to PATCH2.
2575 With two arguments, renames PATCH1 to PATCH2.
2576
2576
2577 Returns 0 on success."""
2577 Returns 0 on success."""
2578
2578
2579 q = repo.mq
2579 q = repo.mq
2580
2580
2581 if not name:
2581 if not name:
2582 name = patch
2582 name = patch
2583 patch = None
2583 patch = None
2584
2584
2585 if patch:
2585 if patch:
2586 patch = q.lookup(patch)
2586 patch = q.lookup(patch)
2587 else:
2587 else:
2588 if not q.applied:
2588 if not q.applied:
2589 ui.write(_('no patches applied\n'))
2589 ui.write(_('no patches applied\n'))
2590 return
2590 return
2591 patch = q.lookup('qtip')
2591 patch = q.lookup('qtip')
2592 absdest = q.join(name)
2592 absdest = q.join(name)
2593 if os.path.isdir(absdest):
2593 if os.path.isdir(absdest):
2594 name = normname(os.path.join(name, os.path.basename(patch)))
2594 name = normname(os.path.join(name, os.path.basename(patch)))
2595 absdest = q.join(name)
2595 absdest = q.join(name)
2596 q.checkpatchname(name)
2596 q.checkpatchname(name)
2597
2597
2598 ui.note(_('renaming %s to %s\n') % (patch, name))
2598 ui.note(_('renaming %s to %s\n') % (patch, name))
2599 i = q.find_series(patch)
2599 i = q.find_series(patch)
2600 guards = q.guard_re.findall(q.full_series[i])
2600 guards = q.guard_re.findall(q.full_series[i])
2601 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2601 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2602 q.parse_series()
2602 q.parse_series()
2603 q.series_dirty = 1
2603 q.series_dirty = 1
2604
2604
2605 info = q.isapplied(patch)
2605 info = q.isapplied(patch)
2606 if info:
2606 if info:
2607 q.applied[info[0]] = statusentry(info[1], name)
2607 q.applied[info[0]] = statusentry(info[1], name)
2608 q.applied_dirty = 1
2608 q.applied_dirty = 1
2609
2609
2610 destdir = os.path.dirname(absdest)
2610 destdir = os.path.dirname(absdest)
2611 if not os.path.isdir(destdir):
2611 if not os.path.isdir(destdir):
2612 os.makedirs(destdir)
2612 os.makedirs(destdir)
2613 util.rename(q.join(patch), absdest)
2613 util.rename(q.join(patch), absdest)
2614 r = q.qrepo()
2614 r = q.qrepo()
2615 if r and patch in r.dirstate:
2615 if r and patch in r.dirstate:
2616 wctx = r[None]
2616 wctx = r[None]
2617 wlock = r.wlock()
2617 wlock = r.wlock()
2618 try:
2618 try:
2619 if r.dirstate[patch] == 'a':
2619 if r.dirstate[patch] == 'a':
2620 r.dirstate.forget(patch)
2620 r.dirstate.drop(patch)
2621 r.dirstate.add(name)
2621 r.dirstate.add(name)
2622 else:
2622 else:
2623 if r.dirstate[name] == 'r':
2623 if r.dirstate[name] == 'r':
2624 wctx.undelete([name])
2624 wctx.undelete([name])
2625 wctx.copy(patch, name)
2625 wctx.copy(patch, name)
2626 wctx.remove([patch], False)
2626 wctx.remove([patch], False)
2627 finally:
2627 finally:
2628 wlock.release()
2628 wlock.release()
2629
2629
2630 q.save_dirty()
2630 q.save_dirty()
2631
2631
2632 @command("qrestore",
2632 @command("qrestore",
2633 [('d', 'delete', None, _('delete save entry')),
2633 [('d', 'delete', None, _('delete save entry')),
2634 ('u', 'update', None, _('update queue working directory'))],
2634 ('u', 'update', None, _('update queue working directory'))],
2635 _('hg qrestore [-d] [-u] REV'))
2635 _('hg qrestore [-d] [-u] REV'))
2636 def restore(ui, repo, rev, **opts):
2636 def restore(ui, repo, rev, **opts):
2637 """restore the queue state saved by a revision (DEPRECATED)
2637 """restore the queue state saved by a revision (DEPRECATED)
2638
2638
2639 This command is deprecated, use :hg:`rebase` instead."""
2639 This command is deprecated, use :hg:`rebase` instead."""
2640 rev = repo.lookup(rev)
2640 rev = repo.lookup(rev)
2641 q = repo.mq
2641 q = repo.mq
2642 q.restore(repo, rev, delete=opts.get('delete'),
2642 q.restore(repo, rev, delete=opts.get('delete'),
2643 qupdate=opts.get('update'))
2643 qupdate=opts.get('update'))
2644 q.save_dirty()
2644 q.save_dirty()
2645 return 0
2645 return 0
2646
2646
2647 @command("qsave",
2647 @command("qsave",
2648 [('c', 'copy', None, _('copy patch directory')),
2648 [('c', 'copy', None, _('copy patch directory')),
2649 ('n', 'name', '',
2649 ('n', 'name', '',
2650 _('copy directory name'), _('NAME')),
2650 _('copy directory name'), _('NAME')),
2651 ('e', 'empty', None, _('clear queue status file')),
2651 ('e', 'empty', None, _('clear queue status file')),
2652 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2652 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2653 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2653 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2654 def save(ui, repo, **opts):
2654 def save(ui, repo, **opts):
2655 """save current queue state (DEPRECATED)
2655 """save current queue state (DEPRECATED)
2656
2656
2657 This command is deprecated, use :hg:`rebase` instead."""
2657 This command is deprecated, use :hg:`rebase` instead."""
2658 q = repo.mq
2658 q = repo.mq
2659 message = cmdutil.logmessage(opts)
2659 message = cmdutil.logmessage(opts)
2660 ret = q.save(repo, msg=message)
2660 ret = q.save(repo, msg=message)
2661 if ret:
2661 if ret:
2662 return ret
2662 return ret
2663 q.save_dirty()
2663 q.save_dirty()
2664 if opts.get('copy'):
2664 if opts.get('copy'):
2665 path = q.path
2665 path = q.path
2666 if opts.get('name'):
2666 if opts.get('name'):
2667 newpath = os.path.join(q.basepath, opts.get('name'))
2667 newpath = os.path.join(q.basepath, opts.get('name'))
2668 if os.path.exists(newpath):
2668 if os.path.exists(newpath):
2669 if not os.path.isdir(newpath):
2669 if not os.path.isdir(newpath):
2670 raise util.Abort(_('destination %s exists and is not '
2670 raise util.Abort(_('destination %s exists and is not '
2671 'a directory') % newpath)
2671 'a directory') % newpath)
2672 if not opts.get('force'):
2672 if not opts.get('force'):
2673 raise util.Abort(_('destination %s exists, '
2673 raise util.Abort(_('destination %s exists, '
2674 'use -f to force') % newpath)
2674 'use -f to force') % newpath)
2675 else:
2675 else:
2676 newpath = savename(path)
2676 newpath = savename(path)
2677 ui.warn(_("copy %s to %s\n") % (path, newpath))
2677 ui.warn(_("copy %s to %s\n") % (path, newpath))
2678 util.copyfiles(path, newpath)
2678 util.copyfiles(path, newpath)
2679 if opts.get('empty'):
2679 if opts.get('empty'):
2680 try:
2680 try:
2681 os.unlink(q.join(q.status_path))
2681 os.unlink(q.join(q.status_path))
2682 except:
2682 except:
2683 pass
2683 pass
2684 return 0
2684 return 0
2685
2685
2686 @command("strip",
2686 @command("strip",
2687 [('f', 'force', None, _('force removal of changesets, discard '
2687 [('f', 'force', None, _('force removal of changesets, discard '
2688 'uncommitted changes (no backup)')),
2688 'uncommitted changes (no backup)')),
2689 ('b', 'backup', None, _('bundle only changesets with local revision'
2689 ('b', 'backup', None, _('bundle only changesets with local revision'
2690 ' number greater than REV which are not'
2690 ' number greater than REV which are not'
2691 ' descendants of REV (DEPRECATED)')),
2691 ' descendants of REV (DEPRECATED)')),
2692 ('n', 'no-backup', None, _('no backups')),
2692 ('n', 'no-backup', None, _('no backups')),
2693 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2693 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2694 ('k', 'keep', None, _("do not modify working copy during strip"))],
2694 ('k', 'keep', None, _("do not modify working copy during strip"))],
2695 _('hg strip [-k] [-f] [-n] REV...'))
2695 _('hg strip [-k] [-f] [-n] REV...'))
2696 def strip(ui, repo, *revs, **opts):
2696 def strip(ui, repo, *revs, **opts):
2697 """strip changesets and all their descendants from the repository
2697 """strip changesets and all their descendants from the repository
2698
2698
2699 The strip command removes the specified changesets and all their
2699 The strip command removes the specified changesets and all their
2700 descendants. If the working directory has uncommitted changes, the
2700 descendants. If the working directory has uncommitted changes, the
2701 operation is aborted unless the --force flag is supplied, in which
2701 operation is aborted unless the --force flag is supplied, in which
2702 case changes will be discarded.
2702 case changes will be discarded.
2703
2703
2704 If a parent of the working directory is stripped, then the working
2704 If a parent of the working directory is stripped, then the working
2705 directory will automatically be updated to the most recent
2705 directory will automatically be updated to the most recent
2706 available ancestor of the stripped parent after the operation
2706 available ancestor of the stripped parent after the operation
2707 completes.
2707 completes.
2708
2708
2709 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2709 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2710 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2710 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2711 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2711 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2712 where BUNDLE is the bundle file created by the strip. Note that
2712 where BUNDLE is the bundle file created by the strip. Note that
2713 the local revision numbers will in general be different after the
2713 the local revision numbers will in general be different after the
2714 restore.
2714 restore.
2715
2715
2716 Use the --no-backup option to discard the backup bundle once the
2716 Use the --no-backup option to discard the backup bundle once the
2717 operation completes.
2717 operation completes.
2718
2718
2719 Return 0 on success.
2719 Return 0 on success.
2720 """
2720 """
2721 backup = 'all'
2721 backup = 'all'
2722 if opts.get('backup'):
2722 if opts.get('backup'):
2723 backup = 'strip'
2723 backup = 'strip'
2724 elif opts.get('no_backup') or opts.get('nobackup'):
2724 elif opts.get('no_backup') or opts.get('nobackup'):
2725 backup = 'none'
2725 backup = 'none'
2726
2726
2727 cl = repo.changelog
2727 cl = repo.changelog
2728 revs = set(scmutil.revrange(repo, revs))
2728 revs = set(scmutil.revrange(repo, revs))
2729 if not revs:
2729 if not revs:
2730 raise util.Abort(_('empty revision set'))
2730 raise util.Abort(_('empty revision set'))
2731
2731
2732 descendants = set(cl.descendants(*revs))
2732 descendants = set(cl.descendants(*revs))
2733 strippedrevs = revs.union(descendants)
2733 strippedrevs = revs.union(descendants)
2734 roots = revs.difference(descendants)
2734 roots = revs.difference(descendants)
2735
2735
2736 update = False
2736 update = False
2737 # if one of the wdir parent is stripped we'll need
2737 # if one of the wdir parent is stripped we'll need
2738 # to update away to an earlier revision
2738 # to update away to an earlier revision
2739 for p in repo.dirstate.parents():
2739 for p in repo.dirstate.parents():
2740 if p != nullid and cl.rev(p) in strippedrevs:
2740 if p != nullid and cl.rev(p) in strippedrevs:
2741 update = True
2741 update = True
2742 break
2742 break
2743
2743
2744 rootnodes = set(cl.node(r) for r in roots)
2744 rootnodes = set(cl.node(r) for r in roots)
2745
2745
2746 q = repo.mq
2746 q = repo.mq
2747 if q.applied:
2747 if q.applied:
2748 # refresh queue state if we're about to strip
2748 # refresh queue state if we're about to strip
2749 # applied patches
2749 # applied patches
2750 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2750 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2751 q.applied_dirty = True
2751 q.applied_dirty = True
2752 start = 0
2752 start = 0
2753 end = len(q.applied)
2753 end = len(q.applied)
2754 for i, statusentry in enumerate(q.applied):
2754 for i, statusentry in enumerate(q.applied):
2755 if statusentry.node in rootnodes:
2755 if statusentry.node in rootnodes:
2756 # if one of the stripped roots is an applied
2756 # if one of the stripped roots is an applied
2757 # patch, only part of the queue is stripped
2757 # patch, only part of the queue is stripped
2758 start = i
2758 start = i
2759 break
2759 break
2760 del q.applied[start:end]
2760 del q.applied[start:end]
2761 q.save_dirty()
2761 q.save_dirty()
2762
2762
2763 revs = list(rootnodes)
2763 revs = list(rootnodes)
2764 if update and opts.get('keep'):
2764 if update and opts.get('keep'):
2765 wlock = repo.wlock()
2765 wlock = repo.wlock()
2766 try:
2766 try:
2767 urev = repo.mq.qparents(repo, revs[0])
2767 urev = repo.mq.qparents(repo, revs[0])
2768 repo.dirstate.rebuild(urev, repo[urev].manifest())
2768 repo.dirstate.rebuild(urev, repo[urev].manifest())
2769 repo.dirstate.write()
2769 repo.dirstate.write()
2770 update = False
2770 update = False
2771 finally:
2771 finally:
2772 wlock.release()
2772 wlock.release()
2773
2773
2774 repo.mq.strip(repo, revs, backup=backup, update=update,
2774 repo.mq.strip(repo, revs, backup=backup, update=update,
2775 force=opts.get('force'))
2775 force=opts.get('force'))
2776 return 0
2776 return 0
2777
2777
2778 @command("qselect",
2778 @command("qselect",
2779 [('n', 'none', None, _('disable all guards')),
2779 [('n', 'none', None, _('disable all guards')),
2780 ('s', 'series', None, _('list all guards in series file')),
2780 ('s', 'series', None, _('list all guards in series file')),
2781 ('', 'pop', None, _('pop to before first guarded applied patch')),
2781 ('', 'pop', None, _('pop to before first guarded applied patch')),
2782 ('', 'reapply', None, _('pop, then reapply patches'))],
2782 ('', 'reapply', None, _('pop, then reapply patches'))],
2783 _('hg qselect [OPTION]... [GUARD]...'))
2783 _('hg qselect [OPTION]... [GUARD]...'))
2784 def select(ui, repo, *args, **opts):
2784 def select(ui, repo, *args, **opts):
2785 '''set or print guarded patches to push
2785 '''set or print guarded patches to push
2786
2786
2787 Use the :hg:`qguard` command to set or print guards on patch, then use
2787 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
2788 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
2789 it has no guards or any positive guards match the currently
2790 selected guard, but will not be pushed if any negative guards
2790 selected guard, but will not be pushed if any negative guards
2791 match the current guard. For example::
2791 match the current guard. For example::
2792
2792
2793 qguard foo.patch -- -stable (negative guard)
2793 qguard foo.patch -- -stable (negative guard)
2794 qguard bar.patch +stable (positive guard)
2794 qguard bar.patch +stable (positive guard)
2795 qselect stable
2795 qselect stable
2796
2796
2797 This activates the "stable" guard. mq will skip foo.patch (because
2797 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
2798 it has a negative match) but push bar.patch (because it has a
2799 positive match).
2799 positive match).
2800
2800
2801 With no arguments, prints the currently active guards.
2801 With no arguments, prints the currently active guards.
2802 With one argument, sets the active guard.
2802 With one argument, sets the active guard.
2803
2803
2804 Use -n/--none to deactivate guards (no other arguments needed).
2804 Use -n/--none to deactivate guards (no other arguments needed).
2805 When no guards are active, patches with positive guards are
2805 When no guards are active, patches with positive guards are
2806 skipped and patches with negative guards are pushed.
2806 skipped and patches with negative guards are pushed.
2807
2807
2808 qselect can change the guards on applied patches. It does not pop
2808 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
2809 guarded patches by default. Use --pop to pop back to the last
2810 applied patch that is not guarded. Use --reapply (which implies
2810 applied patch that is not guarded. Use --reapply (which implies
2811 --pop) to push back to the current patch afterwards, but skip
2811 --pop) to push back to the current patch afterwards, but skip
2812 guarded patches.
2812 guarded patches.
2813
2813
2814 Use -s/--series to print a list of all guards in the series file
2814 Use -s/--series to print a list of all guards in the series file
2815 (no other arguments needed). Use -v for more information.
2815 (no other arguments needed). Use -v for more information.
2816
2816
2817 Returns 0 on success.'''
2817 Returns 0 on success.'''
2818
2818
2819 q = repo.mq
2819 q = repo.mq
2820 guards = q.active()
2820 guards = q.active()
2821 if args or opts.get('none'):
2821 if args or opts.get('none'):
2822 old_unapplied = q.unapplied(repo)
2822 old_unapplied = q.unapplied(repo)
2823 old_guarded = [i for i in xrange(len(q.applied)) if
2823 old_guarded = [i for i in xrange(len(q.applied)) if
2824 not q.pushable(i)[0]]
2824 not q.pushable(i)[0]]
2825 q.set_active(args)
2825 q.set_active(args)
2826 q.save_dirty()
2826 q.save_dirty()
2827 if not args:
2827 if not args:
2828 ui.status(_('guards deactivated\n'))
2828 ui.status(_('guards deactivated\n'))
2829 if not opts.get('pop') and not opts.get('reapply'):
2829 if not opts.get('pop') and not opts.get('reapply'):
2830 unapplied = q.unapplied(repo)
2830 unapplied = q.unapplied(repo)
2831 guarded = [i for i in xrange(len(q.applied))
2831 guarded = [i for i in xrange(len(q.applied))
2832 if not q.pushable(i)[0]]
2832 if not q.pushable(i)[0]]
2833 if len(unapplied) != len(old_unapplied):
2833 if len(unapplied) != len(old_unapplied):
2834 ui.status(_('number of unguarded, unapplied patches has '
2834 ui.status(_('number of unguarded, unapplied patches has '
2835 'changed from %d to %d\n') %
2835 'changed from %d to %d\n') %
2836 (len(old_unapplied), len(unapplied)))
2836 (len(old_unapplied), len(unapplied)))
2837 if len(guarded) != len(old_guarded):
2837 if len(guarded) != len(old_guarded):
2838 ui.status(_('number of guarded, applied patches has changed '
2838 ui.status(_('number of guarded, applied patches has changed '
2839 'from %d to %d\n') %
2839 'from %d to %d\n') %
2840 (len(old_guarded), len(guarded)))
2840 (len(old_guarded), len(guarded)))
2841 elif opts.get('series'):
2841 elif opts.get('series'):
2842 guards = {}
2842 guards = {}
2843 noguards = 0
2843 noguards = 0
2844 for gs in q.series_guards:
2844 for gs in q.series_guards:
2845 if not gs:
2845 if not gs:
2846 noguards += 1
2846 noguards += 1
2847 for g in gs:
2847 for g in gs:
2848 guards.setdefault(g, 0)
2848 guards.setdefault(g, 0)
2849 guards[g] += 1
2849 guards[g] += 1
2850 if ui.verbose:
2850 if ui.verbose:
2851 guards['NONE'] = noguards
2851 guards['NONE'] = noguards
2852 guards = guards.items()
2852 guards = guards.items()
2853 guards.sort(key=lambda x: x[0][1:])
2853 guards.sort(key=lambda x: x[0][1:])
2854 if guards:
2854 if guards:
2855 ui.note(_('guards in series file:\n'))
2855 ui.note(_('guards in series file:\n'))
2856 for guard, count in guards:
2856 for guard, count in guards:
2857 ui.note('%2d ' % count)
2857 ui.note('%2d ' % count)
2858 ui.write(guard, '\n')
2858 ui.write(guard, '\n')
2859 else:
2859 else:
2860 ui.note(_('no guards in series file\n'))
2860 ui.note(_('no guards in series file\n'))
2861 else:
2861 else:
2862 if guards:
2862 if guards:
2863 ui.note(_('active guards:\n'))
2863 ui.note(_('active guards:\n'))
2864 for g in guards:
2864 for g in guards:
2865 ui.write(g, '\n')
2865 ui.write(g, '\n')
2866 else:
2866 else:
2867 ui.write(_('no active guards\n'))
2867 ui.write(_('no active guards\n'))
2868 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2868 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2869 popped = False
2869 popped = False
2870 if opts.get('pop') or opts.get('reapply'):
2870 if opts.get('pop') or opts.get('reapply'):
2871 for i in xrange(len(q.applied)):
2871 for i in xrange(len(q.applied)):
2872 pushable, reason = q.pushable(i)
2872 pushable, reason = q.pushable(i)
2873 if not pushable:
2873 if not pushable:
2874 ui.status(_('popping guarded patches\n'))
2874 ui.status(_('popping guarded patches\n'))
2875 popped = True
2875 popped = True
2876 if i == 0:
2876 if i == 0:
2877 q.pop(repo, all=True)
2877 q.pop(repo, all=True)
2878 else:
2878 else:
2879 q.pop(repo, i - 1)
2879 q.pop(repo, i - 1)
2880 break
2880 break
2881 if popped:
2881 if popped:
2882 try:
2882 try:
2883 if reapply:
2883 if reapply:
2884 ui.status(_('reapplying unguarded patches\n'))
2884 ui.status(_('reapplying unguarded patches\n'))
2885 q.push(repo, reapply)
2885 q.push(repo, reapply)
2886 finally:
2886 finally:
2887 q.save_dirty()
2887 q.save_dirty()
2888
2888
2889 @command("qfinish",
2889 @command("qfinish",
2890 [('a', 'applied', None, _('finish all applied changesets'))],
2890 [('a', 'applied', None, _('finish all applied changesets'))],
2891 _('hg qfinish [-a] [REV]...'))
2891 _('hg qfinish [-a] [REV]...'))
2892 def finish(ui, repo, *revrange, **opts):
2892 def finish(ui, repo, *revrange, **opts):
2893 """move applied patches into repository history
2893 """move applied patches into repository history
2894
2894
2895 Finishes the specified revisions (corresponding to applied
2895 Finishes the specified revisions (corresponding to applied
2896 patches) by moving them out of mq control into regular repository
2896 patches) by moving them out of mq control into regular repository
2897 history.
2897 history.
2898
2898
2899 Accepts a revision range or the -a/--applied option. If --applied
2899 Accepts a revision range or the -a/--applied option. If --applied
2900 is specified, all applied mq revisions are removed from mq
2900 is specified, all applied mq revisions are removed from mq
2901 control. Otherwise, the given revisions must be at the base of the
2901 control. Otherwise, the given revisions must be at the base of the
2902 stack of applied patches.
2902 stack of applied patches.
2903
2903
2904 This can be especially useful if your changes have been applied to
2904 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
2905 an upstream repository, or if you are about to push your changes
2906 to upstream.
2906 to upstream.
2907
2907
2908 Returns 0 on success.
2908 Returns 0 on success.
2909 """
2909 """
2910 if not opts.get('applied') and not revrange:
2910 if not opts.get('applied') and not revrange:
2911 raise util.Abort(_('no revisions specified'))
2911 raise util.Abort(_('no revisions specified'))
2912 elif opts.get('applied'):
2912 elif opts.get('applied'):
2913 revrange = ('qbase::qtip',) + revrange
2913 revrange = ('qbase::qtip',) + revrange
2914
2914
2915 q = repo.mq
2915 q = repo.mq
2916 if not q.applied:
2916 if not q.applied:
2917 ui.status(_('no patches applied\n'))
2917 ui.status(_('no patches applied\n'))
2918 return 0
2918 return 0
2919
2919
2920 revs = scmutil.revrange(repo, revrange)
2920 revs = scmutil.revrange(repo, revrange)
2921 q.finish(repo, revs)
2921 q.finish(repo, revs)
2922 q.save_dirty()
2922 q.save_dirty()
2923 return 0
2923 return 0
2924
2924
2925 @command("qqueue",
2925 @command("qqueue",
2926 [('l', 'list', False, _('list all available queues')),
2926 [('l', 'list', False, _('list all available queues')),
2927 ('c', 'create', False, _('create new queue')),
2927 ('c', 'create', False, _('create new queue')),
2928 ('', 'rename', False, _('rename active queue')),
2928 ('', 'rename', False, _('rename active queue')),
2929 ('', 'delete', False, _('delete reference to queue')),
2929 ('', 'delete', False, _('delete reference to queue')),
2930 ('', 'purge', False, _('delete queue, and remove patch dir')),
2930 ('', 'purge', False, _('delete queue, and remove patch dir')),
2931 ],
2931 ],
2932 _('[OPTION] [QUEUE]'))
2932 _('[OPTION] [QUEUE]'))
2933 def qqueue(ui, repo, name=None, **opts):
2933 def qqueue(ui, repo, name=None, **opts):
2934 '''manage multiple patch queues
2934 '''manage multiple patch queues
2935
2935
2936 Supports switching between different patch queues, as well as creating
2936 Supports switching between different patch queues, as well as creating
2937 new patch queues and deleting existing ones.
2937 new patch queues and deleting existing ones.
2938
2938
2939 Omitting a queue name or specifying -l/--list will show you the registered
2939 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
2940 queues - by default the "normal" patches queue is registered. The currently
2941 active queue will be marked with "(active)".
2941 active queue will be marked with "(active)".
2942
2942
2943 To create a new queue, use -c/--create. The queue is automatically made
2943 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
2944 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
2945 currently active queue in the repository. Then the queue will only be
2946 created and switching will fail.
2946 created and switching will fail.
2947
2947
2948 To delete an existing queue, use --delete. You cannot delete the currently
2948 To delete an existing queue, use --delete. You cannot delete the currently
2949 active queue.
2949 active queue.
2950
2950
2951 Returns 0 on success.
2951 Returns 0 on success.
2952 '''
2952 '''
2953
2953
2954 q = repo.mq
2954 q = repo.mq
2955
2955
2956 _defaultqueue = 'patches'
2956 _defaultqueue = 'patches'
2957 _allqueues = 'patches.queues'
2957 _allqueues = 'patches.queues'
2958 _activequeue = 'patches.queue'
2958 _activequeue = 'patches.queue'
2959
2959
2960 def _getcurrent():
2960 def _getcurrent():
2961 cur = os.path.basename(q.path)
2961 cur = os.path.basename(q.path)
2962 if cur.startswith('patches-'):
2962 if cur.startswith('patches-'):
2963 cur = cur[8:]
2963 cur = cur[8:]
2964 return cur
2964 return cur
2965
2965
2966 def _noqueues():
2966 def _noqueues():
2967 try:
2967 try:
2968 fh = repo.opener(_allqueues, 'r')
2968 fh = repo.opener(_allqueues, 'r')
2969 fh.close()
2969 fh.close()
2970 except IOError:
2970 except IOError:
2971 return True
2971 return True
2972
2972
2973 return False
2973 return False
2974
2974
2975 def _getqueues():
2975 def _getqueues():
2976 current = _getcurrent()
2976 current = _getcurrent()
2977
2977
2978 try:
2978 try:
2979 fh = repo.opener(_allqueues, 'r')
2979 fh = repo.opener(_allqueues, 'r')
2980 queues = [queue.strip() for queue in fh if queue.strip()]
2980 queues = [queue.strip() for queue in fh if queue.strip()]
2981 fh.close()
2981 fh.close()
2982 if current not in queues:
2982 if current not in queues:
2983 queues.append(current)
2983 queues.append(current)
2984 except IOError:
2984 except IOError:
2985 queues = [_defaultqueue]
2985 queues = [_defaultqueue]
2986
2986
2987 return sorted(queues)
2987 return sorted(queues)
2988
2988
2989 def _setactive(name):
2989 def _setactive(name):
2990 if q.applied:
2990 if q.applied:
2991 raise util.Abort(_('patches applied - cannot set new queue active'))
2991 raise util.Abort(_('patches applied - cannot set new queue active'))
2992 _setactivenocheck(name)
2992 _setactivenocheck(name)
2993
2993
2994 def _setactivenocheck(name):
2994 def _setactivenocheck(name):
2995 fh = repo.opener(_activequeue, 'w')
2995 fh = repo.opener(_activequeue, 'w')
2996 if name != 'patches':
2996 if name != 'patches':
2997 fh.write(name)
2997 fh.write(name)
2998 fh.close()
2998 fh.close()
2999
2999
3000 def _addqueue(name):
3000 def _addqueue(name):
3001 fh = repo.opener(_allqueues, 'a')
3001 fh = repo.opener(_allqueues, 'a')
3002 fh.write('%s\n' % (name,))
3002 fh.write('%s\n' % (name,))
3003 fh.close()
3003 fh.close()
3004
3004
3005 def _queuedir(name):
3005 def _queuedir(name):
3006 if name == 'patches':
3006 if name == 'patches':
3007 return repo.join('patches')
3007 return repo.join('patches')
3008 else:
3008 else:
3009 return repo.join('patches-' + name)
3009 return repo.join('patches-' + name)
3010
3010
3011 def _validname(name):
3011 def _validname(name):
3012 for n in name:
3012 for n in name:
3013 if n in ':\\/.':
3013 if n in ':\\/.':
3014 return False
3014 return False
3015 return True
3015 return True
3016
3016
3017 def _delete(name):
3017 def _delete(name):
3018 if name not in existing:
3018 if name not in existing:
3019 raise util.Abort(_('cannot delete queue that does not exist'))
3019 raise util.Abort(_('cannot delete queue that does not exist'))
3020
3020
3021 current = _getcurrent()
3021 current = _getcurrent()
3022
3022
3023 if name == current:
3023 if name == current:
3024 raise util.Abort(_('cannot delete currently active queue'))
3024 raise util.Abort(_('cannot delete currently active queue'))
3025
3025
3026 fh = repo.opener('patches.queues.new', 'w')
3026 fh = repo.opener('patches.queues.new', 'w')
3027 for queue in existing:
3027 for queue in existing:
3028 if queue == name:
3028 if queue == name:
3029 continue
3029 continue
3030 fh.write('%s\n' % (queue,))
3030 fh.write('%s\n' % (queue,))
3031 fh.close()
3031 fh.close()
3032 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3032 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3033
3033
3034 if not name or opts.get('list'):
3034 if not name or opts.get('list'):
3035 current = _getcurrent()
3035 current = _getcurrent()
3036 for queue in _getqueues():
3036 for queue in _getqueues():
3037 ui.write('%s' % (queue,))
3037 ui.write('%s' % (queue,))
3038 if queue == current and not ui.quiet:
3038 if queue == current and not ui.quiet:
3039 ui.write(_(' (active)\n'))
3039 ui.write(_(' (active)\n'))
3040 else:
3040 else:
3041 ui.write('\n')
3041 ui.write('\n')
3042 return
3042 return
3043
3043
3044 if not _validname(name):
3044 if not _validname(name):
3045 raise util.Abort(
3045 raise util.Abort(
3046 _('invalid queue name, may not contain the characters ":\\/."'))
3046 _('invalid queue name, may not contain the characters ":\\/."'))
3047
3047
3048 existing = _getqueues()
3048 existing = _getqueues()
3049
3049
3050 if opts.get('create'):
3050 if opts.get('create'):
3051 if name in existing:
3051 if name in existing:
3052 raise util.Abort(_('queue "%s" already exists') % name)
3052 raise util.Abort(_('queue "%s" already exists') % name)
3053 if _noqueues():
3053 if _noqueues():
3054 _addqueue(_defaultqueue)
3054 _addqueue(_defaultqueue)
3055 _addqueue(name)
3055 _addqueue(name)
3056 _setactive(name)
3056 _setactive(name)
3057 elif opts.get('rename'):
3057 elif opts.get('rename'):
3058 current = _getcurrent()
3058 current = _getcurrent()
3059 if name == current:
3059 if name == current:
3060 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3060 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3061 if name in existing:
3061 if name in existing:
3062 raise util.Abort(_('queue "%s" already exists') % name)
3062 raise util.Abort(_('queue "%s" already exists') % name)
3063
3063
3064 olddir = _queuedir(current)
3064 olddir = _queuedir(current)
3065 newdir = _queuedir(name)
3065 newdir = _queuedir(name)
3066
3066
3067 if os.path.exists(newdir):
3067 if os.path.exists(newdir):
3068 raise util.Abort(_('non-queue directory "%s" already exists') %
3068 raise util.Abort(_('non-queue directory "%s" already exists') %
3069 newdir)
3069 newdir)
3070
3070
3071 fh = repo.opener('patches.queues.new', 'w')
3071 fh = repo.opener('patches.queues.new', 'w')
3072 for queue in existing:
3072 for queue in existing:
3073 if queue == current:
3073 if queue == current:
3074 fh.write('%s\n' % (name,))
3074 fh.write('%s\n' % (name,))
3075 if os.path.exists(olddir):
3075 if os.path.exists(olddir):
3076 util.rename(olddir, newdir)
3076 util.rename(olddir, newdir)
3077 else:
3077 else:
3078 fh.write('%s\n' % (queue,))
3078 fh.write('%s\n' % (queue,))
3079 fh.close()
3079 fh.close()
3080 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3080 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3081 _setactivenocheck(name)
3081 _setactivenocheck(name)
3082 elif opts.get('delete'):
3082 elif opts.get('delete'):
3083 _delete(name)
3083 _delete(name)
3084 elif opts.get('purge'):
3084 elif opts.get('purge'):
3085 if name in existing:
3085 if name in existing:
3086 _delete(name)
3086 _delete(name)
3087 qdir = _queuedir(name)
3087 qdir = _queuedir(name)
3088 if os.path.exists(qdir):
3088 if os.path.exists(qdir):
3089 shutil.rmtree(qdir)
3089 shutil.rmtree(qdir)
3090 else:
3090 else:
3091 if name not in existing:
3091 if name not in existing:
3092 raise util.Abort(_('use --create to create a new queue'))
3092 raise util.Abort(_('use --create to create a new queue'))
3093 _setactive(name)
3093 _setactive(name)
3094
3094
3095 def reposetup(ui, repo):
3095 def reposetup(ui, repo):
3096 class mqrepo(repo.__class__):
3096 class mqrepo(repo.__class__):
3097 @util.propertycache
3097 @util.propertycache
3098 def mq(self):
3098 def mq(self):
3099 return queue(self.ui, self.join(""))
3099 return queue(self.ui, self.join(""))
3100
3100
3101 def abort_if_wdir_patched(self, errmsg, force=False):
3101 def abort_if_wdir_patched(self, errmsg, force=False):
3102 if self.mq.applied and not force:
3102 if self.mq.applied and not force:
3103 parents = self.dirstate.parents()
3103 parents = self.dirstate.parents()
3104 patches = [s.node for s in self.mq.applied]
3104 patches = [s.node for s in self.mq.applied]
3105 if parents[0] in patches or parents[1] in patches:
3105 if parents[0] in patches or parents[1] in patches:
3106 raise util.Abort(errmsg)
3106 raise util.Abort(errmsg)
3107
3107
3108 def commit(self, text="", user=None, date=None, match=None,
3108 def commit(self, text="", user=None, date=None, match=None,
3109 force=False, editor=False, extra={}):
3109 force=False, editor=False, extra={}):
3110 self.abort_if_wdir_patched(
3110 self.abort_if_wdir_patched(
3111 _('cannot commit over an applied mq patch'),
3111 _('cannot commit over an applied mq patch'),
3112 force)
3112 force)
3113
3113
3114 return super(mqrepo, self).commit(text, user, date, match, force,
3114 return super(mqrepo, self).commit(text, user, date, match, force,
3115 editor, extra)
3115 editor, extra)
3116
3116
3117 def checkpush(self, force, revs):
3117 def checkpush(self, force, revs):
3118 if self.mq.applied and not force:
3118 if self.mq.applied and not force:
3119 haspatches = True
3119 haspatches = True
3120 if revs:
3120 if revs:
3121 # Assume applied patches have no non-patch descendants
3121 # Assume applied patches have no non-patch descendants
3122 # and are not on remote already. If they appear in the
3122 # and are not on remote already. If they appear in the
3123 # set of resolved 'revs', bail out.
3123 # set of resolved 'revs', bail out.
3124 applied = set(e.node for e in self.mq.applied)
3124 applied = set(e.node for e in self.mq.applied)
3125 haspatches = bool([n for n in revs if n in applied])
3125 haspatches = bool([n for n in revs if n in applied])
3126 if haspatches:
3126 if haspatches:
3127 raise util.Abort(_('source has mq patches applied'))
3127 raise util.Abort(_('source has mq patches applied'))
3128 super(mqrepo, self).checkpush(force, revs)
3128 super(mqrepo, self).checkpush(force, revs)
3129
3129
3130 def _findtags(self):
3130 def _findtags(self):
3131 '''augment tags from base class with patch tags'''
3131 '''augment tags from base class with patch tags'''
3132 result = super(mqrepo, self)._findtags()
3132 result = super(mqrepo, self)._findtags()
3133
3133
3134 q = self.mq
3134 q = self.mq
3135 if not q.applied:
3135 if not q.applied:
3136 return result
3136 return result
3137
3137
3138 mqtags = [(patch.node, patch.name) for patch in q.applied]
3138 mqtags = [(patch.node, patch.name) for patch in q.applied]
3139
3139
3140 try:
3140 try:
3141 self.changelog.rev(mqtags[-1][0])
3141 self.changelog.rev(mqtags[-1][0])
3142 except error.RepoLookupError:
3142 except error.RepoLookupError:
3143 self.ui.warn(_('mq status file refers to unknown node %s\n')
3143 self.ui.warn(_('mq status file refers to unknown node %s\n')
3144 % short(mqtags[-1][0]))
3144 % short(mqtags[-1][0]))
3145 return result
3145 return result
3146
3146
3147 mqtags.append((mqtags[-1][0], 'qtip'))
3147 mqtags.append((mqtags[-1][0], 'qtip'))
3148 mqtags.append((mqtags[0][0], 'qbase'))
3148 mqtags.append((mqtags[0][0], 'qbase'))
3149 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3149 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3150 tags = result[0]
3150 tags = result[0]
3151 for patch in mqtags:
3151 for patch in mqtags:
3152 if patch[1] in tags:
3152 if patch[1] in tags:
3153 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3153 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3154 % patch[1])
3154 % patch[1])
3155 else:
3155 else:
3156 tags[patch[1]] = patch[0]
3156 tags[patch[1]] = patch[0]
3157
3157
3158 return result
3158 return result
3159
3159
3160 def _branchtags(self, partial, lrev):
3160 def _branchtags(self, partial, lrev):
3161 q = self.mq
3161 q = self.mq
3162 if not q.applied:
3162 if not q.applied:
3163 return super(mqrepo, self)._branchtags(partial, lrev)
3163 return super(mqrepo, self)._branchtags(partial, lrev)
3164
3164
3165 cl = self.changelog
3165 cl = self.changelog
3166 qbasenode = q.applied[0].node
3166 qbasenode = q.applied[0].node
3167 try:
3167 try:
3168 qbase = cl.rev(qbasenode)
3168 qbase = cl.rev(qbasenode)
3169 except error.LookupError:
3169 except error.LookupError:
3170 self.ui.warn(_('mq status file refers to unknown node %s\n')
3170 self.ui.warn(_('mq status file refers to unknown node %s\n')
3171 % short(qbasenode))
3171 % short(qbasenode))
3172 return super(mqrepo, self)._branchtags(partial, lrev)
3172 return super(mqrepo, self)._branchtags(partial, lrev)
3173
3173
3174 start = lrev + 1
3174 start = lrev + 1
3175 if start < qbase:
3175 if start < qbase:
3176 # update the cache (excluding the patches) and save it
3176 # update the cache (excluding the patches) and save it
3177 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3177 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3178 self._updatebranchcache(partial, ctxgen)
3178 self._updatebranchcache(partial, ctxgen)
3179 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3179 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3180 start = qbase
3180 start = qbase
3181 # if start = qbase, the cache is as updated as it should be.
3181 # if start = qbase, the cache is as updated as it should be.
3182 # if start > qbase, the cache includes (part of) the patches.
3182 # if start > qbase, the cache includes (part of) the patches.
3183 # we might as well use it, but we won't save it.
3183 # we might as well use it, but we won't save it.
3184
3184
3185 # update the cache up to the tip
3185 # update the cache up to the tip
3186 ctxgen = (self[r] for r in xrange(start, len(cl)))
3186 ctxgen = (self[r] for r in xrange(start, len(cl)))
3187 self._updatebranchcache(partial, ctxgen)
3187 self._updatebranchcache(partial, ctxgen)
3188
3188
3189 return partial
3189 return partial
3190
3190
3191 if repo.local():
3191 if repo.local():
3192 repo.__class__ = mqrepo
3192 repo.__class__ = mqrepo
3193
3193
3194 def mqimport(orig, ui, repo, *args, **kwargs):
3194 def mqimport(orig, ui, repo, *args, **kwargs):
3195 if (hasattr(repo, 'abort_if_wdir_patched')
3195 if (hasattr(repo, 'abort_if_wdir_patched')
3196 and not kwargs.get('no_commit', False)):
3196 and not kwargs.get('no_commit', False)):
3197 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3197 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
3198 kwargs.get('force'))
3198 kwargs.get('force'))
3199 return orig(ui, repo, *args, **kwargs)
3199 return orig(ui, repo, *args, **kwargs)
3200
3200
3201 def mqinit(orig, ui, *args, **kwargs):
3201 def mqinit(orig, ui, *args, **kwargs):
3202 mq = kwargs.pop('mq', None)
3202 mq = kwargs.pop('mq', None)
3203
3203
3204 if not mq:
3204 if not mq:
3205 return orig(ui, *args, **kwargs)
3205 return orig(ui, *args, **kwargs)
3206
3206
3207 if args:
3207 if args:
3208 repopath = args[0]
3208 repopath = args[0]
3209 if not hg.islocal(repopath):
3209 if not hg.islocal(repopath):
3210 raise util.Abort(_('only a local queue repository '
3210 raise util.Abort(_('only a local queue repository '
3211 'may be initialized'))
3211 'may be initialized'))
3212 else:
3212 else:
3213 repopath = cmdutil.findrepo(os.getcwd())
3213 repopath = cmdutil.findrepo(os.getcwd())
3214 if not repopath:
3214 if not repopath:
3215 raise util.Abort(_('there is no Mercurial repository here '
3215 raise util.Abort(_('there is no Mercurial repository here '
3216 '(.hg not found)'))
3216 '(.hg not found)'))
3217 repo = hg.repository(ui, repopath)
3217 repo = hg.repository(ui, repopath)
3218 return qinit(ui, repo, True)
3218 return qinit(ui, repo, True)
3219
3219
3220 def mqcommand(orig, ui, repo, *args, **kwargs):
3220 def mqcommand(orig, ui, repo, *args, **kwargs):
3221 """Add --mq option to operate on patch repository instead of main"""
3221 """Add --mq option to operate on patch repository instead of main"""
3222
3222
3223 # some commands do not like getting unknown options
3223 # some commands do not like getting unknown options
3224 mq = kwargs.pop('mq', None)
3224 mq = kwargs.pop('mq', None)
3225
3225
3226 if not mq:
3226 if not mq:
3227 return orig(ui, repo, *args, **kwargs)
3227 return orig(ui, repo, *args, **kwargs)
3228
3228
3229 q = repo.mq
3229 q = repo.mq
3230 r = q.qrepo()
3230 r = q.qrepo()
3231 if not r:
3231 if not r:
3232 raise util.Abort(_('no queue repository'))
3232 raise util.Abort(_('no queue repository'))
3233 return orig(r.ui, r, *args, **kwargs)
3233 return orig(r.ui, r, *args, **kwargs)
3234
3234
3235 def summary(orig, ui, repo, *args, **kwargs):
3235 def summary(orig, ui, repo, *args, **kwargs):
3236 r = orig(ui, repo, *args, **kwargs)
3236 r = orig(ui, repo, *args, **kwargs)
3237 q = repo.mq
3237 q = repo.mq
3238 m = []
3238 m = []
3239 a, u = len(q.applied), len(q.unapplied(repo))
3239 a, u = len(q.applied), len(q.unapplied(repo))
3240 if a:
3240 if a:
3241 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3241 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3242 if u:
3242 if u:
3243 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3243 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3244 if m:
3244 if m:
3245 ui.write("mq: %s\n" % ', '.join(m))
3245 ui.write("mq: %s\n" % ', '.join(m))
3246 else:
3246 else:
3247 ui.note(_("mq: (empty queue)\n"))
3247 ui.note(_("mq: (empty queue)\n"))
3248 return r
3248 return r
3249
3249
3250 def revsetmq(repo, subset, x):
3250 def revsetmq(repo, subset, x):
3251 """``mq()``
3251 """``mq()``
3252 Changesets managed by MQ.
3252 Changesets managed by MQ.
3253 """
3253 """
3254 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3254 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3255 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3255 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3256 return [r for r in subset if r in applied]
3256 return [r for r in subset if r in applied]
3257
3257
3258 def extsetup(ui):
3258 def extsetup(ui):
3259 revset.symbols['mq'] = revsetmq
3259 revset.symbols['mq'] = revsetmq
3260
3260
3261 # tell hggettext to extract docstrings from these functions:
3261 # tell hggettext to extract docstrings from these functions:
3262 i18nfunctions = [revsetmq]
3262 i18nfunctions = [revsetmq]
3263
3263
3264 def uisetup(ui):
3264 def uisetup(ui):
3265 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3265 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3266
3266
3267 extensions.wrapcommand(commands.table, 'import', mqimport)
3267 extensions.wrapcommand(commands.table, 'import', mqimport)
3268 extensions.wrapcommand(commands.table, 'summary', summary)
3268 extensions.wrapcommand(commands.table, 'summary', summary)
3269
3269
3270 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3270 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3271 entry[1].extend(mqopt)
3271 entry[1].extend(mqopt)
3272
3272
3273 nowrap = set(commands.norepo.split(" ") + ['qrecord'])
3273 nowrap = set(commands.norepo.split(" ") + ['qrecord'])
3274
3274
3275 def dotable(cmdtable):
3275 def dotable(cmdtable):
3276 for cmd in cmdtable.keys():
3276 for cmd in cmdtable.keys():
3277 cmd = cmdutil.parsealiases(cmd)[0]
3277 cmd = cmdutil.parsealiases(cmd)[0]
3278 if cmd in nowrap:
3278 if cmd in nowrap:
3279 continue
3279 continue
3280 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3280 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3281 entry[1].extend(mqopt)
3281 entry[1].extend(mqopt)
3282
3282
3283 dotable(commands.table)
3283 dotable(commands.table)
3284
3284
3285 for extname, extmodule in extensions.extensions():
3285 for extname, extmodule in extensions.extensions():
3286 if extmodule.__file__ != __file__:
3286 if extmodule.__file__ != __file__:
3287 dotable(getattr(extmodule, 'cmdtable', {}))
3287 dotable(getattr(extmodule, 'cmdtable', {}))
3288
3288
3289
3289
3290 colortable = {'qguard.negative': 'red',
3290 colortable = {'qguard.negative': 'red',
3291 'qguard.positive': 'yellow',
3291 'qguard.positive': 'yellow',
3292 'qguard.unguarded': 'green',
3292 'qguard.unguarded': 'green',
3293 'qseries.applied': 'blue bold underline',
3293 'qseries.applied': 'blue bold underline',
3294 'qseries.guarded': 'black bold',
3294 'qseries.guarded': 'black bold',
3295 'qseries.missing': 'red bold',
3295 'qseries.missing': 'red bold',
3296 'qseries.unapplied': 'black bold'}
3296 '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].remove(forget, unlink=False)
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.forget(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,1127 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, list):
839 wlock = self._repo.wlock()
839 wlock = self._repo.wlock()
840 try:
840 try:
841 for f in list:
841 for f in list:
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.ui.warn(_("%s not added!\n") % f)
844 else:
844 else:
845 self._repo.dirstate.forget(f)
845 self._repo.dirstate.drop(f)
846 finally:
846 finally:
847 wlock.release()
847 wlock.release()
848
848
849 def ancestors(self):
849 def ancestors(self):
850 for a in self._repo.changelog.ancestors(
850 for a in self._repo.changelog.ancestors(
851 *[p.rev() for p in self._parents]):
851 *[p.rev() for p in self._parents]):
852 yield changectx(self._repo, a)
852 yield changectx(self._repo, a)
853
853
854 def remove(self, list, unlink=False):
854 def remove(self, list, unlink=False):
855 wlock = self._repo.wlock()
855 wlock = self._repo.wlock()
856 try:
856 try:
857 if unlink:
857 if unlink:
858 for f in list:
858 for f in list:
859 try:
859 try:
860 util.unlinkpath(self._repo.wjoin(f))
860 util.unlinkpath(self._repo.wjoin(f))
861 except OSError, inst:
861 except OSError, inst:
862 if inst.errno != errno.ENOENT:
862 if inst.errno != errno.ENOENT:
863 raise
863 raise
864 for f in list:
864 for f in list:
865 if self._repo.dirstate[f] == 'a':
865 if self._repo.dirstate[f] == 'a':
866 self._repo.dirstate.forget(f)
866 self._repo.dirstate.drop(f)
867 elif f not in self._repo.dirstate:
867 elif f not in self._repo.dirstate:
868 self._repo.ui.warn(_("%s not tracked!\n") % f)
868 self._repo.ui.warn(_("%s not tracked!\n") % f)
869 else:
869 else:
870 self._repo.dirstate.remove(f)
870 self._repo.dirstate.remove(f)
871 finally:
871 finally:
872 wlock.release()
872 wlock.release()
873
873
874 def undelete(self, list):
874 def undelete(self, list):
875 pctxs = self.parents()
875 pctxs = self.parents()
876 wlock = self._repo.wlock()
876 wlock = self._repo.wlock()
877 try:
877 try:
878 for f in list:
878 for f in list:
879 if self._repo.dirstate[f] != 'r':
879 if self._repo.dirstate[f] != 'r':
880 self._repo.ui.warn(_("%s not removed!\n") % f)
880 self._repo.ui.warn(_("%s not removed!\n") % f)
881 else:
881 else:
882 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
882 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
883 t = fctx.data()
883 t = fctx.data()
884 self._repo.wwrite(f, t, fctx.flags())
884 self._repo.wwrite(f, t, fctx.flags())
885 self._repo.dirstate.normal(f)
885 self._repo.dirstate.normal(f)
886 finally:
886 finally:
887 wlock.release()
887 wlock.release()
888
888
889 def copy(self, source, dest):
889 def copy(self, source, dest):
890 p = self._repo.wjoin(dest)
890 p = self._repo.wjoin(dest)
891 if not os.path.lexists(p):
891 if not os.path.lexists(p):
892 self._repo.ui.warn(_("%s does not exist!\n") % dest)
892 self._repo.ui.warn(_("%s does not exist!\n") % dest)
893 elif not (os.path.isfile(p) or os.path.islink(p)):
893 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 "
894 self._repo.ui.warn(_("copy failed: %s is not a file or a "
895 "symbolic link\n") % dest)
895 "symbolic link\n") % dest)
896 else:
896 else:
897 wlock = self._repo.wlock()
897 wlock = self._repo.wlock()
898 try:
898 try:
899 if self._repo.dirstate[dest] in '?r':
899 if self._repo.dirstate[dest] in '?r':
900 self._repo.dirstate.add(dest)
900 self._repo.dirstate.add(dest)
901 self._repo.dirstate.copy(source, dest)
901 self._repo.dirstate.copy(source, dest)
902 finally:
902 finally:
903 wlock.release()
903 wlock.release()
904
904
905 class workingfilectx(filectx):
905 class workingfilectx(filectx):
906 """A workingfilectx object makes access to data related to a particular
906 """A workingfilectx object makes access to data related to a particular
907 file in the working directory convenient."""
907 file in the working directory convenient."""
908 def __init__(self, repo, path, filelog=None, workingctx=None):
908 def __init__(self, repo, path, filelog=None, workingctx=None):
909 """changeid can be a changeset revision, node, or tag.
909 """changeid can be a changeset revision, node, or tag.
910 fileid can be a file revision or node."""
910 fileid can be a file revision or node."""
911 self._repo = repo
911 self._repo = repo
912 self._path = path
912 self._path = path
913 self._changeid = None
913 self._changeid = None
914 self._filerev = self._filenode = None
914 self._filerev = self._filenode = None
915
915
916 if filelog:
916 if filelog:
917 self._filelog = filelog
917 self._filelog = filelog
918 if workingctx:
918 if workingctx:
919 self._changectx = workingctx
919 self._changectx = workingctx
920
920
921 @propertycache
921 @propertycache
922 def _changectx(self):
922 def _changectx(self):
923 return workingctx(self._repo)
923 return workingctx(self._repo)
924
924
925 def __nonzero__(self):
925 def __nonzero__(self):
926 return True
926 return True
927
927
928 def __str__(self):
928 def __str__(self):
929 return "%s@%s" % (self.path(), self._changectx)
929 return "%s@%s" % (self.path(), self._changectx)
930
930
931 def __repr__(self):
931 def __repr__(self):
932 return "<workingfilectx %s>" % str(self)
932 return "<workingfilectx %s>" % str(self)
933
933
934 def data(self):
934 def data(self):
935 return self._repo.wread(self._path)
935 return self._repo.wread(self._path)
936 def renamed(self):
936 def renamed(self):
937 rp = self._repo.dirstate.copied(self._path)
937 rp = self._repo.dirstate.copied(self._path)
938 if not rp:
938 if not rp:
939 return None
939 return None
940 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
940 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
941
941
942 def parents(self):
942 def parents(self):
943 '''return parent filectxs, following copies if necessary'''
943 '''return parent filectxs, following copies if necessary'''
944 def filenode(ctx, path):
944 def filenode(ctx, path):
945 return ctx._manifest.get(path, nullid)
945 return ctx._manifest.get(path, nullid)
946
946
947 path = self._path
947 path = self._path
948 fl = self._filelog
948 fl = self._filelog
949 pcl = self._changectx._parents
949 pcl = self._changectx._parents
950 renamed = self.renamed()
950 renamed = self.renamed()
951
951
952 if renamed:
952 if renamed:
953 pl = [renamed + (None,)]
953 pl = [renamed + (None,)]
954 else:
954 else:
955 pl = [(path, filenode(pcl[0], path), fl)]
955 pl = [(path, filenode(pcl[0], path), fl)]
956
956
957 for pc in pcl[1:]:
957 for pc in pcl[1:]:
958 pl.append((path, filenode(pc, path), fl))
958 pl.append((path, filenode(pc, path), fl))
959
959
960 return [filectx(self._repo, p, fileid=n, filelog=l)
960 return [filectx(self._repo, p, fileid=n, filelog=l)
961 for p, n, l in pl if n != nullid]
961 for p, n, l in pl if n != nullid]
962
962
963 def children(self):
963 def children(self):
964 return []
964 return []
965
965
966 def size(self):
966 def size(self):
967 return os.lstat(self._repo.wjoin(self._path)).st_size
967 return os.lstat(self._repo.wjoin(self._path)).st_size
968 def date(self):
968 def date(self):
969 t, tz = self._changectx.date()
969 t, tz = self._changectx.date()
970 try:
970 try:
971 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
971 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
972 except OSError, err:
972 except OSError, err:
973 if err.errno != errno.ENOENT:
973 if err.errno != errno.ENOENT:
974 raise
974 raise
975 return (t, tz)
975 return (t, tz)
976
976
977 def cmp(self, fctx):
977 def cmp(self, fctx):
978 """compare with other file context
978 """compare with other file context
979
979
980 returns True if different than fctx.
980 returns True if different than fctx.
981 """
981 """
982 # fctx should be a filectx (not a wfctx)
982 # fctx should be a filectx (not a wfctx)
983 # invert comparison to reuse the same code path
983 # invert comparison to reuse the same code path
984 return fctx.cmp(self)
984 return fctx.cmp(self)
985
985
986 class memctx(object):
986 class memctx(object):
987 """Use memctx to perform in-memory commits via localrepo.commitctx().
987 """Use memctx to perform in-memory commits via localrepo.commitctx().
988
988
989 Revision information is supplied at initialization time while
989 Revision information is supplied at initialization time while
990 related files data and is made available through a callback
990 related files data and is made available through a callback
991 mechanism. 'repo' is the current localrepo, 'parents' is a
991 mechanism. 'repo' is the current localrepo, 'parents' is a
992 sequence of two parent revisions identifiers (pass None for every
992 sequence of two parent revisions identifiers (pass None for every
993 missing parent), 'text' is the commit message and 'files' lists
993 missing parent), 'text' is the commit message and 'files' lists
994 names of files touched by the revision (normalized and relative to
994 names of files touched by the revision (normalized and relative to
995 repository root).
995 repository root).
996
996
997 filectxfn(repo, memctx, path) is a callable receiving the
997 filectxfn(repo, memctx, path) is a callable receiving the
998 repository, the current memctx object and the normalized path of
998 repository, the current memctx object and the normalized path of
999 requested file, relative to repository root. It is fired by the
999 requested file, relative to repository root. It is fired by the
1000 commit function for every file in 'files', but calls order is
1000 commit function for every file in 'files', but calls order is
1001 undefined. If the file is available in the revision being
1001 undefined. If the file is available in the revision being
1002 committed (updated or added), filectxfn returns a memfilectx
1002 committed (updated or added), filectxfn returns a memfilectx
1003 object. If the file was removed, filectxfn raises an
1003 object. If the file was removed, filectxfn raises an
1004 IOError. Moved files are represented by marking the source file
1004 IOError. Moved files are represented by marking the source file
1005 removed and the new file added with copy information (see
1005 removed and the new file added with copy information (see
1006 memfilectx).
1006 memfilectx).
1007
1007
1008 user receives the committer name and defaults to current
1008 user receives the committer name and defaults to current
1009 repository username, date is the commit date in any format
1009 repository username, date is the commit date in any format
1010 supported by util.parsedate() and defaults to current date, extra
1010 supported by util.parsedate() and defaults to current date, extra
1011 is a dictionary of metadata or is left empty.
1011 is a dictionary of metadata or is left empty.
1012 """
1012 """
1013 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1013 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1014 date=None, extra=None):
1014 date=None, extra=None):
1015 self._repo = repo
1015 self._repo = repo
1016 self._rev = None
1016 self._rev = None
1017 self._node = None
1017 self._node = None
1018 self._text = text
1018 self._text = text
1019 self._date = date and util.parsedate(date) or util.makedate()
1019 self._date = date and util.parsedate(date) or util.makedate()
1020 self._user = user
1020 self._user = user
1021 parents = [(p or nullid) for p in parents]
1021 parents = [(p or nullid) for p in parents]
1022 p1, p2 = parents
1022 p1, p2 = parents
1023 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1023 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1024 files = sorted(set(files))
1024 files = sorted(set(files))
1025 self._status = [files, [], [], [], []]
1025 self._status = [files, [], [], [], []]
1026 self._filectxfn = filectxfn
1026 self._filectxfn = filectxfn
1027
1027
1028 self._extra = extra and extra.copy() or {}
1028 self._extra = extra and extra.copy() or {}
1029 if 'branch' not in self._extra:
1029 if 'branch' not in self._extra:
1030 self._extra['branch'] = 'default'
1030 self._extra['branch'] = 'default'
1031 elif self._extra.get('branch') == '':
1031 elif self._extra.get('branch') == '':
1032 self._extra['branch'] = 'default'
1032 self._extra['branch'] = 'default'
1033
1033
1034 def __str__(self):
1034 def __str__(self):
1035 return str(self._parents[0]) + "+"
1035 return str(self._parents[0]) + "+"
1036
1036
1037 def __int__(self):
1037 def __int__(self):
1038 return self._rev
1038 return self._rev
1039
1039
1040 def __nonzero__(self):
1040 def __nonzero__(self):
1041 return True
1041 return True
1042
1042
1043 def __getitem__(self, key):
1043 def __getitem__(self, key):
1044 return self.filectx(key)
1044 return self.filectx(key)
1045
1045
1046 def p1(self):
1046 def p1(self):
1047 return self._parents[0]
1047 return self._parents[0]
1048 def p2(self):
1048 def p2(self):
1049 return self._parents[1]
1049 return self._parents[1]
1050
1050
1051 def user(self):
1051 def user(self):
1052 return self._user or self._repo.ui.username()
1052 return self._user or self._repo.ui.username()
1053 def date(self):
1053 def date(self):
1054 return self._date
1054 return self._date
1055 def description(self):
1055 def description(self):
1056 return self._text
1056 return self._text
1057 def files(self):
1057 def files(self):
1058 return self.modified()
1058 return self.modified()
1059 def modified(self):
1059 def modified(self):
1060 return self._status[0]
1060 return self._status[0]
1061 def added(self):
1061 def added(self):
1062 return self._status[1]
1062 return self._status[1]
1063 def removed(self):
1063 def removed(self):
1064 return self._status[2]
1064 return self._status[2]
1065 def deleted(self):
1065 def deleted(self):
1066 return self._status[3]
1066 return self._status[3]
1067 def unknown(self):
1067 def unknown(self):
1068 return self._status[4]
1068 return self._status[4]
1069 def ignored(self):
1069 def ignored(self):
1070 return self._status[5]
1070 return self._status[5]
1071 def clean(self):
1071 def clean(self):
1072 return self._status[6]
1072 return self._status[6]
1073 def branch(self):
1073 def branch(self):
1074 return encoding.tolocal(self._extra['branch'])
1074 return encoding.tolocal(self._extra['branch'])
1075 def extra(self):
1075 def extra(self):
1076 return self._extra
1076 return self._extra
1077 def flags(self, f):
1077 def flags(self, f):
1078 return self[f].flags()
1078 return self[f].flags()
1079
1079
1080 def parents(self):
1080 def parents(self):
1081 """return contexts for each parent changeset"""
1081 """return contexts for each parent changeset"""
1082 return self._parents
1082 return self._parents
1083
1083
1084 def filectx(self, path, filelog=None):
1084 def filectx(self, path, filelog=None):
1085 """get a file context from the working directory"""
1085 """get a file context from the working directory"""
1086 return self._filectxfn(self._repo, self, path)
1086 return self._filectxfn(self._repo, self, path)
1087
1087
1088 def commit(self):
1088 def commit(self):
1089 """commit context to the repo"""
1089 """commit context to the repo"""
1090 return self._repo.commitctx(self)
1090 return self._repo.commitctx(self)
1091
1091
1092 class memfilectx(object):
1092 class memfilectx(object):
1093 """memfilectx represents an in-memory file to commit.
1093 """memfilectx represents an in-memory file to commit.
1094
1094
1095 See memctx for more details.
1095 See memctx for more details.
1096 """
1096 """
1097 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1097 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1098 """
1098 """
1099 path is the normalized file path relative to repository root.
1099 path is the normalized file path relative to repository root.
1100 data is the file content as a string.
1100 data is the file content as a string.
1101 islink is True if the file is a symbolic link.
1101 islink is True if the file is a symbolic link.
1102 isexec is True if the file is executable.
1102 isexec is True if the file is executable.
1103 copied is the source file path if current file was copied in the
1103 copied is the source file path if current file was copied in the
1104 revision being committed, or None."""
1104 revision being committed, or None."""
1105 self._path = path
1105 self._path = path
1106 self._data = data
1106 self._data = data
1107 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1107 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1108 self._copied = None
1108 self._copied = None
1109 if copied:
1109 if copied:
1110 self._copied = (copied, nullid)
1110 self._copied = (copied, nullid)
1111
1111
1112 def __nonzero__(self):
1112 def __nonzero__(self):
1113 return True
1113 return True
1114 def __str__(self):
1114 def __str__(self):
1115 return "%s@%s" % (self.path(), self._changectx)
1115 return "%s@%s" % (self.path(), self._changectx)
1116 def path(self):
1116 def path(self):
1117 return self._path
1117 return self._path
1118 def data(self):
1118 def data(self):
1119 return self._data
1119 return self._data
1120 def flags(self):
1120 def flags(self):
1121 return self._flags
1121 return self._flags
1122 def isexec(self):
1122 def isexec(self):
1123 return 'x' in self._flags
1123 return 'x' in self._flags
1124 def islink(self):
1124 def islink(self):
1125 return 'l' in self._flags
1125 return 'l' in self._flags
1126 def renamed(self):
1126 def renamed(self):
1127 return self._copied
1127 return self._copied
@@ -1,724 +1,721 b''
1 # dirstate.py - working directory tracking for mercurial
1 # dirstate.py - working directory tracking 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 nullid
8 from node import nullid
9 from i18n import _
9 from i18n import _
10 import scmutil, util, ignore, osutil, parsers, encoding
10 import scmutil, util, ignore, osutil, parsers, encoding
11 import struct, os, stat, errno
11 import struct, os, stat, errno
12 import cStringIO
12 import cStringIO
13
13
14 _format = ">cllll"
14 _format = ">cllll"
15 propertycache = util.propertycache
15 propertycache = util.propertycache
16
16
17 def _finddirs(path):
17 def _finddirs(path):
18 pos = path.rfind('/')
18 pos = path.rfind('/')
19 while pos != -1:
19 while pos != -1:
20 yield path[:pos]
20 yield path[:pos]
21 pos = path.rfind('/', 0, pos)
21 pos = path.rfind('/', 0, pos)
22
22
23 def _incdirs(dirs, path):
23 def _incdirs(dirs, path):
24 for base in _finddirs(path):
24 for base in _finddirs(path):
25 if base in dirs:
25 if base in dirs:
26 dirs[base] += 1
26 dirs[base] += 1
27 return
27 return
28 dirs[base] = 1
28 dirs[base] = 1
29
29
30 def _decdirs(dirs, path):
30 def _decdirs(dirs, path):
31 for base in _finddirs(path):
31 for base in _finddirs(path):
32 if dirs[base] > 1:
32 if dirs[base] > 1:
33 dirs[base] -= 1
33 dirs[base] -= 1
34 return
34 return
35 del dirs[base]
35 del dirs[base]
36
36
37 class dirstate(object):
37 class dirstate(object):
38
38
39 def __init__(self, opener, ui, root, validate):
39 def __init__(self, opener, ui, root, validate):
40 '''Create a new dirstate object.
40 '''Create a new dirstate object.
41
41
42 opener is an open()-like callable that can be used to open the
42 opener is an open()-like callable that can be used to open the
43 dirstate file; root is the root of the directory tracked by
43 dirstate file; root is the root of the directory tracked by
44 the dirstate.
44 the dirstate.
45 '''
45 '''
46 self._opener = opener
46 self._opener = opener
47 self._validate = validate
47 self._validate = validate
48 self._root = root
48 self._root = root
49 self._rootdir = os.path.join(root, '')
49 self._rootdir = os.path.join(root, '')
50 self._dirty = False
50 self._dirty = False
51 self._dirtypl = False
51 self._dirtypl = False
52 self._lastnormaltime = None
52 self._lastnormaltime = None
53 self._ui = ui
53 self._ui = ui
54
54
55 @propertycache
55 @propertycache
56 def _map(self):
56 def _map(self):
57 '''Return the dirstate contents as a map from filename to
57 '''Return the dirstate contents as a map from filename to
58 (state, mode, size, time).'''
58 (state, mode, size, time).'''
59 self._read()
59 self._read()
60 return self._map
60 return self._map
61
61
62 @propertycache
62 @propertycache
63 def _copymap(self):
63 def _copymap(self):
64 self._read()
64 self._read()
65 return self._copymap
65 return self._copymap
66
66
67 @propertycache
67 @propertycache
68 def _foldmap(self):
68 def _foldmap(self):
69 f = {}
69 f = {}
70 for name in self._map:
70 for name in self._map:
71 f[os.path.normcase(name)] = name
71 f[os.path.normcase(name)] = name
72 return f
72 return f
73
73
74 @propertycache
74 @propertycache
75 def _branch(self):
75 def _branch(self):
76 try:
76 try:
77 return self._opener.read("branch").strip() or "default"
77 return self._opener.read("branch").strip() or "default"
78 except IOError:
78 except IOError:
79 return "default"
79 return "default"
80
80
81 @propertycache
81 @propertycache
82 def _pl(self):
82 def _pl(self):
83 try:
83 try:
84 fp = self._opener("dirstate")
84 fp = self._opener("dirstate")
85 st = fp.read(40)
85 st = fp.read(40)
86 fp.close()
86 fp.close()
87 l = len(st)
87 l = len(st)
88 if l == 40:
88 if l == 40:
89 return st[:20], st[20:40]
89 return st[:20], st[20:40]
90 elif l > 0 and l < 40:
90 elif l > 0 and l < 40:
91 raise util.Abort(_('working directory state appears damaged!'))
91 raise util.Abort(_('working directory state appears damaged!'))
92 except IOError, err:
92 except IOError, err:
93 if err.errno != errno.ENOENT:
93 if err.errno != errno.ENOENT:
94 raise
94 raise
95 return [nullid, nullid]
95 return [nullid, nullid]
96
96
97 @propertycache
97 @propertycache
98 def _dirs(self):
98 def _dirs(self):
99 dirs = {}
99 dirs = {}
100 for f, s in self._map.iteritems():
100 for f, s in self._map.iteritems():
101 if s[0] != 'r':
101 if s[0] != 'r':
102 _incdirs(dirs, f)
102 _incdirs(dirs, f)
103 return dirs
103 return dirs
104
104
105 @propertycache
105 @propertycache
106 def _ignore(self):
106 def _ignore(self):
107 files = [self._join('.hgignore')]
107 files = [self._join('.hgignore')]
108 for name, path in self._ui.configitems("ui"):
108 for name, path in self._ui.configitems("ui"):
109 if name == 'ignore' or name.startswith('ignore.'):
109 if name == 'ignore' or name.startswith('ignore.'):
110 files.append(util.expandpath(path))
110 files.append(util.expandpath(path))
111 return ignore.ignore(self._root, files, self._ui.warn)
111 return ignore.ignore(self._root, files, self._ui.warn)
112
112
113 @propertycache
113 @propertycache
114 def _slash(self):
114 def _slash(self):
115 return self._ui.configbool('ui', 'slash') and os.sep != '/'
115 return self._ui.configbool('ui', 'slash') and os.sep != '/'
116
116
117 @propertycache
117 @propertycache
118 def _checklink(self):
118 def _checklink(self):
119 return util.checklink(self._root)
119 return util.checklink(self._root)
120
120
121 @propertycache
121 @propertycache
122 def _checkexec(self):
122 def _checkexec(self):
123 return util.checkexec(self._root)
123 return util.checkexec(self._root)
124
124
125 @propertycache
125 @propertycache
126 def _checkcase(self):
126 def _checkcase(self):
127 return not util.checkcase(self._join('.hg'))
127 return not util.checkcase(self._join('.hg'))
128
128
129 def _join(self, f):
129 def _join(self, f):
130 # much faster than os.path.join()
130 # much faster than os.path.join()
131 # it's safe because f is always a relative path
131 # it's safe because f is always a relative path
132 return self._rootdir + f
132 return self._rootdir + f
133
133
134 def flagfunc(self, fallback):
134 def flagfunc(self, fallback):
135 if self._checklink:
135 if self._checklink:
136 if self._checkexec:
136 if self._checkexec:
137 def f(x):
137 def f(x):
138 p = self._join(x)
138 p = self._join(x)
139 if os.path.islink(p):
139 if os.path.islink(p):
140 return 'l'
140 return 'l'
141 if util.isexec(p):
141 if util.isexec(p):
142 return 'x'
142 return 'x'
143 return ''
143 return ''
144 return f
144 return f
145 def f(x):
145 def f(x):
146 if os.path.islink(self._join(x)):
146 if os.path.islink(self._join(x)):
147 return 'l'
147 return 'l'
148 if 'x' in fallback(x):
148 if 'x' in fallback(x):
149 return 'x'
149 return 'x'
150 return ''
150 return ''
151 return f
151 return f
152 if self._checkexec:
152 if self._checkexec:
153 def f(x):
153 def f(x):
154 if 'l' in fallback(x):
154 if 'l' in fallback(x):
155 return 'l'
155 return 'l'
156 if util.isexec(self._join(x)):
156 if util.isexec(self._join(x)):
157 return 'x'
157 return 'x'
158 return ''
158 return ''
159 return f
159 return f
160 return fallback
160 return fallback
161
161
162 def getcwd(self):
162 def getcwd(self):
163 cwd = os.getcwd()
163 cwd = os.getcwd()
164 if cwd == self._root:
164 if cwd == self._root:
165 return ''
165 return ''
166 # self._root ends with a path separator if self._root is '/' or 'C:\'
166 # self._root ends with a path separator if self._root is '/' or 'C:\'
167 rootsep = self._root
167 rootsep = self._root
168 if not util.endswithsep(rootsep):
168 if not util.endswithsep(rootsep):
169 rootsep += os.sep
169 rootsep += os.sep
170 if cwd.startswith(rootsep):
170 if cwd.startswith(rootsep):
171 return cwd[len(rootsep):]
171 return cwd[len(rootsep):]
172 else:
172 else:
173 # we're outside the repo. return an absolute path.
173 # we're outside the repo. return an absolute path.
174 return cwd
174 return cwd
175
175
176 def pathto(self, f, cwd=None):
176 def pathto(self, f, cwd=None):
177 if cwd is None:
177 if cwd is None:
178 cwd = self.getcwd()
178 cwd = self.getcwd()
179 path = util.pathto(self._root, cwd, f)
179 path = util.pathto(self._root, cwd, f)
180 if self._slash:
180 if self._slash:
181 return util.normpath(path)
181 return util.normpath(path)
182 return path
182 return path
183
183
184 def __getitem__(self, key):
184 def __getitem__(self, key):
185 '''Return the current state of key (a filename) in the dirstate.
185 '''Return the current state of key (a filename) in the dirstate.
186
186
187 States are:
187 States are:
188 n normal
188 n normal
189 m needs merging
189 m needs merging
190 r marked for removal
190 r marked for removal
191 a marked for addition
191 a marked for addition
192 ? not tracked
192 ? not tracked
193 '''
193 '''
194 return self._map.get(key, ("?",))[0]
194 return self._map.get(key, ("?",))[0]
195
195
196 def __contains__(self, key):
196 def __contains__(self, key):
197 return key in self._map
197 return key in self._map
198
198
199 def __iter__(self):
199 def __iter__(self):
200 for x in sorted(self._map):
200 for x in sorted(self._map):
201 yield x
201 yield x
202
202
203 def parents(self):
203 def parents(self):
204 return [self._validate(p) for p in self._pl]
204 return [self._validate(p) for p in self._pl]
205
205
206 def p1(self):
206 def p1(self):
207 return self._validate(self._pl[0])
207 return self._validate(self._pl[0])
208
208
209 def p2(self):
209 def p2(self):
210 return self._validate(self._pl[1])
210 return self._validate(self._pl[1])
211
211
212 def branch(self):
212 def branch(self):
213 return encoding.tolocal(self._branch)
213 return encoding.tolocal(self._branch)
214
214
215 def setparents(self, p1, p2=nullid):
215 def setparents(self, p1, p2=nullid):
216 self._dirty = self._dirtypl = True
216 self._dirty = self._dirtypl = True
217 self._pl = p1, p2
217 self._pl = p1, p2
218
218
219 def setbranch(self, branch):
219 def setbranch(self, branch):
220 if branch in ['tip', '.', 'null']:
220 if branch in ['tip', '.', 'null']:
221 raise util.Abort(_('the name \'%s\' is reserved') % branch)
221 raise util.Abort(_('the name \'%s\' is reserved') % branch)
222 self._branch = encoding.fromlocal(branch)
222 self._branch = encoding.fromlocal(branch)
223 self._opener.write("branch", self._branch + '\n')
223 self._opener.write("branch", self._branch + '\n')
224
224
225 def _read(self):
225 def _read(self):
226 self._map = {}
226 self._map = {}
227 self._copymap = {}
227 self._copymap = {}
228 try:
228 try:
229 st = self._opener.read("dirstate")
229 st = self._opener.read("dirstate")
230 except IOError, err:
230 except IOError, err:
231 if err.errno != errno.ENOENT:
231 if err.errno != errno.ENOENT:
232 raise
232 raise
233 return
233 return
234 if not st:
234 if not st:
235 return
235 return
236
236
237 p = parsers.parse_dirstate(self._map, self._copymap, st)
237 p = parsers.parse_dirstate(self._map, self._copymap, st)
238 if not self._dirtypl:
238 if not self._dirtypl:
239 self._pl = p
239 self._pl = p
240
240
241 def invalidate(self):
241 def invalidate(self):
242 for a in ("_map", "_copymap", "_foldmap", "_branch", "_pl", "_dirs",
242 for a in ("_map", "_copymap", "_foldmap", "_branch", "_pl", "_dirs",
243 "_ignore"):
243 "_ignore"):
244 if a in self.__dict__:
244 if a in self.__dict__:
245 delattr(self, a)
245 delattr(self, a)
246 self._lastnormaltime = None
246 self._lastnormaltime = None
247 self._dirty = False
247 self._dirty = False
248
248
249 def copy(self, source, dest):
249 def copy(self, source, dest):
250 """Mark dest as a copy of source. Unmark dest if source is None."""
250 """Mark dest as a copy of source. Unmark dest if source is None."""
251 if source == dest:
251 if source == dest:
252 return
252 return
253 self._dirty = True
253 self._dirty = True
254 if source is not None:
254 if source is not None:
255 self._copymap[dest] = source
255 self._copymap[dest] = source
256 elif dest in self._copymap:
256 elif dest in self._copymap:
257 del self._copymap[dest]
257 del self._copymap[dest]
258
258
259 def copied(self, file):
259 def copied(self, file):
260 return self._copymap.get(file, None)
260 return self._copymap.get(file, None)
261
261
262 def copies(self):
262 def copies(self):
263 return self._copymap
263 return self._copymap
264
264
265 def _droppath(self, f):
265 def _droppath(self, f):
266 if self[f] not in "?r" and "_dirs" in self.__dict__:
266 if self[f] not in "?r" and "_dirs" in self.__dict__:
267 _decdirs(self._dirs, f)
267 _decdirs(self._dirs, f)
268
268
269 def _addpath(self, f, check=False):
269 def _addpath(self, f, check=False):
270 oldstate = self[f]
270 oldstate = self[f]
271 if check or oldstate == "r":
271 if check or oldstate == "r":
272 scmutil.checkfilename(f)
272 scmutil.checkfilename(f)
273 if f in self._dirs:
273 if f in self._dirs:
274 raise util.Abort(_('directory %r already in dirstate') % f)
274 raise util.Abort(_('directory %r already in dirstate') % f)
275 # shadows
275 # shadows
276 for d in _finddirs(f):
276 for d in _finddirs(f):
277 if d in self._dirs:
277 if d in self._dirs:
278 break
278 break
279 if d in self._map and self[d] != 'r':
279 if d in self._map and self[d] != 'r':
280 raise util.Abort(
280 raise util.Abort(
281 _('file %r in dirstate clashes with %r') % (d, f))
281 _('file %r in dirstate clashes with %r') % (d, f))
282 if oldstate in "?r" and "_dirs" in self.__dict__:
282 if oldstate in "?r" and "_dirs" in self.__dict__:
283 _incdirs(self._dirs, f)
283 _incdirs(self._dirs, f)
284
284
285 def normal(self, f):
285 def normal(self, f):
286 '''Mark a file normal and clean.'''
286 '''Mark a file normal and clean.'''
287 self._dirty = True
287 self._dirty = True
288 self._addpath(f)
288 self._addpath(f)
289 s = os.lstat(self._join(f))
289 s = os.lstat(self._join(f))
290 mtime = int(s.st_mtime)
290 mtime = int(s.st_mtime)
291 self._map[f] = ('n', s.st_mode, s.st_size, mtime)
291 self._map[f] = ('n', s.st_mode, s.st_size, mtime)
292 if f in self._copymap:
292 if f in self._copymap:
293 del self._copymap[f]
293 del self._copymap[f]
294 if mtime > self._lastnormaltime:
294 if mtime > self._lastnormaltime:
295 # Remember the most recent modification timeslot for status(),
295 # Remember the most recent modification timeslot for status(),
296 # to make sure we won't miss future size-preserving file content
296 # to make sure we won't miss future size-preserving file content
297 # modifications that happen within the same timeslot.
297 # modifications that happen within the same timeslot.
298 self._lastnormaltime = mtime
298 self._lastnormaltime = mtime
299
299
300 def normallookup(self, f):
300 def normallookup(self, f):
301 '''Mark a file normal, but possibly dirty.'''
301 '''Mark a file normal, but possibly dirty.'''
302 if self._pl[1] != nullid and f in self._map:
302 if self._pl[1] != nullid and f in self._map:
303 # if there is a merge going on and the file was either
303 # if there is a merge going on and the file was either
304 # in state 'm' (-1) or coming from other parent (-2) before
304 # in state 'm' (-1) or coming from other parent (-2) before
305 # being removed, restore that state.
305 # being removed, restore that state.
306 entry = self._map[f]
306 entry = self._map[f]
307 if entry[0] == 'r' and entry[2] in (-1, -2):
307 if entry[0] == 'r' and entry[2] in (-1, -2):
308 source = self._copymap.get(f)
308 source = self._copymap.get(f)
309 if entry[2] == -1:
309 if entry[2] == -1:
310 self.merge(f)
310 self.merge(f)
311 elif entry[2] == -2:
311 elif entry[2] == -2:
312 self.otherparent(f)
312 self.otherparent(f)
313 if source:
313 if source:
314 self.copy(source, f)
314 self.copy(source, f)
315 return
315 return
316 if entry[0] == 'm' or entry[0] == 'n' and entry[2] == -2:
316 if entry[0] == 'm' or entry[0] == 'n' and entry[2] == -2:
317 return
317 return
318 self._dirty = True
318 self._dirty = True
319 self._addpath(f)
319 self._addpath(f)
320 self._map[f] = ('n', 0, -1, -1)
320 self._map[f] = ('n', 0, -1, -1)
321 if f in self._copymap:
321 if f in self._copymap:
322 del self._copymap[f]
322 del self._copymap[f]
323
323
324 def otherparent(self, f):
324 def otherparent(self, f):
325 '''Mark as coming from the other parent, always dirty.'''
325 '''Mark as coming from the other parent, always dirty.'''
326 if self._pl[1] == nullid:
326 if self._pl[1] == nullid:
327 raise util.Abort(_("setting %r to other parent "
327 raise util.Abort(_("setting %r to other parent "
328 "only allowed in merges") % f)
328 "only allowed in merges") % f)
329 self._dirty = True
329 self._dirty = True
330 self._addpath(f)
330 self._addpath(f)
331 self._map[f] = ('n', 0, -2, -1)
331 self._map[f] = ('n', 0, -2, -1)
332 if f in self._copymap:
332 if f in self._copymap:
333 del self._copymap[f]
333 del self._copymap[f]
334
334
335 def add(self, f):
335 def add(self, f):
336 '''Mark a file added.'''
336 '''Mark a file added.'''
337 self._dirty = True
337 self._dirty = True
338 self._addpath(f, True)
338 self._addpath(f, True)
339 self._map[f] = ('a', 0, -1, -1)
339 self._map[f] = ('a', 0, -1, -1)
340 if f in self._copymap:
340 if f in self._copymap:
341 del self._copymap[f]
341 del self._copymap[f]
342
342
343 def remove(self, f):
343 def remove(self, f):
344 '''Mark a file removed.'''
344 '''Mark a file removed.'''
345 self._dirty = True
345 self._dirty = True
346 self._droppath(f)
346 self._droppath(f)
347 size = 0
347 size = 0
348 if self._pl[1] != nullid and f in self._map:
348 if self._pl[1] != nullid and f in self._map:
349 # backup the previous state
349 # backup the previous state
350 entry = self._map[f]
350 entry = self._map[f]
351 if entry[0] == 'm': # merge
351 if entry[0] == 'm': # merge
352 size = -1
352 size = -1
353 elif entry[0] == 'n' and entry[2] == -2: # other parent
353 elif entry[0] == 'n' and entry[2] == -2: # other parent
354 size = -2
354 size = -2
355 self._map[f] = ('r', 0, size, 0)
355 self._map[f] = ('r', 0, size, 0)
356 if size == 0 and f in self._copymap:
356 if size == 0 and f in self._copymap:
357 del self._copymap[f]
357 del self._copymap[f]
358
358
359 def merge(self, f):
359 def merge(self, f):
360 '''Mark a file merged.'''
360 '''Mark a file merged.'''
361 self._dirty = True
361 self._dirty = True
362 s = os.lstat(self._join(f))
362 s = os.lstat(self._join(f))
363 self._addpath(f)
363 self._addpath(f)
364 self._map[f] = ('m', s.st_mode, s.st_size, int(s.st_mtime))
364 self._map[f] = ('m', s.st_mode, s.st_size, int(s.st_mtime))
365 if f in self._copymap:
365 if f in self._copymap:
366 del self._copymap[f]
366 del self._copymap[f]
367
367
368 def forget(self, f):
368 def drop(self, f):
369 '''Forget a file.'''
369 '''Drop a file from the dirstate'''
370 self._dirty = True
370 self._dirty = True
371 try:
371 self._droppath(f)
372 self._droppath(f)
372 del self._map[f]
373 del self._map[f]
374 except KeyError:
375 self._ui.warn(_("not in dirstate: %s\n") % f)
376
373
377 def _normalize(self, path, isknown):
374 def _normalize(self, path, isknown):
378 normed = os.path.normcase(path)
375 normed = os.path.normcase(path)
379 folded = self._foldmap.get(normed, None)
376 folded = self._foldmap.get(normed, None)
380 if folded is None:
377 if folded is None:
381 if isknown or not os.path.lexists(os.path.join(self._root, path)):
378 if isknown or not os.path.lexists(os.path.join(self._root, path)):
382 folded = path
379 folded = path
383 else:
380 else:
384 folded = self._foldmap.setdefault(normed,
381 folded = self._foldmap.setdefault(normed,
385 util.fspath(path, self._root))
382 util.fspath(path, self._root))
386 return folded
383 return folded
387
384
388 def normalize(self, path, isknown=False):
385 def normalize(self, path, isknown=False):
389 '''
386 '''
390 normalize the case of a pathname when on a casefolding filesystem
387 normalize the case of a pathname when on a casefolding filesystem
391
388
392 isknown specifies whether the filename came from walking the
389 isknown specifies whether the filename came from walking the
393 disk, to avoid extra filesystem access
390 disk, to avoid extra filesystem access
394
391
395 The normalized case is determined based on the following precedence:
392 The normalized case is determined based on the following precedence:
396
393
397 - version of name already stored in the dirstate
394 - version of name already stored in the dirstate
398 - version of name stored on disk
395 - version of name stored on disk
399 - version provided via command arguments
396 - version provided via command arguments
400 '''
397 '''
401
398
402 if self._checkcase:
399 if self._checkcase:
403 return self._normalize(path, isknown)
400 return self._normalize(path, isknown)
404 return path
401 return path
405
402
406 def clear(self):
403 def clear(self):
407 self._map = {}
404 self._map = {}
408 if "_dirs" in self.__dict__:
405 if "_dirs" in self.__dict__:
409 delattr(self, "_dirs")
406 delattr(self, "_dirs")
410 self._copymap = {}
407 self._copymap = {}
411 self._pl = [nullid, nullid]
408 self._pl = [nullid, nullid]
412 self._lastnormaltime = None
409 self._lastnormaltime = None
413 self._dirty = True
410 self._dirty = True
414
411
415 def rebuild(self, parent, files):
412 def rebuild(self, parent, files):
416 self.clear()
413 self.clear()
417 for f in files:
414 for f in files:
418 if 'x' in files.flags(f):
415 if 'x' in files.flags(f):
419 self._map[f] = ('n', 0777, -1, 0)
416 self._map[f] = ('n', 0777, -1, 0)
420 else:
417 else:
421 self._map[f] = ('n', 0666, -1, 0)
418 self._map[f] = ('n', 0666, -1, 0)
422 self._pl = (parent, nullid)
419 self._pl = (parent, nullid)
423 self._dirty = True
420 self._dirty = True
424
421
425 def write(self):
422 def write(self):
426 if not self._dirty:
423 if not self._dirty:
427 return
424 return
428 st = self._opener("dirstate", "w", atomictemp=True)
425 st = self._opener("dirstate", "w", atomictemp=True)
429
426
430 # use the modification time of the newly created temporary file as the
427 # use the modification time of the newly created temporary file as the
431 # filesystem's notion of 'now'
428 # filesystem's notion of 'now'
432 now = int(util.fstat(st).st_mtime)
429 now = int(util.fstat(st).st_mtime)
433
430
434 cs = cStringIO.StringIO()
431 cs = cStringIO.StringIO()
435 copymap = self._copymap
432 copymap = self._copymap
436 pack = struct.pack
433 pack = struct.pack
437 write = cs.write
434 write = cs.write
438 write("".join(self._pl))
435 write("".join(self._pl))
439 for f, e in self._map.iteritems():
436 for f, e in self._map.iteritems():
440 if e[0] == 'n' and e[3] == now:
437 if e[0] == 'n' and e[3] == now:
441 # The file was last modified "simultaneously" with the current
438 # The file was last modified "simultaneously" with the current
442 # write to dirstate (i.e. within the same second for file-
439 # write to dirstate (i.e. within the same second for file-
443 # systems with a granularity of 1 sec). This commonly happens
440 # systems with a granularity of 1 sec). This commonly happens
444 # for at least a couple of files on 'update'.
441 # for at least a couple of files on 'update'.
445 # The user could change the file without changing its size
442 # The user could change the file without changing its size
446 # within the same second. Invalidate the file's stat data in
443 # within the same second. Invalidate the file's stat data in
447 # dirstate, forcing future 'status' calls to compare the
444 # dirstate, forcing future 'status' calls to compare the
448 # contents of the file. This prevents mistakenly treating such
445 # contents of the file. This prevents mistakenly treating such
449 # files as clean.
446 # files as clean.
450 e = (e[0], 0, -1, -1) # mark entry as 'unset'
447 e = (e[0], 0, -1, -1) # mark entry as 'unset'
451 self._map[f] = e
448 self._map[f] = e
452
449
453 if f in copymap:
450 if f in copymap:
454 f = "%s\0%s" % (f, copymap[f])
451 f = "%s\0%s" % (f, copymap[f])
455 e = pack(_format, e[0], e[1], e[2], e[3], len(f))
452 e = pack(_format, e[0], e[1], e[2], e[3], len(f))
456 write(e)
453 write(e)
457 write(f)
454 write(f)
458 st.write(cs.getvalue())
455 st.write(cs.getvalue())
459 st.rename()
456 st.rename()
460 self._lastnormaltime = None
457 self._lastnormaltime = None
461 self._dirty = self._dirtypl = False
458 self._dirty = self._dirtypl = False
462
459
463 def _dirignore(self, f):
460 def _dirignore(self, f):
464 if f == '.':
461 if f == '.':
465 return False
462 return False
466 if self._ignore(f):
463 if self._ignore(f):
467 return True
464 return True
468 for p in _finddirs(f):
465 for p in _finddirs(f):
469 if self._ignore(p):
466 if self._ignore(p):
470 return True
467 return True
471 return False
468 return False
472
469
473 def walk(self, match, subrepos, unknown, ignored):
470 def walk(self, match, subrepos, unknown, ignored):
474 '''
471 '''
475 Walk recursively through the directory tree, finding all files
472 Walk recursively through the directory tree, finding all files
476 matched by match.
473 matched by match.
477
474
478 Return a dict mapping filename to stat-like object (either
475 Return a dict mapping filename to stat-like object (either
479 mercurial.osutil.stat instance or return value of os.stat()).
476 mercurial.osutil.stat instance or return value of os.stat()).
480 '''
477 '''
481
478
482 def fwarn(f, msg):
479 def fwarn(f, msg):
483 self._ui.warn('%s: %s\n' % (self.pathto(f), msg))
480 self._ui.warn('%s: %s\n' % (self.pathto(f), msg))
484 return False
481 return False
485
482
486 def badtype(mode):
483 def badtype(mode):
487 kind = _('unknown')
484 kind = _('unknown')
488 if stat.S_ISCHR(mode):
485 if stat.S_ISCHR(mode):
489 kind = _('character device')
486 kind = _('character device')
490 elif stat.S_ISBLK(mode):
487 elif stat.S_ISBLK(mode):
491 kind = _('block device')
488 kind = _('block device')
492 elif stat.S_ISFIFO(mode):
489 elif stat.S_ISFIFO(mode):
493 kind = _('fifo')
490 kind = _('fifo')
494 elif stat.S_ISSOCK(mode):
491 elif stat.S_ISSOCK(mode):
495 kind = _('socket')
492 kind = _('socket')
496 elif stat.S_ISDIR(mode):
493 elif stat.S_ISDIR(mode):
497 kind = _('directory')
494 kind = _('directory')
498 return _('unsupported file type (type is %s)') % kind
495 return _('unsupported file type (type is %s)') % kind
499
496
500 ignore = self._ignore
497 ignore = self._ignore
501 dirignore = self._dirignore
498 dirignore = self._dirignore
502 if ignored:
499 if ignored:
503 ignore = util.never
500 ignore = util.never
504 dirignore = util.never
501 dirignore = util.never
505 elif not unknown:
502 elif not unknown:
506 # if unknown and ignored are False, skip step 2
503 # if unknown and ignored are False, skip step 2
507 ignore = util.always
504 ignore = util.always
508 dirignore = util.always
505 dirignore = util.always
509
506
510 matchfn = match.matchfn
507 matchfn = match.matchfn
511 badfn = match.bad
508 badfn = match.bad
512 dmap = self._map
509 dmap = self._map
513 normpath = util.normpath
510 normpath = util.normpath
514 listdir = osutil.listdir
511 listdir = osutil.listdir
515 lstat = os.lstat
512 lstat = os.lstat
516 getkind = stat.S_IFMT
513 getkind = stat.S_IFMT
517 dirkind = stat.S_IFDIR
514 dirkind = stat.S_IFDIR
518 regkind = stat.S_IFREG
515 regkind = stat.S_IFREG
519 lnkkind = stat.S_IFLNK
516 lnkkind = stat.S_IFLNK
520 join = self._join
517 join = self._join
521 work = []
518 work = []
522 wadd = work.append
519 wadd = work.append
523
520
524 exact = skipstep3 = False
521 exact = skipstep3 = False
525 if matchfn == match.exact: # match.exact
522 if matchfn == match.exact: # match.exact
526 exact = True
523 exact = True
527 dirignore = util.always # skip step 2
524 dirignore = util.always # skip step 2
528 elif match.files() and not match.anypats(): # match.match, no patterns
525 elif match.files() and not match.anypats(): # match.match, no patterns
529 skipstep3 = True
526 skipstep3 = True
530
527
531 if self._checkcase:
528 if self._checkcase:
532 normalize = self._normalize
529 normalize = self._normalize
533 skipstep3 = False
530 skipstep3 = False
534 else:
531 else:
535 normalize = lambda x, y: x
532 normalize = lambda x, y: x
536
533
537 files = sorted(match.files())
534 files = sorted(match.files())
538 subrepos.sort()
535 subrepos.sort()
539 i, j = 0, 0
536 i, j = 0, 0
540 while i < len(files) and j < len(subrepos):
537 while i < len(files) and j < len(subrepos):
541 subpath = subrepos[j] + "/"
538 subpath = subrepos[j] + "/"
542 if files[i] < subpath:
539 if files[i] < subpath:
543 i += 1
540 i += 1
544 continue
541 continue
545 while i < len(files) and files[i].startswith(subpath):
542 while i < len(files) and files[i].startswith(subpath):
546 del files[i]
543 del files[i]
547 j += 1
544 j += 1
548
545
549 if not files or '.' in files:
546 if not files or '.' in files:
550 files = ['']
547 files = ['']
551 results = dict.fromkeys(subrepos)
548 results = dict.fromkeys(subrepos)
552 results['.hg'] = None
549 results['.hg'] = None
553
550
554 # step 1: find all explicit files
551 # step 1: find all explicit files
555 for ff in files:
552 for ff in files:
556 nf = normalize(normpath(ff), False)
553 nf = normalize(normpath(ff), False)
557 if nf in results:
554 if nf in results:
558 continue
555 continue
559
556
560 try:
557 try:
561 st = lstat(join(nf))
558 st = lstat(join(nf))
562 kind = getkind(st.st_mode)
559 kind = getkind(st.st_mode)
563 if kind == dirkind:
560 if kind == dirkind:
564 skipstep3 = False
561 skipstep3 = False
565 if nf in dmap:
562 if nf in dmap:
566 #file deleted on disk but still in dirstate
563 #file deleted on disk but still in dirstate
567 results[nf] = None
564 results[nf] = None
568 match.dir(nf)
565 match.dir(nf)
569 if not dirignore(nf):
566 if not dirignore(nf):
570 wadd(nf)
567 wadd(nf)
571 elif kind == regkind or kind == lnkkind:
568 elif kind == regkind or kind == lnkkind:
572 results[nf] = st
569 results[nf] = st
573 else:
570 else:
574 badfn(ff, badtype(kind))
571 badfn(ff, badtype(kind))
575 if nf in dmap:
572 if nf in dmap:
576 results[nf] = None
573 results[nf] = None
577 except OSError, inst:
574 except OSError, inst:
578 if nf in dmap: # does it exactly match a file?
575 if nf in dmap: # does it exactly match a file?
579 results[nf] = None
576 results[nf] = None
580 else: # does it match a directory?
577 else: # does it match a directory?
581 prefix = nf + "/"
578 prefix = nf + "/"
582 for fn in dmap:
579 for fn in dmap:
583 if fn.startswith(prefix):
580 if fn.startswith(prefix):
584 match.dir(nf)
581 match.dir(nf)
585 skipstep3 = False
582 skipstep3 = False
586 break
583 break
587 else:
584 else:
588 badfn(ff, inst.strerror)
585 badfn(ff, inst.strerror)
589
586
590 # step 2: visit subdirectories
587 # step 2: visit subdirectories
591 while work:
588 while work:
592 nd = work.pop()
589 nd = work.pop()
593 skip = None
590 skip = None
594 if nd == '.':
591 if nd == '.':
595 nd = ''
592 nd = ''
596 else:
593 else:
597 skip = '.hg'
594 skip = '.hg'
598 try:
595 try:
599 entries = listdir(join(nd), stat=True, skip=skip)
596 entries = listdir(join(nd), stat=True, skip=skip)
600 except OSError, inst:
597 except OSError, inst:
601 if inst.errno == errno.EACCES:
598 if inst.errno == errno.EACCES:
602 fwarn(nd, inst.strerror)
599 fwarn(nd, inst.strerror)
603 continue
600 continue
604 raise
601 raise
605 for f, kind, st in entries:
602 for f, kind, st in entries:
606 nf = normalize(nd and (nd + "/" + f) or f, True)
603 nf = normalize(nd and (nd + "/" + f) or f, True)
607 if nf not in results:
604 if nf not in results:
608 if kind == dirkind:
605 if kind == dirkind:
609 if not ignore(nf):
606 if not ignore(nf):
610 match.dir(nf)
607 match.dir(nf)
611 wadd(nf)
608 wadd(nf)
612 if nf in dmap and matchfn(nf):
609 if nf in dmap and matchfn(nf):
613 results[nf] = None
610 results[nf] = None
614 elif kind == regkind or kind == lnkkind:
611 elif kind == regkind or kind == lnkkind:
615 if nf in dmap:
612 if nf in dmap:
616 if matchfn(nf):
613 if matchfn(nf):
617 results[nf] = st
614 results[nf] = st
618 elif matchfn(nf) and not ignore(nf):
615 elif matchfn(nf) and not ignore(nf):
619 results[nf] = st
616 results[nf] = st
620 elif nf in dmap and matchfn(nf):
617 elif nf in dmap and matchfn(nf):
621 results[nf] = None
618 results[nf] = None
622
619
623 # step 3: report unseen items in the dmap hash
620 # step 3: report unseen items in the dmap hash
624 if not skipstep3 and not exact:
621 if not skipstep3 and not exact:
625 visit = sorted([f for f in dmap if f not in results and matchfn(f)])
622 visit = sorted([f for f in dmap if f not in results and matchfn(f)])
626 for nf, st in zip(visit, util.statfiles([join(i) for i in visit])):
623 for nf, st in zip(visit, util.statfiles([join(i) for i in visit])):
627 if not st is None and not getkind(st.st_mode) in (regkind, lnkkind):
624 if not st is None and not getkind(st.st_mode) in (regkind, lnkkind):
628 st = None
625 st = None
629 results[nf] = st
626 results[nf] = st
630 for s in subrepos:
627 for s in subrepos:
631 del results[s]
628 del results[s]
632 del results['.hg']
629 del results['.hg']
633 return results
630 return results
634
631
635 def status(self, match, subrepos, ignored, clean, unknown):
632 def status(self, match, subrepos, ignored, clean, unknown):
636 '''Determine the status of the working copy relative to the
633 '''Determine the status of the working copy relative to the
637 dirstate and return a tuple of lists (unsure, modified, added,
634 dirstate and return a tuple of lists (unsure, modified, added,
638 removed, deleted, unknown, ignored, clean), where:
635 removed, deleted, unknown, ignored, clean), where:
639
636
640 unsure:
637 unsure:
641 files that might have been modified since the dirstate was
638 files that might have been modified since the dirstate was
642 written, but need to be read to be sure (size is the same
639 written, but need to be read to be sure (size is the same
643 but mtime differs)
640 but mtime differs)
644 modified:
641 modified:
645 files that have definitely been modified since the dirstate
642 files that have definitely been modified since the dirstate
646 was written (different size or mode)
643 was written (different size or mode)
647 added:
644 added:
648 files that have been explicitly added with hg add
645 files that have been explicitly added with hg add
649 removed:
646 removed:
650 files that have been explicitly removed with hg remove
647 files that have been explicitly removed with hg remove
651 deleted:
648 deleted:
652 files that have been deleted through other means ("missing")
649 files that have been deleted through other means ("missing")
653 unknown:
650 unknown:
654 files not in the dirstate that are not ignored
651 files not in the dirstate that are not ignored
655 ignored:
652 ignored:
656 files not in the dirstate that are ignored
653 files not in the dirstate that are ignored
657 (by _dirignore())
654 (by _dirignore())
658 clean:
655 clean:
659 files that have definitely not been modified since the
656 files that have definitely not been modified since the
660 dirstate was written
657 dirstate was written
661 '''
658 '''
662 listignored, listclean, listunknown = ignored, clean, unknown
659 listignored, listclean, listunknown = ignored, clean, unknown
663 lookup, modified, added, unknown, ignored = [], [], [], [], []
660 lookup, modified, added, unknown, ignored = [], [], [], [], []
664 removed, deleted, clean = [], [], []
661 removed, deleted, clean = [], [], []
665
662
666 dmap = self._map
663 dmap = self._map
667 ladd = lookup.append # aka "unsure"
664 ladd = lookup.append # aka "unsure"
668 madd = modified.append
665 madd = modified.append
669 aadd = added.append
666 aadd = added.append
670 uadd = unknown.append
667 uadd = unknown.append
671 iadd = ignored.append
668 iadd = ignored.append
672 radd = removed.append
669 radd = removed.append
673 dadd = deleted.append
670 dadd = deleted.append
674 cadd = clean.append
671 cadd = clean.append
675
672
676 lnkkind = stat.S_IFLNK
673 lnkkind = stat.S_IFLNK
677
674
678 for fn, st in self.walk(match, subrepos, listunknown,
675 for fn, st in self.walk(match, subrepos, listunknown,
679 listignored).iteritems():
676 listignored).iteritems():
680 if fn not in dmap:
677 if fn not in dmap:
681 if (listignored or match.exact(fn)) and self._dirignore(fn):
678 if (listignored or match.exact(fn)) and self._dirignore(fn):
682 if listignored:
679 if listignored:
683 iadd(fn)
680 iadd(fn)
684 elif listunknown:
681 elif listunknown:
685 uadd(fn)
682 uadd(fn)
686 continue
683 continue
687
684
688 state, mode, size, time = dmap[fn]
685 state, mode, size, time = dmap[fn]
689
686
690 if not st and state in "nma":
687 if not st and state in "nma":
691 dadd(fn)
688 dadd(fn)
692 elif state == 'n':
689 elif state == 'n':
693 # The "mode & lnkkind != lnkkind or self._checklink"
690 # The "mode & lnkkind != lnkkind or self._checklink"
694 # lines are an expansion of "islink => checklink"
691 # lines are an expansion of "islink => checklink"
695 # where islink means "is this a link?" and checklink
692 # where islink means "is this a link?" and checklink
696 # means "can we check links?".
693 # means "can we check links?".
697 mtime = int(st.st_mtime)
694 mtime = int(st.st_mtime)
698 if (size >= 0 and
695 if (size >= 0 and
699 (size != st.st_size
696 (size != st.st_size
700 or ((mode ^ st.st_mode) & 0100 and self._checkexec))
697 or ((mode ^ st.st_mode) & 0100 and self._checkexec))
701 and (mode & lnkkind != lnkkind or self._checklink)
698 and (mode & lnkkind != lnkkind or self._checklink)
702 or size == -2 # other parent
699 or size == -2 # other parent
703 or fn in self._copymap):
700 or fn in self._copymap):
704 madd(fn)
701 madd(fn)
705 elif (mtime != time
702 elif (mtime != time
706 and (mode & lnkkind != lnkkind or self._checklink)):
703 and (mode & lnkkind != lnkkind or self._checklink)):
707 ladd(fn)
704 ladd(fn)
708 elif mtime == self._lastnormaltime:
705 elif mtime == self._lastnormaltime:
709 # fn may have been changed in the same timeslot without
706 # fn may have been changed in the same timeslot without
710 # changing its size. This can happen if we quickly do
707 # changing its size. This can happen if we quickly do
711 # multiple commits in a single transaction.
708 # multiple commits in a single transaction.
712 # Force lookup, so we don't miss such a racy file change.
709 # Force lookup, so we don't miss such a racy file change.
713 ladd(fn)
710 ladd(fn)
714 elif listclean:
711 elif listclean:
715 cadd(fn)
712 cadd(fn)
716 elif state == 'm':
713 elif state == 'm':
717 madd(fn)
714 madd(fn)
718 elif state == 'a':
715 elif state == 'a':
719 aadd(fn)
716 aadd(fn)
720 elif state == 'r':
717 elif state == 'r':
721 radd(fn)
718 radd(fn)
722
719
723 return (lookup, modified, added, removed, deleted, unknown, ignored,
720 return (lookup, modified, added, removed, deleted, unknown, ignored,
724 clean)
721 clean)
@@ -1,1986 +1,1986 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup, subrepo, discovery, pushkey
10 import repo, changegroup, subrepo, discovery, pushkey
11 import changelog, dirstate, filelog, manifest, context, bookmarks
11 import changelog, dirstate, filelog, manifest, context, bookmarks
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import scmutil, util, extensions, hook, error
13 import scmutil, util, extensions, hook, error
14 import match as matchmod
14 import match as matchmod
15 import merge as mergemod
15 import merge as mergemod
16 import tags as tagsmod
16 import tags as tagsmod
17 from lock import release
17 from lock import release
18 import weakref, errno, os, time, inspect
18 import weakref, errno, os, time, inspect
19 propertycache = util.propertycache
19 propertycache = util.propertycache
20
20
21 class localrepository(repo.repository):
21 class localrepository(repo.repository):
22 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
22 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
23 'known', 'getbundle'))
23 'known', 'getbundle'))
24 supportedformats = set(('revlogv1', 'generaldelta'))
24 supportedformats = set(('revlogv1', 'generaldelta'))
25 supported = supportedformats | set(('store', 'fncache', 'shared',
25 supported = supportedformats | set(('store', 'fncache', 'shared',
26 'dotencode'))
26 'dotencode'))
27
27
28 def __init__(self, baseui, path=None, create=False):
28 def __init__(self, baseui, path=None, create=False):
29 repo.repository.__init__(self)
29 repo.repository.__init__(self)
30 self.root = os.path.realpath(util.expandpath(path))
30 self.root = os.path.realpath(util.expandpath(path))
31 self.path = os.path.join(self.root, ".hg")
31 self.path = os.path.join(self.root, ".hg")
32 self.origroot = path
32 self.origroot = path
33 self.auditor = scmutil.pathauditor(self.root, self._checknested)
33 self.auditor = scmutil.pathauditor(self.root, self._checknested)
34 self.opener = scmutil.opener(self.path)
34 self.opener = scmutil.opener(self.path)
35 self.wopener = scmutil.opener(self.root)
35 self.wopener = scmutil.opener(self.root)
36 self.baseui = baseui
36 self.baseui = baseui
37 self.ui = baseui.copy()
37 self.ui = baseui.copy()
38
38
39 try:
39 try:
40 self.ui.readconfig(self.join("hgrc"), self.root)
40 self.ui.readconfig(self.join("hgrc"), self.root)
41 extensions.loadall(self.ui)
41 extensions.loadall(self.ui)
42 except IOError:
42 except IOError:
43 pass
43 pass
44
44
45 if not os.path.isdir(self.path):
45 if not os.path.isdir(self.path):
46 if create:
46 if create:
47 if not os.path.exists(path):
47 if not os.path.exists(path):
48 util.makedirs(path)
48 util.makedirs(path)
49 util.makedir(self.path, notindexed=True)
49 util.makedir(self.path, notindexed=True)
50 requirements = ["revlogv1"]
50 requirements = ["revlogv1"]
51 if self.ui.configbool('format', 'usestore', True):
51 if self.ui.configbool('format', 'usestore', True):
52 os.mkdir(os.path.join(self.path, "store"))
52 os.mkdir(os.path.join(self.path, "store"))
53 requirements.append("store")
53 requirements.append("store")
54 if self.ui.configbool('format', 'usefncache', True):
54 if self.ui.configbool('format', 'usefncache', True):
55 requirements.append("fncache")
55 requirements.append("fncache")
56 if self.ui.configbool('format', 'dotencode', True):
56 if self.ui.configbool('format', 'dotencode', True):
57 requirements.append('dotencode')
57 requirements.append('dotencode')
58 # create an invalid changelog
58 # create an invalid changelog
59 self.opener.append(
59 self.opener.append(
60 "00changelog.i",
60 "00changelog.i",
61 '\0\0\0\2' # represents revlogv2
61 '\0\0\0\2' # represents revlogv2
62 ' dummy changelog to prevent using the old repo layout'
62 ' dummy changelog to prevent using the old repo layout'
63 )
63 )
64 if self.ui.configbool('format', 'generaldelta', False):
64 if self.ui.configbool('format', 'generaldelta', False):
65 requirements.append("generaldelta")
65 requirements.append("generaldelta")
66 else:
66 else:
67 raise error.RepoError(_("repository %s not found") % path)
67 raise error.RepoError(_("repository %s not found") % path)
68 elif create:
68 elif create:
69 raise error.RepoError(_("repository %s already exists") % path)
69 raise error.RepoError(_("repository %s already exists") % path)
70 else:
70 else:
71 # find requirements
71 # find requirements
72 requirements = set()
72 requirements = set()
73 try:
73 try:
74 requirements = set(self.opener.read("requires").splitlines())
74 requirements = set(self.opener.read("requires").splitlines())
75 except IOError, inst:
75 except IOError, inst:
76 if inst.errno != errno.ENOENT:
76 if inst.errno != errno.ENOENT:
77 raise
77 raise
78 for r in requirements - self.supported:
78 for r in requirements - self.supported:
79 raise error.RequirementError(
79 raise error.RequirementError(
80 _("requirement '%s' not supported") % r)
80 _("requirement '%s' not supported") % r)
81
81
82 self.sharedpath = self.path
82 self.sharedpath = self.path
83 try:
83 try:
84 s = os.path.realpath(self.opener.read("sharedpath"))
84 s = os.path.realpath(self.opener.read("sharedpath"))
85 if not os.path.exists(s):
85 if not os.path.exists(s):
86 raise error.RepoError(
86 raise error.RepoError(
87 _('.hg/sharedpath points to nonexistent directory %s') % s)
87 _('.hg/sharedpath points to nonexistent directory %s') % s)
88 self.sharedpath = s
88 self.sharedpath = s
89 except IOError, inst:
89 except IOError, inst:
90 if inst.errno != errno.ENOENT:
90 if inst.errno != errno.ENOENT:
91 raise
91 raise
92
92
93 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
93 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
94 self.spath = self.store.path
94 self.spath = self.store.path
95 self.sopener = self.store.opener
95 self.sopener = self.store.opener
96 self.sjoin = self.store.join
96 self.sjoin = self.store.join
97 self.opener.createmode = self.store.createmode
97 self.opener.createmode = self.store.createmode
98 self._applyrequirements(requirements)
98 self._applyrequirements(requirements)
99 if create:
99 if create:
100 self._writerequirements()
100 self._writerequirements()
101
101
102 # These two define the set of tags for this repository. _tags
102 # These two define the set of tags for this repository. _tags
103 # maps tag name to node; _tagtypes maps tag name to 'global' or
103 # maps tag name to node; _tagtypes maps tag name to 'global' or
104 # 'local'. (Global tags are defined by .hgtags across all
104 # 'local'. (Global tags are defined by .hgtags across all
105 # heads, and local tags are defined in .hg/localtags.) They
105 # heads, and local tags are defined in .hg/localtags.) They
106 # constitute the in-memory cache of tags.
106 # constitute the in-memory cache of tags.
107 self._tags = None
107 self._tags = None
108 self._tagtypes = None
108 self._tagtypes = None
109
109
110 self._branchcache = None
110 self._branchcache = None
111 self._branchcachetip = None
111 self._branchcachetip = None
112 self.nodetagscache = None
112 self.nodetagscache = None
113 self.filterpats = {}
113 self.filterpats = {}
114 self._datafilters = {}
114 self._datafilters = {}
115 self._transref = self._lockref = self._wlockref = None
115 self._transref = self._lockref = self._wlockref = None
116
116
117 def _applyrequirements(self, requirements):
117 def _applyrequirements(self, requirements):
118 self.requirements = requirements
118 self.requirements = requirements
119 openerreqs = set(('revlogv1', 'generaldelta'))
119 openerreqs = set(('revlogv1', 'generaldelta'))
120 self.sopener.options = dict((r, 1) for r in requirements
120 self.sopener.options = dict((r, 1) for r in requirements
121 if r in openerreqs)
121 if r in openerreqs)
122
122
123 def _writerequirements(self):
123 def _writerequirements(self):
124 reqfile = self.opener("requires", "w")
124 reqfile = self.opener("requires", "w")
125 for r in self.requirements:
125 for r in self.requirements:
126 reqfile.write("%s\n" % r)
126 reqfile.write("%s\n" % r)
127 reqfile.close()
127 reqfile.close()
128
128
129 def _checknested(self, path):
129 def _checknested(self, path):
130 """Determine if path is a legal nested repository."""
130 """Determine if path is a legal nested repository."""
131 if not path.startswith(self.root):
131 if not path.startswith(self.root):
132 return False
132 return False
133 subpath = path[len(self.root) + 1:]
133 subpath = path[len(self.root) + 1:]
134
134
135 # XXX: Checking against the current working copy is wrong in
135 # XXX: Checking against the current working copy is wrong in
136 # the sense that it can reject things like
136 # the sense that it can reject things like
137 #
137 #
138 # $ hg cat -r 10 sub/x.txt
138 # $ hg cat -r 10 sub/x.txt
139 #
139 #
140 # if sub/ is no longer a subrepository in the working copy
140 # if sub/ is no longer a subrepository in the working copy
141 # parent revision.
141 # parent revision.
142 #
142 #
143 # However, it can of course also allow things that would have
143 # However, it can of course also allow things that would have
144 # been rejected before, such as the above cat command if sub/
144 # been rejected before, such as the above cat command if sub/
145 # is a subrepository now, but was a normal directory before.
145 # is a subrepository now, but was a normal directory before.
146 # The old path auditor would have rejected by mistake since it
146 # The old path auditor would have rejected by mistake since it
147 # panics when it sees sub/.hg/.
147 # panics when it sees sub/.hg/.
148 #
148 #
149 # All in all, checking against the working copy seems sensible
149 # All in all, checking against the working copy seems sensible
150 # since we want to prevent access to nested repositories on
150 # since we want to prevent access to nested repositories on
151 # the filesystem *now*.
151 # the filesystem *now*.
152 ctx = self[None]
152 ctx = self[None]
153 parts = util.splitpath(subpath)
153 parts = util.splitpath(subpath)
154 while parts:
154 while parts:
155 prefix = os.sep.join(parts)
155 prefix = os.sep.join(parts)
156 if prefix in ctx.substate:
156 if prefix in ctx.substate:
157 if prefix == subpath:
157 if prefix == subpath:
158 return True
158 return True
159 else:
159 else:
160 sub = ctx.sub(prefix)
160 sub = ctx.sub(prefix)
161 return sub.checknested(subpath[len(prefix) + 1:])
161 return sub.checknested(subpath[len(prefix) + 1:])
162 else:
162 else:
163 parts.pop()
163 parts.pop()
164 return False
164 return False
165
165
166 @util.propertycache
166 @util.propertycache
167 def _bookmarks(self):
167 def _bookmarks(self):
168 return bookmarks.read(self)
168 return bookmarks.read(self)
169
169
170 @util.propertycache
170 @util.propertycache
171 def _bookmarkcurrent(self):
171 def _bookmarkcurrent(self):
172 return bookmarks.readcurrent(self)
172 return bookmarks.readcurrent(self)
173
173
174 @propertycache
174 @propertycache
175 def changelog(self):
175 def changelog(self):
176 c = changelog.changelog(self.sopener)
176 c = changelog.changelog(self.sopener)
177 if 'HG_PENDING' in os.environ:
177 if 'HG_PENDING' in os.environ:
178 p = os.environ['HG_PENDING']
178 p = os.environ['HG_PENDING']
179 if p.startswith(self.root):
179 if p.startswith(self.root):
180 c.readpending('00changelog.i.a')
180 c.readpending('00changelog.i.a')
181 return c
181 return c
182
182
183 @propertycache
183 @propertycache
184 def manifest(self):
184 def manifest(self):
185 return manifest.manifest(self.sopener)
185 return manifest.manifest(self.sopener)
186
186
187 @propertycache
187 @propertycache
188 def dirstate(self):
188 def dirstate(self):
189 warned = [0]
189 warned = [0]
190 def validate(node):
190 def validate(node):
191 try:
191 try:
192 self.changelog.rev(node)
192 self.changelog.rev(node)
193 return node
193 return node
194 except error.LookupError:
194 except error.LookupError:
195 if not warned[0]:
195 if not warned[0]:
196 warned[0] = True
196 warned[0] = True
197 self.ui.warn(_("warning: ignoring unknown"
197 self.ui.warn(_("warning: ignoring unknown"
198 " working parent %s!\n") % short(node))
198 " working parent %s!\n") % short(node))
199 return nullid
199 return nullid
200
200
201 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
201 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
202
202
203 def __getitem__(self, changeid):
203 def __getitem__(self, changeid):
204 if changeid is None:
204 if changeid is None:
205 return context.workingctx(self)
205 return context.workingctx(self)
206 return context.changectx(self, changeid)
206 return context.changectx(self, changeid)
207
207
208 def __contains__(self, changeid):
208 def __contains__(self, changeid):
209 try:
209 try:
210 return bool(self.lookup(changeid))
210 return bool(self.lookup(changeid))
211 except error.RepoLookupError:
211 except error.RepoLookupError:
212 return False
212 return False
213
213
214 def __nonzero__(self):
214 def __nonzero__(self):
215 return True
215 return True
216
216
217 def __len__(self):
217 def __len__(self):
218 return len(self.changelog)
218 return len(self.changelog)
219
219
220 def __iter__(self):
220 def __iter__(self):
221 for i in xrange(len(self)):
221 for i in xrange(len(self)):
222 yield i
222 yield i
223
223
224 def url(self):
224 def url(self):
225 return 'file:' + self.root
225 return 'file:' + self.root
226
226
227 def hook(self, name, throw=False, **args):
227 def hook(self, name, throw=False, **args):
228 return hook.hook(self.ui, self, name, throw, **args)
228 return hook.hook(self.ui, self, name, throw, **args)
229
229
230 tag_disallowed = ':\r\n'
230 tag_disallowed = ':\r\n'
231
231
232 def _tag(self, names, node, message, local, user, date, extra={}):
232 def _tag(self, names, node, message, local, user, date, extra={}):
233 if isinstance(names, str):
233 if isinstance(names, str):
234 allchars = names
234 allchars = names
235 names = (names,)
235 names = (names,)
236 else:
236 else:
237 allchars = ''.join(names)
237 allchars = ''.join(names)
238 for c in self.tag_disallowed:
238 for c in self.tag_disallowed:
239 if c in allchars:
239 if c in allchars:
240 raise util.Abort(_('%r cannot be used in a tag name') % c)
240 raise util.Abort(_('%r cannot be used in a tag name') % c)
241
241
242 branches = self.branchmap()
242 branches = self.branchmap()
243 for name in names:
243 for name in names:
244 self.hook('pretag', throw=True, node=hex(node), tag=name,
244 self.hook('pretag', throw=True, node=hex(node), tag=name,
245 local=local)
245 local=local)
246 if name in branches:
246 if name in branches:
247 self.ui.warn(_("warning: tag %s conflicts with existing"
247 self.ui.warn(_("warning: tag %s conflicts with existing"
248 " branch name\n") % name)
248 " branch name\n") % name)
249
249
250 def writetags(fp, names, munge, prevtags):
250 def writetags(fp, names, munge, prevtags):
251 fp.seek(0, 2)
251 fp.seek(0, 2)
252 if prevtags and prevtags[-1] != '\n':
252 if prevtags and prevtags[-1] != '\n':
253 fp.write('\n')
253 fp.write('\n')
254 for name in names:
254 for name in names:
255 m = munge and munge(name) or name
255 m = munge and munge(name) or name
256 if self._tagtypes and name in self._tagtypes:
256 if self._tagtypes and name in self._tagtypes:
257 old = self._tags.get(name, nullid)
257 old = self._tags.get(name, nullid)
258 fp.write('%s %s\n' % (hex(old), m))
258 fp.write('%s %s\n' % (hex(old), m))
259 fp.write('%s %s\n' % (hex(node), m))
259 fp.write('%s %s\n' % (hex(node), m))
260 fp.close()
260 fp.close()
261
261
262 prevtags = ''
262 prevtags = ''
263 if local:
263 if local:
264 try:
264 try:
265 fp = self.opener('localtags', 'r+')
265 fp = self.opener('localtags', 'r+')
266 except IOError:
266 except IOError:
267 fp = self.opener('localtags', 'a')
267 fp = self.opener('localtags', 'a')
268 else:
268 else:
269 prevtags = fp.read()
269 prevtags = fp.read()
270
270
271 # local tags are stored in the current charset
271 # local tags are stored in the current charset
272 writetags(fp, names, None, prevtags)
272 writetags(fp, names, None, prevtags)
273 for name in names:
273 for name in names:
274 self.hook('tag', node=hex(node), tag=name, local=local)
274 self.hook('tag', node=hex(node), tag=name, local=local)
275 return
275 return
276
276
277 try:
277 try:
278 fp = self.wfile('.hgtags', 'rb+')
278 fp = self.wfile('.hgtags', 'rb+')
279 except IOError:
279 except IOError:
280 fp = self.wfile('.hgtags', 'ab')
280 fp = self.wfile('.hgtags', 'ab')
281 else:
281 else:
282 prevtags = fp.read()
282 prevtags = fp.read()
283
283
284 # committed tags are stored in UTF-8
284 # committed tags are stored in UTF-8
285 writetags(fp, names, encoding.fromlocal, prevtags)
285 writetags(fp, names, encoding.fromlocal, prevtags)
286
286
287 fp.close()
287 fp.close()
288
288
289 if '.hgtags' not in self.dirstate:
289 if '.hgtags' not in self.dirstate:
290 self[None].add(['.hgtags'])
290 self[None].add(['.hgtags'])
291
291
292 m = matchmod.exact(self.root, '', ['.hgtags'])
292 m = matchmod.exact(self.root, '', ['.hgtags'])
293 tagnode = self.commit(message, user, date, extra=extra, match=m)
293 tagnode = self.commit(message, user, date, extra=extra, match=m)
294
294
295 for name in names:
295 for name in names:
296 self.hook('tag', node=hex(node), tag=name, local=local)
296 self.hook('tag', node=hex(node), tag=name, local=local)
297
297
298 return tagnode
298 return tagnode
299
299
300 def tag(self, names, node, message, local, user, date):
300 def tag(self, names, node, message, local, user, date):
301 '''tag a revision with one or more symbolic names.
301 '''tag a revision with one or more symbolic names.
302
302
303 names is a list of strings or, when adding a single tag, names may be a
303 names is a list of strings or, when adding a single tag, names may be a
304 string.
304 string.
305
305
306 if local is True, the tags are stored in a per-repository file.
306 if local is True, the tags are stored in a per-repository file.
307 otherwise, they are stored in the .hgtags file, and a new
307 otherwise, they are stored in the .hgtags file, and a new
308 changeset is committed with the change.
308 changeset is committed with the change.
309
309
310 keyword arguments:
310 keyword arguments:
311
311
312 local: whether to store tags in non-version-controlled file
312 local: whether to store tags in non-version-controlled file
313 (default False)
313 (default False)
314
314
315 message: commit message to use if committing
315 message: commit message to use if committing
316
316
317 user: name of user to use if committing
317 user: name of user to use if committing
318
318
319 date: date tuple to use if committing'''
319 date: date tuple to use if committing'''
320
320
321 if not local:
321 if not local:
322 for x in self.status()[:5]:
322 for x in self.status()[:5]:
323 if '.hgtags' in x:
323 if '.hgtags' in x:
324 raise util.Abort(_('working copy of .hgtags is changed '
324 raise util.Abort(_('working copy of .hgtags is changed '
325 '(please commit .hgtags manually)'))
325 '(please commit .hgtags manually)'))
326
326
327 self.tags() # instantiate the cache
327 self.tags() # instantiate the cache
328 self._tag(names, node, message, local, user, date)
328 self._tag(names, node, message, local, user, date)
329
329
330 def tags(self):
330 def tags(self):
331 '''return a mapping of tag to node'''
331 '''return a mapping of tag to node'''
332 if self._tags is None:
332 if self._tags is None:
333 (self._tags, self._tagtypes) = self._findtags()
333 (self._tags, self._tagtypes) = self._findtags()
334
334
335 return self._tags
335 return self._tags
336
336
337 def _findtags(self):
337 def _findtags(self):
338 '''Do the hard work of finding tags. Return a pair of dicts
338 '''Do the hard work of finding tags. Return a pair of dicts
339 (tags, tagtypes) where tags maps tag name to node, and tagtypes
339 (tags, tagtypes) where tags maps tag name to node, and tagtypes
340 maps tag name to a string like \'global\' or \'local\'.
340 maps tag name to a string like \'global\' or \'local\'.
341 Subclasses or extensions are free to add their own tags, but
341 Subclasses or extensions are free to add their own tags, but
342 should be aware that the returned dicts will be retained for the
342 should be aware that the returned dicts will be retained for the
343 duration of the localrepo object.'''
343 duration of the localrepo object.'''
344
344
345 # XXX what tagtype should subclasses/extensions use? Currently
345 # XXX what tagtype should subclasses/extensions use? Currently
346 # mq and bookmarks add tags, but do not set the tagtype at all.
346 # mq and bookmarks add tags, but do not set the tagtype at all.
347 # Should each extension invent its own tag type? Should there
347 # Should each extension invent its own tag type? Should there
348 # be one tagtype for all such "virtual" tags? Or is the status
348 # be one tagtype for all such "virtual" tags? Or is the status
349 # quo fine?
349 # quo fine?
350
350
351 alltags = {} # map tag name to (node, hist)
351 alltags = {} # map tag name to (node, hist)
352 tagtypes = {}
352 tagtypes = {}
353
353
354 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
354 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
355 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
355 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
356
356
357 # Build the return dicts. Have to re-encode tag names because
357 # Build the return dicts. Have to re-encode tag names because
358 # the tags module always uses UTF-8 (in order not to lose info
358 # the tags module always uses UTF-8 (in order not to lose info
359 # writing to the cache), but the rest of Mercurial wants them in
359 # writing to the cache), but the rest of Mercurial wants them in
360 # local encoding.
360 # local encoding.
361 tags = {}
361 tags = {}
362 for (name, (node, hist)) in alltags.iteritems():
362 for (name, (node, hist)) in alltags.iteritems():
363 if node != nullid:
363 if node != nullid:
364 try:
364 try:
365 # ignore tags to unknown nodes
365 # ignore tags to unknown nodes
366 self.changelog.lookup(node)
366 self.changelog.lookup(node)
367 tags[encoding.tolocal(name)] = node
367 tags[encoding.tolocal(name)] = node
368 except error.LookupError:
368 except error.LookupError:
369 pass
369 pass
370 tags['tip'] = self.changelog.tip()
370 tags['tip'] = self.changelog.tip()
371 tagtypes = dict([(encoding.tolocal(name), value)
371 tagtypes = dict([(encoding.tolocal(name), value)
372 for (name, value) in tagtypes.iteritems()])
372 for (name, value) in tagtypes.iteritems()])
373 return (tags, tagtypes)
373 return (tags, tagtypes)
374
374
375 def tagtype(self, tagname):
375 def tagtype(self, tagname):
376 '''
376 '''
377 return the type of the given tag. result can be:
377 return the type of the given tag. result can be:
378
378
379 'local' : a local tag
379 'local' : a local tag
380 'global' : a global tag
380 'global' : a global tag
381 None : tag does not exist
381 None : tag does not exist
382 '''
382 '''
383
383
384 self.tags()
384 self.tags()
385
385
386 return self._tagtypes.get(tagname)
386 return self._tagtypes.get(tagname)
387
387
388 def tagslist(self):
388 def tagslist(self):
389 '''return a list of tags ordered by revision'''
389 '''return a list of tags ordered by revision'''
390 l = []
390 l = []
391 for t, n in self.tags().iteritems():
391 for t, n in self.tags().iteritems():
392 r = self.changelog.rev(n)
392 r = self.changelog.rev(n)
393 l.append((r, t, n))
393 l.append((r, t, n))
394 return [(t, n) for r, t, n in sorted(l)]
394 return [(t, n) for r, t, n in sorted(l)]
395
395
396 def nodetags(self, node):
396 def nodetags(self, node):
397 '''return the tags associated with a node'''
397 '''return the tags associated with a node'''
398 if not self.nodetagscache:
398 if not self.nodetagscache:
399 self.nodetagscache = {}
399 self.nodetagscache = {}
400 for t, n in self.tags().iteritems():
400 for t, n in self.tags().iteritems():
401 self.nodetagscache.setdefault(n, []).append(t)
401 self.nodetagscache.setdefault(n, []).append(t)
402 for tags in self.nodetagscache.itervalues():
402 for tags in self.nodetagscache.itervalues():
403 tags.sort()
403 tags.sort()
404 return self.nodetagscache.get(node, [])
404 return self.nodetagscache.get(node, [])
405
405
406 def nodebookmarks(self, node):
406 def nodebookmarks(self, node):
407 marks = []
407 marks = []
408 for bookmark, n in self._bookmarks.iteritems():
408 for bookmark, n in self._bookmarks.iteritems():
409 if n == node:
409 if n == node:
410 marks.append(bookmark)
410 marks.append(bookmark)
411 return sorted(marks)
411 return sorted(marks)
412
412
413 def _branchtags(self, partial, lrev):
413 def _branchtags(self, partial, lrev):
414 # TODO: rename this function?
414 # TODO: rename this function?
415 tiprev = len(self) - 1
415 tiprev = len(self) - 1
416 if lrev != tiprev:
416 if lrev != tiprev:
417 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
417 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
418 self._updatebranchcache(partial, ctxgen)
418 self._updatebranchcache(partial, ctxgen)
419 self._writebranchcache(partial, self.changelog.tip(), tiprev)
419 self._writebranchcache(partial, self.changelog.tip(), tiprev)
420
420
421 return partial
421 return partial
422
422
423 def updatebranchcache(self):
423 def updatebranchcache(self):
424 tip = self.changelog.tip()
424 tip = self.changelog.tip()
425 if self._branchcache is not None and self._branchcachetip == tip:
425 if self._branchcache is not None and self._branchcachetip == tip:
426 return self._branchcache
426 return self._branchcache
427
427
428 oldtip = self._branchcachetip
428 oldtip = self._branchcachetip
429 self._branchcachetip = tip
429 self._branchcachetip = tip
430 if oldtip is None or oldtip not in self.changelog.nodemap:
430 if oldtip is None or oldtip not in self.changelog.nodemap:
431 partial, last, lrev = self._readbranchcache()
431 partial, last, lrev = self._readbranchcache()
432 else:
432 else:
433 lrev = self.changelog.rev(oldtip)
433 lrev = self.changelog.rev(oldtip)
434 partial = self._branchcache
434 partial = self._branchcache
435
435
436 self._branchtags(partial, lrev)
436 self._branchtags(partial, lrev)
437 # this private cache holds all heads (not just tips)
437 # this private cache holds all heads (not just tips)
438 self._branchcache = partial
438 self._branchcache = partial
439
439
440 def branchmap(self):
440 def branchmap(self):
441 '''returns a dictionary {branch: [branchheads]}'''
441 '''returns a dictionary {branch: [branchheads]}'''
442 self.updatebranchcache()
442 self.updatebranchcache()
443 return self._branchcache
443 return self._branchcache
444
444
445 def branchtags(self):
445 def branchtags(self):
446 '''return a dict where branch names map to the tipmost head of
446 '''return a dict where branch names map to the tipmost head of
447 the branch, open heads come before closed'''
447 the branch, open heads come before closed'''
448 bt = {}
448 bt = {}
449 for bn, heads in self.branchmap().iteritems():
449 for bn, heads in self.branchmap().iteritems():
450 tip = heads[-1]
450 tip = heads[-1]
451 for h in reversed(heads):
451 for h in reversed(heads):
452 if 'close' not in self.changelog.read(h)[5]:
452 if 'close' not in self.changelog.read(h)[5]:
453 tip = h
453 tip = h
454 break
454 break
455 bt[bn] = tip
455 bt[bn] = tip
456 return bt
456 return bt
457
457
458 def _readbranchcache(self):
458 def _readbranchcache(self):
459 partial = {}
459 partial = {}
460 try:
460 try:
461 f = self.opener("cache/branchheads")
461 f = self.opener("cache/branchheads")
462 lines = f.read().split('\n')
462 lines = f.read().split('\n')
463 f.close()
463 f.close()
464 except (IOError, OSError):
464 except (IOError, OSError):
465 return {}, nullid, nullrev
465 return {}, nullid, nullrev
466
466
467 try:
467 try:
468 last, lrev = lines.pop(0).split(" ", 1)
468 last, lrev = lines.pop(0).split(" ", 1)
469 last, lrev = bin(last), int(lrev)
469 last, lrev = bin(last), int(lrev)
470 if lrev >= len(self) or self[lrev].node() != last:
470 if lrev >= len(self) or self[lrev].node() != last:
471 # invalidate the cache
471 # invalidate the cache
472 raise ValueError('invalidating branch cache (tip differs)')
472 raise ValueError('invalidating branch cache (tip differs)')
473 for l in lines:
473 for l in lines:
474 if not l:
474 if not l:
475 continue
475 continue
476 node, label = l.split(" ", 1)
476 node, label = l.split(" ", 1)
477 label = encoding.tolocal(label.strip())
477 label = encoding.tolocal(label.strip())
478 partial.setdefault(label, []).append(bin(node))
478 partial.setdefault(label, []).append(bin(node))
479 except KeyboardInterrupt:
479 except KeyboardInterrupt:
480 raise
480 raise
481 except Exception, inst:
481 except Exception, inst:
482 if self.ui.debugflag:
482 if self.ui.debugflag:
483 self.ui.warn(str(inst), '\n')
483 self.ui.warn(str(inst), '\n')
484 partial, last, lrev = {}, nullid, nullrev
484 partial, last, lrev = {}, nullid, nullrev
485 return partial, last, lrev
485 return partial, last, lrev
486
486
487 def _writebranchcache(self, branches, tip, tiprev):
487 def _writebranchcache(self, branches, tip, tiprev):
488 try:
488 try:
489 f = self.opener("cache/branchheads", "w", atomictemp=True)
489 f = self.opener("cache/branchheads", "w", atomictemp=True)
490 f.write("%s %s\n" % (hex(tip), tiprev))
490 f.write("%s %s\n" % (hex(tip), tiprev))
491 for label, nodes in branches.iteritems():
491 for label, nodes in branches.iteritems():
492 for node in nodes:
492 for node in nodes:
493 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
493 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
494 f.rename()
494 f.rename()
495 except (IOError, OSError):
495 except (IOError, OSError):
496 pass
496 pass
497
497
498 def _updatebranchcache(self, partial, ctxgen):
498 def _updatebranchcache(self, partial, ctxgen):
499 # collect new branch entries
499 # collect new branch entries
500 newbranches = {}
500 newbranches = {}
501 for c in ctxgen:
501 for c in ctxgen:
502 newbranches.setdefault(c.branch(), []).append(c.node())
502 newbranches.setdefault(c.branch(), []).append(c.node())
503 # if older branchheads are reachable from new ones, they aren't
503 # if older branchheads are reachable from new ones, they aren't
504 # really branchheads. Note checking parents is insufficient:
504 # really branchheads. Note checking parents is insufficient:
505 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
505 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
506 for branch, newnodes in newbranches.iteritems():
506 for branch, newnodes in newbranches.iteritems():
507 bheads = partial.setdefault(branch, [])
507 bheads = partial.setdefault(branch, [])
508 bheads.extend(newnodes)
508 bheads.extend(newnodes)
509 if len(bheads) <= 1:
509 if len(bheads) <= 1:
510 continue
510 continue
511 bheads = sorted(bheads, key=lambda x: self[x].rev())
511 bheads = sorted(bheads, key=lambda x: self[x].rev())
512 # starting from tip means fewer passes over reachable
512 # starting from tip means fewer passes over reachable
513 while newnodes:
513 while newnodes:
514 latest = newnodes.pop()
514 latest = newnodes.pop()
515 if latest not in bheads:
515 if latest not in bheads:
516 continue
516 continue
517 minbhrev = self[bheads[0]].node()
517 minbhrev = self[bheads[0]].node()
518 reachable = self.changelog.reachable(latest, minbhrev)
518 reachable = self.changelog.reachable(latest, minbhrev)
519 reachable.remove(latest)
519 reachable.remove(latest)
520 if reachable:
520 if reachable:
521 bheads = [b for b in bheads if b not in reachable]
521 bheads = [b for b in bheads if b not in reachable]
522 partial[branch] = bheads
522 partial[branch] = bheads
523
523
524 def lookup(self, key):
524 def lookup(self, key):
525 if isinstance(key, int):
525 if isinstance(key, int):
526 return self.changelog.node(key)
526 return self.changelog.node(key)
527 elif key == '.':
527 elif key == '.':
528 return self.dirstate.p1()
528 return self.dirstate.p1()
529 elif key == 'null':
529 elif key == 'null':
530 return nullid
530 return nullid
531 elif key == 'tip':
531 elif key == 'tip':
532 return self.changelog.tip()
532 return self.changelog.tip()
533 n = self.changelog._match(key)
533 n = self.changelog._match(key)
534 if n:
534 if n:
535 return n
535 return n
536 if key in self._bookmarks:
536 if key in self._bookmarks:
537 return self._bookmarks[key]
537 return self._bookmarks[key]
538 if key in self.tags():
538 if key in self.tags():
539 return self.tags()[key]
539 return self.tags()[key]
540 if key in self.branchtags():
540 if key in self.branchtags():
541 return self.branchtags()[key]
541 return self.branchtags()[key]
542 n = self.changelog._partialmatch(key)
542 n = self.changelog._partialmatch(key)
543 if n:
543 if n:
544 return n
544 return n
545
545
546 # can't find key, check if it might have come from damaged dirstate
546 # can't find key, check if it might have come from damaged dirstate
547 if key in self.dirstate.parents():
547 if key in self.dirstate.parents():
548 raise error.Abort(_("working directory has unknown parent '%s'!")
548 raise error.Abort(_("working directory has unknown parent '%s'!")
549 % short(key))
549 % short(key))
550 try:
550 try:
551 if len(key) == 20:
551 if len(key) == 20:
552 key = hex(key)
552 key = hex(key)
553 except TypeError:
553 except TypeError:
554 pass
554 pass
555 raise error.RepoLookupError(_("unknown revision '%s'") % key)
555 raise error.RepoLookupError(_("unknown revision '%s'") % key)
556
556
557 def lookupbranch(self, key, remote=None):
557 def lookupbranch(self, key, remote=None):
558 repo = remote or self
558 repo = remote or self
559 if key in repo.branchmap():
559 if key in repo.branchmap():
560 return key
560 return key
561
561
562 repo = (remote and remote.local()) and remote or self
562 repo = (remote and remote.local()) and remote or self
563 return repo[key].branch()
563 return repo[key].branch()
564
564
565 def known(self, nodes):
565 def known(self, nodes):
566 nm = self.changelog.nodemap
566 nm = self.changelog.nodemap
567 return [(n in nm) for n in nodes]
567 return [(n in nm) for n in nodes]
568
568
569 def local(self):
569 def local(self):
570 return True
570 return True
571
571
572 def join(self, f):
572 def join(self, f):
573 return os.path.join(self.path, f)
573 return os.path.join(self.path, f)
574
574
575 def wjoin(self, f):
575 def wjoin(self, f):
576 return os.path.join(self.root, f)
576 return os.path.join(self.root, f)
577
577
578 def file(self, f):
578 def file(self, f):
579 if f[0] == '/':
579 if f[0] == '/':
580 f = f[1:]
580 f = f[1:]
581 return filelog.filelog(self.sopener, f)
581 return filelog.filelog(self.sopener, f)
582
582
583 def changectx(self, changeid):
583 def changectx(self, changeid):
584 return self[changeid]
584 return self[changeid]
585
585
586 def parents(self, changeid=None):
586 def parents(self, changeid=None):
587 '''get list of changectxs for parents of changeid'''
587 '''get list of changectxs for parents of changeid'''
588 return self[changeid].parents()
588 return self[changeid].parents()
589
589
590 def filectx(self, path, changeid=None, fileid=None):
590 def filectx(self, path, changeid=None, fileid=None):
591 """changeid can be a changeset revision, node, or tag.
591 """changeid can be a changeset revision, node, or tag.
592 fileid can be a file revision or node."""
592 fileid can be a file revision or node."""
593 return context.filectx(self, path, changeid, fileid)
593 return context.filectx(self, path, changeid, fileid)
594
594
595 def getcwd(self):
595 def getcwd(self):
596 return self.dirstate.getcwd()
596 return self.dirstate.getcwd()
597
597
598 def pathto(self, f, cwd=None):
598 def pathto(self, f, cwd=None):
599 return self.dirstate.pathto(f, cwd)
599 return self.dirstate.pathto(f, cwd)
600
600
601 def wfile(self, f, mode='r'):
601 def wfile(self, f, mode='r'):
602 return self.wopener(f, mode)
602 return self.wopener(f, mode)
603
603
604 def _link(self, f):
604 def _link(self, f):
605 return os.path.islink(self.wjoin(f))
605 return os.path.islink(self.wjoin(f))
606
606
607 def _loadfilter(self, filter):
607 def _loadfilter(self, filter):
608 if filter not in self.filterpats:
608 if filter not in self.filterpats:
609 l = []
609 l = []
610 for pat, cmd in self.ui.configitems(filter):
610 for pat, cmd in self.ui.configitems(filter):
611 if cmd == '!':
611 if cmd == '!':
612 continue
612 continue
613 mf = matchmod.match(self.root, '', [pat])
613 mf = matchmod.match(self.root, '', [pat])
614 fn = None
614 fn = None
615 params = cmd
615 params = cmd
616 for name, filterfn in self._datafilters.iteritems():
616 for name, filterfn in self._datafilters.iteritems():
617 if cmd.startswith(name):
617 if cmd.startswith(name):
618 fn = filterfn
618 fn = filterfn
619 params = cmd[len(name):].lstrip()
619 params = cmd[len(name):].lstrip()
620 break
620 break
621 if not fn:
621 if not fn:
622 fn = lambda s, c, **kwargs: util.filter(s, c)
622 fn = lambda s, c, **kwargs: util.filter(s, c)
623 # Wrap old filters not supporting keyword arguments
623 # Wrap old filters not supporting keyword arguments
624 if not inspect.getargspec(fn)[2]:
624 if not inspect.getargspec(fn)[2]:
625 oldfn = fn
625 oldfn = fn
626 fn = lambda s, c, **kwargs: oldfn(s, c)
626 fn = lambda s, c, **kwargs: oldfn(s, c)
627 l.append((mf, fn, params))
627 l.append((mf, fn, params))
628 self.filterpats[filter] = l
628 self.filterpats[filter] = l
629 return self.filterpats[filter]
629 return self.filterpats[filter]
630
630
631 def _filter(self, filterpats, filename, data):
631 def _filter(self, filterpats, filename, data):
632 for mf, fn, cmd in filterpats:
632 for mf, fn, cmd in filterpats:
633 if mf(filename):
633 if mf(filename):
634 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
634 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
635 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
635 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
636 break
636 break
637
637
638 return data
638 return data
639
639
640 @propertycache
640 @propertycache
641 def _encodefilterpats(self):
641 def _encodefilterpats(self):
642 return self._loadfilter('encode')
642 return self._loadfilter('encode')
643
643
644 @propertycache
644 @propertycache
645 def _decodefilterpats(self):
645 def _decodefilterpats(self):
646 return self._loadfilter('decode')
646 return self._loadfilter('decode')
647
647
648 def adddatafilter(self, name, filter):
648 def adddatafilter(self, name, filter):
649 self._datafilters[name] = filter
649 self._datafilters[name] = filter
650
650
651 def wread(self, filename):
651 def wread(self, filename):
652 if self._link(filename):
652 if self._link(filename):
653 data = os.readlink(self.wjoin(filename))
653 data = os.readlink(self.wjoin(filename))
654 else:
654 else:
655 data = self.wopener.read(filename)
655 data = self.wopener.read(filename)
656 return self._filter(self._encodefilterpats, filename, data)
656 return self._filter(self._encodefilterpats, filename, data)
657
657
658 def wwrite(self, filename, data, flags):
658 def wwrite(self, filename, data, flags):
659 data = self._filter(self._decodefilterpats, filename, data)
659 data = self._filter(self._decodefilterpats, filename, data)
660 if 'l' in flags:
660 if 'l' in flags:
661 self.wopener.symlink(data, filename)
661 self.wopener.symlink(data, filename)
662 else:
662 else:
663 self.wopener.write(filename, data)
663 self.wopener.write(filename, data)
664 if 'x' in flags:
664 if 'x' in flags:
665 util.setflags(self.wjoin(filename), False, True)
665 util.setflags(self.wjoin(filename), False, True)
666
666
667 def wwritedata(self, filename, data):
667 def wwritedata(self, filename, data):
668 return self._filter(self._decodefilterpats, filename, data)
668 return self._filter(self._decodefilterpats, filename, data)
669
669
670 def transaction(self, desc):
670 def transaction(self, desc):
671 tr = self._transref and self._transref() or None
671 tr = self._transref and self._transref() or None
672 if tr and tr.running():
672 if tr and tr.running():
673 return tr.nest()
673 return tr.nest()
674
674
675 # abort here if the journal already exists
675 # abort here if the journal already exists
676 if os.path.exists(self.sjoin("journal")):
676 if os.path.exists(self.sjoin("journal")):
677 raise error.RepoError(
677 raise error.RepoError(
678 _("abandoned transaction found - run hg recover"))
678 _("abandoned transaction found - run hg recover"))
679
679
680 journalfiles = self._writejournal(desc)
680 journalfiles = self._writejournal(desc)
681 renames = [(x, undoname(x)) for x in journalfiles]
681 renames = [(x, undoname(x)) for x in journalfiles]
682
682
683 tr = transaction.transaction(self.ui.warn, self.sopener,
683 tr = transaction.transaction(self.ui.warn, self.sopener,
684 self.sjoin("journal"),
684 self.sjoin("journal"),
685 aftertrans(renames),
685 aftertrans(renames),
686 self.store.createmode)
686 self.store.createmode)
687 self._transref = weakref.ref(tr)
687 self._transref = weakref.ref(tr)
688 return tr
688 return tr
689
689
690 def _writejournal(self, desc):
690 def _writejournal(self, desc):
691 # save dirstate for rollback
691 # save dirstate for rollback
692 try:
692 try:
693 ds = self.opener.read("dirstate")
693 ds = self.opener.read("dirstate")
694 except IOError:
694 except IOError:
695 ds = ""
695 ds = ""
696 self.opener.write("journal.dirstate", ds)
696 self.opener.write("journal.dirstate", ds)
697 self.opener.write("journal.branch",
697 self.opener.write("journal.branch",
698 encoding.fromlocal(self.dirstate.branch()))
698 encoding.fromlocal(self.dirstate.branch()))
699 self.opener.write("journal.desc",
699 self.opener.write("journal.desc",
700 "%d\n%s\n" % (len(self), desc))
700 "%d\n%s\n" % (len(self), desc))
701
701
702 bkname = self.join('bookmarks')
702 bkname = self.join('bookmarks')
703 if os.path.exists(bkname):
703 if os.path.exists(bkname):
704 util.copyfile(bkname, self.join('journal.bookmarks'))
704 util.copyfile(bkname, self.join('journal.bookmarks'))
705 else:
705 else:
706 self.opener.write('journal.bookmarks', '')
706 self.opener.write('journal.bookmarks', '')
707
707
708 return (self.sjoin('journal'), self.join('journal.dirstate'),
708 return (self.sjoin('journal'), self.join('journal.dirstate'),
709 self.join('journal.branch'), self.join('journal.desc'),
709 self.join('journal.branch'), self.join('journal.desc'),
710 self.join('journal.bookmarks'))
710 self.join('journal.bookmarks'))
711
711
712 def recover(self):
712 def recover(self):
713 lock = self.lock()
713 lock = self.lock()
714 try:
714 try:
715 if os.path.exists(self.sjoin("journal")):
715 if os.path.exists(self.sjoin("journal")):
716 self.ui.status(_("rolling back interrupted transaction\n"))
716 self.ui.status(_("rolling back interrupted transaction\n"))
717 transaction.rollback(self.sopener, self.sjoin("journal"),
717 transaction.rollback(self.sopener, self.sjoin("journal"),
718 self.ui.warn)
718 self.ui.warn)
719 self.invalidate()
719 self.invalidate()
720 return True
720 return True
721 else:
721 else:
722 self.ui.warn(_("no interrupted transaction available\n"))
722 self.ui.warn(_("no interrupted transaction available\n"))
723 return False
723 return False
724 finally:
724 finally:
725 lock.release()
725 lock.release()
726
726
727 def rollback(self, dryrun=False):
727 def rollback(self, dryrun=False):
728 wlock = lock = None
728 wlock = lock = None
729 try:
729 try:
730 wlock = self.wlock()
730 wlock = self.wlock()
731 lock = self.lock()
731 lock = self.lock()
732 if os.path.exists(self.sjoin("undo")):
732 if os.path.exists(self.sjoin("undo")):
733 try:
733 try:
734 args = self.opener.read("undo.desc").splitlines()
734 args = self.opener.read("undo.desc").splitlines()
735 if len(args) >= 3 and self.ui.verbose:
735 if len(args) >= 3 and self.ui.verbose:
736 desc = _("repository tip rolled back to revision %s"
736 desc = _("repository tip rolled back to revision %s"
737 " (undo %s: %s)\n") % (
737 " (undo %s: %s)\n") % (
738 int(args[0]) - 1, args[1], args[2])
738 int(args[0]) - 1, args[1], args[2])
739 elif len(args) >= 2:
739 elif len(args) >= 2:
740 desc = _("repository tip rolled back to revision %s"
740 desc = _("repository tip rolled back to revision %s"
741 " (undo %s)\n") % (
741 " (undo %s)\n") % (
742 int(args[0]) - 1, args[1])
742 int(args[0]) - 1, args[1])
743 except IOError:
743 except IOError:
744 desc = _("rolling back unknown transaction\n")
744 desc = _("rolling back unknown transaction\n")
745 self.ui.status(desc)
745 self.ui.status(desc)
746 if dryrun:
746 if dryrun:
747 return
747 return
748 transaction.rollback(self.sopener, self.sjoin("undo"),
748 transaction.rollback(self.sopener, self.sjoin("undo"),
749 self.ui.warn)
749 self.ui.warn)
750 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
750 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
751 if os.path.exists(self.join('undo.bookmarks')):
751 if os.path.exists(self.join('undo.bookmarks')):
752 util.rename(self.join('undo.bookmarks'),
752 util.rename(self.join('undo.bookmarks'),
753 self.join('bookmarks'))
753 self.join('bookmarks'))
754 try:
754 try:
755 branch = self.opener.read("undo.branch")
755 branch = self.opener.read("undo.branch")
756 self.dirstate.setbranch(branch)
756 self.dirstate.setbranch(branch)
757 except IOError:
757 except IOError:
758 self.ui.warn(_("named branch could not be reset, "
758 self.ui.warn(_("named branch could not be reset, "
759 "current branch is still: %s\n")
759 "current branch is still: %s\n")
760 % self.dirstate.branch())
760 % self.dirstate.branch())
761 self.invalidate()
761 self.invalidate()
762 self.dirstate.invalidate()
762 self.dirstate.invalidate()
763 self.destroyed()
763 self.destroyed()
764 parents = tuple([p.rev() for p in self.parents()])
764 parents = tuple([p.rev() for p in self.parents()])
765 if len(parents) > 1:
765 if len(parents) > 1:
766 self.ui.status(_("working directory now based on "
766 self.ui.status(_("working directory now based on "
767 "revisions %d and %d\n") % parents)
767 "revisions %d and %d\n") % parents)
768 else:
768 else:
769 self.ui.status(_("working directory now based on "
769 self.ui.status(_("working directory now based on "
770 "revision %d\n") % parents)
770 "revision %d\n") % parents)
771 else:
771 else:
772 self.ui.warn(_("no rollback information available\n"))
772 self.ui.warn(_("no rollback information available\n"))
773 return 1
773 return 1
774 finally:
774 finally:
775 release(lock, wlock)
775 release(lock, wlock)
776
776
777 def invalidatecaches(self):
777 def invalidatecaches(self):
778 self._tags = None
778 self._tags = None
779 self._tagtypes = None
779 self._tagtypes = None
780 self.nodetagscache = None
780 self.nodetagscache = None
781 self._branchcache = None # in UTF-8
781 self._branchcache = None # in UTF-8
782 self._branchcachetip = None
782 self._branchcachetip = None
783
783
784 def invalidate(self):
784 def invalidate(self):
785 for a in ("changelog", "manifest", "_bookmarks", "_bookmarkcurrent"):
785 for a in ("changelog", "manifest", "_bookmarks", "_bookmarkcurrent"):
786 if a in self.__dict__:
786 if a in self.__dict__:
787 delattr(self, a)
787 delattr(self, a)
788 self.invalidatecaches()
788 self.invalidatecaches()
789
789
790 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
790 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
791 try:
791 try:
792 l = lock.lock(lockname, 0, releasefn, desc=desc)
792 l = lock.lock(lockname, 0, releasefn, desc=desc)
793 except error.LockHeld, inst:
793 except error.LockHeld, inst:
794 if not wait:
794 if not wait:
795 raise
795 raise
796 self.ui.warn(_("waiting for lock on %s held by %r\n") %
796 self.ui.warn(_("waiting for lock on %s held by %r\n") %
797 (desc, inst.locker))
797 (desc, inst.locker))
798 # default to 600 seconds timeout
798 # default to 600 seconds timeout
799 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
799 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
800 releasefn, desc=desc)
800 releasefn, desc=desc)
801 if acquirefn:
801 if acquirefn:
802 acquirefn()
802 acquirefn()
803 return l
803 return l
804
804
805 def lock(self, wait=True):
805 def lock(self, wait=True):
806 '''Lock the repository store (.hg/store) and return a weak reference
806 '''Lock the repository store (.hg/store) and return a weak reference
807 to the lock. Use this before modifying the store (e.g. committing or
807 to the lock. Use this before modifying the store (e.g. committing or
808 stripping). If you are opening a transaction, get a lock as well.)'''
808 stripping). If you are opening a transaction, get a lock as well.)'''
809 l = self._lockref and self._lockref()
809 l = self._lockref and self._lockref()
810 if l is not None and l.held:
810 if l is not None and l.held:
811 l.lock()
811 l.lock()
812 return l
812 return l
813
813
814 l = self._lock(self.sjoin("lock"), wait, self.store.write,
814 l = self._lock(self.sjoin("lock"), wait, self.store.write,
815 self.invalidate, _('repository %s') % self.origroot)
815 self.invalidate, _('repository %s') % self.origroot)
816 self._lockref = weakref.ref(l)
816 self._lockref = weakref.ref(l)
817 return l
817 return l
818
818
819 def wlock(self, wait=True):
819 def wlock(self, wait=True):
820 '''Lock the non-store parts of the repository (everything under
820 '''Lock the non-store parts of the repository (everything under
821 .hg except .hg/store) and return a weak reference to the lock.
821 .hg except .hg/store) and return a weak reference to the lock.
822 Use this before modifying files in .hg.'''
822 Use this before modifying files in .hg.'''
823 l = self._wlockref and self._wlockref()
823 l = self._wlockref and self._wlockref()
824 if l is not None and l.held:
824 if l is not None and l.held:
825 l.lock()
825 l.lock()
826 return l
826 return l
827
827
828 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
828 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
829 self.dirstate.invalidate, _('working directory of %s') %
829 self.dirstate.invalidate, _('working directory of %s') %
830 self.origroot)
830 self.origroot)
831 self._wlockref = weakref.ref(l)
831 self._wlockref = weakref.ref(l)
832 return l
832 return l
833
833
834 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
834 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
835 """
835 """
836 commit an individual file as part of a larger transaction
836 commit an individual file as part of a larger transaction
837 """
837 """
838
838
839 fname = fctx.path()
839 fname = fctx.path()
840 text = fctx.data()
840 text = fctx.data()
841 flog = self.file(fname)
841 flog = self.file(fname)
842 fparent1 = manifest1.get(fname, nullid)
842 fparent1 = manifest1.get(fname, nullid)
843 fparent2 = fparent2o = manifest2.get(fname, nullid)
843 fparent2 = fparent2o = manifest2.get(fname, nullid)
844
844
845 meta = {}
845 meta = {}
846 copy = fctx.renamed()
846 copy = fctx.renamed()
847 if copy and copy[0] != fname:
847 if copy and copy[0] != fname:
848 # Mark the new revision of this file as a copy of another
848 # Mark the new revision of this file as a copy of another
849 # file. This copy data will effectively act as a parent
849 # file. This copy data will effectively act as a parent
850 # of this new revision. If this is a merge, the first
850 # of this new revision. If this is a merge, the first
851 # parent will be the nullid (meaning "look up the copy data")
851 # parent will be the nullid (meaning "look up the copy data")
852 # and the second one will be the other parent. For example:
852 # and the second one will be the other parent. For example:
853 #
853 #
854 # 0 --- 1 --- 3 rev1 changes file foo
854 # 0 --- 1 --- 3 rev1 changes file foo
855 # \ / rev2 renames foo to bar and changes it
855 # \ / rev2 renames foo to bar and changes it
856 # \- 2 -/ rev3 should have bar with all changes and
856 # \- 2 -/ rev3 should have bar with all changes and
857 # should record that bar descends from
857 # should record that bar descends from
858 # bar in rev2 and foo in rev1
858 # bar in rev2 and foo in rev1
859 #
859 #
860 # this allows this merge to succeed:
860 # this allows this merge to succeed:
861 #
861 #
862 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
862 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
863 # \ / merging rev3 and rev4 should use bar@rev2
863 # \ / merging rev3 and rev4 should use bar@rev2
864 # \- 2 --- 4 as the merge base
864 # \- 2 --- 4 as the merge base
865 #
865 #
866
866
867 cfname = copy[0]
867 cfname = copy[0]
868 crev = manifest1.get(cfname)
868 crev = manifest1.get(cfname)
869 newfparent = fparent2
869 newfparent = fparent2
870
870
871 if manifest2: # branch merge
871 if manifest2: # branch merge
872 if fparent2 == nullid or crev is None: # copied on remote side
872 if fparent2 == nullid or crev is None: # copied on remote side
873 if cfname in manifest2:
873 if cfname in manifest2:
874 crev = manifest2[cfname]
874 crev = manifest2[cfname]
875 newfparent = fparent1
875 newfparent = fparent1
876
876
877 # find source in nearest ancestor if we've lost track
877 # find source in nearest ancestor if we've lost track
878 if not crev:
878 if not crev:
879 self.ui.debug(" %s: searching for copy revision for %s\n" %
879 self.ui.debug(" %s: searching for copy revision for %s\n" %
880 (fname, cfname))
880 (fname, cfname))
881 for ancestor in self[None].ancestors():
881 for ancestor in self[None].ancestors():
882 if cfname in ancestor:
882 if cfname in ancestor:
883 crev = ancestor[cfname].filenode()
883 crev = ancestor[cfname].filenode()
884 break
884 break
885
885
886 if crev:
886 if crev:
887 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
887 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
888 meta["copy"] = cfname
888 meta["copy"] = cfname
889 meta["copyrev"] = hex(crev)
889 meta["copyrev"] = hex(crev)
890 fparent1, fparent2 = nullid, newfparent
890 fparent1, fparent2 = nullid, newfparent
891 else:
891 else:
892 self.ui.warn(_("warning: can't find ancestor for '%s' "
892 self.ui.warn(_("warning: can't find ancestor for '%s' "
893 "copied from '%s'!\n") % (fname, cfname))
893 "copied from '%s'!\n") % (fname, cfname))
894
894
895 elif fparent2 != nullid:
895 elif fparent2 != nullid:
896 # is one parent an ancestor of the other?
896 # is one parent an ancestor of the other?
897 fparentancestor = flog.ancestor(fparent1, fparent2)
897 fparentancestor = flog.ancestor(fparent1, fparent2)
898 if fparentancestor == fparent1:
898 if fparentancestor == fparent1:
899 fparent1, fparent2 = fparent2, nullid
899 fparent1, fparent2 = fparent2, nullid
900 elif fparentancestor == fparent2:
900 elif fparentancestor == fparent2:
901 fparent2 = nullid
901 fparent2 = nullid
902
902
903 # is the file changed?
903 # is the file changed?
904 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
904 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
905 changelist.append(fname)
905 changelist.append(fname)
906 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
906 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
907
907
908 # are just the flags changed during merge?
908 # are just the flags changed during merge?
909 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
909 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
910 changelist.append(fname)
910 changelist.append(fname)
911
911
912 return fparent1
912 return fparent1
913
913
914 def commit(self, text="", user=None, date=None, match=None, force=False,
914 def commit(self, text="", user=None, date=None, match=None, force=False,
915 editor=False, extra={}):
915 editor=False, extra={}):
916 """Add a new revision to current repository.
916 """Add a new revision to current repository.
917
917
918 Revision information is gathered from the working directory,
918 Revision information is gathered from the working directory,
919 match can be used to filter the committed files. If editor is
919 match can be used to filter the committed files. If editor is
920 supplied, it is called to get a commit message.
920 supplied, it is called to get a commit message.
921 """
921 """
922
922
923 def fail(f, msg):
923 def fail(f, msg):
924 raise util.Abort('%s: %s' % (f, msg))
924 raise util.Abort('%s: %s' % (f, msg))
925
925
926 if not match:
926 if not match:
927 match = matchmod.always(self.root, '')
927 match = matchmod.always(self.root, '')
928
928
929 if not force:
929 if not force:
930 vdirs = []
930 vdirs = []
931 match.dir = vdirs.append
931 match.dir = vdirs.append
932 match.bad = fail
932 match.bad = fail
933
933
934 wlock = self.wlock()
934 wlock = self.wlock()
935 try:
935 try:
936 wctx = self[None]
936 wctx = self[None]
937 merge = len(wctx.parents()) > 1
937 merge = len(wctx.parents()) > 1
938
938
939 if (not force and merge and match and
939 if (not force and merge and match and
940 (match.files() or match.anypats())):
940 (match.files() or match.anypats())):
941 raise util.Abort(_('cannot partially commit a merge '
941 raise util.Abort(_('cannot partially commit a merge '
942 '(do not specify files or patterns)'))
942 '(do not specify files or patterns)'))
943
943
944 changes = self.status(match=match, clean=force)
944 changes = self.status(match=match, clean=force)
945 if force:
945 if force:
946 changes[0].extend(changes[6]) # mq may commit unchanged files
946 changes[0].extend(changes[6]) # mq may commit unchanged files
947
947
948 # check subrepos
948 # check subrepos
949 subs = []
949 subs = []
950 removedsubs = set()
950 removedsubs = set()
951 for p in wctx.parents():
951 for p in wctx.parents():
952 removedsubs.update(s for s in p.substate if match(s))
952 removedsubs.update(s for s in p.substate if match(s))
953 for s in wctx.substate:
953 for s in wctx.substate:
954 removedsubs.discard(s)
954 removedsubs.discard(s)
955 if match(s) and wctx.sub(s).dirty():
955 if match(s) and wctx.sub(s).dirty():
956 subs.append(s)
956 subs.append(s)
957 if (subs or removedsubs):
957 if (subs or removedsubs):
958 if (not match('.hgsub') and
958 if (not match('.hgsub') and
959 '.hgsub' in (wctx.modified() + wctx.added())):
959 '.hgsub' in (wctx.modified() + wctx.added())):
960 raise util.Abort(_("can't commit subrepos without .hgsub"))
960 raise util.Abort(_("can't commit subrepos without .hgsub"))
961 if '.hgsubstate' not in changes[0]:
961 if '.hgsubstate' not in changes[0]:
962 changes[0].insert(0, '.hgsubstate')
962 changes[0].insert(0, '.hgsubstate')
963
963
964 if subs and not self.ui.configbool('ui', 'commitsubrepos', True):
964 if subs and not self.ui.configbool('ui', 'commitsubrepos', True):
965 changedsubs = [s for s in subs if wctx.sub(s).dirty(True)]
965 changedsubs = [s for s in subs if wctx.sub(s).dirty(True)]
966 if changedsubs:
966 if changedsubs:
967 raise util.Abort(_("uncommitted changes in subrepo %s")
967 raise util.Abort(_("uncommitted changes in subrepo %s")
968 % changedsubs[0])
968 % changedsubs[0])
969
969
970 # make sure all explicit patterns are matched
970 # make sure all explicit patterns are matched
971 if not force and match.files():
971 if not force and match.files():
972 matched = set(changes[0] + changes[1] + changes[2])
972 matched = set(changes[0] + changes[1] + changes[2])
973
973
974 for f in match.files():
974 for f in match.files():
975 if f == '.' or f in matched or f in wctx.substate:
975 if f == '.' or f in matched or f in wctx.substate:
976 continue
976 continue
977 if f in changes[3]: # missing
977 if f in changes[3]: # missing
978 fail(f, _('file not found!'))
978 fail(f, _('file not found!'))
979 if f in vdirs: # visited directory
979 if f in vdirs: # visited directory
980 d = f + '/'
980 d = f + '/'
981 for mf in matched:
981 for mf in matched:
982 if mf.startswith(d):
982 if mf.startswith(d):
983 break
983 break
984 else:
984 else:
985 fail(f, _("no match under directory!"))
985 fail(f, _("no match under directory!"))
986 elif f not in self.dirstate:
986 elif f not in self.dirstate:
987 fail(f, _("file not tracked!"))
987 fail(f, _("file not tracked!"))
988
988
989 if (not force and not extra.get("close") and not merge
989 if (not force and not extra.get("close") and not merge
990 and not (changes[0] or changes[1] or changes[2])
990 and not (changes[0] or changes[1] or changes[2])
991 and wctx.branch() == wctx.p1().branch()):
991 and wctx.branch() == wctx.p1().branch()):
992 return None
992 return None
993
993
994 ms = mergemod.mergestate(self)
994 ms = mergemod.mergestate(self)
995 for f in changes[0]:
995 for f in changes[0]:
996 if f in ms and ms[f] == 'u':
996 if f in ms and ms[f] == 'u':
997 raise util.Abort(_("unresolved merge conflicts "
997 raise util.Abort(_("unresolved merge conflicts "
998 "(see hg help resolve)"))
998 "(see hg help resolve)"))
999
999
1000 cctx = context.workingctx(self, text, user, date, extra, changes)
1000 cctx = context.workingctx(self, text, user, date, extra, changes)
1001 if editor:
1001 if editor:
1002 cctx._text = editor(self, cctx, subs)
1002 cctx._text = editor(self, cctx, subs)
1003 edited = (text != cctx._text)
1003 edited = (text != cctx._text)
1004
1004
1005 # commit subs
1005 # commit subs
1006 if subs or removedsubs:
1006 if subs or removedsubs:
1007 state = wctx.substate.copy()
1007 state = wctx.substate.copy()
1008 for s in sorted(subs):
1008 for s in sorted(subs):
1009 sub = wctx.sub(s)
1009 sub = wctx.sub(s)
1010 self.ui.status(_('committing subrepository %s\n') %
1010 self.ui.status(_('committing subrepository %s\n') %
1011 subrepo.subrelpath(sub))
1011 subrepo.subrelpath(sub))
1012 sr = sub.commit(cctx._text, user, date)
1012 sr = sub.commit(cctx._text, user, date)
1013 state[s] = (state[s][0], sr)
1013 state[s] = (state[s][0], sr)
1014 subrepo.writestate(self, state)
1014 subrepo.writestate(self, state)
1015
1015
1016 # Save commit message in case this transaction gets rolled back
1016 # Save commit message in case this transaction gets rolled back
1017 # (e.g. by a pretxncommit hook). Leave the content alone on
1017 # (e.g. by a pretxncommit hook). Leave the content alone on
1018 # the assumption that the user will use the same editor again.
1018 # the assumption that the user will use the same editor again.
1019 msgfile = self.opener('last-message.txt', 'wb')
1019 msgfile = self.opener('last-message.txt', 'wb')
1020 msgfile.write(cctx._text)
1020 msgfile.write(cctx._text)
1021 msgfile.close()
1021 msgfile.close()
1022
1022
1023 p1, p2 = self.dirstate.parents()
1023 p1, p2 = self.dirstate.parents()
1024 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1024 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1025 try:
1025 try:
1026 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1026 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1027 ret = self.commitctx(cctx, True)
1027 ret = self.commitctx(cctx, True)
1028 except:
1028 except:
1029 if edited:
1029 if edited:
1030 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
1030 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
1031 self.ui.write(
1031 self.ui.write(
1032 _('note: commit message saved in %s\n') % msgfn)
1032 _('note: commit message saved in %s\n') % msgfn)
1033 raise
1033 raise
1034
1034
1035 # update bookmarks, dirstate and mergestate
1035 # update bookmarks, dirstate and mergestate
1036 bookmarks.update(self, p1, ret)
1036 bookmarks.update(self, p1, ret)
1037 for f in changes[0] + changes[1]:
1037 for f in changes[0] + changes[1]:
1038 self.dirstate.normal(f)
1038 self.dirstate.normal(f)
1039 for f in changes[2]:
1039 for f in changes[2]:
1040 self.dirstate.forget(f)
1040 self.dirstate.drop(f)
1041 self.dirstate.setparents(ret)
1041 self.dirstate.setparents(ret)
1042 ms.reset()
1042 ms.reset()
1043 finally:
1043 finally:
1044 wlock.release()
1044 wlock.release()
1045
1045
1046 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1046 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1047 return ret
1047 return ret
1048
1048
1049 def commitctx(self, ctx, error=False):
1049 def commitctx(self, ctx, error=False):
1050 """Add a new revision to current repository.
1050 """Add a new revision to current repository.
1051 Revision information is passed via the context argument.
1051 Revision information is passed via the context argument.
1052 """
1052 """
1053
1053
1054 tr = lock = None
1054 tr = lock = None
1055 removed = list(ctx.removed())
1055 removed = list(ctx.removed())
1056 p1, p2 = ctx.p1(), ctx.p2()
1056 p1, p2 = ctx.p1(), ctx.p2()
1057 user = ctx.user()
1057 user = ctx.user()
1058
1058
1059 lock = self.lock()
1059 lock = self.lock()
1060 try:
1060 try:
1061 tr = self.transaction("commit")
1061 tr = self.transaction("commit")
1062 trp = weakref.proxy(tr)
1062 trp = weakref.proxy(tr)
1063
1063
1064 if ctx.files():
1064 if ctx.files():
1065 m1 = p1.manifest().copy()
1065 m1 = p1.manifest().copy()
1066 m2 = p2.manifest()
1066 m2 = p2.manifest()
1067
1067
1068 # check in files
1068 # check in files
1069 new = {}
1069 new = {}
1070 changed = []
1070 changed = []
1071 linkrev = len(self)
1071 linkrev = len(self)
1072 for f in sorted(ctx.modified() + ctx.added()):
1072 for f in sorted(ctx.modified() + ctx.added()):
1073 self.ui.note(f + "\n")
1073 self.ui.note(f + "\n")
1074 try:
1074 try:
1075 fctx = ctx[f]
1075 fctx = ctx[f]
1076 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1076 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1077 changed)
1077 changed)
1078 m1.set(f, fctx.flags())
1078 m1.set(f, fctx.flags())
1079 except OSError, inst:
1079 except OSError, inst:
1080 self.ui.warn(_("trouble committing %s!\n") % f)
1080 self.ui.warn(_("trouble committing %s!\n") % f)
1081 raise
1081 raise
1082 except IOError, inst:
1082 except IOError, inst:
1083 errcode = getattr(inst, 'errno', errno.ENOENT)
1083 errcode = getattr(inst, 'errno', errno.ENOENT)
1084 if error or errcode and errcode != errno.ENOENT:
1084 if error or errcode and errcode != errno.ENOENT:
1085 self.ui.warn(_("trouble committing %s!\n") % f)
1085 self.ui.warn(_("trouble committing %s!\n") % f)
1086 raise
1086 raise
1087 else:
1087 else:
1088 removed.append(f)
1088 removed.append(f)
1089
1089
1090 # update manifest
1090 # update manifest
1091 m1.update(new)
1091 m1.update(new)
1092 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1092 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1093 drop = [f for f in removed if f in m1]
1093 drop = [f for f in removed if f in m1]
1094 for f in drop:
1094 for f in drop:
1095 del m1[f]
1095 del m1[f]
1096 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1096 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1097 p2.manifestnode(), (new, drop))
1097 p2.manifestnode(), (new, drop))
1098 files = changed + removed
1098 files = changed + removed
1099 else:
1099 else:
1100 mn = p1.manifestnode()
1100 mn = p1.manifestnode()
1101 files = []
1101 files = []
1102
1102
1103 # update changelog
1103 # update changelog
1104 self.changelog.delayupdate()
1104 self.changelog.delayupdate()
1105 n = self.changelog.add(mn, files, ctx.description(),
1105 n = self.changelog.add(mn, files, ctx.description(),
1106 trp, p1.node(), p2.node(),
1106 trp, p1.node(), p2.node(),
1107 user, ctx.date(), ctx.extra().copy())
1107 user, ctx.date(), ctx.extra().copy())
1108 p = lambda: self.changelog.writepending() and self.root or ""
1108 p = lambda: self.changelog.writepending() and self.root or ""
1109 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1109 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1110 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1110 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1111 parent2=xp2, pending=p)
1111 parent2=xp2, pending=p)
1112 self.changelog.finalize(trp)
1112 self.changelog.finalize(trp)
1113 tr.close()
1113 tr.close()
1114
1114
1115 if self._branchcache:
1115 if self._branchcache:
1116 self.updatebranchcache()
1116 self.updatebranchcache()
1117 return n
1117 return n
1118 finally:
1118 finally:
1119 if tr:
1119 if tr:
1120 tr.release()
1120 tr.release()
1121 lock.release()
1121 lock.release()
1122
1122
1123 def destroyed(self):
1123 def destroyed(self):
1124 '''Inform the repository that nodes have been destroyed.
1124 '''Inform the repository that nodes have been destroyed.
1125 Intended for use by strip and rollback, so there's a common
1125 Intended for use by strip and rollback, so there's a common
1126 place for anything that has to be done after destroying history.'''
1126 place for anything that has to be done after destroying history.'''
1127 # XXX it might be nice if we could take the list of destroyed
1127 # XXX it might be nice if we could take the list of destroyed
1128 # nodes, but I don't see an easy way for rollback() to do that
1128 # nodes, but I don't see an easy way for rollback() to do that
1129
1129
1130 # Ensure the persistent tag cache is updated. Doing it now
1130 # Ensure the persistent tag cache is updated. Doing it now
1131 # means that the tag cache only has to worry about destroyed
1131 # means that the tag cache only has to worry about destroyed
1132 # heads immediately after a strip/rollback. That in turn
1132 # heads immediately after a strip/rollback. That in turn
1133 # guarantees that "cachetip == currenttip" (comparing both rev
1133 # guarantees that "cachetip == currenttip" (comparing both rev
1134 # and node) always means no nodes have been added or destroyed.
1134 # and node) always means no nodes have been added or destroyed.
1135
1135
1136 # XXX this is suboptimal when qrefresh'ing: we strip the current
1136 # XXX this is suboptimal when qrefresh'ing: we strip the current
1137 # head, refresh the tag cache, then immediately add a new head.
1137 # head, refresh the tag cache, then immediately add a new head.
1138 # But I think doing it this way is necessary for the "instant
1138 # But I think doing it this way is necessary for the "instant
1139 # tag cache retrieval" case to work.
1139 # tag cache retrieval" case to work.
1140 self.invalidatecaches()
1140 self.invalidatecaches()
1141
1141
1142 def walk(self, match, node=None):
1142 def walk(self, match, node=None):
1143 '''
1143 '''
1144 walk recursively through the directory tree or a given
1144 walk recursively through the directory tree or a given
1145 changeset, finding all files matched by the match
1145 changeset, finding all files matched by the match
1146 function
1146 function
1147 '''
1147 '''
1148 return self[node].walk(match)
1148 return self[node].walk(match)
1149
1149
1150 def status(self, node1='.', node2=None, match=None,
1150 def status(self, node1='.', node2=None, match=None,
1151 ignored=False, clean=False, unknown=False,
1151 ignored=False, clean=False, unknown=False,
1152 listsubrepos=False):
1152 listsubrepos=False):
1153 """return status of files between two nodes or node and working directory
1153 """return status of files between two nodes or node and working directory
1154
1154
1155 If node1 is None, use the first dirstate parent instead.
1155 If node1 is None, use the first dirstate parent instead.
1156 If node2 is None, compare node1 with working directory.
1156 If node2 is None, compare node1 with working directory.
1157 """
1157 """
1158
1158
1159 def mfmatches(ctx):
1159 def mfmatches(ctx):
1160 mf = ctx.manifest().copy()
1160 mf = ctx.manifest().copy()
1161 for fn in mf.keys():
1161 for fn in mf.keys():
1162 if not match(fn):
1162 if not match(fn):
1163 del mf[fn]
1163 del mf[fn]
1164 return mf
1164 return mf
1165
1165
1166 if isinstance(node1, context.changectx):
1166 if isinstance(node1, context.changectx):
1167 ctx1 = node1
1167 ctx1 = node1
1168 else:
1168 else:
1169 ctx1 = self[node1]
1169 ctx1 = self[node1]
1170 if isinstance(node2, context.changectx):
1170 if isinstance(node2, context.changectx):
1171 ctx2 = node2
1171 ctx2 = node2
1172 else:
1172 else:
1173 ctx2 = self[node2]
1173 ctx2 = self[node2]
1174
1174
1175 working = ctx2.rev() is None
1175 working = ctx2.rev() is None
1176 parentworking = working and ctx1 == self['.']
1176 parentworking = working and ctx1 == self['.']
1177 match = match or matchmod.always(self.root, self.getcwd())
1177 match = match or matchmod.always(self.root, self.getcwd())
1178 listignored, listclean, listunknown = ignored, clean, unknown
1178 listignored, listclean, listunknown = ignored, clean, unknown
1179
1179
1180 # load earliest manifest first for caching reasons
1180 # load earliest manifest first for caching reasons
1181 if not working and ctx2.rev() < ctx1.rev():
1181 if not working and ctx2.rev() < ctx1.rev():
1182 ctx2.manifest()
1182 ctx2.manifest()
1183
1183
1184 if not parentworking:
1184 if not parentworking:
1185 def bad(f, msg):
1185 def bad(f, msg):
1186 if f not in ctx1:
1186 if f not in ctx1:
1187 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1187 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1188 match.bad = bad
1188 match.bad = bad
1189
1189
1190 if working: # we need to scan the working dir
1190 if working: # we need to scan the working dir
1191 subrepos = []
1191 subrepos = []
1192 if '.hgsub' in self.dirstate:
1192 if '.hgsub' in self.dirstate:
1193 subrepos = ctx1.substate.keys()
1193 subrepos = ctx1.substate.keys()
1194 s = self.dirstate.status(match, subrepos, listignored,
1194 s = self.dirstate.status(match, subrepos, listignored,
1195 listclean, listunknown)
1195 listclean, listunknown)
1196 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1196 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1197
1197
1198 # check for any possibly clean files
1198 # check for any possibly clean files
1199 if parentworking and cmp:
1199 if parentworking and cmp:
1200 fixup = []
1200 fixup = []
1201 # do a full compare of any files that might have changed
1201 # do a full compare of any files that might have changed
1202 for f in sorted(cmp):
1202 for f in sorted(cmp):
1203 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1203 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1204 or ctx1[f].cmp(ctx2[f])):
1204 or ctx1[f].cmp(ctx2[f])):
1205 modified.append(f)
1205 modified.append(f)
1206 else:
1206 else:
1207 fixup.append(f)
1207 fixup.append(f)
1208
1208
1209 # update dirstate for files that are actually clean
1209 # update dirstate for files that are actually clean
1210 if fixup:
1210 if fixup:
1211 if listclean:
1211 if listclean:
1212 clean += fixup
1212 clean += fixup
1213
1213
1214 try:
1214 try:
1215 # updating the dirstate is optional
1215 # updating the dirstate is optional
1216 # so we don't wait on the lock
1216 # so we don't wait on the lock
1217 wlock = self.wlock(False)
1217 wlock = self.wlock(False)
1218 try:
1218 try:
1219 for f in fixup:
1219 for f in fixup:
1220 self.dirstate.normal(f)
1220 self.dirstate.normal(f)
1221 finally:
1221 finally:
1222 wlock.release()
1222 wlock.release()
1223 except error.LockError:
1223 except error.LockError:
1224 pass
1224 pass
1225
1225
1226 if not parentworking:
1226 if not parentworking:
1227 mf1 = mfmatches(ctx1)
1227 mf1 = mfmatches(ctx1)
1228 if working:
1228 if working:
1229 # we are comparing working dir against non-parent
1229 # we are comparing working dir against non-parent
1230 # generate a pseudo-manifest for the working dir
1230 # generate a pseudo-manifest for the working dir
1231 mf2 = mfmatches(self['.'])
1231 mf2 = mfmatches(self['.'])
1232 for f in cmp + modified + added:
1232 for f in cmp + modified + added:
1233 mf2[f] = None
1233 mf2[f] = None
1234 mf2.set(f, ctx2.flags(f))
1234 mf2.set(f, ctx2.flags(f))
1235 for f in removed:
1235 for f in removed:
1236 if f in mf2:
1236 if f in mf2:
1237 del mf2[f]
1237 del mf2[f]
1238 else:
1238 else:
1239 # we are comparing two revisions
1239 # we are comparing two revisions
1240 deleted, unknown, ignored = [], [], []
1240 deleted, unknown, ignored = [], [], []
1241 mf2 = mfmatches(ctx2)
1241 mf2 = mfmatches(ctx2)
1242
1242
1243 modified, added, clean = [], [], []
1243 modified, added, clean = [], [], []
1244 for fn in mf2:
1244 for fn in mf2:
1245 if fn in mf1:
1245 if fn in mf1:
1246 if (fn not in deleted and
1246 if (fn not in deleted and
1247 (mf1.flags(fn) != mf2.flags(fn) or
1247 (mf1.flags(fn) != mf2.flags(fn) or
1248 (mf1[fn] != mf2[fn] and
1248 (mf1[fn] != mf2[fn] and
1249 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1249 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1250 modified.append(fn)
1250 modified.append(fn)
1251 elif listclean:
1251 elif listclean:
1252 clean.append(fn)
1252 clean.append(fn)
1253 del mf1[fn]
1253 del mf1[fn]
1254 elif fn not in deleted:
1254 elif fn not in deleted:
1255 added.append(fn)
1255 added.append(fn)
1256 removed = mf1.keys()
1256 removed = mf1.keys()
1257
1257
1258 r = modified, added, removed, deleted, unknown, ignored, clean
1258 r = modified, added, removed, deleted, unknown, ignored, clean
1259
1259
1260 if listsubrepos:
1260 if listsubrepos:
1261 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1261 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1262 if working:
1262 if working:
1263 rev2 = None
1263 rev2 = None
1264 else:
1264 else:
1265 rev2 = ctx2.substate[subpath][1]
1265 rev2 = ctx2.substate[subpath][1]
1266 try:
1266 try:
1267 submatch = matchmod.narrowmatcher(subpath, match)
1267 submatch = matchmod.narrowmatcher(subpath, match)
1268 s = sub.status(rev2, match=submatch, ignored=listignored,
1268 s = sub.status(rev2, match=submatch, ignored=listignored,
1269 clean=listclean, unknown=listunknown,
1269 clean=listclean, unknown=listunknown,
1270 listsubrepos=True)
1270 listsubrepos=True)
1271 for rfiles, sfiles in zip(r, s):
1271 for rfiles, sfiles in zip(r, s):
1272 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1272 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1273 except error.LookupError:
1273 except error.LookupError:
1274 self.ui.status(_("skipping missing subrepository: %s\n")
1274 self.ui.status(_("skipping missing subrepository: %s\n")
1275 % subpath)
1275 % subpath)
1276
1276
1277 for l in r:
1277 for l in r:
1278 l.sort()
1278 l.sort()
1279 return r
1279 return r
1280
1280
1281 def heads(self, start=None):
1281 def heads(self, start=None):
1282 heads = self.changelog.heads(start)
1282 heads = self.changelog.heads(start)
1283 # sort the output in rev descending order
1283 # sort the output in rev descending order
1284 return sorted(heads, key=self.changelog.rev, reverse=True)
1284 return sorted(heads, key=self.changelog.rev, reverse=True)
1285
1285
1286 def branchheads(self, branch=None, start=None, closed=False):
1286 def branchheads(self, branch=None, start=None, closed=False):
1287 '''return a (possibly filtered) list of heads for the given branch
1287 '''return a (possibly filtered) list of heads for the given branch
1288
1288
1289 Heads are returned in topological order, from newest to oldest.
1289 Heads are returned in topological order, from newest to oldest.
1290 If branch is None, use the dirstate branch.
1290 If branch is None, use the dirstate branch.
1291 If start is not None, return only heads reachable from start.
1291 If start is not None, return only heads reachable from start.
1292 If closed is True, return heads that are marked as closed as well.
1292 If closed is True, return heads that are marked as closed as well.
1293 '''
1293 '''
1294 if branch is None:
1294 if branch is None:
1295 branch = self[None].branch()
1295 branch = self[None].branch()
1296 branches = self.branchmap()
1296 branches = self.branchmap()
1297 if branch not in branches:
1297 if branch not in branches:
1298 return []
1298 return []
1299 # the cache returns heads ordered lowest to highest
1299 # the cache returns heads ordered lowest to highest
1300 bheads = list(reversed(branches[branch]))
1300 bheads = list(reversed(branches[branch]))
1301 if start is not None:
1301 if start is not None:
1302 # filter out the heads that cannot be reached from startrev
1302 # filter out the heads that cannot be reached from startrev
1303 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1303 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1304 bheads = [h for h in bheads if h in fbheads]
1304 bheads = [h for h in bheads if h in fbheads]
1305 if not closed:
1305 if not closed:
1306 bheads = [h for h in bheads if
1306 bheads = [h for h in bheads if
1307 ('close' not in self.changelog.read(h)[5])]
1307 ('close' not in self.changelog.read(h)[5])]
1308 return bheads
1308 return bheads
1309
1309
1310 def branches(self, nodes):
1310 def branches(self, nodes):
1311 if not nodes:
1311 if not nodes:
1312 nodes = [self.changelog.tip()]
1312 nodes = [self.changelog.tip()]
1313 b = []
1313 b = []
1314 for n in nodes:
1314 for n in nodes:
1315 t = n
1315 t = n
1316 while 1:
1316 while 1:
1317 p = self.changelog.parents(n)
1317 p = self.changelog.parents(n)
1318 if p[1] != nullid or p[0] == nullid:
1318 if p[1] != nullid or p[0] == nullid:
1319 b.append((t, n, p[0], p[1]))
1319 b.append((t, n, p[0], p[1]))
1320 break
1320 break
1321 n = p[0]
1321 n = p[0]
1322 return b
1322 return b
1323
1323
1324 def between(self, pairs):
1324 def between(self, pairs):
1325 r = []
1325 r = []
1326
1326
1327 for top, bottom in pairs:
1327 for top, bottom in pairs:
1328 n, l, i = top, [], 0
1328 n, l, i = top, [], 0
1329 f = 1
1329 f = 1
1330
1330
1331 while n != bottom and n != nullid:
1331 while n != bottom and n != nullid:
1332 p = self.changelog.parents(n)[0]
1332 p = self.changelog.parents(n)[0]
1333 if i == f:
1333 if i == f:
1334 l.append(n)
1334 l.append(n)
1335 f = f * 2
1335 f = f * 2
1336 n = p
1336 n = p
1337 i += 1
1337 i += 1
1338
1338
1339 r.append(l)
1339 r.append(l)
1340
1340
1341 return r
1341 return r
1342
1342
1343 def pull(self, remote, heads=None, force=False):
1343 def pull(self, remote, heads=None, force=False):
1344 lock = self.lock()
1344 lock = self.lock()
1345 try:
1345 try:
1346 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1346 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1347 force=force)
1347 force=force)
1348 common, fetch, rheads = tmp
1348 common, fetch, rheads = tmp
1349 if not fetch:
1349 if not fetch:
1350 self.ui.status(_("no changes found\n"))
1350 self.ui.status(_("no changes found\n"))
1351 result = 0
1351 result = 0
1352 else:
1352 else:
1353 if heads is None and list(common) == [nullid]:
1353 if heads is None and list(common) == [nullid]:
1354 self.ui.status(_("requesting all changes\n"))
1354 self.ui.status(_("requesting all changes\n"))
1355 elif heads is None and remote.capable('changegroupsubset'):
1355 elif heads is None and remote.capable('changegroupsubset'):
1356 # issue1320, avoid a race if remote changed after discovery
1356 # issue1320, avoid a race if remote changed after discovery
1357 heads = rheads
1357 heads = rheads
1358
1358
1359 if remote.capable('getbundle'):
1359 if remote.capable('getbundle'):
1360 cg = remote.getbundle('pull', common=common,
1360 cg = remote.getbundle('pull', common=common,
1361 heads=heads or rheads)
1361 heads=heads or rheads)
1362 elif heads is None:
1362 elif heads is None:
1363 cg = remote.changegroup(fetch, 'pull')
1363 cg = remote.changegroup(fetch, 'pull')
1364 elif not remote.capable('changegroupsubset'):
1364 elif not remote.capable('changegroupsubset'):
1365 raise util.Abort(_("partial pull cannot be done because "
1365 raise util.Abort(_("partial pull cannot be done because "
1366 "other repository doesn't support "
1366 "other repository doesn't support "
1367 "changegroupsubset."))
1367 "changegroupsubset."))
1368 else:
1368 else:
1369 cg = remote.changegroupsubset(fetch, heads, 'pull')
1369 cg = remote.changegroupsubset(fetch, heads, 'pull')
1370 result = self.addchangegroup(cg, 'pull', remote.url(),
1370 result = self.addchangegroup(cg, 'pull', remote.url(),
1371 lock=lock)
1371 lock=lock)
1372 finally:
1372 finally:
1373 lock.release()
1373 lock.release()
1374
1374
1375 return result
1375 return result
1376
1376
1377 def checkpush(self, force, revs):
1377 def checkpush(self, force, revs):
1378 """Extensions can override this function if additional checks have
1378 """Extensions can override this function if additional checks have
1379 to be performed before pushing, or call it if they override push
1379 to be performed before pushing, or call it if they override push
1380 command.
1380 command.
1381 """
1381 """
1382 pass
1382 pass
1383
1383
1384 def push(self, remote, force=False, revs=None, newbranch=False):
1384 def push(self, remote, force=False, revs=None, newbranch=False):
1385 '''Push outgoing changesets (limited by revs) from the current
1385 '''Push outgoing changesets (limited by revs) from the current
1386 repository to remote. Return an integer:
1386 repository to remote. Return an integer:
1387 - 0 means HTTP error *or* nothing to push
1387 - 0 means HTTP error *or* nothing to push
1388 - 1 means we pushed and remote head count is unchanged *or*
1388 - 1 means we pushed and remote head count is unchanged *or*
1389 we have outgoing changesets but refused to push
1389 we have outgoing changesets but refused to push
1390 - other values as described by addchangegroup()
1390 - other values as described by addchangegroup()
1391 '''
1391 '''
1392 # there are two ways to push to remote repo:
1392 # there are two ways to push to remote repo:
1393 #
1393 #
1394 # addchangegroup assumes local user can lock remote
1394 # addchangegroup assumes local user can lock remote
1395 # repo (local filesystem, old ssh servers).
1395 # repo (local filesystem, old ssh servers).
1396 #
1396 #
1397 # unbundle assumes local user cannot lock remote repo (new ssh
1397 # unbundle assumes local user cannot lock remote repo (new ssh
1398 # servers, http servers).
1398 # servers, http servers).
1399
1399
1400 self.checkpush(force, revs)
1400 self.checkpush(force, revs)
1401 lock = None
1401 lock = None
1402 unbundle = remote.capable('unbundle')
1402 unbundle = remote.capable('unbundle')
1403 if not unbundle:
1403 if not unbundle:
1404 lock = remote.lock()
1404 lock = remote.lock()
1405 try:
1405 try:
1406 cg, remote_heads = discovery.prepush(self, remote, force, revs,
1406 cg, remote_heads = discovery.prepush(self, remote, force, revs,
1407 newbranch)
1407 newbranch)
1408 ret = remote_heads
1408 ret = remote_heads
1409 if cg is not None:
1409 if cg is not None:
1410 if unbundle:
1410 if unbundle:
1411 # local repo finds heads on server, finds out what
1411 # local repo finds heads on server, finds out what
1412 # revs it must push. once revs transferred, if server
1412 # revs it must push. once revs transferred, if server
1413 # finds it has different heads (someone else won
1413 # finds it has different heads (someone else won
1414 # commit/push race), server aborts.
1414 # commit/push race), server aborts.
1415 if force:
1415 if force:
1416 remote_heads = ['force']
1416 remote_heads = ['force']
1417 # ssh: return remote's addchangegroup()
1417 # ssh: return remote's addchangegroup()
1418 # http: return remote's addchangegroup() or 0 for error
1418 # http: return remote's addchangegroup() or 0 for error
1419 ret = remote.unbundle(cg, remote_heads, 'push')
1419 ret = remote.unbundle(cg, remote_heads, 'push')
1420 else:
1420 else:
1421 # we return an integer indicating remote head count change
1421 # we return an integer indicating remote head count change
1422 ret = remote.addchangegroup(cg, 'push', self.url(),
1422 ret = remote.addchangegroup(cg, 'push', self.url(),
1423 lock=lock)
1423 lock=lock)
1424 finally:
1424 finally:
1425 if lock is not None:
1425 if lock is not None:
1426 lock.release()
1426 lock.release()
1427
1427
1428 self.ui.debug("checking for updated bookmarks\n")
1428 self.ui.debug("checking for updated bookmarks\n")
1429 rb = remote.listkeys('bookmarks')
1429 rb = remote.listkeys('bookmarks')
1430 for k in rb.keys():
1430 for k in rb.keys():
1431 if k in self._bookmarks:
1431 if k in self._bookmarks:
1432 nr, nl = rb[k], hex(self._bookmarks[k])
1432 nr, nl = rb[k], hex(self._bookmarks[k])
1433 if nr in self:
1433 if nr in self:
1434 cr = self[nr]
1434 cr = self[nr]
1435 cl = self[nl]
1435 cl = self[nl]
1436 if cl in cr.descendants():
1436 if cl in cr.descendants():
1437 r = remote.pushkey('bookmarks', k, nr, nl)
1437 r = remote.pushkey('bookmarks', k, nr, nl)
1438 if r:
1438 if r:
1439 self.ui.status(_("updating bookmark %s\n") % k)
1439 self.ui.status(_("updating bookmark %s\n") % k)
1440 else:
1440 else:
1441 self.ui.warn(_('updating bookmark %s'
1441 self.ui.warn(_('updating bookmark %s'
1442 ' failed!\n') % k)
1442 ' failed!\n') % k)
1443
1443
1444 return ret
1444 return ret
1445
1445
1446 def changegroupinfo(self, nodes, source):
1446 def changegroupinfo(self, nodes, source):
1447 if self.ui.verbose or source == 'bundle':
1447 if self.ui.verbose or source == 'bundle':
1448 self.ui.status(_("%d changesets found\n") % len(nodes))
1448 self.ui.status(_("%d changesets found\n") % len(nodes))
1449 if self.ui.debugflag:
1449 if self.ui.debugflag:
1450 self.ui.debug("list of changesets:\n")
1450 self.ui.debug("list of changesets:\n")
1451 for node in nodes:
1451 for node in nodes:
1452 self.ui.debug("%s\n" % hex(node))
1452 self.ui.debug("%s\n" % hex(node))
1453
1453
1454 def changegroupsubset(self, bases, heads, source):
1454 def changegroupsubset(self, bases, heads, source):
1455 """Compute a changegroup consisting of all the nodes that are
1455 """Compute a changegroup consisting of all the nodes that are
1456 descendents of any of the bases and ancestors of any of the heads.
1456 descendents of any of the bases and ancestors of any of the heads.
1457 Return a chunkbuffer object whose read() method will return
1457 Return a chunkbuffer object whose read() method will return
1458 successive changegroup chunks.
1458 successive changegroup chunks.
1459
1459
1460 It is fairly complex as determining which filenodes and which
1460 It is fairly complex as determining which filenodes and which
1461 manifest nodes need to be included for the changeset to be complete
1461 manifest nodes need to be included for the changeset to be complete
1462 is non-trivial.
1462 is non-trivial.
1463
1463
1464 Another wrinkle is doing the reverse, figuring out which changeset in
1464 Another wrinkle is doing the reverse, figuring out which changeset in
1465 the changegroup a particular filenode or manifestnode belongs to.
1465 the changegroup a particular filenode or manifestnode belongs to.
1466 """
1466 """
1467 cl = self.changelog
1467 cl = self.changelog
1468 if not bases:
1468 if not bases:
1469 bases = [nullid]
1469 bases = [nullid]
1470 csets, bases, heads = cl.nodesbetween(bases, heads)
1470 csets, bases, heads = cl.nodesbetween(bases, heads)
1471 # We assume that all ancestors of bases are known
1471 # We assume that all ancestors of bases are known
1472 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1472 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1473 return self._changegroupsubset(common, csets, heads, source)
1473 return self._changegroupsubset(common, csets, heads, source)
1474
1474
1475 def getbundle(self, source, heads=None, common=None):
1475 def getbundle(self, source, heads=None, common=None):
1476 """Like changegroupsubset, but returns the set difference between the
1476 """Like changegroupsubset, but returns the set difference between the
1477 ancestors of heads and the ancestors common.
1477 ancestors of heads and the ancestors common.
1478
1478
1479 If heads is None, use the local heads. If common is None, use [nullid].
1479 If heads is None, use the local heads. If common is None, use [nullid].
1480
1480
1481 The nodes in common might not all be known locally due to the way the
1481 The nodes in common might not all be known locally due to the way the
1482 current discovery protocol works.
1482 current discovery protocol works.
1483 """
1483 """
1484 cl = self.changelog
1484 cl = self.changelog
1485 if common:
1485 if common:
1486 nm = cl.nodemap
1486 nm = cl.nodemap
1487 common = [n for n in common if n in nm]
1487 common = [n for n in common if n in nm]
1488 else:
1488 else:
1489 common = [nullid]
1489 common = [nullid]
1490 if not heads:
1490 if not heads:
1491 heads = cl.heads()
1491 heads = cl.heads()
1492 common, missing = cl.findcommonmissing(common, heads)
1492 common, missing = cl.findcommonmissing(common, heads)
1493 if not missing:
1493 if not missing:
1494 return None
1494 return None
1495 return self._changegroupsubset(common, missing, heads, source)
1495 return self._changegroupsubset(common, missing, heads, source)
1496
1496
1497 def _changegroupsubset(self, commonrevs, csets, heads, source):
1497 def _changegroupsubset(self, commonrevs, csets, heads, source):
1498
1498
1499 cl = self.changelog
1499 cl = self.changelog
1500 mf = self.manifest
1500 mf = self.manifest
1501 mfs = {} # needed manifests
1501 mfs = {} # needed manifests
1502 fnodes = {} # needed file nodes
1502 fnodes = {} # needed file nodes
1503 changedfiles = set()
1503 changedfiles = set()
1504 fstate = ['', {}]
1504 fstate = ['', {}]
1505 count = [0]
1505 count = [0]
1506
1506
1507 # can we go through the fast path ?
1507 # can we go through the fast path ?
1508 heads.sort()
1508 heads.sort()
1509 if heads == sorted(self.heads()):
1509 if heads == sorted(self.heads()):
1510 return self._changegroup(csets, source)
1510 return self._changegroup(csets, source)
1511
1511
1512 # slow path
1512 # slow path
1513 self.hook('preoutgoing', throw=True, source=source)
1513 self.hook('preoutgoing', throw=True, source=source)
1514 self.changegroupinfo(csets, source)
1514 self.changegroupinfo(csets, source)
1515
1515
1516 # filter any nodes that claim to be part of the known set
1516 # filter any nodes that claim to be part of the known set
1517 def prune(revlog, missing):
1517 def prune(revlog, missing):
1518 for n in missing:
1518 for n in missing:
1519 if revlog.linkrev(revlog.rev(n)) not in commonrevs:
1519 if revlog.linkrev(revlog.rev(n)) not in commonrevs:
1520 yield n
1520 yield n
1521
1521
1522 def lookup(revlog, x):
1522 def lookup(revlog, x):
1523 if revlog == cl:
1523 if revlog == cl:
1524 c = cl.read(x)
1524 c = cl.read(x)
1525 changedfiles.update(c[3])
1525 changedfiles.update(c[3])
1526 mfs.setdefault(c[0], x)
1526 mfs.setdefault(c[0], x)
1527 count[0] += 1
1527 count[0] += 1
1528 self.ui.progress(_('bundling'), count[0], unit=_('changesets'))
1528 self.ui.progress(_('bundling'), count[0], unit=_('changesets'))
1529 return x
1529 return x
1530 elif revlog == mf:
1530 elif revlog == mf:
1531 clnode = mfs[x]
1531 clnode = mfs[x]
1532 mdata = mf.readfast(x)
1532 mdata = mf.readfast(x)
1533 for f in changedfiles:
1533 for f in changedfiles:
1534 if f in mdata:
1534 if f in mdata:
1535 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1535 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1536 count[0] += 1
1536 count[0] += 1
1537 self.ui.progress(_('bundling'), count[0],
1537 self.ui.progress(_('bundling'), count[0],
1538 unit=_('manifests'), total=len(mfs))
1538 unit=_('manifests'), total=len(mfs))
1539 return mfs[x]
1539 return mfs[x]
1540 else:
1540 else:
1541 self.ui.progress(
1541 self.ui.progress(
1542 _('bundling'), count[0], item=fstate[0],
1542 _('bundling'), count[0], item=fstate[0],
1543 unit=_('files'), total=len(changedfiles))
1543 unit=_('files'), total=len(changedfiles))
1544 return fstate[1][x]
1544 return fstate[1][x]
1545
1545
1546 bundler = changegroup.bundle10(lookup)
1546 bundler = changegroup.bundle10(lookup)
1547 reorder = self.ui.config('bundle', 'reorder', 'auto')
1547 reorder = self.ui.config('bundle', 'reorder', 'auto')
1548 if reorder == 'auto':
1548 if reorder == 'auto':
1549 reorder = None
1549 reorder = None
1550 else:
1550 else:
1551 reorder = util.parsebool(reorder)
1551 reorder = util.parsebool(reorder)
1552
1552
1553 def gengroup():
1553 def gengroup():
1554 # Create a changenode group generator that will call our functions
1554 # Create a changenode group generator that will call our functions
1555 # back to lookup the owning changenode and collect information.
1555 # back to lookup the owning changenode and collect information.
1556 for chunk in cl.group(csets, bundler, reorder=reorder):
1556 for chunk in cl.group(csets, bundler, reorder=reorder):
1557 yield chunk
1557 yield chunk
1558 self.ui.progress(_('bundling'), None)
1558 self.ui.progress(_('bundling'), None)
1559
1559
1560 # Create a generator for the manifestnodes that calls our lookup
1560 # Create a generator for the manifestnodes that calls our lookup
1561 # and data collection functions back.
1561 # and data collection functions back.
1562 count[0] = 0
1562 count[0] = 0
1563 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1563 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1564 yield chunk
1564 yield chunk
1565 self.ui.progress(_('bundling'), None)
1565 self.ui.progress(_('bundling'), None)
1566
1566
1567 mfs.clear()
1567 mfs.clear()
1568
1568
1569 # Go through all our files in order sorted by name.
1569 # Go through all our files in order sorted by name.
1570 count[0] = 0
1570 count[0] = 0
1571 for fname in sorted(changedfiles):
1571 for fname in sorted(changedfiles):
1572 filerevlog = self.file(fname)
1572 filerevlog = self.file(fname)
1573 if not len(filerevlog):
1573 if not len(filerevlog):
1574 raise util.Abort(_("empty or missing revlog for %s") % fname)
1574 raise util.Abort(_("empty or missing revlog for %s") % fname)
1575 fstate[0] = fname
1575 fstate[0] = fname
1576 fstate[1] = fnodes.pop(fname, {})
1576 fstate[1] = fnodes.pop(fname, {})
1577 first = True
1577 first = True
1578
1578
1579 for chunk in filerevlog.group(prune(filerevlog, fstate[1]),
1579 for chunk in filerevlog.group(prune(filerevlog, fstate[1]),
1580 bundler, reorder=reorder):
1580 bundler, reorder=reorder):
1581 if first:
1581 if first:
1582 if chunk == bundler.close():
1582 if chunk == bundler.close():
1583 break
1583 break
1584 count[0] += 1
1584 count[0] += 1
1585 yield bundler.fileheader(fname)
1585 yield bundler.fileheader(fname)
1586 first = False
1586 first = False
1587 yield chunk
1587 yield chunk
1588 # Signal that no more groups are left.
1588 # Signal that no more groups are left.
1589 yield bundler.close()
1589 yield bundler.close()
1590 self.ui.progress(_('bundling'), None)
1590 self.ui.progress(_('bundling'), None)
1591
1591
1592 if csets:
1592 if csets:
1593 self.hook('outgoing', node=hex(csets[0]), source=source)
1593 self.hook('outgoing', node=hex(csets[0]), source=source)
1594
1594
1595 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1595 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1596
1596
1597 def changegroup(self, basenodes, source):
1597 def changegroup(self, basenodes, source):
1598 # to avoid a race we use changegroupsubset() (issue1320)
1598 # to avoid a race we use changegroupsubset() (issue1320)
1599 return self.changegroupsubset(basenodes, self.heads(), source)
1599 return self.changegroupsubset(basenodes, self.heads(), source)
1600
1600
1601 def _changegroup(self, nodes, source):
1601 def _changegroup(self, nodes, source):
1602 """Compute the changegroup of all nodes that we have that a recipient
1602 """Compute the changegroup of all nodes that we have that a recipient
1603 doesn't. Return a chunkbuffer object whose read() method will return
1603 doesn't. Return a chunkbuffer object whose read() method will return
1604 successive changegroup chunks.
1604 successive changegroup chunks.
1605
1605
1606 This is much easier than the previous function as we can assume that
1606 This is much easier than the previous function as we can assume that
1607 the recipient has any changenode we aren't sending them.
1607 the recipient has any changenode we aren't sending them.
1608
1608
1609 nodes is the set of nodes to send"""
1609 nodes is the set of nodes to send"""
1610
1610
1611 cl = self.changelog
1611 cl = self.changelog
1612 mf = self.manifest
1612 mf = self.manifest
1613 mfs = {}
1613 mfs = {}
1614 changedfiles = set()
1614 changedfiles = set()
1615 fstate = ['']
1615 fstate = ['']
1616 count = [0]
1616 count = [0]
1617
1617
1618 self.hook('preoutgoing', throw=True, source=source)
1618 self.hook('preoutgoing', throw=True, source=source)
1619 self.changegroupinfo(nodes, source)
1619 self.changegroupinfo(nodes, source)
1620
1620
1621 revset = set([cl.rev(n) for n in nodes])
1621 revset = set([cl.rev(n) for n in nodes])
1622
1622
1623 def gennodelst(log):
1623 def gennodelst(log):
1624 for r in log:
1624 for r in log:
1625 if log.linkrev(r) in revset:
1625 if log.linkrev(r) in revset:
1626 yield log.node(r)
1626 yield log.node(r)
1627
1627
1628 def lookup(revlog, x):
1628 def lookup(revlog, x):
1629 if revlog == cl:
1629 if revlog == cl:
1630 c = cl.read(x)
1630 c = cl.read(x)
1631 changedfiles.update(c[3])
1631 changedfiles.update(c[3])
1632 mfs.setdefault(c[0], x)
1632 mfs.setdefault(c[0], x)
1633 count[0] += 1
1633 count[0] += 1
1634 self.ui.progress(_('bundling'), count[0], unit=_('changesets'))
1634 self.ui.progress(_('bundling'), count[0], unit=_('changesets'))
1635 return x
1635 return x
1636 elif revlog == mf:
1636 elif revlog == mf:
1637 count[0] += 1
1637 count[0] += 1
1638 self.ui.progress(_('bundling'), count[0],
1638 self.ui.progress(_('bundling'), count[0],
1639 unit=_('manifests'), total=len(mfs))
1639 unit=_('manifests'), total=len(mfs))
1640 return cl.node(revlog.linkrev(revlog.rev(x)))
1640 return cl.node(revlog.linkrev(revlog.rev(x)))
1641 else:
1641 else:
1642 self.ui.progress(
1642 self.ui.progress(
1643 _('bundling'), count[0], item=fstate[0],
1643 _('bundling'), count[0], item=fstate[0],
1644 total=len(changedfiles), unit=_('files'))
1644 total=len(changedfiles), unit=_('files'))
1645 return cl.node(revlog.linkrev(revlog.rev(x)))
1645 return cl.node(revlog.linkrev(revlog.rev(x)))
1646
1646
1647 bundler = changegroup.bundle10(lookup)
1647 bundler = changegroup.bundle10(lookup)
1648 reorder = self.ui.config('bundle', 'reorder', 'auto')
1648 reorder = self.ui.config('bundle', 'reorder', 'auto')
1649 if reorder == 'auto':
1649 if reorder == 'auto':
1650 reorder = None
1650 reorder = None
1651 else:
1651 else:
1652 reorder = util.parsebool(reorder)
1652 reorder = util.parsebool(reorder)
1653
1653
1654 def gengroup():
1654 def gengroup():
1655 '''yield a sequence of changegroup chunks (strings)'''
1655 '''yield a sequence of changegroup chunks (strings)'''
1656 # construct a list of all changed files
1656 # construct a list of all changed files
1657
1657
1658 for chunk in cl.group(nodes, bundler, reorder=reorder):
1658 for chunk in cl.group(nodes, bundler, reorder=reorder):
1659 yield chunk
1659 yield chunk
1660 self.ui.progress(_('bundling'), None)
1660 self.ui.progress(_('bundling'), None)
1661
1661
1662 count[0] = 0
1662 count[0] = 0
1663 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1663 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1664 yield chunk
1664 yield chunk
1665 self.ui.progress(_('bundling'), None)
1665 self.ui.progress(_('bundling'), None)
1666
1666
1667 count[0] = 0
1667 count[0] = 0
1668 for fname in sorted(changedfiles):
1668 for fname in sorted(changedfiles):
1669 filerevlog = self.file(fname)
1669 filerevlog = self.file(fname)
1670 if not len(filerevlog):
1670 if not len(filerevlog):
1671 raise util.Abort(_("empty or missing revlog for %s") % fname)
1671 raise util.Abort(_("empty or missing revlog for %s") % fname)
1672 fstate[0] = fname
1672 fstate[0] = fname
1673 first = True
1673 first = True
1674 for chunk in filerevlog.group(gennodelst(filerevlog), bundler,
1674 for chunk in filerevlog.group(gennodelst(filerevlog), bundler,
1675 reorder=reorder):
1675 reorder=reorder):
1676 if first:
1676 if first:
1677 if chunk == bundler.close():
1677 if chunk == bundler.close():
1678 break
1678 break
1679 count[0] += 1
1679 count[0] += 1
1680 yield bundler.fileheader(fname)
1680 yield bundler.fileheader(fname)
1681 first = False
1681 first = False
1682 yield chunk
1682 yield chunk
1683 yield bundler.close()
1683 yield bundler.close()
1684 self.ui.progress(_('bundling'), None)
1684 self.ui.progress(_('bundling'), None)
1685
1685
1686 if nodes:
1686 if nodes:
1687 self.hook('outgoing', node=hex(nodes[0]), source=source)
1687 self.hook('outgoing', node=hex(nodes[0]), source=source)
1688
1688
1689 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1689 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1690
1690
1691 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1691 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1692 """Add the changegroup returned by source.read() to this repo.
1692 """Add the changegroup returned by source.read() to this repo.
1693 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1693 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1694 the URL of the repo where this changegroup is coming from.
1694 the URL of the repo where this changegroup is coming from.
1695 If lock is not None, the function takes ownership of the lock
1695 If lock is not None, the function takes ownership of the lock
1696 and releases it after the changegroup is added.
1696 and releases it after the changegroup is added.
1697
1697
1698 Return an integer summarizing the change to this repo:
1698 Return an integer summarizing the change to this repo:
1699 - nothing changed or no source: 0
1699 - nothing changed or no source: 0
1700 - more heads than before: 1+added heads (2..n)
1700 - more heads than before: 1+added heads (2..n)
1701 - fewer heads than before: -1-removed heads (-2..-n)
1701 - fewer heads than before: -1-removed heads (-2..-n)
1702 - number of heads stays the same: 1
1702 - number of heads stays the same: 1
1703 """
1703 """
1704 def csmap(x):
1704 def csmap(x):
1705 self.ui.debug("add changeset %s\n" % short(x))
1705 self.ui.debug("add changeset %s\n" % short(x))
1706 return len(cl)
1706 return len(cl)
1707
1707
1708 def revmap(x):
1708 def revmap(x):
1709 return cl.rev(x)
1709 return cl.rev(x)
1710
1710
1711 if not source:
1711 if not source:
1712 return 0
1712 return 0
1713
1713
1714 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1714 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1715
1715
1716 changesets = files = revisions = 0
1716 changesets = files = revisions = 0
1717 efiles = set()
1717 efiles = set()
1718
1718
1719 # write changelog data to temp files so concurrent readers will not see
1719 # write changelog data to temp files so concurrent readers will not see
1720 # inconsistent view
1720 # inconsistent view
1721 cl = self.changelog
1721 cl = self.changelog
1722 cl.delayupdate()
1722 cl.delayupdate()
1723 oldheads = cl.heads()
1723 oldheads = cl.heads()
1724
1724
1725 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
1725 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
1726 try:
1726 try:
1727 trp = weakref.proxy(tr)
1727 trp = weakref.proxy(tr)
1728 # pull off the changeset group
1728 # pull off the changeset group
1729 self.ui.status(_("adding changesets\n"))
1729 self.ui.status(_("adding changesets\n"))
1730 clstart = len(cl)
1730 clstart = len(cl)
1731 class prog(object):
1731 class prog(object):
1732 step = _('changesets')
1732 step = _('changesets')
1733 count = 1
1733 count = 1
1734 ui = self.ui
1734 ui = self.ui
1735 total = None
1735 total = None
1736 def __call__(self):
1736 def __call__(self):
1737 self.ui.progress(self.step, self.count, unit=_('chunks'),
1737 self.ui.progress(self.step, self.count, unit=_('chunks'),
1738 total=self.total)
1738 total=self.total)
1739 self.count += 1
1739 self.count += 1
1740 pr = prog()
1740 pr = prog()
1741 source.callback = pr
1741 source.callback = pr
1742
1742
1743 source.changelogheader()
1743 source.changelogheader()
1744 if (cl.addgroup(source, csmap, trp) is None
1744 if (cl.addgroup(source, csmap, trp) is None
1745 and not emptyok):
1745 and not emptyok):
1746 raise util.Abort(_("received changelog group is empty"))
1746 raise util.Abort(_("received changelog group is empty"))
1747 clend = len(cl)
1747 clend = len(cl)
1748 changesets = clend - clstart
1748 changesets = clend - clstart
1749 for c in xrange(clstart, clend):
1749 for c in xrange(clstart, clend):
1750 efiles.update(self[c].files())
1750 efiles.update(self[c].files())
1751 efiles = len(efiles)
1751 efiles = len(efiles)
1752 self.ui.progress(_('changesets'), None)
1752 self.ui.progress(_('changesets'), None)
1753
1753
1754 # pull off the manifest group
1754 # pull off the manifest group
1755 self.ui.status(_("adding manifests\n"))
1755 self.ui.status(_("adding manifests\n"))
1756 pr.step = _('manifests')
1756 pr.step = _('manifests')
1757 pr.count = 1
1757 pr.count = 1
1758 pr.total = changesets # manifests <= changesets
1758 pr.total = changesets # manifests <= changesets
1759 # no need to check for empty manifest group here:
1759 # no need to check for empty manifest group here:
1760 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1760 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1761 # no new manifest will be created and the manifest group will
1761 # no new manifest will be created and the manifest group will
1762 # be empty during the pull
1762 # be empty during the pull
1763 source.manifestheader()
1763 source.manifestheader()
1764 self.manifest.addgroup(source, revmap, trp)
1764 self.manifest.addgroup(source, revmap, trp)
1765 self.ui.progress(_('manifests'), None)
1765 self.ui.progress(_('manifests'), None)
1766
1766
1767 needfiles = {}
1767 needfiles = {}
1768 if self.ui.configbool('server', 'validate', default=False):
1768 if self.ui.configbool('server', 'validate', default=False):
1769 # validate incoming csets have their manifests
1769 # validate incoming csets have their manifests
1770 for cset in xrange(clstart, clend):
1770 for cset in xrange(clstart, clend):
1771 mfest = self.changelog.read(self.changelog.node(cset))[0]
1771 mfest = self.changelog.read(self.changelog.node(cset))[0]
1772 mfest = self.manifest.readdelta(mfest)
1772 mfest = self.manifest.readdelta(mfest)
1773 # store file nodes we must see
1773 # store file nodes we must see
1774 for f, n in mfest.iteritems():
1774 for f, n in mfest.iteritems():
1775 needfiles.setdefault(f, set()).add(n)
1775 needfiles.setdefault(f, set()).add(n)
1776
1776
1777 # process the files
1777 # process the files
1778 self.ui.status(_("adding file changes\n"))
1778 self.ui.status(_("adding file changes\n"))
1779 pr.step = 'files'
1779 pr.step = 'files'
1780 pr.count = 1
1780 pr.count = 1
1781 pr.total = efiles
1781 pr.total = efiles
1782 source.callback = None
1782 source.callback = None
1783
1783
1784 while 1:
1784 while 1:
1785 chunkdata = source.filelogheader()
1785 chunkdata = source.filelogheader()
1786 if not chunkdata:
1786 if not chunkdata:
1787 break
1787 break
1788 f = chunkdata["filename"]
1788 f = chunkdata["filename"]
1789 self.ui.debug("adding %s revisions\n" % f)
1789 self.ui.debug("adding %s revisions\n" % f)
1790 pr()
1790 pr()
1791 fl = self.file(f)
1791 fl = self.file(f)
1792 o = len(fl)
1792 o = len(fl)
1793 if fl.addgroup(source, revmap, trp) is None:
1793 if fl.addgroup(source, revmap, trp) is None:
1794 raise util.Abort(_("received file revlog group is empty"))
1794 raise util.Abort(_("received file revlog group is empty"))
1795 revisions += len(fl) - o
1795 revisions += len(fl) - o
1796 files += 1
1796 files += 1
1797 if f in needfiles:
1797 if f in needfiles:
1798 needs = needfiles[f]
1798 needs = needfiles[f]
1799 for new in xrange(o, len(fl)):
1799 for new in xrange(o, len(fl)):
1800 n = fl.node(new)
1800 n = fl.node(new)
1801 if n in needs:
1801 if n in needs:
1802 needs.remove(n)
1802 needs.remove(n)
1803 if not needs:
1803 if not needs:
1804 del needfiles[f]
1804 del needfiles[f]
1805 self.ui.progress(_('files'), None)
1805 self.ui.progress(_('files'), None)
1806
1806
1807 for f, needs in needfiles.iteritems():
1807 for f, needs in needfiles.iteritems():
1808 fl = self.file(f)
1808 fl = self.file(f)
1809 for n in needs:
1809 for n in needs:
1810 try:
1810 try:
1811 fl.rev(n)
1811 fl.rev(n)
1812 except error.LookupError:
1812 except error.LookupError:
1813 raise util.Abort(
1813 raise util.Abort(
1814 _('missing file data for %s:%s - run hg verify') %
1814 _('missing file data for %s:%s - run hg verify') %
1815 (f, hex(n)))
1815 (f, hex(n)))
1816
1816
1817 dh = 0
1817 dh = 0
1818 if oldheads:
1818 if oldheads:
1819 heads = cl.heads()
1819 heads = cl.heads()
1820 dh = len(heads) - len(oldheads)
1820 dh = len(heads) - len(oldheads)
1821 for h in heads:
1821 for h in heads:
1822 if h not in oldheads and 'close' in self[h].extra():
1822 if h not in oldheads and 'close' in self[h].extra():
1823 dh -= 1
1823 dh -= 1
1824 htext = ""
1824 htext = ""
1825 if dh:
1825 if dh:
1826 htext = _(" (%+d heads)") % dh
1826 htext = _(" (%+d heads)") % dh
1827
1827
1828 self.ui.status(_("added %d changesets"
1828 self.ui.status(_("added %d changesets"
1829 " with %d changes to %d files%s\n")
1829 " with %d changes to %d files%s\n")
1830 % (changesets, revisions, files, htext))
1830 % (changesets, revisions, files, htext))
1831
1831
1832 if changesets > 0:
1832 if changesets > 0:
1833 p = lambda: cl.writepending() and self.root or ""
1833 p = lambda: cl.writepending() and self.root or ""
1834 self.hook('pretxnchangegroup', throw=True,
1834 self.hook('pretxnchangegroup', throw=True,
1835 node=hex(cl.node(clstart)), source=srctype,
1835 node=hex(cl.node(clstart)), source=srctype,
1836 url=url, pending=p)
1836 url=url, pending=p)
1837
1837
1838 # make changelog see real files again
1838 # make changelog see real files again
1839 cl.finalize(trp)
1839 cl.finalize(trp)
1840
1840
1841 tr.close()
1841 tr.close()
1842 finally:
1842 finally:
1843 tr.release()
1843 tr.release()
1844 if lock:
1844 if lock:
1845 lock.release()
1845 lock.release()
1846
1846
1847 if changesets > 0:
1847 if changesets > 0:
1848 # forcefully update the on-disk branch cache
1848 # forcefully update the on-disk branch cache
1849 self.ui.debug("updating the branch cache\n")
1849 self.ui.debug("updating the branch cache\n")
1850 self.updatebranchcache()
1850 self.updatebranchcache()
1851 self.hook("changegroup", node=hex(cl.node(clstart)),
1851 self.hook("changegroup", node=hex(cl.node(clstart)),
1852 source=srctype, url=url)
1852 source=srctype, url=url)
1853
1853
1854 for i in xrange(clstart, clend):
1854 for i in xrange(clstart, clend):
1855 self.hook("incoming", node=hex(cl.node(i)),
1855 self.hook("incoming", node=hex(cl.node(i)),
1856 source=srctype, url=url)
1856 source=srctype, url=url)
1857
1857
1858 # never return 0 here:
1858 # never return 0 here:
1859 if dh < 0:
1859 if dh < 0:
1860 return dh - 1
1860 return dh - 1
1861 else:
1861 else:
1862 return dh + 1
1862 return dh + 1
1863
1863
1864 def stream_in(self, remote, requirements):
1864 def stream_in(self, remote, requirements):
1865 lock = self.lock()
1865 lock = self.lock()
1866 try:
1866 try:
1867 fp = remote.stream_out()
1867 fp = remote.stream_out()
1868 l = fp.readline()
1868 l = fp.readline()
1869 try:
1869 try:
1870 resp = int(l)
1870 resp = int(l)
1871 except ValueError:
1871 except ValueError:
1872 raise error.ResponseError(
1872 raise error.ResponseError(
1873 _('Unexpected response from remote server:'), l)
1873 _('Unexpected response from remote server:'), l)
1874 if resp == 1:
1874 if resp == 1:
1875 raise util.Abort(_('operation forbidden by server'))
1875 raise util.Abort(_('operation forbidden by server'))
1876 elif resp == 2:
1876 elif resp == 2:
1877 raise util.Abort(_('locking the remote repository failed'))
1877 raise util.Abort(_('locking the remote repository failed'))
1878 elif resp != 0:
1878 elif resp != 0:
1879 raise util.Abort(_('the server sent an unknown error code'))
1879 raise util.Abort(_('the server sent an unknown error code'))
1880 self.ui.status(_('streaming all changes\n'))
1880 self.ui.status(_('streaming all changes\n'))
1881 l = fp.readline()
1881 l = fp.readline()
1882 try:
1882 try:
1883 total_files, total_bytes = map(int, l.split(' ', 1))
1883 total_files, total_bytes = map(int, l.split(' ', 1))
1884 except (ValueError, TypeError):
1884 except (ValueError, TypeError):
1885 raise error.ResponseError(
1885 raise error.ResponseError(
1886 _('Unexpected response from remote server:'), l)
1886 _('Unexpected response from remote server:'), l)
1887 self.ui.status(_('%d files to transfer, %s of data\n') %
1887 self.ui.status(_('%d files to transfer, %s of data\n') %
1888 (total_files, util.bytecount(total_bytes)))
1888 (total_files, util.bytecount(total_bytes)))
1889 start = time.time()
1889 start = time.time()
1890 for i in xrange(total_files):
1890 for i in xrange(total_files):
1891 # XXX doesn't support '\n' or '\r' in filenames
1891 # XXX doesn't support '\n' or '\r' in filenames
1892 l = fp.readline()
1892 l = fp.readline()
1893 try:
1893 try:
1894 name, size = l.split('\0', 1)
1894 name, size = l.split('\0', 1)
1895 size = int(size)
1895 size = int(size)
1896 except (ValueError, TypeError):
1896 except (ValueError, TypeError):
1897 raise error.ResponseError(
1897 raise error.ResponseError(
1898 _('Unexpected response from remote server:'), l)
1898 _('Unexpected response from remote server:'), l)
1899 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1899 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1900 # for backwards compat, name was partially encoded
1900 # for backwards compat, name was partially encoded
1901 ofp = self.sopener(store.decodedir(name), 'w')
1901 ofp = self.sopener(store.decodedir(name), 'w')
1902 for chunk in util.filechunkiter(fp, limit=size):
1902 for chunk in util.filechunkiter(fp, limit=size):
1903 ofp.write(chunk)
1903 ofp.write(chunk)
1904 ofp.close()
1904 ofp.close()
1905 elapsed = time.time() - start
1905 elapsed = time.time() - start
1906 if elapsed <= 0:
1906 if elapsed <= 0:
1907 elapsed = 0.001
1907 elapsed = 0.001
1908 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1908 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1909 (util.bytecount(total_bytes), elapsed,
1909 (util.bytecount(total_bytes), elapsed,
1910 util.bytecount(total_bytes / elapsed)))
1910 util.bytecount(total_bytes / elapsed)))
1911
1911
1912 # new requirements = old non-format requirements + new format-related
1912 # new requirements = old non-format requirements + new format-related
1913 # requirements from the streamed-in repository
1913 # requirements from the streamed-in repository
1914 requirements.update(set(self.requirements) - self.supportedformats)
1914 requirements.update(set(self.requirements) - self.supportedformats)
1915 self._applyrequirements(requirements)
1915 self._applyrequirements(requirements)
1916 self._writerequirements()
1916 self._writerequirements()
1917
1917
1918 self.invalidate()
1918 self.invalidate()
1919 return len(self.heads()) + 1
1919 return len(self.heads()) + 1
1920 finally:
1920 finally:
1921 lock.release()
1921 lock.release()
1922
1922
1923 def clone(self, remote, heads=[], stream=False):
1923 def clone(self, remote, heads=[], stream=False):
1924 '''clone remote repository.
1924 '''clone remote repository.
1925
1925
1926 keyword arguments:
1926 keyword arguments:
1927 heads: list of revs to clone (forces use of pull)
1927 heads: list of revs to clone (forces use of pull)
1928 stream: use streaming clone if possible'''
1928 stream: use streaming clone if possible'''
1929
1929
1930 # now, all clients that can request uncompressed clones can
1930 # now, all clients that can request uncompressed clones can
1931 # read repo formats supported by all servers that can serve
1931 # read repo formats supported by all servers that can serve
1932 # them.
1932 # them.
1933
1933
1934 # if revlog format changes, client will have to check version
1934 # if revlog format changes, client will have to check version
1935 # and format flags on "stream" capability, and use
1935 # and format flags on "stream" capability, and use
1936 # uncompressed only if compatible.
1936 # uncompressed only if compatible.
1937
1937
1938 if stream and not heads:
1938 if stream and not heads:
1939 # 'stream' means remote revlog format is revlogv1 only
1939 # 'stream' means remote revlog format is revlogv1 only
1940 if remote.capable('stream'):
1940 if remote.capable('stream'):
1941 return self.stream_in(remote, set(('revlogv1',)))
1941 return self.stream_in(remote, set(('revlogv1',)))
1942 # otherwise, 'streamreqs' contains the remote revlog format
1942 # otherwise, 'streamreqs' contains the remote revlog format
1943 streamreqs = remote.capable('streamreqs')
1943 streamreqs = remote.capable('streamreqs')
1944 if streamreqs:
1944 if streamreqs:
1945 streamreqs = set(streamreqs.split(','))
1945 streamreqs = set(streamreqs.split(','))
1946 # if we support it, stream in and adjust our requirements
1946 # if we support it, stream in and adjust our requirements
1947 if not streamreqs - self.supportedformats:
1947 if not streamreqs - self.supportedformats:
1948 return self.stream_in(remote, streamreqs)
1948 return self.stream_in(remote, streamreqs)
1949 return self.pull(remote, heads)
1949 return self.pull(remote, heads)
1950
1950
1951 def pushkey(self, namespace, key, old, new):
1951 def pushkey(self, namespace, key, old, new):
1952 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1952 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1953 old=old, new=new)
1953 old=old, new=new)
1954 ret = pushkey.push(self, namespace, key, old, new)
1954 ret = pushkey.push(self, namespace, key, old, new)
1955 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1955 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1956 ret=ret)
1956 ret=ret)
1957 return ret
1957 return ret
1958
1958
1959 def listkeys(self, namespace):
1959 def listkeys(self, namespace):
1960 self.hook('prelistkeys', throw=True, namespace=namespace)
1960 self.hook('prelistkeys', throw=True, namespace=namespace)
1961 values = pushkey.list(self, namespace)
1961 values = pushkey.list(self, namespace)
1962 self.hook('listkeys', namespace=namespace, values=values)
1962 self.hook('listkeys', namespace=namespace, values=values)
1963 return values
1963 return values
1964
1964
1965 def debugwireargs(self, one, two, three=None, four=None, five=None):
1965 def debugwireargs(self, one, two, three=None, four=None, five=None):
1966 '''used to test argument passing over the wire'''
1966 '''used to test argument passing over the wire'''
1967 return "%s %s %s %s %s" % (one, two, three, four, five)
1967 return "%s %s %s %s %s" % (one, two, three, four, five)
1968
1968
1969 # used to avoid circular references so destructors work
1969 # used to avoid circular references so destructors work
1970 def aftertrans(files):
1970 def aftertrans(files):
1971 renamefiles = [tuple(t) for t in files]
1971 renamefiles = [tuple(t) for t in files]
1972 def a():
1972 def a():
1973 for src, dest in renamefiles:
1973 for src, dest in renamefiles:
1974 util.rename(src, dest)
1974 util.rename(src, dest)
1975 return a
1975 return a
1976
1976
1977 def undoname(fn):
1977 def undoname(fn):
1978 base, name = os.path.split(fn)
1978 base, name = os.path.split(fn)
1979 assert name.startswith('journal')
1979 assert name.startswith('journal')
1980 return os.path.join(base, name.replace('journal', 'undo', 1))
1980 return os.path.join(base, name.replace('journal', 'undo', 1))
1981
1981
1982 def instance(ui, path, create):
1982 def instance(ui, path, create):
1983 return localrepository(ui, util.localpath(path), create)
1983 return localrepository(ui, util.localpath(path), create)
1984
1984
1985 def islocal(path):
1985 def islocal(path):
1986 return True
1986 return True
@@ -1,566 +1,566 b''
1 # merge.py - directory-level update/merge handling for Mercurial
1 # merge.py - directory-level update/merge handling 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, hex, bin
8 from node import nullid, nullrev, hex, bin
9 from i18n import _
9 from i18n import _
10 import scmutil, util, filemerge, copies, subrepo
10 import scmutil, util, filemerge, copies, subrepo
11 import errno, os, shutil
11 import errno, os, shutil
12
12
13 class mergestate(object):
13 class mergestate(object):
14 '''track 3-way merge state of individual files'''
14 '''track 3-way merge state of individual files'''
15 def __init__(self, repo):
15 def __init__(self, repo):
16 self._repo = repo
16 self._repo = repo
17 self._dirty = False
17 self._dirty = False
18 self._read()
18 self._read()
19 def reset(self, node=None):
19 def reset(self, node=None):
20 self._state = {}
20 self._state = {}
21 if node:
21 if node:
22 self._local = node
22 self._local = node
23 shutil.rmtree(self._repo.join("merge"), True)
23 shutil.rmtree(self._repo.join("merge"), True)
24 self._dirty = False
24 self._dirty = False
25 def _read(self):
25 def _read(self):
26 self._state = {}
26 self._state = {}
27 try:
27 try:
28 f = self._repo.opener("merge/state")
28 f = self._repo.opener("merge/state")
29 for i, l in enumerate(f):
29 for i, l in enumerate(f):
30 if i == 0:
30 if i == 0:
31 self._local = bin(l[:-1])
31 self._local = bin(l[:-1])
32 else:
32 else:
33 bits = l[:-1].split("\0")
33 bits = l[:-1].split("\0")
34 self._state[bits[0]] = bits[1:]
34 self._state[bits[0]] = bits[1:]
35 f.close()
35 f.close()
36 except IOError, err:
36 except IOError, err:
37 if err.errno != errno.ENOENT:
37 if err.errno != errno.ENOENT:
38 raise
38 raise
39 self._dirty = False
39 self._dirty = False
40 def commit(self):
40 def commit(self):
41 if self._dirty:
41 if self._dirty:
42 f = self._repo.opener("merge/state", "w")
42 f = self._repo.opener("merge/state", "w")
43 f.write(hex(self._local) + "\n")
43 f.write(hex(self._local) + "\n")
44 for d, v in self._state.iteritems():
44 for d, v in self._state.iteritems():
45 f.write("\0".join([d] + v) + "\n")
45 f.write("\0".join([d] + v) + "\n")
46 f.close()
46 f.close()
47 self._dirty = False
47 self._dirty = False
48 def add(self, fcl, fco, fca, fd, flags):
48 def add(self, fcl, fco, fca, fd, flags):
49 hash = util.sha1(fcl.path()).hexdigest()
49 hash = util.sha1(fcl.path()).hexdigest()
50 self._repo.opener.write("merge/" + hash, fcl.data())
50 self._repo.opener.write("merge/" + hash, fcl.data())
51 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
51 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
52 hex(fca.filenode()), fco.path(), flags]
52 hex(fca.filenode()), fco.path(), flags]
53 self._dirty = True
53 self._dirty = True
54 def __contains__(self, dfile):
54 def __contains__(self, dfile):
55 return dfile in self._state
55 return dfile in self._state
56 def __getitem__(self, dfile):
56 def __getitem__(self, dfile):
57 return self._state[dfile][0]
57 return self._state[dfile][0]
58 def __iter__(self):
58 def __iter__(self):
59 l = self._state.keys()
59 l = self._state.keys()
60 l.sort()
60 l.sort()
61 for f in l:
61 for f in l:
62 yield f
62 yield f
63 def mark(self, dfile, state):
63 def mark(self, dfile, state):
64 self._state[dfile][0] = state
64 self._state[dfile][0] = state
65 self._dirty = True
65 self._dirty = True
66 def resolve(self, dfile, wctx, octx):
66 def resolve(self, dfile, wctx, octx):
67 if self[dfile] == 'r':
67 if self[dfile] == 'r':
68 return 0
68 return 0
69 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
69 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
70 f = self._repo.opener("merge/" + hash)
70 f = self._repo.opener("merge/" + hash)
71 self._repo.wwrite(dfile, f.read(), flags)
71 self._repo.wwrite(dfile, f.read(), flags)
72 f.close()
72 f.close()
73 fcd = wctx[dfile]
73 fcd = wctx[dfile]
74 fco = octx[ofile]
74 fco = octx[ofile]
75 fca = self._repo.filectx(afile, fileid=anode)
75 fca = self._repo.filectx(afile, fileid=anode)
76 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
76 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
77 if r is None:
77 if r is None:
78 # no real conflict
78 # no real conflict
79 del self._state[dfile]
79 del self._state[dfile]
80 elif not r:
80 elif not r:
81 self.mark(dfile, 'r')
81 self.mark(dfile, 'r')
82 return r
82 return r
83
83
84 def _checkunknown(wctx, mctx):
84 def _checkunknown(wctx, mctx):
85 "check for collisions between unknown files and files in mctx"
85 "check for collisions between unknown files and files in mctx"
86 for f in wctx.unknown():
86 for f in wctx.unknown():
87 if f in mctx and mctx[f].cmp(wctx[f]):
87 if f in mctx and mctx[f].cmp(wctx[f]):
88 raise util.Abort(_("untracked file in working directory differs"
88 raise util.Abort(_("untracked file in working directory differs"
89 " from file in requested revision: '%s'") % f)
89 " from file in requested revision: '%s'") % f)
90
90
91 def _checkcollision(mctx):
91 def _checkcollision(mctx):
92 "check for case folding collisions in the destination context"
92 "check for case folding collisions in the destination context"
93 folded = {}
93 folded = {}
94 for fn in mctx:
94 for fn in mctx:
95 fold = fn.lower()
95 fold = fn.lower()
96 if fold in folded:
96 if fold in folded:
97 raise util.Abort(_("case-folding collision between %s and %s")
97 raise util.Abort(_("case-folding collision between %s and %s")
98 % (fn, folded[fold]))
98 % (fn, folded[fold]))
99 folded[fold] = fn
99 folded[fold] = fn
100
100
101 def _forgetremoved(wctx, mctx, branchmerge):
101 def _forgetremoved(wctx, mctx, branchmerge):
102 """
102 """
103 Forget removed files
103 Forget removed files
104
104
105 If we're jumping between revisions (as opposed to merging), and if
105 If we're jumping between revisions (as opposed to merging), and if
106 neither the working directory nor the target rev has the file,
106 neither the working directory nor the target rev has the file,
107 then we need to remove it from the dirstate, to prevent the
107 then we need to remove it from the dirstate, to prevent the
108 dirstate from listing the file when it is no longer in the
108 dirstate from listing the file when it is no longer in the
109 manifest.
109 manifest.
110
110
111 If we're merging, and the other revision has removed a file
111 If we're merging, and the other revision has removed a file
112 that is not present in the working directory, we need to mark it
112 that is not present in the working directory, we need to mark it
113 as removed.
113 as removed.
114 """
114 """
115
115
116 action = []
116 action = []
117 state = branchmerge and 'r' or 'f'
117 state = branchmerge and 'r' or 'f'
118 for f in wctx.deleted():
118 for f in wctx.deleted():
119 if f not in mctx:
119 if f not in mctx:
120 action.append((f, state))
120 action.append((f, state))
121
121
122 if not branchmerge:
122 if not branchmerge:
123 for f in wctx.removed():
123 for f in wctx.removed():
124 if f not in mctx:
124 if f not in mctx:
125 action.append((f, "f"))
125 action.append((f, "f"))
126
126
127 return action
127 return action
128
128
129 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
129 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
130 """
130 """
131 Merge p1 and p2 with ancestor pa and generate merge action list
131 Merge p1 and p2 with ancestor pa and generate merge action list
132
132
133 overwrite = whether we clobber working files
133 overwrite = whether we clobber working files
134 partial = function to filter file lists
134 partial = function to filter file lists
135 """
135 """
136
136
137 def fmerge(f, f2, fa):
137 def fmerge(f, f2, fa):
138 """merge flags"""
138 """merge flags"""
139 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
139 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
140 if m == n: # flags agree
140 if m == n: # flags agree
141 return m # unchanged
141 return m # unchanged
142 if m and n and not a: # flags set, don't agree, differ from parent
142 if m and n and not a: # flags set, don't agree, differ from parent
143 r = repo.ui.promptchoice(
143 r = repo.ui.promptchoice(
144 _(" conflicting flags for %s\n"
144 _(" conflicting flags for %s\n"
145 "(n)one, e(x)ec or sym(l)ink?") % f,
145 "(n)one, e(x)ec or sym(l)ink?") % f,
146 (_("&None"), _("E&xec"), _("Sym&link")), 0)
146 (_("&None"), _("E&xec"), _("Sym&link")), 0)
147 if r == 1:
147 if r == 1:
148 return "x" # Exec
148 return "x" # Exec
149 if r == 2:
149 if r == 2:
150 return "l" # Symlink
150 return "l" # Symlink
151 return ""
151 return ""
152 if m and m != a: # changed from a to m
152 if m and m != a: # changed from a to m
153 return m
153 return m
154 if n and n != a: # changed from a to n
154 if n and n != a: # changed from a to n
155 return n
155 return n
156 return '' # flag was cleared
156 return '' # flag was cleared
157
157
158 def act(msg, m, f, *args):
158 def act(msg, m, f, *args):
159 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
159 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
160 action.append((f, m) + args)
160 action.append((f, m) + args)
161
161
162 action, copy = [], {}
162 action, copy = [], {}
163
163
164 if overwrite:
164 if overwrite:
165 pa = p1
165 pa = p1
166 elif pa == p2: # backwards
166 elif pa == p2: # backwards
167 pa = p1.p1()
167 pa = p1.p1()
168 elif pa and repo.ui.configbool("merge", "followcopies", True):
168 elif pa and repo.ui.configbool("merge", "followcopies", True):
169 dirs = repo.ui.configbool("merge", "followdirs", True)
169 dirs = repo.ui.configbool("merge", "followdirs", True)
170 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
170 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
171 for of, fl in diverge.iteritems():
171 for of, fl in diverge.iteritems():
172 act("divergent renames", "dr", of, fl)
172 act("divergent renames", "dr", of, fl)
173
173
174 repo.ui.note(_("resolving manifests\n"))
174 repo.ui.note(_("resolving manifests\n"))
175 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
175 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
176 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
176 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
177
177
178 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
178 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
179 copied = set(copy.values())
179 copied = set(copy.values())
180
180
181 if '.hgsubstate' in m1:
181 if '.hgsubstate' in m1:
182 # check whether sub state is modified
182 # check whether sub state is modified
183 for s in p1.substate:
183 for s in p1.substate:
184 if p1.sub(s).dirty():
184 if p1.sub(s).dirty():
185 m1['.hgsubstate'] += "+"
185 m1['.hgsubstate'] += "+"
186 break
186 break
187
187
188 # Compare manifests
188 # Compare manifests
189 for f, n in m1.iteritems():
189 for f, n in m1.iteritems():
190 if partial and not partial(f):
190 if partial and not partial(f):
191 continue
191 continue
192 if f in m2:
192 if f in m2:
193 rflags = fmerge(f, f, f)
193 rflags = fmerge(f, f, f)
194 a = ma.get(f, nullid)
194 a = ma.get(f, nullid)
195 if n == m2[f] or m2[f] == a: # same or local newer
195 if n == m2[f] or m2[f] == a: # same or local newer
196 # is file locally modified or flags need changing?
196 # is file locally modified or flags need changing?
197 # dirstate flags may need to be made current
197 # dirstate flags may need to be made current
198 if m1.flags(f) != rflags or n[20:]:
198 if m1.flags(f) != rflags or n[20:]:
199 act("update permissions", "e", f, rflags)
199 act("update permissions", "e", f, rflags)
200 elif n == a: # remote newer
200 elif n == a: # remote newer
201 act("remote is newer", "g", f, rflags)
201 act("remote is newer", "g", f, rflags)
202 else: # both changed
202 else: # both changed
203 act("versions differ", "m", f, f, f, rflags, False)
203 act("versions differ", "m", f, f, f, rflags, False)
204 elif f in copied: # files we'll deal with on m2 side
204 elif f in copied: # files we'll deal with on m2 side
205 pass
205 pass
206 elif f in copy:
206 elif f in copy:
207 f2 = copy[f]
207 f2 = copy[f]
208 if f2 not in m2: # directory rename
208 if f2 not in m2: # directory rename
209 act("remote renamed directory to " + f2, "d",
209 act("remote renamed directory to " + f2, "d",
210 f, None, f2, m1.flags(f))
210 f, None, f2, m1.flags(f))
211 else: # case 2 A,B/B/B or case 4,21 A/B/B
211 else: # case 2 A,B/B/B or case 4,21 A/B/B
212 act("local copied/moved to " + f2, "m",
212 act("local copied/moved to " + f2, "m",
213 f, f2, f, fmerge(f, f2, f2), False)
213 f, f2, f, fmerge(f, f2, f2), False)
214 elif f in ma: # clean, a different, no remote
214 elif f in ma: # clean, a different, no remote
215 if n != ma[f]:
215 if n != ma[f]:
216 if repo.ui.promptchoice(
216 if repo.ui.promptchoice(
217 _(" local changed %s which remote deleted\n"
217 _(" local changed %s which remote deleted\n"
218 "use (c)hanged version or (d)elete?") % f,
218 "use (c)hanged version or (d)elete?") % f,
219 (_("&Changed"), _("&Delete")), 0):
219 (_("&Changed"), _("&Delete")), 0):
220 act("prompt delete", "r", f)
220 act("prompt delete", "r", f)
221 else:
221 else:
222 act("prompt keep", "a", f)
222 act("prompt keep", "a", f)
223 elif n[20:] == "a": # added, no remote
223 elif n[20:] == "a": # added, no remote
224 act("remote deleted", "f", f)
224 act("remote deleted", "f", f)
225 elif n[20:] != "u":
225 elif n[20:] != "u":
226 act("other deleted", "r", f)
226 act("other deleted", "r", f)
227
227
228 for f, n in m2.iteritems():
228 for f, n in m2.iteritems():
229 if partial and not partial(f):
229 if partial and not partial(f):
230 continue
230 continue
231 if f in m1 or f in copied: # files already visited
231 if f in m1 or f in copied: # files already visited
232 continue
232 continue
233 if f in copy:
233 if f in copy:
234 f2 = copy[f]
234 f2 = copy[f]
235 if f2 not in m1: # directory rename
235 if f2 not in m1: # directory rename
236 act("local renamed directory to " + f2, "d",
236 act("local renamed directory to " + f2, "d",
237 None, f, f2, m2.flags(f))
237 None, f, f2, m2.flags(f))
238 elif f2 in m2: # rename case 1, A/A,B/A
238 elif f2 in m2: # rename case 1, A/A,B/A
239 act("remote copied to " + f, "m",
239 act("remote copied to " + f, "m",
240 f2, f, f, fmerge(f2, f, f2), False)
240 f2, f, f, fmerge(f2, f, f2), False)
241 else: # case 3,20 A/B/A
241 else: # case 3,20 A/B/A
242 act("remote moved to " + f, "m",
242 act("remote moved to " + f, "m",
243 f2, f, f, fmerge(f2, f, f2), True)
243 f2, f, f, fmerge(f2, f, f2), True)
244 elif f not in ma:
244 elif f not in ma:
245 act("remote created", "g", f, m2.flags(f))
245 act("remote created", "g", f, m2.flags(f))
246 elif n != ma[f]:
246 elif n != ma[f]:
247 if repo.ui.promptchoice(
247 if repo.ui.promptchoice(
248 _("remote changed %s which local deleted\n"
248 _("remote changed %s which local deleted\n"
249 "use (c)hanged version or leave (d)eleted?") % f,
249 "use (c)hanged version or leave (d)eleted?") % f,
250 (_("&Changed"), _("&Deleted")), 0) == 0:
250 (_("&Changed"), _("&Deleted")), 0) == 0:
251 act("prompt recreating", "g", f, m2.flags(f))
251 act("prompt recreating", "g", f, m2.flags(f))
252
252
253 return action
253 return action
254
254
255 def actionkey(a):
255 def actionkey(a):
256 return a[1] == 'r' and -1 or 0, a
256 return a[1] == 'r' and -1 or 0, a
257
257
258 def applyupdates(repo, action, wctx, mctx, actx, overwrite):
258 def applyupdates(repo, action, wctx, mctx, actx, overwrite):
259 """apply the merge action list to the working directory
259 """apply the merge action list to the working directory
260
260
261 wctx is the working copy context
261 wctx is the working copy context
262 mctx is the context to be merged into the working copy
262 mctx is the context to be merged into the working copy
263 actx is the context of the common ancestor
263 actx is the context of the common ancestor
264
264
265 Return a tuple of counts (updated, merged, removed, unresolved) that
265 Return a tuple of counts (updated, merged, removed, unresolved) that
266 describes how many files were affected by the update.
266 describes how many files were affected by the update.
267 """
267 """
268
268
269 updated, merged, removed, unresolved = 0, 0, 0, 0
269 updated, merged, removed, unresolved = 0, 0, 0, 0
270 ms = mergestate(repo)
270 ms = mergestate(repo)
271 ms.reset(wctx.p1().node())
271 ms.reset(wctx.p1().node())
272 moves = []
272 moves = []
273 action.sort(key=actionkey)
273 action.sort(key=actionkey)
274
274
275 # prescan for merges
275 # prescan for merges
276 u = repo.ui
276 u = repo.ui
277 for a in action:
277 for a in action:
278 f, m = a[:2]
278 f, m = a[:2]
279 if m == 'm': # merge
279 if m == 'm': # merge
280 f2, fd, flags, move = a[2:]
280 f2, fd, flags, move = a[2:]
281 if f == '.hgsubstate': # merged internally
281 if f == '.hgsubstate': # merged internally
282 continue
282 continue
283 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
283 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
284 fcl = wctx[f]
284 fcl = wctx[f]
285 fco = mctx[f2]
285 fco = mctx[f2]
286 if mctx == actx: # backwards, use working dir parent as ancestor
286 if mctx == actx: # backwards, use working dir parent as ancestor
287 if fcl.parents():
287 if fcl.parents():
288 fca = fcl.p1()
288 fca = fcl.p1()
289 else:
289 else:
290 fca = repo.filectx(f, fileid=nullrev)
290 fca = repo.filectx(f, fileid=nullrev)
291 else:
291 else:
292 fca = fcl.ancestor(fco, actx)
292 fca = fcl.ancestor(fco, actx)
293 if not fca:
293 if not fca:
294 fca = repo.filectx(f, fileid=nullrev)
294 fca = repo.filectx(f, fileid=nullrev)
295 ms.add(fcl, fco, fca, fd, flags)
295 ms.add(fcl, fco, fca, fd, flags)
296 if f != fd and move:
296 if f != fd and move:
297 moves.append(f)
297 moves.append(f)
298
298
299 audit = scmutil.pathauditor(repo.root)
299 audit = scmutil.pathauditor(repo.root)
300
300
301 # remove renamed files after safely stored
301 # remove renamed files after safely stored
302 for f in moves:
302 for f in moves:
303 if os.path.lexists(repo.wjoin(f)):
303 if os.path.lexists(repo.wjoin(f)):
304 repo.ui.debug("removing %s\n" % f)
304 repo.ui.debug("removing %s\n" % f)
305 audit(f)
305 audit(f)
306 os.unlink(repo.wjoin(f))
306 os.unlink(repo.wjoin(f))
307
307
308 numupdates = len(action)
308 numupdates = len(action)
309 for i, a in enumerate(action):
309 for i, a in enumerate(action):
310 f, m = a[:2]
310 f, m = a[:2]
311 u.progress(_('updating'), i + 1, item=f, total=numupdates,
311 u.progress(_('updating'), i + 1, item=f, total=numupdates,
312 unit=_('files'))
312 unit=_('files'))
313 if f and f[0] == "/":
313 if f and f[0] == "/":
314 continue
314 continue
315 if m == "r": # remove
315 if m == "r": # remove
316 repo.ui.note(_("removing %s\n") % f)
316 repo.ui.note(_("removing %s\n") % f)
317 audit(f)
317 audit(f)
318 if f == '.hgsubstate': # subrepo states need updating
318 if f == '.hgsubstate': # subrepo states need updating
319 subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
319 subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
320 try:
320 try:
321 util.unlinkpath(repo.wjoin(f))
321 util.unlinkpath(repo.wjoin(f))
322 except OSError, inst:
322 except OSError, inst:
323 if inst.errno != errno.ENOENT:
323 if inst.errno != errno.ENOENT:
324 repo.ui.warn(_("update failed to remove %s: %s!\n") %
324 repo.ui.warn(_("update failed to remove %s: %s!\n") %
325 (f, inst.strerror))
325 (f, inst.strerror))
326 removed += 1
326 removed += 1
327 elif m == "m": # merge
327 elif m == "m": # merge
328 if f == '.hgsubstate': # subrepo states need updating
328 if f == '.hgsubstate': # subrepo states need updating
329 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx), overwrite)
329 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx), overwrite)
330 continue
330 continue
331 f2, fd, flags, move = a[2:]
331 f2, fd, flags, move = a[2:]
332 repo.wopener.audit(fd)
332 repo.wopener.audit(fd)
333 r = ms.resolve(fd, wctx, mctx)
333 r = ms.resolve(fd, wctx, mctx)
334 if r is not None and r > 0:
334 if r is not None and r > 0:
335 unresolved += 1
335 unresolved += 1
336 else:
336 else:
337 if r is None:
337 if r is None:
338 updated += 1
338 updated += 1
339 else:
339 else:
340 merged += 1
340 merged += 1
341 util.setflags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
341 util.setflags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
342 if (move and repo.dirstate.normalize(fd) != f
342 if (move and repo.dirstate.normalize(fd) != f
343 and os.path.lexists(repo.wjoin(f))):
343 and os.path.lexists(repo.wjoin(f))):
344 repo.ui.debug("removing %s\n" % f)
344 repo.ui.debug("removing %s\n" % f)
345 audit(f)
345 audit(f)
346 os.unlink(repo.wjoin(f))
346 os.unlink(repo.wjoin(f))
347 elif m == "g": # get
347 elif m == "g": # get
348 flags = a[2]
348 flags = a[2]
349 repo.ui.note(_("getting %s\n") % f)
349 repo.ui.note(_("getting %s\n") % f)
350 t = mctx.filectx(f).data()
350 t = mctx.filectx(f).data()
351 repo.wwrite(f, t, flags)
351 repo.wwrite(f, t, flags)
352 t = None
352 t = None
353 updated += 1
353 updated += 1
354 if f == '.hgsubstate': # subrepo states need updating
354 if f == '.hgsubstate': # subrepo states need updating
355 subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
355 subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
356 elif m == "d": # directory rename
356 elif m == "d": # directory rename
357 f2, fd, flags = a[2:]
357 f2, fd, flags = a[2:]
358 if f:
358 if f:
359 repo.ui.note(_("moving %s to %s\n") % (f, fd))
359 repo.ui.note(_("moving %s to %s\n") % (f, fd))
360 audit(f)
360 audit(f)
361 t = wctx.filectx(f).data()
361 t = wctx.filectx(f).data()
362 repo.wwrite(fd, t, flags)
362 repo.wwrite(fd, t, flags)
363 util.unlinkpath(repo.wjoin(f))
363 util.unlinkpath(repo.wjoin(f))
364 if f2:
364 if f2:
365 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
365 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
366 t = mctx.filectx(f2).data()
366 t = mctx.filectx(f2).data()
367 repo.wwrite(fd, t, flags)
367 repo.wwrite(fd, t, flags)
368 updated += 1
368 updated += 1
369 elif m == "dr": # divergent renames
369 elif m == "dr": # divergent renames
370 fl = a[2]
370 fl = a[2]
371 repo.ui.warn(_("note: possible conflict - %s was renamed "
371 repo.ui.warn(_("note: possible conflict - %s was renamed "
372 "multiple times to:\n") % f)
372 "multiple times to:\n") % f)
373 for nf in fl:
373 for nf in fl:
374 repo.ui.warn(" %s\n" % nf)
374 repo.ui.warn(" %s\n" % nf)
375 elif m == "e": # exec
375 elif m == "e": # exec
376 flags = a[2]
376 flags = a[2]
377 repo.wopener.audit(f)
377 repo.wopener.audit(f)
378 util.setflags(repo.wjoin(f), 'l' in flags, 'x' in flags)
378 util.setflags(repo.wjoin(f), 'l' in flags, 'x' in flags)
379 ms.commit()
379 ms.commit()
380 u.progress(_('updating'), None, total=numupdates, unit=_('files'))
380 u.progress(_('updating'), None, total=numupdates, unit=_('files'))
381
381
382 return updated, merged, removed, unresolved
382 return updated, merged, removed, unresolved
383
383
384 def recordupdates(repo, action, branchmerge):
384 def recordupdates(repo, action, branchmerge):
385 "record merge actions to the dirstate"
385 "record merge actions to the dirstate"
386
386
387 for a in action:
387 for a in action:
388 f, m = a[:2]
388 f, m = a[:2]
389 if m == "r": # remove
389 if m == "r": # remove
390 if branchmerge:
390 if branchmerge:
391 repo.dirstate.remove(f)
391 repo.dirstate.remove(f)
392 else:
392 else:
393 repo.dirstate.forget(f)
393 repo.dirstate.drop(f)
394 elif m == "a": # re-add
394 elif m == "a": # re-add
395 if not branchmerge:
395 if not branchmerge:
396 repo.dirstate.add(f)
396 repo.dirstate.add(f)
397 elif m == "f": # forget
397 elif m == "f": # forget
398 repo.dirstate.forget(f)
398 repo.dirstate.drop(f)
399 elif m == "e": # exec change
399 elif m == "e": # exec change
400 repo.dirstate.normallookup(f)
400 repo.dirstate.normallookup(f)
401 elif m == "g": # get
401 elif m == "g": # get
402 if branchmerge:
402 if branchmerge:
403 repo.dirstate.otherparent(f)
403 repo.dirstate.otherparent(f)
404 else:
404 else:
405 repo.dirstate.normal(f)
405 repo.dirstate.normal(f)
406 elif m == "m": # merge
406 elif m == "m": # merge
407 f2, fd, flag, move = a[2:]
407 f2, fd, flag, move = a[2:]
408 if branchmerge:
408 if branchmerge:
409 # We've done a branch merge, mark this file as merged
409 # We've done a branch merge, mark this file as merged
410 # so that we properly record the merger later
410 # so that we properly record the merger later
411 repo.dirstate.merge(fd)
411 repo.dirstate.merge(fd)
412 if f != f2: # copy/rename
412 if f != f2: # copy/rename
413 if move:
413 if move:
414 repo.dirstate.remove(f)
414 repo.dirstate.remove(f)
415 if f != fd:
415 if f != fd:
416 repo.dirstate.copy(f, fd)
416 repo.dirstate.copy(f, fd)
417 else:
417 else:
418 repo.dirstate.copy(f2, fd)
418 repo.dirstate.copy(f2, fd)
419 else:
419 else:
420 # We've update-merged a locally modified file, so
420 # We've update-merged a locally modified file, so
421 # we set the dirstate to emulate a normal checkout
421 # we set the dirstate to emulate a normal checkout
422 # of that file some time in the past. Thus our
422 # of that file some time in the past. Thus our
423 # merge will appear as a normal local file
423 # merge will appear as a normal local file
424 # modification.
424 # modification.
425 if f2 == fd: # file not locally copied/moved
425 if f2 == fd: # file not locally copied/moved
426 repo.dirstate.normallookup(fd)
426 repo.dirstate.normallookup(fd)
427 if move:
427 if move:
428 repo.dirstate.forget(f)
428 repo.dirstate.drop(f)
429 elif m == "d": # directory rename
429 elif m == "d": # directory rename
430 f2, fd, flag = a[2:]
430 f2, fd, flag = a[2:]
431 if not f2 and f not in repo.dirstate:
431 if not f2 and f not in repo.dirstate:
432 # untracked file moved
432 # untracked file moved
433 continue
433 continue
434 if branchmerge:
434 if branchmerge:
435 repo.dirstate.add(fd)
435 repo.dirstate.add(fd)
436 if f:
436 if f:
437 repo.dirstate.remove(f)
437 repo.dirstate.remove(f)
438 repo.dirstate.copy(f, fd)
438 repo.dirstate.copy(f, fd)
439 if f2:
439 if f2:
440 repo.dirstate.copy(f2, fd)
440 repo.dirstate.copy(f2, fd)
441 else:
441 else:
442 repo.dirstate.normal(fd)
442 repo.dirstate.normal(fd)
443 if f:
443 if f:
444 repo.dirstate.forget(f)
444 repo.dirstate.drop(f)
445
445
446 def update(repo, node, branchmerge, force, partial, ancestor=None):
446 def update(repo, node, branchmerge, force, partial, ancestor=None):
447 """
447 """
448 Perform a merge between the working directory and the given node
448 Perform a merge between the working directory and the given node
449
449
450 node = the node to update to, or None if unspecified
450 node = the node to update to, or None if unspecified
451 branchmerge = whether to merge between branches
451 branchmerge = whether to merge between branches
452 force = whether to force branch merging or file overwriting
452 force = whether to force branch merging or file overwriting
453 partial = a function to filter file lists (dirstate not updated)
453 partial = a function to filter file lists (dirstate not updated)
454
454
455 The table below shows all the behaviors of the update command
455 The table below shows all the behaviors of the update command
456 given the -c and -C or no options, whether the working directory
456 given the -c and -C or no options, whether the working directory
457 is dirty, whether a revision is specified, and the relationship of
457 is dirty, whether a revision is specified, and the relationship of
458 the parent rev to the target rev (linear, on the same named
458 the parent rev to the target rev (linear, on the same named
459 branch, or on another named branch).
459 branch, or on another named branch).
460
460
461 This logic is tested by test-update-branches.t.
461 This logic is tested by test-update-branches.t.
462
462
463 -c -C dirty rev | linear same cross
463 -c -C dirty rev | linear same cross
464 n n n n | ok (1) x
464 n n n n | ok (1) x
465 n n n y | ok ok ok
465 n n n y | ok ok ok
466 n n y * | merge (2) (2)
466 n n y * | merge (2) (2)
467 n y * * | --- discard ---
467 n y * * | --- discard ---
468 y n y * | --- (3) ---
468 y n y * | --- (3) ---
469 y n n * | --- ok ---
469 y n n * | --- ok ---
470 y y * * | --- (4) ---
470 y y * * | --- (4) ---
471
471
472 x = can't happen
472 x = can't happen
473 * = don't-care
473 * = don't-care
474 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
474 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
475 2 = abort: crosses branches (use 'hg merge' to merge or
475 2 = abort: crosses branches (use 'hg merge' to merge or
476 use 'hg update -C' to discard changes)
476 use 'hg update -C' to discard changes)
477 3 = abort: uncommitted local changes
477 3 = abort: uncommitted local changes
478 4 = incompatible options (checked in commands.py)
478 4 = incompatible options (checked in commands.py)
479
479
480 Return the same tuple as applyupdates().
480 Return the same tuple as applyupdates().
481 """
481 """
482
482
483 onode = node
483 onode = node
484 wlock = repo.wlock()
484 wlock = repo.wlock()
485 try:
485 try:
486 wc = repo[None]
486 wc = repo[None]
487 if node is None:
487 if node is None:
488 # tip of current branch
488 # tip of current branch
489 try:
489 try:
490 node = repo.branchtags()[wc.branch()]
490 node = repo.branchtags()[wc.branch()]
491 except KeyError:
491 except KeyError:
492 if wc.branch() == "default": # no default branch!
492 if wc.branch() == "default": # no default branch!
493 node = repo.lookup("tip") # update to tip
493 node = repo.lookup("tip") # update to tip
494 else:
494 else:
495 raise util.Abort(_("branch %s not found") % wc.branch())
495 raise util.Abort(_("branch %s not found") % wc.branch())
496 overwrite = force and not branchmerge
496 overwrite = force and not branchmerge
497 pl = wc.parents()
497 pl = wc.parents()
498 p1, p2 = pl[0], repo[node]
498 p1, p2 = pl[0], repo[node]
499 if ancestor:
499 if ancestor:
500 pa = repo[ancestor]
500 pa = repo[ancestor]
501 else:
501 else:
502 pa = p1.ancestor(p2)
502 pa = p1.ancestor(p2)
503
503
504 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
504 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
505
505
506 ### check phase
506 ### check phase
507 if not overwrite and len(pl) > 1:
507 if not overwrite and len(pl) > 1:
508 raise util.Abort(_("outstanding uncommitted merges"))
508 raise util.Abort(_("outstanding uncommitted merges"))
509 if branchmerge:
509 if branchmerge:
510 if pa == p2:
510 if pa == p2:
511 raise util.Abort(_("merging with a working directory ancestor"
511 raise util.Abort(_("merging with a working directory ancestor"
512 " has no effect"))
512 " has no effect"))
513 elif pa == p1:
513 elif pa == p1:
514 if p1.branch() == p2.branch():
514 if p1.branch() == p2.branch():
515 raise util.Abort(_("nothing to merge (use 'hg update'"
515 raise util.Abort(_("nothing to merge (use 'hg update'"
516 " or check 'hg heads')"))
516 " or check 'hg heads')"))
517 if not force and (wc.files() or wc.deleted()):
517 if not force and (wc.files() or wc.deleted()):
518 raise util.Abort(_("outstanding uncommitted changes "
518 raise util.Abort(_("outstanding uncommitted changes "
519 "(use 'hg status' to list changes)"))
519 "(use 'hg status' to list changes)"))
520 for s in wc.substate:
520 for s in wc.substate:
521 if wc.sub(s).dirty():
521 if wc.sub(s).dirty():
522 raise util.Abort(_("outstanding uncommitted changes in "
522 raise util.Abort(_("outstanding uncommitted changes in "
523 "subrepository '%s'") % s)
523 "subrepository '%s'") % s)
524
524
525 elif not overwrite:
525 elif not overwrite:
526 if pa == p1 or pa == p2: # linear
526 if pa == p1 or pa == p2: # linear
527 pass # all good
527 pass # all good
528 elif wc.files() or wc.deleted():
528 elif wc.files() or wc.deleted():
529 raise util.Abort(_("crosses branches (merge branches or use"
529 raise util.Abort(_("crosses branches (merge branches or use"
530 " --clean to discard changes)"))
530 " --clean to discard changes)"))
531 elif onode is None:
531 elif onode is None:
532 raise util.Abort(_("crosses branches (merge branches or use"
532 raise util.Abort(_("crosses branches (merge branches or use"
533 " --check to force update)"))
533 " --check to force update)"))
534 else:
534 else:
535 # Allow jumping branches if clean and specific rev given
535 # Allow jumping branches if clean and specific rev given
536 overwrite = True
536 overwrite = True
537
537
538 ### calculate phase
538 ### calculate phase
539 action = []
539 action = []
540 wc.status(unknown=True) # prime cache
540 wc.status(unknown=True) # prime cache
541 if not force:
541 if not force:
542 _checkunknown(wc, p2)
542 _checkunknown(wc, p2)
543 if not util.checkcase(repo.path):
543 if not util.checkcase(repo.path):
544 _checkcollision(p2)
544 _checkcollision(p2)
545 action += _forgetremoved(wc, p2, branchmerge)
545 action += _forgetremoved(wc, p2, branchmerge)
546 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
546 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
547
547
548 ### apply phase
548 ### apply phase
549 if not branchmerge: # just jump to the new rev
549 if not branchmerge: # just jump to the new rev
550 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
550 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
551 if not partial:
551 if not partial:
552 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
552 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
553
553
554 stats = applyupdates(repo, action, wc, p2, pa, overwrite)
554 stats = applyupdates(repo, action, wc, p2, pa, overwrite)
555
555
556 if not partial:
556 if not partial:
557 repo.dirstate.setparents(fp1, fp2)
557 repo.dirstate.setparents(fp1, fp2)
558 recordupdates(repo, action, branchmerge)
558 recordupdates(repo, action, branchmerge)
559 if not branchmerge:
559 if not branchmerge:
560 repo.dirstate.setbranch(p2.branch())
560 repo.dirstate.setbranch(p2.branch())
561 finally:
561 finally:
562 wlock.release()
562 wlock.release()
563
563
564 if not partial:
564 if not partial:
565 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
565 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
566 return stats
566 return stats
General Comments 0
You need to be logged in to leave comments. Login now