##// END OF EJS Templates
filectx: use cmp(self, fctx) instead of cmp(self, text)...
Nicolas Dumazet -
r11702:eb07fbc2 default
parent child Browse files
Show More
@@ -1,1086 +1,1086 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, subrepo, patch
10 import ancestor, bdiff, error, util, subrepo, patch
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)
78 return subrepo.state(self)
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 self._changeset[5].get("branch")
112 return 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
117
118 def parents(self):
118 def parents(self):
119 """return contexts for each parent changeset"""
119 """return contexts for each parent changeset"""
120 return self._parents
120 return self._parents
121
121
122 def p1(self):
122 def p1(self):
123 return self._parents[0]
123 return self._parents[0]
124
124
125 def p2(self):
125 def p2(self):
126 if len(self._parents) == 2:
126 if len(self._parents) == 2:
127 return self._parents[1]
127 return self._parents[1]
128 return changectx(self._repo, -1)
128 return changectx(self._repo, -1)
129
129
130 def children(self):
130 def children(self):
131 """return contexts for each child changeset"""
131 """return contexts for each child changeset"""
132 c = self._repo.changelog.children(self._node)
132 c = self._repo.changelog.children(self._node)
133 return [changectx(self._repo, x) for x in c]
133 return [changectx(self._repo, x) for x in c]
134
134
135 def ancestors(self):
135 def ancestors(self):
136 for a in self._repo.changelog.ancestors(self._rev):
136 for a in self._repo.changelog.ancestors(self._rev):
137 yield changectx(self._repo, a)
137 yield changectx(self._repo, a)
138
138
139 def descendants(self):
139 def descendants(self):
140 for d in self._repo.changelog.descendants(self._rev):
140 for d in self._repo.changelog.descendants(self._rev):
141 yield changectx(self._repo, d)
141 yield changectx(self._repo, d)
142
142
143 def _fileinfo(self, path):
143 def _fileinfo(self, path):
144 if '_manifest' in self.__dict__:
144 if '_manifest' in self.__dict__:
145 try:
145 try:
146 return self._manifest[path], self._manifest.flags(path)
146 return self._manifest[path], self._manifest.flags(path)
147 except KeyError:
147 except KeyError:
148 raise error.LookupError(self._node, path,
148 raise error.LookupError(self._node, path,
149 _('not found in manifest'))
149 _('not found in manifest'))
150 if '_manifestdelta' in self.__dict__ or path in self.files():
150 if '_manifestdelta' in self.__dict__ or path in self.files():
151 if path in self._manifestdelta:
151 if path in self._manifestdelta:
152 return self._manifestdelta[path], self._manifestdelta.flags(path)
152 return self._manifestdelta[path], self._manifestdelta.flags(path)
153 node, flag = self._repo.manifest.find(self._changeset[0], path)
153 node, flag = self._repo.manifest.find(self._changeset[0], path)
154 if not node:
154 if not node:
155 raise error.LookupError(self._node, path,
155 raise error.LookupError(self._node, path,
156 _('not found in manifest'))
156 _('not found in manifest'))
157
157
158 return node, flag
158 return node, flag
159
159
160 def filenode(self, path):
160 def filenode(self, path):
161 return self._fileinfo(path)[0]
161 return self._fileinfo(path)[0]
162
162
163 def flags(self, path):
163 def flags(self, path):
164 try:
164 try:
165 return self._fileinfo(path)[1]
165 return self._fileinfo(path)[1]
166 except error.LookupError:
166 except error.LookupError:
167 return ''
167 return ''
168
168
169 def filectx(self, path, fileid=None, filelog=None):
169 def filectx(self, path, fileid=None, filelog=None):
170 """get a file context from this changeset"""
170 """get a file context from this changeset"""
171 if fileid is None:
171 if fileid is None:
172 fileid = self.filenode(path)
172 fileid = self.filenode(path)
173 return filectx(self._repo, path, fileid=fileid,
173 return filectx(self._repo, path, fileid=fileid,
174 changectx=self, filelog=filelog)
174 changectx=self, filelog=filelog)
175
175
176 def ancestor(self, c2):
176 def ancestor(self, c2):
177 """
177 """
178 return the ancestor context of self and c2
178 return the ancestor context of self and c2
179 """
179 """
180 # deal with workingctxs
180 # deal with workingctxs
181 n2 = c2._node
181 n2 = c2._node
182 if n2 == None:
182 if n2 == None:
183 n2 = c2._parents[0]._node
183 n2 = c2._parents[0]._node
184 n = self._repo.changelog.ancestor(self._node, n2)
184 n = self._repo.changelog.ancestor(self._node, n2)
185 return changectx(self._repo, n)
185 return changectx(self._repo, n)
186
186
187 def walk(self, match):
187 def walk(self, match):
188 fset = set(match.files())
188 fset = set(match.files())
189 # for dirstate.walk, files=['.'] means "walk the whole tree".
189 # for dirstate.walk, files=['.'] means "walk the whole tree".
190 # follow that here, too
190 # follow that here, too
191 fset.discard('.')
191 fset.discard('.')
192 for fn in self:
192 for fn in self:
193 for ffn in fset:
193 for ffn in fset:
194 # match if the file is the exact name or a directory
194 # match if the file is the exact name or a directory
195 if ffn == fn or fn.startswith("%s/" % ffn):
195 if ffn == fn or fn.startswith("%s/" % ffn):
196 fset.remove(ffn)
196 fset.remove(ffn)
197 break
197 break
198 if match(fn):
198 if match(fn):
199 yield fn
199 yield fn
200 for fn in sorted(fset):
200 for fn in sorted(fset):
201 if match.bad(fn, 'No such file in rev ' + str(self)) and match(fn):
201 if match.bad(fn, 'No such file in rev ' + str(self)) and match(fn):
202 yield fn
202 yield fn
203
203
204 def sub(self, path):
204 def sub(self, path):
205 return subrepo.subrepo(self, path)
205 return subrepo.subrepo(self, path)
206
206
207 def diff(self, ctx2=None, match=None, **opts):
207 def diff(self, ctx2=None, match=None, **opts):
208 """Returns a diff generator for the given contexts and matcher"""
208 """Returns a diff generator for the given contexts and matcher"""
209 if ctx2 is None:
209 if ctx2 is None:
210 ctx2 = self.p1()
210 ctx2 = self.p1()
211 if ctx2 is not None and not isinstance(ctx2, changectx):
211 if ctx2 is not None and not isinstance(ctx2, changectx):
212 ctx2 = self._repo[ctx2]
212 ctx2 = self._repo[ctx2]
213 diffopts = patch.diffopts(self._repo.ui, opts)
213 diffopts = patch.diffopts(self._repo.ui, opts)
214 return patch.diff(self._repo, ctx2.node(), self.node(),
214 return patch.diff(self._repo, ctx2.node(), self.node(),
215 match=match, opts=diffopts)
215 match=match, opts=diffopts)
216
216
217 class filectx(object):
217 class filectx(object):
218 """A filecontext object makes access to data related to a particular
218 """A filecontext object makes access to data related to a particular
219 filerevision convenient."""
219 filerevision convenient."""
220 def __init__(self, repo, path, changeid=None, fileid=None,
220 def __init__(self, repo, path, changeid=None, fileid=None,
221 filelog=None, changectx=None):
221 filelog=None, changectx=None):
222 """changeid can be a changeset revision, node, or tag.
222 """changeid can be a changeset revision, node, or tag.
223 fileid can be a file revision or node."""
223 fileid can be a file revision or node."""
224 self._repo = repo
224 self._repo = repo
225 self._path = path
225 self._path = path
226
226
227 assert (changeid is not None
227 assert (changeid is not None
228 or fileid is not None
228 or fileid is not None
229 or changectx is not None), \
229 or changectx is not None), \
230 ("bad args: changeid=%r, fileid=%r, changectx=%r"
230 ("bad args: changeid=%r, fileid=%r, changectx=%r"
231 % (changeid, fileid, changectx))
231 % (changeid, fileid, changectx))
232
232
233 if filelog:
233 if filelog:
234 self._filelog = filelog
234 self._filelog = filelog
235
235
236 if changeid is not None:
236 if changeid is not None:
237 self._changeid = changeid
237 self._changeid = changeid
238 if changectx is not None:
238 if changectx is not None:
239 self._changectx = changectx
239 self._changectx = changectx
240 if fileid is not None:
240 if fileid is not None:
241 self._fileid = fileid
241 self._fileid = fileid
242
242
243 @propertycache
243 @propertycache
244 def _changectx(self):
244 def _changectx(self):
245 return changectx(self._repo, self._changeid)
245 return changectx(self._repo, self._changeid)
246
246
247 @propertycache
247 @propertycache
248 def _filelog(self):
248 def _filelog(self):
249 return self._repo.file(self._path)
249 return self._repo.file(self._path)
250
250
251 @propertycache
251 @propertycache
252 def _changeid(self):
252 def _changeid(self):
253 if '_changectx' in self.__dict__:
253 if '_changectx' in self.__dict__:
254 return self._changectx.rev()
254 return self._changectx.rev()
255 else:
255 else:
256 return self._filelog.linkrev(self._filerev)
256 return self._filelog.linkrev(self._filerev)
257
257
258 @propertycache
258 @propertycache
259 def _filenode(self):
259 def _filenode(self):
260 if '_fileid' in self.__dict__:
260 if '_fileid' in self.__dict__:
261 return self._filelog.lookup(self._fileid)
261 return self._filelog.lookup(self._fileid)
262 else:
262 else:
263 return self._changectx.filenode(self._path)
263 return self._changectx.filenode(self._path)
264
264
265 @propertycache
265 @propertycache
266 def _filerev(self):
266 def _filerev(self):
267 return self._filelog.rev(self._filenode)
267 return self._filelog.rev(self._filenode)
268
268
269 @propertycache
269 @propertycache
270 def _repopath(self):
270 def _repopath(self):
271 return self._path
271 return self._path
272
272
273 def __nonzero__(self):
273 def __nonzero__(self):
274 try:
274 try:
275 self._filenode
275 self._filenode
276 return True
276 return True
277 except error.LookupError:
277 except error.LookupError:
278 # file is missing
278 # file is missing
279 return False
279 return False
280
280
281 def __str__(self):
281 def __str__(self):
282 return "%s@%s" % (self.path(), short(self.node()))
282 return "%s@%s" % (self.path(), short(self.node()))
283
283
284 def __repr__(self):
284 def __repr__(self):
285 return "<filectx %s>" % str(self)
285 return "<filectx %s>" % str(self)
286
286
287 def __hash__(self):
287 def __hash__(self):
288 try:
288 try:
289 return hash((self._path, self._filenode))
289 return hash((self._path, self._filenode))
290 except AttributeError:
290 except AttributeError:
291 return id(self)
291 return id(self)
292
292
293 def __eq__(self, other):
293 def __eq__(self, other):
294 try:
294 try:
295 return (self._path == other._path
295 return (self._path == other._path
296 and self._filenode == other._filenode)
296 and self._filenode == other._filenode)
297 except AttributeError:
297 except AttributeError:
298 return False
298 return False
299
299
300 def __ne__(self, other):
300 def __ne__(self, other):
301 return not (self == other)
301 return not (self == other)
302
302
303 def filectx(self, fileid):
303 def filectx(self, fileid):
304 '''opens an arbitrary revision of the file without
304 '''opens an arbitrary revision of the file without
305 opening a new filelog'''
305 opening a new filelog'''
306 return filectx(self._repo, self._path, fileid=fileid,
306 return filectx(self._repo, self._path, fileid=fileid,
307 filelog=self._filelog)
307 filelog=self._filelog)
308
308
309 def filerev(self):
309 def filerev(self):
310 return self._filerev
310 return self._filerev
311 def filenode(self):
311 def filenode(self):
312 return self._filenode
312 return self._filenode
313 def flags(self):
313 def flags(self):
314 return self._changectx.flags(self._path)
314 return self._changectx.flags(self._path)
315 def filelog(self):
315 def filelog(self):
316 return self._filelog
316 return self._filelog
317
317
318 def rev(self):
318 def rev(self):
319 if '_changectx' in self.__dict__:
319 if '_changectx' in self.__dict__:
320 return self._changectx.rev()
320 return self._changectx.rev()
321 if '_changeid' in self.__dict__:
321 if '_changeid' in self.__dict__:
322 return self._changectx.rev()
322 return self._changectx.rev()
323 return self._filelog.linkrev(self._filerev)
323 return self._filelog.linkrev(self._filerev)
324
324
325 def linkrev(self):
325 def linkrev(self):
326 return self._filelog.linkrev(self._filerev)
326 return self._filelog.linkrev(self._filerev)
327 def node(self):
327 def node(self):
328 return self._changectx.node()
328 return self._changectx.node()
329 def hex(self):
329 def hex(self):
330 return hex(self.node())
330 return hex(self.node())
331 def user(self):
331 def user(self):
332 return self._changectx.user()
332 return self._changectx.user()
333 def date(self):
333 def date(self):
334 return self._changectx.date()
334 return self._changectx.date()
335 def files(self):
335 def files(self):
336 return self._changectx.files()
336 return self._changectx.files()
337 def description(self):
337 def description(self):
338 return self._changectx.description()
338 return self._changectx.description()
339 def branch(self):
339 def branch(self):
340 return self._changectx.branch()
340 return self._changectx.branch()
341 def extra(self):
341 def extra(self):
342 return self._changectx.extra()
342 return self._changectx.extra()
343 def manifest(self):
343 def manifest(self):
344 return self._changectx.manifest()
344 return self._changectx.manifest()
345 def changectx(self):
345 def changectx(self):
346 return self._changectx
346 return self._changectx
347
347
348 def data(self):
348 def data(self):
349 return self._filelog.read(self._filenode)
349 return self._filelog.read(self._filenode)
350 def path(self):
350 def path(self):
351 return self._path
351 return self._path
352 def size(self):
352 def size(self):
353 return self._filelog.size(self._filerev)
353 return self._filelog.size(self._filerev)
354
354
355 def cmp(self, text):
355 def cmp(self, fctx):
356 """compare text with stored file revision
356 """compare with other file context
357
357
358 returns True if text is different than what is stored.
358 returns True if different than fctx.
359 """
359 """
360 return self._filelog.cmp(self._filenode, text)
360 return self._filelog.cmp(self._filenode, fctx.data())
361
361
362 def renamed(self):
362 def renamed(self):
363 """check if file was actually renamed in this changeset revision
363 """check if file was actually renamed in this changeset revision
364
364
365 If rename logged in file revision, we report copy for changeset only
365 If rename logged in file revision, we report copy for changeset only
366 if file revisions linkrev points back to the changeset in question
366 if file revisions linkrev points back to the changeset in question
367 or both changeset parents contain different file revisions.
367 or both changeset parents contain different file revisions.
368 """
368 """
369
369
370 renamed = self._filelog.renamed(self._filenode)
370 renamed = self._filelog.renamed(self._filenode)
371 if not renamed:
371 if not renamed:
372 return renamed
372 return renamed
373
373
374 if self.rev() == self.linkrev():
374 if self.rev() == self.linkrev():
375 return renamed
375 return renamed
376
376
377 name = self.path()
377 name = self.path()
378 fnode = self._filenode
378 fnode = self._filenode
379 for p in self._changectx.parents():
379 for p in self._changectx.parents():
380 try:
380 try:
381 if fnode == p.filenode(name):
381 if fnode == p.filenode(name):
382 return None
382 return None
383 except error.LookupError:
383 except error.LookupError:
384 pass
384 pass
385 return renamed
385 return renamed
386
386
387 def parents(self):
387 def parents(self):
388 p = self._path
388 p = self._path
389 fl = self._filelog
389 fl = self._filelog
390 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
390 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
391
391
392 r = self._filelog.renamed(self._filenode)
392 r = self._filelog.renamed(self._filenode)
393 if r:
393 if r:
394 pl[0] = (r[0], r[1], None)
394 pl[0] = (r[0], r[1], None)
395
395
396 return [filectx(self._repo, p, fileid=n, filelog=l)
396 return [filectx(self._repo, p, fileid=n, filelog=l)
397 for p, n, l in pl if n != nullid]
397 for p, n, l in pl if n != nullid]
398
398
399 def children(self):
399 def children(self):
400 # hard for renames
400 # hard for renames
401 c = self._filelog.children(self._filenode)
401 c = self._filelog.children(self._filenode)
402 return [filectx(self._repo, self._path, fileid=x,
402 return [filectx(self._repo, self._path, fileid=x,
403 filelog=self._filelog) for x in c]
403 filelog=self._filelog) for x in c]
404
404
405 def annotate(self, follow=False, linenumber=None):
405 def annotate(self, follow=False, linenumber=None):
406 '''returns a list of tuples of (ctx, line) for each line
406 '''returns a list of tuples of (ctx, line) for each line
407 in the file, where ctx is the filectx of the node where
407 in the file, where ctx is the filectx of the node where
408 that line was last changed.
408 that line was last changed.
409 This returns tuples of ((ctx, linenumber), line) for each line,
409 This returns tuples of ((ctx, linenumber), line) for each line,
410 if "linenumber" parameter is NOT "None".
410 if "linenumber" parameter is NOT "None".
411 In such tuples, linenumber means one at the first appearance
411 In such tuples, linenumber means one at the first appearance
412 in the managed file.
412 in the managed file.
413 To reduce annotation cost,
413 To reduce annotation cost,
414 this returns fixed value(False is used) as linenumber,
414 this returns fixed value(False is used) as linenumber,
415 if "linenumber" parameter is "False".'''
415 if "linenumber" parameter is "False".'''
416
416
417 def decorate_compat(text, rev):
417 def decorate_compat(text, rev):
418 return ([rev] * len(text.splitlines()), text)
418 return ([rev] * len(text.splitlines()), text)
419
419
420 def without_linenumber(text, rev):
420 def without_linenumber(text, rev):
421 return ([(rev, False)] * len(text.splitlines()), text)
421 return ([(rev, False)] * len(text.splitlines()), text)
422
422
423 def with_linenumber(text, rev):
423 def with_linenumber(text, rev):
424 size = len(text.splitlines())
424 size = len(text.splitlines())
425 return ([(rev, i) for i in xrange(1, size + 1)], text)
425 return ([(rev, i) for i in xrange(1, size + 1)], text)
426
426
427 decorate = (((linenumber is None) and decorate_compat) or
427 decorate = (((linenumber is None) and decorate_compat) or
428 (linenumber and with_linenumber) or
428 (linenumber and with_linenumber) or
429 without_linenumber)
429 without_linenumber)
430
430
431 def pair(parent, child):
431 def pair(parent, child):
432 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
432 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
433 child[0][b1:b2] = parent[0][a1:a2]
433 child[0][b1:b2] = parent[0][a1:a2]
434 return child
434 return child
435
435
436 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
436 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
437 def getctx(path, fileid):
437 def getctx(path, fileid):
438 log = path == self._path and self._filelog or getlog(path)
438 log = path == self._path and self._filelog or getlog(path)
439 return filectx(self._repo, path, fileid=fileid, filelog=log)
439 return filectx(self._repo, path, fileid=fileid, filelog=log)
440 getctx = util.lrucachefunc(getctx)
440 getctx = util.lrucachefunc(getctx)
441
441
442 def parents(f):
442 def parents(f):
443 # we want to reuse filectx objects as much as possible
443 # we want to reuse filectx objects as much as possible
444 p = f._path
444 p = f._path
445 if f._filerev is None: # working dir
445 if f._filerev is None: # working dir
446 pl = [(n.path(), n.filerev()) for n in f.parents()]
446 pl = [(n.path(), n.filerev()) for n in f.parents()]
447 else:
447 else:
448 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
448 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
449
449
450 if follow:
450 if follow:
451 r = f.renamed()
451 r = f.renamed()
452 if r:
452 if r:
453 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
453 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
454
454
455 return [getctx(p, n) for p, n in pl if n != nullrev]
455 return [getctx(p, n) for p, n in pl if n != nullrev]
456
456
457 # use linkrev to find the first changeset where self appeared
457 # use linkrev to find the first changeset where self appeared
458 if self.rev() != self.linkrev():
458 if self.rev() != self.linkrev():
459 base = self.filectx(self.filerev())
459 base = self.filectx(self.filerev())
460 else:
460 else:
461 base = self
461 base = self
462
462
463 # find all ancestors
463 # find all ancestors
464 needed = {base: 1}
464 needed = {base: 1}
465 visit = [base]
465 visit = [base]
466 files = [base._path]
466 files = [base._path]
467 while visit:
467 while visit:
468 f = visit.pop(0)
468 f = visit.pop(0)
469 for p in parents(f):
469 for p in parents(f):
470 if p not in needed:
470 if p not in needed:
471 needed[p] = 1
471 needed[p] = 1
472 visit.append(p)
472 visit.append(p)
473 if p._path not in files:
473 if p._path not in files:
474 files.append(p._path)
474 files.append(p._path)
475 else:
475 else:
476 # count how many times we'll use this
476 # count how many times we'll use this
477 needed[p] += 1
477 needed[p] += 1
478
478
479 # sort by revision (per file) which is a topological order
479 # sort by revision (per file) which is a topological order
480 visit = []
480 visit = []
481 for f in files:
481 for f in files:
482 visit.extend(n for n in needed if n._path == f)
482 visit.extend(n for n in needed if n._path == f)
483
483
484 hist = {}
484 hist = {}
485 for f in sorted(visit, key=lambda x: x.rev()):
485 for f in sorted(visit, key=lambda x: x.rev()):
486 curr = decorate(f.data(), f)
486 curr = decorate(f.data(), f)
487 for p in parents(f):
487 for p in parents(f):
488 curr = pair(hist[p], curr)
488 curr = pair(hist[p], curr)
489 # trim the history of unneeded revs
489 # trim the history of unneeded revs
490 needed[p] -= 1
490 needed[p] -= 1
491 if not needed[p]:
491 if not needed[p]:
492 del hist[p]
492 del hist[p]
493 hist[f] = curr
493 hist[f] = curr
494
494
495 return zip(hist[f][0], hist[f][1].splitlines(True))
495 return zip(hist[f][0], hist[f][1].splitlines(True))
496
496
497 def ancestor(self, fc2, actx=None):
497 def ancestor(self, fc2, actx=None):
498 """
498 """
499 find the common ancestor file context, if any, of self, and fc2
499 find the common ancestor file context, if any, of self, and fc2
500
500
501 If actx is given, it must be the changectx of the common ancestor
501 If actx is given, it must be the changectx of the common ancestor
502 of self's and fc2's respective changesets.
502 of self's and fc2's respective changesets.
503 """
503 """
504
504
505 if actx is None:
505 if actx is None:
506 actx = self.changectx().ancestor(fc2.changectx())
506 actx = self.changectx().ancestor(fc2.changectx())
507
507
508 # the trivial case: changesets are unrelated, files must be too
508 # the trivial case: changesets are unrelated, files must be too
509 if not actx:
509 if not actx:
510 return None
510 return None
511
511
512 # the easy case: no (relevant) renames
512 # the easy case: no (relevant) renames
513 if fc2.path() == self.path() and self.path() in actx:
513 if fc2.path() == self.path() and self.path() in actx:
514 return actx[self.path()]
514 return actx[self.path()]
515 acache = {}
515 acache = {}
516
516
517 # prime the ancestor cache for the working directory
517 # prime the ancestor cache for the working directory
518 for c in (self, fc2):
518 for c in (self, fc2):
519 if c._filerev is None:
519 if c._filerev is None:
520 pl = [(n.path(), n.filenode()) for n in c.parents()]
520 pl = [(n.path(), n.filenode()) for n in c.parents()]
521 acache[(c._path, None)] = pl
521 acache[(c._path, None)] = pl
522
522
523 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
523 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
524 def parents(vertex):
524 def parents(vertex):
525 if vertex in acache:
525 if vertex in acache:
526 return acache[vertex]
526 return acache[vertex]
527 f, n = vertex
527 f, n = vertex
528 if f not in flcache:
528 if f not in flcache:
529 flcache[f] = self._repo.file(f)
529 flcache[f] = self._repo.file(f)
530 fl = flcache[f]
530 fl = flcache[f]
531 pl = [(f, p) for p in fl.parents(n) if p != nullid]
531 pl = [(f, p) for p in fl.parents(n) if p != nullid]
532 re = fl.renamed(n)
532 re = fl.renamed(n)
533 if re:
533 if re:
534 pl.append(re)
534 pl.append(re)
535 acache[vertex] = pl
535 acache[vertex] = pl
536 return pl
536 return pl
537
537
538 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
538 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
539 v = ancestor.ancestor(a, b, parents)
539 v = ancestor.ancestor(a, b, parents)
540 if v:
540 if v:
541 f, n = v
541 f, n = v
542 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
542 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
543
543
544 return None
544 return None
545
545
546 def ancestors(self):
546 def ancestors(self):
547 seen = set(str(self))
547 seen = set(str(self))
548 visit = [self]
548 visit = [self]
549 while visit:
549 while visit:
550 for parent in visit.pop(0).parents():
550 for parent in visit.pop(0).parents():
551 s = str(parent)
551 s = str(parent)
552 if s not in seen:
552 if s not in seen:
553 visit.append(parent)
553 visit.append(parent)
554 seen.add(s)
554 seen.add(s)
555 yield parent
555 yield parent
556
556
557 class workingctx(changectx):
557 class workingctx(changectx):
558 """A workingctx object makes access to data related to
558 """A workingctx object makes access to data related to
559 the current working directory convenient.
559 the current working directory convenient.
560 date - any valid date string or (unixtime, offset), or None.
560 date - any valid date string or (unixtime, offset), or None.
561 user - username string, or None.
561 user - username string, or None.
562 extra - a dictionary of extra values, or None.
562 extra - a dictionary of extra values, or None.
563 changes - a list of file lists as returned by localrepo.status()
563 changes - a list of file lists as returned by localrepo.status()
564 or None to use the repository status.
564 or None to use the repository status.
565 """
565 """
566 def __init__(self, repo, text="", user=None, date=None, extra=None,
566 def __init__(self, repo, text="", user=None, date=None, extra=None,
567 changes=None):
567 changes=None):
568 self._repo = repo
568 self._repo = repo
569 self._rev = None
569 self._rev = None
570 self._node = None
570 self._node = None
571 self._text = text
571 self._text = text
572 if date:
572 if date:
573 self._date = util.parsedate(date)
573 self._date = util.parsedate(date)
574 if user:
574 if user:
575 self._user = user
575 self._user = user
576 if changes:
576 if changes:
577 self._status = list(changes[:4])
577 self._status = list(changes[:4])
578 self._unknown = changes[4]
578 self._unknown = changes[4]
579 self._ignored = changes[5]
579 self._ignored = changes[5]
580 self._clean = changes[6]
580 self._clean = changes[6]
581 else:
581 else:
582 self._unknown = None
582 self._unknown = None
583 self._ignored = None
583 self._ignored = None
584 self._clean = None
584 self._clean = None
585
585
586 self._extra = {}
586 self._extra = {}
587 if extra:
587 if extra:
588 self._extra = extra.copy()
588 self._extra = extra.copy()
589 if 'branch' not in self._extra:
589 if 'branch' not in self._extra:
590 branch = self._repo.dirstate.branch()
590 branch = self._repo.dirstate.branch()
591 try:
591 try:
592 branch = branch.decode('UTF-8').encode('UTF-8')
592 branch = branch.decode('UTF-8').encode('UTF-8')
593 except UnicodeDecodeError:
593 except UnicodeDecodeError:
594 raise util.Abort(_('branch name not in UTF-8!'))
594 raise util.Abort(_('branch name not in UTF-8!'))
595 self._extra['branch'] = branch
595 self._extra['branch'] = branch
596 if self._extra['branch'] == '':
596 if self._extra['branch'] == '':
597 self._extra['branch'] = 'default'
597 self._extra['branch'] = 'default'
598
598
599 def __str__(self):
599 def __str__(self):
600 return str(self._parents[0]) + "+"
600 return str(self._parents[0]) + "+"
601
601
602 def __nonzero__(self):
602 def __nonzero__(self):
603 return True
603 return True
604
604
605 def __contains__(self, key):
605 def __contains__(self, key):
606 return self._repo.dirstate[key] not in "?r"
606 return self._repo.dirstate[key] not in "?r"
607
607
608 @propertycache
608 @propertycache
609 def _manifest(self):
609 def _manifest(self):
610 """generate a manifest corresponding to the working directory"""
610 """generate a manifest corresponding to the working directory"""
611
611
612 if self._unknown is None:
612 if self._unknown is None:
613 self.status(unknown=True)
613 self.status(unknown=True)
614
614
615 man = self._parents[0].manifest().copy()
615 man = self._parents[0].manifest().copy()
616 copied = self._repo.dirstate.copies()
616 copied = self._repo.dirstate.copies()
617 if len(self._parents) > 1:
617 if len(self._parents) > 1:
618 man2 = self.p2().manifest()
618 man2 = self.p2().manifest()
619 def getman(f):
619 def getman(f):
620 if f in man:
620 if f in man:
621 return man
621 return man
622 return man2
622 return man2
623 else:
623 else:
624 getman = lambda f: man
624 getman = lambda f: man
625 def cf(f):
625 def cf(f):
626 f = copied.get(f, f)
626 f = copied.get(f, f)
627 return getman(f).flags(f)
627 return getman(f).flags(f)
628 ff = self._repo.dirstate.flagfunc(cf)
628 ff = self._repo.dirstate.flagfunc(cf)
629 modified, added, removed, deleted = self._status
629 modified, added, removed, deleted = self._status
630 unknown = self._unknown
630 unknown = self._unknown
631 for i, l in (("a", added), ("m", modified), ("u", unknown)):
631 for i, l in (("a", added), ("m", modified), ("u", unknown)):
632 for f in l:
632 for f in l:
633 orig = copied.get(f, f)
633 orig = copied.get(f, f)
634 man[f] = getman(orig).get(orig, nullid) + i
634 man[f] = getman(orig).get(orig, nullid) + i
635 try:
635 try:
636 man.set(f, ff(f))
636 man.set(f, ff(f))
637 except OSError:
637 except OSError:
638 pass
638 pass
639
639
640 for f in deleted + removed:
640 for f in deleted + removed:
641 if f in man:
641 if f in man:
642 del man[f]
642 del man[f]
643
643
644 return man
644 return man
645
645
646 @propertycache
646 @propertycache
647 def _status(self):
647 def _status(self):
648 return self._repo.status()[:4]
648 return self._repo.status()[:4]
649
649
650 @propertycache
650 @propertycache
651 def _user(self):
651 def _user(self):
652 return self._repo.ui.username()
652 return self._repo.ui.username()
653
653
654 @propertycache
654 @propertycache
655 def _date(self):
655 def _date(self):
656 return util.makedate()
656 return util.makedate()
657
657
658 @propertycache
658 @propertycache
659 def _parents(self):
659 def _parents(self):
660 p = self._repo.dirstate.parents()
660 p = self._repo.dirstate.parents()
661 if p[1] == nullid:
661 if p[1] == nullid:
662 p = p[:-1]
662 p = p[:-1]
663 self._parents = [changectx(self._repo, x) for x in p]
663 self._parents = [changectx(self._repo, x) for x in p]
664 return self._parents
664 return self._parents
665
665
666 def status(self, ignored=False, clean=False, unknown=False):
666 def status(self, ignored=False, clean=False, unknown=False):
667 """Explicit status query
667 """Explicit status query
668 Unless this method is used to query the working copy status, the
668 Unless this method is used to query the working copy status, the
669 _status property will implicitly read the status using its default
669 _status property will implicitly read the status using its default
670 arguments."""
670 arguments."""
671 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
671 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
672 self._unknown = self._ignored = self._clean = None
672 self._unknown = self._ignored = self._clean = None
673 if unknown:
673 if unknown:
674 self._unknown = stat[4]
674 self._unknown = stat[4]
675 if ignored:
675 if ignored:
676 self._ignored = stat[5]
676 self._ignored = stat[5]
677 if clean:
677 if clean:
678 self._clean = stat[6]
678 self._clean = stat[6]
679 self._status = stat[:4]
679 self._status = stat[:4]
680 return stat
680 return stat
681
681
682 def manifest(self):
682 def manifest(self):
683 return self._manifest
683 return self._manifest
684 def user(self):
684 def user(self):
685 return self._user or self._repo.ui.username()
685 return self._user or self._repo.ui.username()
686 def date(self):
686 def date(self):
687 return self._date
687 return self._date
688 def description(self):
688 def description(self):
689 return self._text
689 return self._text
690 def files(self):
690 def files(self):
691 return sorted(self._status[0] + self._status[1] + self._status[2])
691 return sorted(self._status[0] + self._status[1] + self._status[2])
692
692
693 def modified(self):
693 def modified(self):
694 return self._status[0]
694 return self._status[0]
695 def added(self):
695 def added(self):
696 return self._status[1]
696 return self._status[1]
697 def removed(self):
697 def removed(self):
698 return self._status[2]
698 return self._status[2]
699 def deleted(self):
699 def deleted(self):
700 return self._status[3]
700 return self._status[3]
701 def unknown(self):
701 def unknown(self):
702 assert self._unknown is not None # must call status first
702 assert self._unknown is not None # must call status first
703 return self._unknown
703 return self._unknown
704 def ignored(self):
704 def ignored(self):
705 assert self._ignored is not None # must call status first
705 assert self._ignored is not None # must call status first
706 return self._ignored
706 return self._ignored
707 def clean(self):
707 def clean(self):
708 assert self._clean is not None # must call status first
708 assert self._clean is not None # must call status first
709 return self._clean
709 return self._clean
710 def branch(self):
710 def branch(self):
711 return self._extra['branch']
711 return self._extra['branch']
712 def extra(self):
712 def extra(self):
713 return self._extra
713 return self._extra
714
714
715 def tags(self):
715 def tags(self):
716 t = []
716 t = []
717 [t.extend(p.tags()) for p in self.parents()]
717 [t.extend(p.tags()) for p in self.parents()]
718 return t
718 return t
719
719
720 def children(self):
720 def children(self):
721 return []
721 return []
722
722
723 def flags(self, path):
723 def flags(self, path):
724 if '_manifest' in self.__dict__:
724 if '_manifest' in self.__dict__:
725 try:
725 try:
726 return self._manifest.flags(path)
726 return self._manifest.flags(path)
727 except KeyError:
727 except KeyError:
728 return ''
728 return ''
729
729
730 orig = self._repo.dirstate.copies().get(path, path)
730 orig = self._repo.dirstate.copies().get(path, path)
731
731
732 def findflag(ctx):
732 def findflag(ctx):
733 mnode = ctx.changeset()[0]
733 mnode = ctx.changeset()[0]
734 node, flag = self._repo.manifest.find(mnode, orig)
734 node, flag = self._repo.manifest.find(mnode, orig)
735 ff = self._repo.dirstate.flagfunc(lambda x: flag or '')
735 ff = self._repo.dirstate.flagfunc(lambda x: flag or '')
736 try:
736 try:
737 return ff(path)
737 return ff(path)
738 except OSError:
738 except OSError:
739 pass
739 pass
740
740
741 flag = findflag(self._parents[0])
741 flag = findflag(self._parents[0])
742 if flag is None and len(self.parents()) > 1:
742 if flag is None and len(self.parents()) > 1:
743 flag = findflag(self._parents[1])
743 flag = findflag(self._parents[1])
744 if flag is None or self._repo.dirstate[path] == 'r':
744 if flag is None or self._repo.dirstate[path] == 'r':
745 return ''
745 return ''
746 return flag
746 return flag
747
747
748 def filectx(self, path, filelog=None):
748 def filectx(self, path, filelog=None):
749 """get a file context from the working directory"""
749 """get a file context from the working directory"""
750 return workingfilectx(self._repo, path, workingctx=self,
750 return workingfilectx(self._repo, path, workingctx=self,
751 filelog=filelog)
751 filelog=filelog)
752
752
753 def ancestor(self, c2):
753 def ancestor(self, c2):
754 """return the ancestor context of self and c2"""
754 """return the ancestor context of self and c2"""
755 return self._parents[0].ancestor(c2) # punt on two parents for now
755 return self._parents[0].ancestor(c2) # punt on two parents for now
756
756
757 def walk(self, match):
757 def walk(self, match):
758 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
758 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
759 True, False))
759 True, False))
760
760
761 def dirty(self, missing=False):
761 def dirty(self, missing=False):
762 "check whether a working directory is modified"
762 "check whether a working directory is modified"
763 # check subrepos first
763 # check subrepos first
764 for s in self.substate:
764 for s in self.substate:
765 if self.sub(s).dirty():
765 if self.sub(s).dirty():
766 return True
766 return True
767 # check current working dir
767 # check current working dir
768 return (self.p2() or self.branch() != self.p1().branch() or
768 return (self.p2() or self.branch() != self.p1().branch() or
769 self.modified() or self.added() or self.removed() or
769 self.modified() or self.added() or self.removed() or
770 (missing and self.deleted()))
770 (missing and self.deleted()))
771
771
772 def add(self, list):
772 def add(self, list):
773 wlock = self._repo.wlock()
773 wlock = self._repo.wlock()
774 ui, ds = self._repo.ui, self._repo.dirstate
774 ui, ds = self._repo.ui, self._repo.dirstate
775 try:
775 try:
776 rejected = []
776 rejected = []
777 for f in list:
777 for f in list:
778 p = self._repo.wjoin(f)
778 p = self._repo.wjoin(f)
779 try:
779 try:
780 st = os.lstat(p)
780 st = os.lstat(p)
781 except:
781 except:
782 ui.warn(_("%s does not exist!\n") % f)
782 ui.warn(_("%s does not exist!\n") % f)
783 rejected.append(f)
783 rejected.append(f)
784 continue
784 continue
785 if st.st_size > 10000000:
785 if st.st_size > 10000000:
786 ui.warn(_("%s: up to %d MB of RAM may be required "
786 ui.warn(_("%s: up to %d MB of RAM may be required "
787 "to manage this file\n"
787 "to manage this file\n"
788 "(use 'hg revert %s' to cancel the "
788 "(use 'hg revert %s' to cancel the "
789 "pending addition)\n")
789 "pending addition)\n")
790 % (f, 3 * st.st_size // 1000000, f))
790 % (f, 3 * st.st_size // 1000000, f))
791 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
791 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
792 ui.warn(_("%s not added: only files and symlinks "
792 ui.warn(_("%s not added: only files and symlinks "
793 "supported currently\n") % f)
793 "supported currently\n") % f)
794 rejected.append(p)
794 rejected.append(p)
795 elif ds[f] in 'amn':
795 elif ds[f] in 'amn':
796 ui.warn(_("%s already tracked!\n") % f)
796 ui.warn(_("%s already tracked!\n") % f)
797 elif ds[f] == 'r':
797 elif ds[f] == 'r':
798 ds.normallookup(f)
798 ds.normallookup(f)
799 else:
799 else:
800 ds.add(f)
800 ds.add(f)
801 return rejected
801 return rejected
802 finally:
802 finally:
803 wlock.release()
803 wlock.release()
804
804
805 def forget(self, list):
805 def forget(self, list):
806 wlock = self._repo.wlock()
806 wlock = self._repo.wlock()
807 try:
807 try:
808 for f in list:
808 for f in list:
809 if self._repo.dirstate[f] != 'a':
809 if self._repo.dirstate[f] != 'a':
810 self._repo.ui.warn(_("%s not added!\n") % f)
810 self._repo.ui.warn(_("%s not added!\n") % f)
811 else:
811 else:
812 self._repo.dirstate.forget(f)
812 self._repo.dirstate.forget(f)
813 finally:
813 finally:
814 wlock.release()
814 wlock.release()
815
815
816 def remove(self, list, unlink=False):
816 def remove(self, list, unlink=False):
817 if unlink:
817 if unlink:
818 for f in list:
818 for f in list:
819 try:
819 try:
820 util.unlink(self._repo.wjoin(f))
820 util.unlink(self._repo.wjoin(f))
821 except OSError, inst:
821 except OSError, inst:
822 if inst.errno != errno.ENOENT:
822 if inst.errno != errno.ENOENT:
823 raise
823 raise
824 wlock = self._repo.wlock()
824 wlock = self._repo.wlock()
825 try:
825 try:
826 for f in list:
826 for f in list:
827 if unlink and os.path.exists(self._repo.wjoin(f)):
827 if unlink and os.path.exists(self._repo.wjoin(f)):
828 self._repo.ui.warn(_("%s still exists!\n") % f)
828 self._repo.ui.warn(_("%s still exists!\n") % f)
829 elif self._repo.dirstate[f] == 'a':
829 elif self._repo.dirstate[f] == 'a':
830 self._repo.dirstate.forget(f)
830 self._repo.dirstate.forget(f)
831 elif f not in self._repo.dirstate:
831 elif f not in self._repo.dirstate:
832 self._repo.ui.warn(_("%s not tracked!\n") % f)
832 self._repo.ui.warn(_("%s not tracked!\n") % f)
833 else:
833 else:
834 self._repo.dirstate.remove(f)
834 self._repo.dirstate.remove(f)
835 finally:
835 finally:
836 wlock.release()
836 wlock.release()
837
837
838 def undelete(self, list):
838 def undelete(self, list):
839 pctxs = self.parents()
839 pctxs = self.parents()
840 wlock = self._repo.wlock()
840 wlock = self._repo.wlock()
841 try:
841 try:
842 for f in list:
842 for f in list:
843 if self._repo.dirstate[f] != 'r':
843 if self._repo.dirstate[f] != 'r':
844 self._repo.ui.warn(_("%s not removed!\n") % f)
844 self._repo.ui.warn(_("%s not removed!\n") % f)
845 else:
845 else:
846 fctx = f in pctxs[0] and pctxs[0] or pctxs[1]
846 fctx = f in pctxs[0] and pctxs[0] or pctxs[1]
847 t = fctx.data()
847 t = fctx.data()
848 self._repo.wwrite(f, t, fctx.flags())
848 self._repo.wwrite(f, t, fctx.flags())
849 self._repo.dirstate.normal(f)
849 self._repo.dirstate.normal(f)
850 finally:
850 finally:
851 wlock.release()
851 wlock.release()
852
852
853 def copy(self, source, dest):
853 def copy(self, source, dest):
854 p = self._repo.wjoin(dest)
854 p = self._repo.wjoin(dest)
855 if not (os.path.exists(p) or os.path.islink(p)):
855 if not (os.path.exists(p) or os.path.islink(p)):
856 self._repo.ui.warn(_("%s does not exist!\n") % dest)
856 self._repo.ui.warn(_("%s does not exist!\n") % dest)
857 elif not (os.path.isfile(p) or os.path.islink(p)):
857 elif not (os.path.isfile(p) or os.path.islink(p)):
858 self._repo.ui.warn(_("copy failed: %s is not a file or a "
858 self._repo.ui.warn(_("copy failed: %s is not a file or a "
859 "symbolic link\n") % dest)
859 "symbolic link\n") % dest)
860 else:
860 else:
861 wlock = self._repo.wlock()
861 wlock = self._repo.wlock()
862 try:
862 try:
863 if self._repo.dirstate[dest] in '?r':
863 if self._repo.dirstate[dest] in '?r':
864 self._repo.dirstate.add(dest)
864 self._repo.dirstate.add(dest)
865 self._repo.dirstate.copy(source, dest)
865 self._repo.dirstate.copy(source, dest)
866 finally:
866 finally:
867 wlock.release()
867 wlock.release()
868
868
869 class workingfilectx(filectx):
869 class workingfilectx(filectx):
870 """A workingfilectx object makes access to data related to a particular
870 """A workingfilectx object makes access to data related to a particular
871 file in the working directory convenient."""
871 file in the working directory convenient."""
872 def __init__(self, repo, path, filelog=None, workingctx=None):
872 def __init__(self, repo, path, filelog=None, workingctx=None):
873 """changeid can be a changeset revision, node, or tag.
873 """changeid can be a changeset revision, node, or tag.
874 fileid can be a file revision or node."""
874 fileid can be a file revision or node."""
875 self._repo = repo
875 self._repo = repo
876 self._path = path
876 self._path = path
877 self._changeid = None
877 self._changeid = None
878 self._filerev = self._filenode = None
878 self._filerev = self._filenode = None
879
879
880 if filelog:
880 if filelog:
881 self._filelog = filelog
881 self._filelog = filelog
882 if workingctx:
882 if workingctx:
883 self._changectx = workingctx
883 self._changectx = workingctx
884
884
885 @propertycache
885 @propertycache
886 def _changectx(self):
886 def _changectx(self):
887 return workingctx(self._repo)
887 return workingctx(self._repo)
888
888
889 def __nonzero__(self):
889 def __nonzero__(self):
890 return True
890 return True
891
891
892 def __str__(self):
892 def __str__(self):
893 return "%s@%s" % (self.path(), self._changectx)
893 return "%s@%s" % (self.path(), self._changectx)
894
894
895 def data(self):
895 def data(self):
896 return self._repo.wread(self._path)
896 return self._repo.wread(self._path)
897 def renamed(self):
897 def renamed(self):
898 rp = self._repo.dirstate.copied(self._path)
898 rp = self._repo.dirstate.copied(self._path)
899 if not rp:
899 if not rp:
900 return None
900 return None
901 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
901 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
902
902
903 def parents(self):
903 def parents(self):
904 '''return parent filectxs, following copies if necessary'''
904 '''return parent filectxs, following copies if necessary'''
905 def filenode(ctx, path):
905 def filenode(ctx, path):
906 return ctx._manifest.get(path, nullid)
906 return ctx._manifest.get(path, nullid)
907
907
908 path = self._path
908 path = self._path
909 fl = self._filelog
909 fl = self._filelog
910 pcl = self._changectx._parents
910 pcl = self._changectx._parents
911 renamed = self.renamed()
911 renamed = self.renamed()
912
912
913 if renamed:
913 if renamed:
914 pl = [renamed + (None,)]
914 pl = [renamed + (None,)]
915 else:
915 else:
916 pl = [(path, filenode(pcl[0], path), fl)]
916 pl = [(path, filenode(pcl[0], path), fl)]
917
917
918 for pc in pcl[1:]:
918 for pc in pcl[1:]:
919 pl.append((path, filenode(pc, path), fl))
919 pl.append((path, filenode(pc, path), fl))
920
920
921 return [filectx(self._repo, p, fileid=n, filelog=l)
921 return [filectx(self._repo, p, fileid=n, filelog=l)
922 for p, n, l in pl if n != nullid]
922 for p, n, l in pl if n != nullid]
923
923
924 def children(self):
924 def children(self):
925 return []
925 return []
926
926
927 def size(self):
927 def size(self):
928 return os.lstat(self._repo.wjoin(self._path)).st_size
928 return os.lstat(self._repo.wjoin(self._path)).st_size
929 def date(self):
929 def date(self):
930 t, tz = self._changectx.date()
930 t, tz = self._changectx.date()
931 try:
931 try:
932 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
932 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
933 except OSError, err:
933 except OSError, err:
934 if err.errno != errno.ENOENT:
934 if err.errno != errno.ENOENT:
935 raise
935 raise
936 return (t, tz)
936 return (t, tz)
937
937
938 def cmp(self, text):
938 def cmp(self, fctx):
939 """compare text with disk content
939 """compare with other file context
940
940
941 returns True if text is different than what is on disk.
941 returns True if different than fctx.
942 """
942 """
943 return self._repo.wread(self._path) != text
943 return self._repo.wread(self._path) != fctx.data()
944
944
945 class memctx(object):
945 class memctx(object):
946 """Use memctx to perform in-memory commits via localrepo.commitctx().
946 """Use memctx to perform in-memory commits via localrepo.commitctx().
947
947
948 Revision information is supplied at initialization time while
948 Revision information is supplied at initialization time while
949 related files data and is made available through a callback
949 related files data and is made available through a callback
950 mechanism. 'repo' is the current localrepo, 'parents' is a
950 mechanism. 'repo' is the current localrepo, 'parents' is a
951 sequence of two parent revisions identifiers (pass None for every
951 sequence of two parent revisions identifiers (pass None for every
952 missing parent), 'text' is the commit message and 'files' lists
952 missing parent), 'text' is the commit message and 'files' lists
953 names of files touched by the revision (normalized and relative to
953 names of files touched by the revision (normalized and relative to
954 repository root).
954 repository root).
955
955
956 filectxfn(repo, memctx, path) is a callable receiving the
956 filectxfn(repo, memctx, path) is a callable receiving the
957 repository, the current memctx object and the normalized path of
957 repository, the current memctx object and the normalized path of
958 requested file, relative to repository root. It is fired by the
958 requested file, relative to repository root. It is fired by the
959 commit function for every file in 'files', but calls order is
959 commit function for every file in 'files', but calls order is
960 undefined. If the file is available in the revision being
960 undefined. If the file is available in the revision being
961 committed (updated or added), filectxfn returns a memfilectx
961 committed (updated or added), filectxfn returns a memfilectx
962 object. If the file was removed, filectxfn raises an
962 object. If the file was removed, filectxfn raises an
963 IOError. Moved files are represented by marking the source file
963 IOError. Moved files are represented by marking the source file
964 removed and the new file added with copy information (see
964 removed and the new file added with copy information (see
965 memfilectx).
965 memfilectx).
966
966
967 user receives the committer name and defaults to current
967 user receives the committer name and defaults to current
968 repository username, date is the commit date in any format
968 repository username, date is the commit date in any format
969 supported by util.parsedate() and defaults to current date, extra
969 supported by util.parsedate() and defaults to current date, extra
970 is a dictionary of metadata or is left empty.
970 is a dictionary of metadata or is left empty.
971 """
971 """
972 def __init__(self, repo, parents, text, files, filectxfn, user=None,
972 def __init__(self, repo, parents, text, files, filectxfn, user=None,
973 date=None, extra=None):
973 date=None, extra=None):
974 self._repo = repo
974 self._repo = repo
975 self._rev = None
975 self._rev = None
976 self._node = None
976 self._node = None
977 self._text = text
977 self._text = text
978 self._date = date and util.parsedate(date) or util.makedate()
978 self._date = date and util.parsedate(date) or util.makedate()
979 self._user = user
979 self._user = user
980 parents = [(p or nullid) for p in parents]
980 parents = [(p or nullid) for p in parents]
981 p1, p2 = parents
981 p1, p2 = parents
982 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
982 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
983 files = sorted(set(files))
983 files = sorted(set(files))
984 self._status = [files, [], [], [], []]
984 self._status = [files, [], [], [], []]
985 self._filectxfn = filectxfn
985 self._filectxfn = filectxfn
986
986
987 self._extra = extra and extra.copy() or {}
987 self._extra = extra and extra.copy() or {}
988 if 'branch' not in self._extra:
988 if 'branch' not in self._extra:
989 self._extra['branch'] = 'default'
989 self._extra['branch'] = 'default'
990 elif self._extra.get('branch') == '':
990 elif self._extra.get('branch') == '':
991 self._extra['branch'] = 'default'
991 self._extra['branch'] = 'default'
992
992
993 def __str__(self):
993 def __str__(self):
994 return str(self._parents[0]) + "+"
994 return str(self._parents[0]) + "+"
995
995
996 def __int__(self):
996 def __int__(self):
997 return self._rev
997 return self._rev
998
998
999 def __nonzero__(self):
999 def __nonzero__(self):
1000 return True
1000 return True
1001
1001
1002 def __getitem__(self, key):
1002 def __getitem__(self, key):
1003 return self.filectx(key)
1003 return self.filectx(key)
1004
1004
1005 def p1(self):
1005 def p1(self):
1006 return self._parents[0]
1006 return self._parents[0]
1007 def p2(self):
1007 def p2(self):
1008 return self._parents[1]
1008 return self._parents[1]
1009
1009
1010 def user(self):
1010 def user(self):
1011 return self._user or self._repo.ui.username()
1011 return self._user or self._repo.ui.username()
1012 def date(self):
1012 def date(self):
1013 return self._date
1013 return self._date
1014 def description(self):
1014 def description(self):
1015 return self._text
1015 return self._text
1016 def files(self):
1016 def files(self):
1017 return self.modified()
1017 return self.modified()
1018 def modified(self):
1018 def modified(self):
1019 return self._status[0]
1019 return self._status[0]
1020 def added(self):
1020 def added(self):
1021 return self._status[1]
1021 return self._status[1]
1022 def removed(self):
1022 def removed(self):
1023 return self._status[2]
1023 return self._status[2]
1024 def deleted(self):
1024 def deleted(self):
1025 return self._status[3]
1025 return self._status[3]
1026 def unknown(self):
1026 def unknown(self):
1027 return self._status[4]
1027 return self._status[4]
1028 def ignored(self):
1028 def ignored(self):
1029 return self._status[5]
1029 return self._status[5]
1030 def clean(self):
1030 def clean(self):
1031 return self._status[6]
1031 return self._status[6]
1032 def branch(self):
1032 def branch(self):
1033 return self._extra['branch']
1033 return self._extra['branch']
1034 def extra(self):
1034 def extra(self):
1035 return self._extra
1035 return self._extra
1036 def flags(self, f):
1036 def flags(self, f):
1037 return self[f].flags()
1037 return self[f].flags()
1038
1038
1039 def parents(self):
1039 def parents(self):
1040 """return contexts for each parent changeset"""
1040 """return contexts for each parent changeset"""
1041 return self._parents
1041 return self._parents
1042
1042
1043 def filectx(self, path, filelog=None):
1043 def filectx(self, path, filelog=None):
1044 """get a file context from the working directory"""
1044 """get a file context from the working directory"""
1045 return self._filectxfn(self._repo, self, path)
1045 return self._filectxfn(self._repo, self, path)
1046
1046
1047 def commit(self):
1047 def commit(self):
1048 """commit context to the repo"""
1048 """commit context to the repo"""
1049 return self._repo.commitctx(self)
1049 return self._repo.commitctx(self)
1050
1050
1051 class memfilectx(object):
1051 class memfilectx(object):
1052 """memfilectx represents an in-memory file to commit.
1052 """memfilectx represents an in-memory file to commit.
1053
1053
1054 See memctx for more details.
1054 See memctx for more details.
1055 """
1055 """
1056 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1056 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1057 """
1057 """
1058 path is the normalized file path relative to repository root.
1058 path is the normalized file path relative to repository root.
1059 data is the file content as a string.
1059 data is the file content as a string.
1060 islink is True if the file is a symbolic link.
1060 islink is True if the file is a symbolic link.
1061 isexec is True if the file is executable.
1061 isexec is True if the file is executable.
1062 copied is the source file path if current file was copied in the
1062 copied is the source file path if current file was copied in the
1063 revision being committed, or None."""
1063 revision being committed, or None."""
1064 self._path = path
1064 self._path = path
1065 self._data = data
1065 self._data = data
1066 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1066 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1067 self._copied = None
1067 self._copied = None
1068 if copied:
1068 if copied:
1069 self._copied = (copied, nullid)
1069 self._copied = (copied, nullid)
1070
1070
1071 def __nonzero__(self):
1071 def __nonzero__(self):
1072 return True
1072 return True
1073 def __str__(self):
1073 def __str__(self):
1074 return "%s@%s" % (self.path(), self._changectx)
1074 return "%s@%s" % (self.path(), self._changectx)
1075 def path(self):
1075 def path(self):
1076 return self._path
1076 return self._path
1077 def data(self):
1077 def data(self):
1078 return self._data
1078 return self._data
1079 def flags(self):
1079 def flags(self):
1080 return self._flags
1080 return self._flags
1081 def isexec(self):
1081 def isexec(self):
1082 return 'x' in self._flags
1082 return 'x' in self._flags
1083 def islink(self):
1083 def islink(self):
1084 return 'l' in self._flags
1084 return 'l' in self._flags
1085 def renamed(self):
1085 def renamed(self):
1086 return self._copied
1086 return self._copied
@@ -1,259 +1,259 b''
1 # filemerge.py - file-level merge handling for Mercurial
1 # filemerge.py - file-level merge handling for Mercurial
2 #
2 #
3 # Copyright 2006, 2007, 2008 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007, 2008 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 short
8 from node import short
9 from i18n import _
9 from i18n import _
10 import util, simplemerge, match, error
10 import util, simplemerge, match, error
11 import os, tempfile, re, filecmp
11 import os, tempfile, re, filecmp
12
12
13 def _toolstr(ui, tool, part, default=""):
13 def _toolstr(ui, tool, part, default=""):
14 return ui.config("merge-tools", tool + "." + part, default)
14 return ui.config("merge-tools", tool + "." + part, default)
15
15
16 def _toolbool(ui, tool, part, default=False):
16 def _toolbool(ui, tool, part, default=False):
17 return ui.configbool("merge-tools", tool + "." + part, default)
17 return ui.configbool("merge-tools", tool + "." + part, default)
18
18
19 def _toollist(ui, tool, part, default=[]):
19 def _toollist(ui, tool, part, default=[]):
20 return ui.configlist("merge-tools", tool + "." + part, default)
20 return ui.configlist("merge-tools", tool + "." + part, default)
21
21
22 _internal = ['internal:' + s
22 _internal = ['internal:' + s
23 for s in 'fail local other merge prompt dump'.split()]
23 for s in 'fail local other merge prompt dump'.split()]
24
24
25 def _findtool(ui, tool):
25 def _findtool(ui, tool):
26 if tool in _internal:
26 if tool in _internal:
27 return tool
27 return tool
28 k = _toolstr(ui, tool, "regkey")
28 k = _toolstr(ui, tool, "regkey")
29 if k:
29 if k:
30 p = util.lookup_reg(k, _toolstr(ui, tool, "regname"))
30 p = util.lookup_reg(k, _toolstr(ui, tool, "regname"))
31 if p:
31 if p:
32 p = util.find_exe(p + _toolstr(ui, tool, "regappend"))
32 p = util.find_exe(p + _toolstr(ui, tool, "regappend"))
33 if p:
33 if p:
34 return p
34 return p
35 return util.find_exe(_toolstr(ui, tool, "executable", tool))
35 return util.find_exe(_toolstr(ui, tool, "executable", tool))
36
36
37 def _picktool(repo, ui, path, binary, symlink):
37 def _picktool(repo, ui, path, binary, symlink):
38 def check(tool, pat, symlink, binary):
38 def check(tool, pat, symlink, binary):
39 tmsg = tool
39 tmsg = tool
40 if pat:
40 if pat:
41 tmsg += " specified for " + pat
41 tmsg += " specified for " + pat
42 if not _findtool(ui, tool):
42 if not _findtool(ui, tool):
43 if pat: # explicitly requested tool deserves a warning
43 if pat: # explicitly requested tool deserves a warning
44 ui.warn(_("couldn't find merge tool %s\n") % tmsg)
44 ui.warn(_("couldn't find merge tool %s\n") % tmsg)
45 else: # configured but non-existing tools are more silent
45 else: # configured but non-existing tools are more silent
46 ui.note(_("couldn't find merge tool %s\n") % tmsg)
46 ui.note(_("couldn't find merge tool %s\n") % tmsg)
47 elif symlink and not _toolbool(ui, tool, "symlink"):
47 elif symlink and not _toolbool(ui, tool, "symlink"):
48 ui.warn(_("tool %s can't handle symlinks\n") % tmsg)
48 ui.warn(_("tool %s can't handle symlinks\n") % tmsg)
49 elif binary and not _toolbool(ui, tool, "binary"):
49 elif binary and not _toolbool(ui, tool, "binary"):
50 ui.warn(_("tool %s can't handle binary\n") % tmsg)
50 ui.warn(_("tool %s can't handle binary\n") % tmsg)
51 elif not util.gui() and _toolbool(ui, tool, "gui"):
51 elif not util.gui() and _toolbool(ui, tool, "gui"):
52 ui.warn(_("tool %s requires a GUI\n") % tmsg)
52 ui.warn(_("tool %s requires a GUI\n") % tmsg)
53 else:
53 else:
54 return True
54 return True
55 return False
55 return False
56
56
57 # HGMERGE takes precedence
57 # HGMERGE takes precedence
58 hgmerge = os.environ.get("HGMERGE")
58 hgmerge = os.environ.get("HGMERGE")
59 if hgmerge:
59 if hgmerge:
60 return (hgmerge, hgmerge)
60 return (hgmerge, hgmerge)
61
61
62 # then patterns
62 # then patterns
63 for pat, tool in ui.configitems("merge-patterns"):
63 for pat, tool in ui.configitems("merge-patterns"):
64 mf = match.match(repo.root, '', [pat])
64 mf = match.match(repo.root, '', [pat])
65 if mf(path) and check(tool, pat, symlink, False):
65 if mf(path) and check(tool, pat, symlink, False):
66 toolpath = _findtool(ui, tool)
66 toolpath = _findtool(ui, tool)
67 return (tool, '"' + toolpath + '"')
67 return (tool, '"' + toolpath + '"')
68
68
69 # then merge tools
69 # then merge tools
70 tools = {}
70 tools = {}
71 for k, v in ui.configitems("merge-tools"):
71 for k, v in ui.configitems("merge-tools"):
72 t = k.split('.')[0]
72 t = k.split('.')[0]
73 if t not in tools:
73 if t not in tools:
74 tools[t] = int(_toolstr(ui, t, "priority", "0"))
74 tools[t] = int(_toolstr(ui, t, "priority", "0"))
75 names = tools.keys()
75 names = tools.keys()
76 tools = sorted([(-p, t) for t, p in tools.items()])
76 tools = sorted([(-p, t) for t, p in tools.items()])
77 uimerge = ui.config("ui", "merge")
77 uimerge = ui.config("ui", "merge")
78 if uimerge:
78 if uimerge:
79 if uimerge not in names:
79 if uimerge not in names:
80 return (uimerge, uimerge)
80 return (uimerge, uimerge)
81 tools.insert(0, (None, uimerge)) # highest priority
81 tools.insert(0, (None, uimerge)) # highest priority
82 tools.append((None, "hgmerge")) # the old default, if found
82 tools.append((None, "hgmerge")) # the old default, if found
83 for p, t in tools:
83 for p, t in tools:
84 if check(t, None, symlink, binary):
84 if check(t, None, symlink, binary):
85 toolpath = _findtool(ui, t)
85 toolpath = _findtool(ui, t)
86 return (t, '"' + toolpath + '"')
86 return (t, '"' + toolpath + '"')
87 # internal merge as last resort
87 # internal merge as last resort
88 return (not (symlink or binary) and "internal:merge" or None, None)
88 return (not (symlink or binary) and "internal:merge" or None, None)
89
89
90 def _eoltype(data):
90 def _eoltype(data):
91 "Guess the EOL type of a file"
91 "Guess the EOL type of a file"
92 if '\0' in data: # binary
92 if '\0' in data: # binary
93 return None
93 return None
94 if '\r\n' in data: # Windows
94 if '\r\n' in data: # Windows
95 return '\r\n'
95 return '\r\n'
96 if '\r' in data: # Old Mac
96 if '\r' in data: # Old Mac
97 return '\r'
97 return '\r'
98 if '\n' in data: # UNIX
98 if '\n' in data: # UNIX
99 return '\n'
99 return '\n'
100 return None # unknown
100 return None # unknown
101
101
102 def _matcheol(file, origfile):
102 def _matcheol(file, origfile):
103 "Convert EOL markers in a file to match origfile"
103 "Convert EOL markers in a file to match origfile"
104 tostyle = _eoltype(open(origfile, "rb").read())
104 tostyle = _eoltype(open(origfile, "rb").read())
105 if tostyle:
105 if tostyle:
106 data = open(file, "rb").read()
106 data = open(file, "rb").read()
107 style = _eoltype(data)
107 style = _eoltype(data)
108 if style:
108 if style:
109 newdata = data.replace(style, tostyle)
109 newdata = data.replace(style, tostyle)
110 if newdata != data:
110 if newdata != data:
111 open(file, "wb").write(newdata)
111 open(file, "wb").write(newdata)
112
112
113 def filemerge(repo, mynode, orig, fcd, fco, fca):
113 def filemerge(repo, mynode, orig, fcd, fco, fca):
114 """perform a 3-way merge in the working directory
114 """perform a 3-way merge in the working directory
115
115
116 mynode = parent node before merge
116 mynode = parent node before merge
117 orig = original local filename before merge
117 orig = original local filename before merge
118 fco = other file context
118 fco = other file context
119 fca = ancestor file context
119 fca = ancestor file context
120 fcd = local file context for current/destination file
120 fcd = local file context for current/destination file
121 """
121 """
122
122
123 def temp(prefix, ctx):
123 def temp(prefix, ctx):
124 pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
124 pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
125 (fd, name) = tempfile.mkstemp(prefix=pre)
125 (fd, name) = tempfile.mkstemp(prefix=pre)
126 data = repo.wwritedata(ctx.path(), ctx.data())
126 data = repo.wwritedata(ctx.path(), ctx.data())
127 f = os.fdopen(fd, "wb")
127 f = os.fdopen(fd, "wb")
128 f.write(data)
128 f.write(data)
129 f.close()
129 f.close()
130 return name
130 return name
131
131
132 def isbin(ctx):
132 def isbin(ctx):
133 try:
133 try:
134 return util.binary(ctx.data())
134 return util.binary(ctx.data())
135 except IOError:
135 except IOError:
136 return False
136 return False
137
137
138 if not fco.cmp(fcd.data()): # files identical?
138 if not fco.cmp(fcd): # files identical?
139 return None
139 return None
140
140
141 if fca == fco: # backwards, use working dir parent as ancestor
141 if fca == fco: # backwards, use working dir parent as ancestor
142 fca = fcd.parents()[0]
142 fca = fcd.parents()[0]
143
143
144 ui = repo.ui
144 ui = repo.ui
145 fd = fcd.path()
145 fd = fcd.path()
146 binary = isbin(fcd) or isbin(fco) or isbin(fca)
146 binary = isbin(fcd) or isbin(fco) or isbin(fca)
147 symlink = 'l' in fcd.flags() + fco.flags()
147 symlink = 'l' in fcd.flags() + fco.flags()
148 tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
148 tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
149 ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
149 ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
150 (tool, fd, binary, symlink))
150 (tool, fd, binary, symlink))
151
151
152 if not tool or tool == 'internal:prompt':
152 if not tool or tool == 'internal:prompt':
153 tool = "internal:local"
153 tool = "internal:local"
154 if ui.promptchoice(_(" no tool found to merge %s\n"
154 if ui.promptchoice(_(" no tool found to merge %s\n"
155 "keep (l)ocal or take (o)ther?") % fd,
155 "keep (l)ocal or take (o)ther?") % fd,
156 (_("&Local"), _("&Other")), 0):
156 (_("&Local"), _("&Other")), 0):
157 tool = "internal:other"
157 tool = "internal:other"
158 if tool == "internal:local":
158 if tool == "internal:local":
159 return 0
159 return 0
160 if tool == "internal:other":
160 if tool == "internal:other":
161 repo.wwrite(fd, fco.data(), fco.flags())
161 repo.wwrite(fd, fco.data(), fco.flags())
162 return 0
162 return 0
163 if tool == "internal:fail":
163 if tool == "internal:fail":
164 return 1
164 return 1
165
165
166 # do the actual merge
166 # do the actual merge
167 a = repo.wjoin(fd)
167 a = repo.wjoin(fd)
168 b = temp("base", fca)
168 b = temp("base", fca)
169 c = temp("other", fco)
169 c = temp("other", fco)
170 out = ""
170 out = ""
171 back = a + ".orig"
171 back = a + ".orig"
172 util.copyfile(a, back)
172 util.copyfile(a, back)
173
173
174 if orig != fco.path():
174 if orig != fco.path():
175 ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
175 ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
176 else:
176 else:
177 ui.status(_("merging %s\n") % fd)
177 ui.status(_("merging %s\n") % fd)
178
178
179 ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))
179 ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))
180
180
181 # do we attempt to simplemerge first?
181 # do we attempt to simplemerge first?
182 try:
182 try:
183 premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
183 premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
184 except error.ConfigError:
184 except error.ConfigError:
185 premerge = _toolstr(ui, tool, "premerge").lower()
185 premerge = _toolstr(ui, tool, "premerge").lower()
186 valid = 'keep'.split()
186 valid = 'keep'.split()
187 if premerge not in valid:
187 if premerge not in valid:
188 _valid = ', '.join(["'" + v + "'" for v in valid])
188 _valid = ', '.join(["'" + v + "'" for v in valid])
189 raise error.ConfigError(_("%s.premerge not valid "
189 raise error.ConfigError(_("%s.premerge not valid "
190 "('%s' is neither boolean nor %s)") %
190 "('%s' is neither boolean nor %s)") %
191 (tool, premerge, _valid))
191 (tool, premerge, _valid))
192
192
193 if premerge:
193 if premerge:
194 r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
194 r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
195 if not r:
195 if not r:
196 ui.debug(" premerge successful\n")
196 ui.debug(" premerge successful\n")
197 os.unlink(back)
197 os.unlink(back)
198 os.unlink(b)
198 os.unlink(b)
199 os.unlink(c)
199 os.unlink(c)
200 return 0
200 return 0
201 if premerge != 'keep':
201 if premerge != 'keep':
202 util.copyfile(back, a) # restore from backup and try again
202 util.copyfile(back, a) # restore from backup and try again
203
203
204 env = dict(HG_FILE=fd,
204 env = dict(HG_FILE=fd,
205 HG_MY_NODE=short(mynode),
205 HG_MY_NODE=short(mynode),
206 HG_OTHER_NODE=str(fco.changectx()),
206 HG_OTHER_NODE=str(fco.changectx()),
207 HG_BASE_NODE=str(fca.changectx()),
207 HG_BASE_NODE=str(fca.changectx()),
208 HG_MY_ISLINK='l' in fcd.flags(),
208 HG_MY_ISLINK='l' in fcd.flags(),
209 HG_OTHER_ISLINK='l' in fco.flags(),
209 HG_OTHER_ISLINK='l' in fco.flags(),
210 HG_BASE_ISLINK='l' in fca.flags())
210 HG_BASE_ISLINK='l' in fca.flags())
211
211
212 if tool == "internal:merge":
212 if tool == "internal:merge":
213 r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
213 r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
214 elif tool == 'internal:dump':
214 elif tool == 'internal:dump':
215 a = repo.wjoin(fd)
215 a = repo.wjoin(fd)
216 util.copyfile(a, a + ".local")
216 util.copyfile(a, a + ".local")
217 repo.wwrite(fd + ".other", fco.data(), fco.flags())
217 repo.wwrite(fd + ".other", fco.data(), fco.flags())
218 repo.wwrite(fd + ".base", fca.data(), fca.flags())
218 repo.wwrite(fd + ".base", fca.data(), fca.flags())
219 return 1 # unresolved
219 return 1 # unresolved
220 else:
220 else:
221 args = _toolstr(ui, tool, "args", '$local $base $other')
221 args = _toolstr(ui, tool, "args", '$local $base $other')
222 if "$output" in args:
222 if "$output" in args:
223 out, a = a, back # read input from backup, write to original
223 out, a = a, back # read input from backup, write to original
224 replace = dict(local=a, base=b, other=c, output=out)
224 replace = dict(local=a, base=b, other=c, output=out)
225 args = re.sub("\$(local|base|other|output)",
225 args = re.sub("\$(local|base|other|output)",
226 lambda x: '"%s"' % util.localpath(replace[x.group()[1:]]), args)
226 lambda x: '"%s"' % util.localpath(replace[x.group()[1:]]), args)
227 r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env)
227 r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env)
228
228
229 if not r and (_toolbool(ui, tool, "checkconflicts") or
229 if not r and (_toolbool(ui, tool, "checkconflicts") or
230 'conflicts' in _toollist(ui, tool, "check")):
230 'conflicts' in _toollist(ui, tool, "check")):
231 if re.match("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data()):
231 if re.match("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data()):
232 r = 1
232 r = 1
233
233
234 checked = False
234 checked = False
235 if 'prompt' in _toollist(ui, tool, "check"):
235 if 'prompt' in _toollist(ui, tool, "check"):
236 checked = True
236 checked = True
237 if ui.promptchoice(_("was merge of '%s' successful (yn)?") % fd,
237 if ui.promptchoice(_("was merge of '%s' successful (yn)?") % fd,
238 (_("&Yes"), _("&No")), 1):
238 (_("&Yes"), _("&No")), 1):
239 r = 1
239 r = 1
240
240
241 if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
241 if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
242 'changed' in _toollist(ui, tool, "check")):
242 'changed' in _toollist(ui, tool, "check")):
243 if filecmp.cmp(repo.wjoin(fd), back):
243 if filecmp.cmp(repo.wjoin(fd), back):
244 if ui.promptchoice(_(" output file %s appears unchanged\n"
244 if ui.promptchoice(_(" output file %s appears unchanged\n"
245 "was merge successful (yn)?") % fd,
245 "was merge successful (yn)?") % fd,
246 (_("&Yes"), _("&No")), 1):
246 (_("&Yes"), _("&No")), 1):
247 r = 1
247 r = 1
248
248
249 if _toolbool(ui, tool, "fixeol"):
249 if _toolbool(ui, tool, "fixeol"):
250 _matcheol(repo.wjoin(fd), back)
250 _matcheol(repo.wjoin(fd), back)
251
251
252 if r:
252 if r:
253 ui.warn(_("merging %s failed!\n") % fd)
253 ui.warn(_("merging %s failed!\n") % fd)
254 else:
254 else:
255 os.unlink(back)
255 os.unlink(back)
256
256
257 os.unlink(b)
257 os.unlink(b)
258 os.unlink(c)
258 os.unlink(c)
259 return r
259 return r
@@ -1,1802 +1,1802 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
11 import changelog, dirstate, filelog, manifest, context
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import util, extensions, hook, error
13 import 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 import url as urlmod
17 import url as urlmod
18 from lock import release
18 from lock import release
19 import weakref, errno, os, time, inspect
19 import weakref, errno, os, time, inspect
20 propertycache = util.propertycache
20 propertycache = util.propertycache
21
21
22 class localrepository(repo.repository):
22 class localrepository(repo.repository):
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey'))
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey'))
24 supported = set('revlogv1 store fncache shared'.split())
24 supported = set('revlogv1 store fncache shared'.split())
25
25
26 def __init__(self, baseui, path=None, create=0):
26 def __init__(self, baseui, path=None, create=0):
27 repo.repository.__init__(self)
27 repo.repository.__init__(self)
28 self.root = os.path.realpath(util.expandpath(path))
28 self.root = os.path.realpath(util.expandpath(path))
29 self.path = os.path.join(self.root, ".hg")
29 self.path = os.path.join(self.root, ".hg")
30 self.origroot = path
30 self.origroot = path
31 self.opener = util.opener(self.path)
31 self.opener = util.opener(self.path)
32 self.wopener = util.opener(self.root)
32 self.wopener = util.opener(self.root)
33 self.baseui = baseui
33 self.baseui = baseui
34 self.ui = baseui.copy()
34 self.ui = baseui.copy()
35
35
36 try:
36 try:
37 self.ui.readconfig(self.join("hgrc"), self.root)
37 self.ui.readconfig(self.join("hgrc"), self.root)
38 extensions.loadall(self.ui)
38 extensions.loadall(self.ui)
39 except IOError:
39 except IOError:
40 pass
40 pass
41
41
42 if not os.path.isdir(self.path):
42 if not os.path.isdir(self.path):
43 if create:
43 if create:
44 if not os.path.exists(path):
44 if not os.path.exists(path):
45 util.makedirs(path)
45 util.makedirs(path)
46 os.mkdir(self.path)
46 os.mkdir(self.path)
47 requirements = ["revlogv1"]
47 requirements = ["revlogv1"]
48 if self.ui.configbool('format', 'usestore', True):
48 if self.ui.configbool('format', 'usestore', True):
49 os.mkdir(os.path.join(self.path, "store"))
49 os.mkdir(os.path.join(self.path, "store"))
50 requirements.append("store")
50 requirements.append("store")
51 if self.ui.configbool('format', 'usefncache', True):
51 if self.ui.configbool('format', 'usefncache', True):
52 requirements.append("fncache")
52 requirements.append("fncache")
53 # create an invalid changelog
53 # create an invalid changelog
54 self.opener("00changelog.i", "a").write(
54 self.opener("00changelog.i", "a").write(
55 '\0\0\0\2' # represents revlogv2
55 '\0\0\0\2' # represents revlogv2
56 ' dummy changelog to prevent using the old repo layout'
56 ' dummy changelog to prevent using the old repo layout'
57 )
57 )
58 reqfile = self.opener("requires", "w")
58 reqfile = self.opener("requires", "w")
59 for r in requirements:
59 for r in requirements:
60 reqfile.write("%s\n" % r)
60 reqfile.write("%s\n" % r)
61 reqfile.close()
61 reqfile.close()
62 else:
62 else:
63 raise error.RepoError(_("repository %s not found") % path)
63 raise error.RepoError(_("repository %s not found") % path)
64 elif create:
64 elif create:
65 raise error.RepoError(_("repository %s already exists") % path)
65 raise error.RepoError(_("repository %s already exists") % path)
66 else:
66 else:
67 # find requirements
67 # find requirements
68 requirements = set()
68 requirements = set()
69 try:
69 try:
70 requirements = set(self.opener("requires").read().splitlines())
70 requirements = set(self.opener("requires").read().splitlines())
71 except IOError, inst:
71 except IOError, inst:
72 if inst.errno != errno.ENOENT:
72 if inst.errno != errno.ENOENT:
73 raise
73 raise
74 for r in requirements - self.supported:
74 for r in requirements - self.supported:
75 raise error.RepoError(_("requirement '%s' not supported") % r)
75 raise error.RepoError(_("requirement '%s' not supported") % r)
76
76
77 self.sharedpath = self.path
77 self.sharedpath = self.path
78 try:
78 try:
79 s = os.path.realpath(self.opener("sharedpath").read())
79 s = os.path.realpath(self.opener("sharedpath").read())
80 if not os.path.exists(s):
80 if not os.path.exists(s):
81 raise error.RepoError(
81 raise error.RepoError(
82 _('.hg/sharedpath points to nonexistent directory %s') % s)
82 _('.hg/sharedpath points to nonexistent directory %s') % s)
83 self.sharedpath = s
83 self.sharedpath = s
84 except IOError, inst:
84 except IOError, inst:
85 if inst.errno != errno.ENOENT:
85 if inst.errno != errno.ENOENT:
86 raise
86 raise
87
87
88 self.store = store.store(requirements, self.sharedpath, util.opener)
88 self.store = store.store(requirements, self.sharedpath, util.opener)
89 self.spath = self.store.path
89 self.spath = self.store.path
90 self.sopener = self.store.opener
90 self.sopener = self.store.opener
91 self.sjoin = self.store.join
91 self.sjoin = self.store.join
92 self.opener.createmode = self.store.createmode
92 self.opener.createmode = self.store.createmode
93 self.sopener.options = {}
93 self.sopener.options = {}
94
94
95 # These two define the set of tags for this repository. _tags
95 # These two define the set of tags for this repository. _tags
96 # maps tag name to node; _tagtypes maps tag name to 'global' or
96 # maps tag name to node; _tagtypes maps tag name to 'global' or
97 # 'local'. (Global tags are defined by .hgtags across all
97 # 'local'. (Global tags are defined by .hgtags across all
98 # heads, and local tags are defined in .hg/localtags.) They
98 # heads, and local tags are defined in .hg/localtags.) They
99 # constitute the in-memory cache of tags.
99 # constitute the in-memory cache of tags.
100 self._tags = None
100 self._tags = None
101 self._tagtypes = None
101 self._tagtypes = None
102
102
103 self._branchcache = None # in UTF-8
103 self._branchcache = None # in UTF-8
104 self._branchcachetip = None
104 self._branchcachetip = None
105 self.nodetagscache = None
105 self.nodetagscache = None
106 self.filterpats = {}
106 self.filterpats = {}
107 self._datafilters = {}
107 self._datafilters = {}
108 self._transref = self._lockref = self._wlockref = None
108 self._transref = self._lockref = self._wlockref = None
109
109
110 @propertycache
110 @propertycache
111 def changelog(self):
111 def changelog(self):
112 c = changelog.changelog(self.sopener)
112 c = changelog.changelog(self.sopener)
113 if 'HG_PENDING' in os.environ:
113 if 'HG_PENDING' in os.environ:
114 p = os.environ['HG_PENDING']
114 p = os.environ['HG_PENDING']
115 if p.startswith(self.root):
115 if p.startswith(self.root):
116 c.readpending('00changelog.i.a')
116 c.readpending('00changelog.i.a')
117 self.sopener.options['defversion'] = c.version
117 self.sopener.options['defversion'] = c.version
118 return c
118 return c
119
119
120 @propertycache
120 @propertycache
121 def manifest(self):
121 def manifest(self):
122 return manifest.manifest(self.sopener)
122 return manifest.manifest(self.sopener)
123
123
124 @propertycache
124 @propertycache
125 def dirstate(self):
125 def dirstate(self):
126 return dirstate.dirstate(self.opener, self.ui, self.root)
126 return dirstate.dirstate(self.opener, self.ui, self.root)
127
127
128 def __getitem__(self, changeid):
128 def __getitem__(self, changeid):
129 if changeid is None:
129 if changeid is None:
130 return context.workingctx(self)
130 return context.workingctx(self)
131 return context.changectx(self, changeid)
131 return context.changectx(self, changeid)
132
132
133 def __contains__(self, changeid):
133 def __contains__(self, changeid):
134 try:
134 try:
135 return bool(self.lookup(changeid))
135 return bool(self.lookup(changeid))
136 except error.RepoLookupError:
136 except error.RepoLookupError:
137 return False
137 return False
138
138
139 def __nonzero__(self):
139 def __nonzero__(self):
140 return True
140 return True
141
141
142 def __len__(self):
142 def __len__(self):
143 return len(self.changelog)
143 return len(self.changelog)
144
144
145 def __iter__(self):
145 def __iter__(self):
146 for i in xrange(len(self)):
146 for i in xrange(len(self)):
147 yield i
147 yield i
148
148
149 def url(self):
149 def url(self):
150 return 'file:' + self.root
150 return 'file:' + self.root
151
151
152 def hook(self, name, throw=False, **args):
152 def hook(self, name, throw=False, **args):
153 return hook.hook(self.ui, self, name, throw, **args)
153 return hook.hook(self.ui, self, name, throw, **args)
154
154
155 tag_disallowed = ':\r\n'
155 tag_disallowed = ':\r\n'
156
156
157 def _tag(self, names, node, message, local, user, date, extra={}):
157 def _tag(self, names, node, message, local, user, date, extra={}):
158 if isinstance(names, str):
158 if isinstance(names, str):
159 allchars = names
159 allchars = names
160 names = (names,)
160 names = (names,)
161 else:
161 else:
162 allchars = ''.join(names)
162 allchars = ''.join(names)
163 for c in self.tag_disallowed:
163 for c in self.tag_disallowed:
164 if c in allchars:
164 if c in allchars:
165 raise util.Abort(_('%r cannot be used in a tag name') % c)
165 raise util.Abort(_('%r cannot be used in a tag name') % c)
166
166
167 branches = self.branchmap()
167 branches = self.branchmap()
168 for name in names:
168 for name in names:
169 self.hook('pretag', throw=True, node=hex(node), tag=name,
169 self.hook('pretag', throw=True, node=hex(node), tag=name,
170 local=local)
170 local=local)
171 if name in branches:
171 if name in branches:
172 self.ui.warn(_("warning: tag %s conflicts with existing"
172 self.ui.warn(_("warning: tag %s conflicts with existing"
173 " branch name\n") % name)
173 " branch name\n") % name)
174
174
175 def writetags(fp, names, munge, prevtags):
175 def writetags(fp, names, munge, prevtags):
176 fp.seek(0, 2)
176 fp.seek(0, 2)
177 if prevtags and prevtags[-1] != '\n':
177 if prevtags and prevtags[-1] != '\n':
178 fp.write('\n')
178 fp.write('\n')
179 for name in names:
179 for name in names:
180 m = munge and munge(name) or name
180 m = munge and munge(name) or name
181 if self._tagtypes and name in self._tagtypes:
181 if self._tagtypes and name in self._tagtypes:
182 old = self._tags.get(name, nullid)
182 old = self._tags.get(name, nullid)
183 fp.write('%s %s\n' % (hex(old), m))
183 fp.write('%s %s\n' % (hex(old), m))
184 fp.write('%s %s\n' % (hex(node), m))
184 fp.write('%s %s\n' % (hex(node), m))
185 fp.close()
185 fp.close()
186
186
187 prevtags = ''
187 prevtags = ''
188 if local:
188 if local:
189 try:
189 try:
190 fp = self.opener('localtags', 'r+')
190 fp = self.opener('localtags', 'r+')
191 except IOError:
191 except IOError:
192 fp = self.opener('localtags', 'a')
192 fp = self.opener('localtags', 'a')
193 else:
193 else:
194 prevtags = fp.read()
194 prevtags = fp.read()
195
195
196 # local tags are stored in the current charset
196 # local tags are stored in the current charset
197 writetags(fp, names, None, prevtags)
197 writetags(fp, names, None, prevtags)
198 for name in names:
198 for name in names:
199 self.hook('tag', node=hex(node), tag=name, local=local)
199 self.hook('tag', node=hex(node), tag=name, local=local)
200 return
200 return
201
201
202 try:
202 try:
203 fp = self.wfile('.hgtags', 'rb+')
203 fp = self.wfile('.hgtags', 'rb+')
204 except IOError:
204 except IOError:
205 fp = self.wfile('.hgtags', 'ab')
205 fp = self.wfile('.hgtags', 'ab')
206 else:
206 else:
207 prevtags = fp.read()
207 prevtags = fp.read()
208
208
209 # committed tags are stored in UTF-8
209 # committed tags are stored in UTF-8
210 writetags(fp, names, encoding.fromlocal, prevtags)
210 writetags(fp, names, encoding.fromlocal, prevtags)
211
211
212 if '.hgtags' not in self.dirstate:
212 if '.hgtags' not in self.dirstate:
213 self[None].add(['.hgtags'])
213 self[None].add(['.hgtags'])
214
214
215 m = matchmod.exact(self.root, '', ['.hgtags'])
215 m = matchmod.exact(self.root, '', ['.hgtags'])
216 tagnode = self.commit(message, user, date, extra=extra, match=m)
216 tagnode = self.commit(message, user, date, extra=extra, match=m)
217
217
218 for name in names:
218 for name in names:
219 self.hook('tag', node=hex(node), tag=name, local=local)
219 self.hook('tag', node=hex(node), tag=name, local=local)
220
220
221 return tagnode
221 return tagnode
222
222
223 def tag(self, names, node, message, local, user, date):
223 def tag(self, names, node, message, local, user, date):
224 '''tag a revision with one or more symbolic names.
224 '''tag a revision with one or more symbolic names.
225
225
226 names is a list of strings or, when adding a single tag, names may be a
226 names is a list of strings or, when adding a single tag, names may be a
227 string.
227 string.
228
228
229 if local is True, the tags are stored in a per-repository file.
229 if local is True, the tags are stored in a per-repository file.
230 otherwise, they are stored in the .hgtags file, and a new
230 otherwise, they are stored in the .hgtags file, and a new
231 changeset is committed with the change.
231 changeset is committed with the change.
232
232
233 keyword arguments:
233 keyword arguments:
234
234
235 local: whether to store tags in non-version-controlled file
235 local: whether to store tags in non-version-controlled file
236 (default False)
236 (default False)
237
237
238 message: commit message to use if committing
238 message: commit message to use if committing
239
239
240 user: name of user to use if committing
240 user: name of user to use if committing
241
241
242 date: date tuple to use if committing'''
242 date: date tuple to use if committing'''
243
243
244 for x in self.status()[:5]:
244 for x in self.status()[:5]:
245 if '.hgtags' in x:
245 if '.hgtags' in x:
246 raise util.Abort(_('working copy of .hgtags is changed '
246 raise util.Abort(_('working copy of .hgtags is changed '
247 '(please commit .hgtags manually)'))
247 '(please commit .hgtags manually)'))
248
248
249 self.tags() # instantiate the cache
249 self.tags() # instantiate the cache
250 self._tag(names, node, message, local, user, date)
250 self._tag(names, node, message, local, user, date)
251
251
252 def tags(self):
252 def tags(self):
253 '''return a mapping of tag to node'''
253 '''return a mapping of tag to node'''
254 if self._tags is None:
254 if self._tags is None:
255 (self._tags, self._tagtypes) = self._findtags()
255 (self._tags, self._tagtypes) = self._findtags()
256
256
257 return self._tags
257 return self._tags
258
258
259 def _findtags(self):
259 def _findtags(self):
260 '''Do the hard work of finding tags. Return a pair of dicts
260 '''Do the hard work of finding tags. Return a pair of dicts
261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
262 maps tag name to a string like \'global\' or \'local\'.
262 maps tag name to a string like \'global\' or \'local\'.
263 Subclasses or extensions are free to add their own tags, but
263 Subclasses or extensions are free to add their own tags, but
264 should be aware that the returned dicts will be retained for the
264 should be aware that the returned dicts will be retained for the
265 duration of the localrepo object.'''
265 duration of the localrepo object.'''
266
266
267 # XXX what tagtype should subclasses/extensions use? Currently
267 # XXX what tagtype should subclasses/extensions use? Currently
268 # mq and bookmarks add tags, but do not set the tagtype at all.
268 # mq and bookmarks add tags, but do not set the tagtype at all.
269 # Should each extension invent its own tag type? Should there
269 # Should each extension invent its own tag type? Should there
270 # be one tagtype for all such "virtual" tags? Or is the status
270 # be one tagtype for all such "virtual" tags? Or is the status
271 # quo fine?
271 # quo fine?
272
272
273 alltags = {} # map tag name to (node, hist)
273 alltags = {} # map tag name to (node, hist)
274 tagtypes = {}
274 tagtypes = {}
275
275
276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
278
278
279 # Build the return dicts. Have to re-encode tag names because
279 # Build the return dicts. Have to re-encode tag names because
280 # the tags module always uses UTF-8 (in order not to lose info
280 # the tags module always uses UTF-8 (in order not to lose info
281 # writing to the cache), but the rest of Mercurial wants them in
281 # writing to the cache), but the rest of Mercurial wants them in
282 # local encoding.
282 # local encoding.
283 tags = {}
283 tags = {}
284 for (name, (node, hist)) in alltags.iteritems():
284 for (name, (node, hist)) in alltags.iteritems():
285 if node != nullid:
285 if node != nullid:
286 tags[encoding.tolocal(name)] = node
286 tags[encoding.tolocal(name)] = node
287 tags['tip'] = self.changelog.tip()
287 tags['tip'] = self.changelog.tip()
288 tagtypes = dict([(encoding.tolocal(name), value)
288 tagtypes = dict([(encoding.tolocal(name), value)
289 for (name, value) in tagtypes.iteritems()])
289 for (name, value) in tagtypes.iteritems()])
290 return (tags, tagtypes)
290 return (tags, tagtypes)
291
291
292 def tagtype(self, tagname):
292 def tagtype(self, tagname):
293 '''
293 '''
294 return the type of the given tag. result can be:
294 return the type of the given tag. result can be:
295
295
296 'local' : a local tag
296 'local' : a local tag
297 'global' : a global tag
297 'global' : a global tag
298 None : tag does not exist
298 None : tag does not exist
299 '''
299 '''
300
300
301 self.tags()
301 self.tags()
302
302
303 return self._tagtypes.get(tagname)
303 return self._tagtypes.get(tagname)
304
304
305 def tagslist(self):
305 def tagslist(self):
306 '''return a list of tags ordered by revision'''
306 '''return a list of tags ordered by revision'''
307 l = []
307 l = []
308 for t, n in self.tags().iteritems():
308 for t, n in self.tags().iteritems():
309 try:
309 try:
310 r = self.changelog.rev(n)
310 r = self.changelog.rev(n)
311 except:
311 except:
312 r = -2 # sort to the beginning of the list if unknown
312 r = -2 # sort to the beginning of the list if unknown
313 l.append((r, t, n))
313 l.append((r, t, n))
314 return [(t, n) for r, t, n in sorted(l)]
314 return [(t, n) for r, t, n in sorted(l)]
315
315
316 def nodetags(self, node):
316 def nodetags(self, node):
317 '''return the tags associated with a node'''
317 '''return the tags associated with a node'''
318 if not self.nodetagscache:
318 if not self.nodetagscache:
319 self.nodetagscache = {}
319 self.nodetagscache = {}
320 for t, n in self.tags().iteritems():
320 for t, n in self.tags().iteritems():
321 self.nodetagscache.setdefault(n, []).append(t)
321 self.nodetagscache.setdefault(n, []).append(t)
322 for tags in self.nodetagscache.itervalues():
322 for tags in self.nodetagscache.itervalues():
323 tags.sort()
323 tags.sort()
324 return self.nodetagscache.get(node, [])
324 return self.nodetagscache.get(node, [])
325
325
326 def _branchtags(self, partial, lrev):
326 def _branchtags(self, partial, lrev):
327 # TODO: rename this function?
327 # TODO: rename this function?
328 tiprev = len(self) - 1
328 tiprev = len(self) - 1
329 if lrev != tiprev:
329 if lrev != tiprev:
330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
331 self._updatebranchcache(partial, ctxgen)
331 self._updatebranchcache(partial, ctxgen)
332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
333
333
334 return partial
334 return partial
335
335
336 def branchmap(self):
336 def branchmap(self):
337 '''returns a dictionary {branch: [branchheads]}'''
337 '''returns a dictionary {branch: [branchheads]}'''
338 tip = self.changelog.tip()
338 tip = self.changelog.tip()
339 if self._branchcache is not None and self._branchcachetip == tip:
339 if self._branchcache is not None and self._branchcachetip == tip:
340 return self._branchcache
340 return self._branchcache
341
341
342 oldtip = self._branchcachetip
342 oldtip = self._branchcachetip
343 self._branchcachetip = tip
343 self._branchcachetip = tip
344 if oldtip is None or oldtip not in self.changelog.nodemap:
344 if oldtip is None or oldtip not in self.changelog.nodemap:
345 partial, last, lrev = self._readbranchcache()
345 partial, last, lrev = self._readbranchcache()
346 else:
346 else:
347 lrev = self.changelog.rev(oldtip)
347 lrev = self.changelog.rev(oldtip)
348 partial = self._branchcache
348 partial = self._branchcache
349
349
350 self._branchtags(partial, lrev)
350 self._branchtags(partial, lrev)
351 # this private cache holds all heads (not just tips)
351 # this private cache holds all heads (not just tips)
352 self._branchcache = partial
352 self._branchcache = partial
353
353
354 return self._branchcache
354 return self._branchcache
355
355
356 def branchtags(self):
356 def branchtags(self):
357 '''return a dict where branch names map to the tipmost head of
357 '''return a dict where branch names map to the tipmost head of
358 the branch, open heads come before closed'''
358 the branch, open heads come before closed'''
359 bt = {}
359 bt = {}
360 for bn, heads in self.branchmap().iteritems():
360 for bn, heads in self.branchmap().iteritems():
361 tip = heads[-1]
361 tip = heads[-1]
362 for h in reversed(heads):
362 for h in reversed(heads):
363 if 'close' not in self.changelog.read(h)[5]:
363 if 'close' not in self.changelog.read(h)[5]:
364 tip = h
364 tip = h
365 break
365 break
366 bt[bn] = tip
366 bt[bn] = tip
367 return bt
367 return bt
368
368
369
369
370 def _readbranchcache(self):
370 def _readbranchcache(self):
371 partial = {}
371 partial = {}
372 try:
372 try:
373 f = self.opener("branchheads.cache")
373 f = self.opener("branchheads.cache")
374 lines = f.read().split('\n')
374 lines = f.read().split('\n')
375 f.close()
375 f.close()
376 except (IOError, OSError):
376 except (IOError, OSError):
377 return {}, nullid, nullrev
377 return {}, nullid, nullrev
378
378
379 try:
379 try:
380 last, lrev = lines.pop(0).split(" ", 1)
380 last, lrev = lines.pop(0).split(" ", 1)
381 last, lrev = bin(last), int(lrev)
381 last, lrev = bin(last), int(lrev)
382 if lrev >= len(self) or self[lrev].node() != last:
382 if lrev >= len(self) or self[lrev].node() != last:
383 # invalidate the cache
383 # invalidate the cache
384 raise ValueError('invalidating branch cache (tip differs)')
384 raise ValueError('invalidating branch cache (tip differs)')
385 for l in lines:
385 for l in lines:
386 if not l:
386 if not l:
387 continue
387 continue
388 node, label = l.split(" ", 1)
388 node, label = l.split(" ", 1)
389 partial.setdefault(label.strip(), []).append(bin(node))
389 partial.setdefault(label.strip(), []).append(bin(node))
390 except KeyboardInterrupt:
390 except KeyboardInterrupt:
391 raise
391 raise
392 except Exception, inst:
392 except Exception, inst:
393 if self.ui.debugflag:
393 if self.ui.debugflag:
394 self.ui.warn(str(inst), '\n')
394 self.ui.warn(str(inst), '\n')
395 partial, last, lrev = {}, nullid, nullrev
395 partial, last, lrev = {}, nullid, nullrev
396 return partial, last, lrev
396 return partial, last, lrev
397
397
398 def _writebranchcache(self, branches, tip, tiprev):
398 def _writebranchcache(self, branches, tip, tiprev):
399 try:
399 try:
400 f = self.opener("branchheads.cache", "w", atomictemp=True)
400 f = self.opener("branchheads.cache", "w", atomictemp=True)
401 f.write("%s %s\n" % (hex(tip), tiprev))
401 f.write("%s %s\n" % (hex(tip), tiprev))
402 for label, nodes in branches.iteritems():
402 for label, nodes in branches.iteritems():
403 for node in nodes:
403 for node in nodes:
404 f.write("%s %s\n" % (hex(node), label))
404 f.write("%s %s\n" % (hex(node), label))
405 f.rename()
405 f.rename()
406 except (IOError, OSError):
406 except (IOError, OSError):
407 pass
407 pass
408
408
409 def _updatebranchcache(self, partial, ctxgen):
409 def _updatebranchcache(self, partial, ctxgen):
410 # collect new branch entries
410 # collect new branch entries
411 newbranches = {}
411 newbranches = {}
412 for c in ctxgen:
412 for c in ctxgen:
413 newbranches.setdefault(c.branch(), []).append(c.node())
413 newbranches.setdefault(c.branch(), []).append(c.node())
414 # if older branchheads are reachable from new ones, they aren't
414 # if older branchheads are reachable from new ones, they aren't
415 # really branchheads. Note checking parents is insufficient:
415 # really branchheads. Note checking parents is insufficient:
416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
417 for branch, newnodes in newbranches.iteritems():
417 for branch, newnodes in newbranches.iteritems():
418 bheads = partial.setdefault(branch, [])
418 bheads = partial.setdefault(branch, [])
419 bheads.extend(newnodes)
419 bheads.extend(newnodes)
420 if len(bheads) <= 1:
420 if len(bheads) <= 1:
421 continue
421 continue
422 # starting from tip means fewer passes over reachable
422 # starting from tip means fewer passes over reachable
423 while newnodes:
423 while newnodes:
424 latest = newnodes.pop()
424 latest = newnodes.pop()
425 if latest not in bheads:
425 if latest not in bheads:
426 continue
426 continue
427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
428 reachable = self.changelog.reachable(latest, minbhrev)
428 reachable = self.changelog.reachable(latest, minbhrev)
429 reachable.remove(latest)
429 reachable.remove(latest)
430 bheads = [b for b in bheads if b not in reachable]
430 bheads = [b for b in bheads if b not in reachable]
431 partial[branch] = bheads
431 partial[branch] = bheads
432
432
433 def lookup(self, key):
433 def lookup(self, key):
434 if isinstance(key, int):
434 if isinstance(key, int):
435 return self.changelog.node(key)
435 return self.changelog.node(key)
436 elif key == '.':
436 elif key == '.':
437 return self.dirstate.parents()[0]
437 return self.dirstate.parents()[0]
438 elif key == 'null':
438 elif key == 'null':
439 return nullid
439 return nullid
440 elif key == 'tip':
440 elif key == 'tip':
441 return self.changelog.tip()
441 return self.changelog.tip()
442 n = self.changelog._match(key)
442 n = self.changelog._match(key)
443 if n:
443 if n:
444 return n
444 return n
445 if key in self.tags():
445 if key in self.tags():
446 return self.tags()[key]
446 return self.tags()[key]
447 if key in self.branchtags():
447 if key in self.branchtags():
448 return self.branchtags()[key]
448 return self.branchtags()[key]
449 n = self.changelog._partialmatch(key)
449 n = self.changelog._partialmatch(key)
450 if n:
450 if n:
451 return n
451 return n
452
452
453 # can't find key, check if it might have come from damaged dirstate
453 # can't find key, check if it might have come from damaged dirstate
454 if key in self.dirstate.parents():
454 if key in self.dirstate.parents():
455 raise error.Abort(_("working directory has unknown parent '%s'!")
455 raise error.Abort(_("working directory has unknown parent '%s'!")
456 % short(key))
456 % short(key))
457 try:
457 try:
458 if len(key) == 20:
458 if len(key) == 20:
459 key = hex(key)
459 key = hex(key)
460 except:
460 except:
461 pass
461 pass
462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
463
463
464 def lookupbranch(self, key, remote=None):
464 def lookupbranch(self, key, remote=None):
465 repo = remote or self
465 repo = remote or self
466 if key in repo.branchmap():
466 if key in repo.branchmap():
467 return key
467 return key
468
468
469 repo = (remote and remote.local()) and remote or self
469 repo = (remote and remote.local()) and remote or self
470 return repo[key].branch()
470 return repo[key].branch()
471
471
472 def local(self):
472 def local(self):
473 return True
473 return True
474
474
475 def join(self, f):
475 def join(self, f):
476 return os.path.join(self.path, f)
476 return os.path.join(self.path, f)
477
477
478 def wjoin(self, f):
478 def wjoin(self, f):
479 return os.path.join(self.root, f)
479 return os.path.join(self.root, f)
480
480
481 def rjoin(self, f):
481 def rjoin(self, f):
482 return os.path.join(self.root, util.pconvert(f))
482 return os.path.join(self.root, util.pconvert(f))
483
483
484 def file(self, f):
484 def file(self, f):
485 if f[0] == '/':
485 if f[0] == '/':
486 f = f[1:]
486 f = f[1:]
487 return filelog.filelog(self.sopener, f)
487 return filelog.filelog(self.sopener, f)
488
488
489 def changectx(self, changeid):
489 def changectx(self, changeid):
490 return self[changeid]
490 return self[changeid]
491
491
492 def parents(self, changeid=None):
492 def parents(self, changeid=None):
493 '''get list of changectxs for parents of changeid'''
493 '''get list of changectxs for parents of changeid'''
494 return self[changeid].parents()
494 return self[changeid].parents()
495
495
496 def filectx(self, path, changeid=None, fileid=None):
496 def filectx(self, path, changeid=None, fileid=None):
497 """changeid can be a changeset revision, node, or tag.
497 """changeid can be a changeset revision, node, or tag.
498 fileid can be a file revision or node."""
498 fileid can be a file revision or node."""
499 return context.filectx(self, path, changeid, fileid)
499 return context.filectx(self, path, changeid, fileid)
500
500
501 def getcwd(self):
501 def getcwd(self):
502 return self.dirstate.getcwd()
502 return self.dirstate.getcwd()
503
503
504 def pathto(self, f, cwd=None):
504 def pathto(self, f, cwd=None):
505 return self.dirstate.pathto(f, cwd)
505 return self.dirstate.pathto(f, cwd)
506
506
507 def wfile(self, f, mode='r'):
507 def wfile(self, f, mode='r'):
508 return self.wopener(f, mode)
508 return self.wopener(f, mode)
509
509
510 def _link(self, f):
510 def _link(self, f):
511 return os.path.islink(self.wjoin(f))
511 return os.path.islink(self.wjoin(f))
512
512
513 def _loadfilter(self, filter):
513 def _loadfilter(self, filter):
514 if filter not in self.filterpats:
514 if filter not in self.filterpats:
515 l = []
515 l = []
516 for pat, cmd in self.ui.configitems(filter):
516 for pat, cmd in self.ui.configitems(filter):
517 if cmd == '!':
517 if cmd == '!':
518 continue
518 continue
519 mf = matchmod.match(self.root, '', [pat])
519 mf = matchmod.match(self.root, '', [pat])
520 fn = None
520 fn = None
521 params = cmd
521 params = cmd
522 for name, filterfn in self._datafilters.iteritems():
522 for name, filterfn in self._datafilters.iteritems():
523 if cmd.startswith(name):
523 if cmd.startswith(name):
524 fn = filterfn
524 fn = filterfn
525 params = cmd[len(name):].lstrip()
525 params = cmd[len(name):].lstrip()
526 break
526 break
527 if not fn:
527 if not fn:
528 fn = lambda s, c, **kwargs: util.filter(s, c)
528 fn = lambda s, c, **kwargs: util.filter(s, c)
529 # Wrap old filters not supporting keyword arguments
529 # Wrap old filters not supporting keyword arguments
530 if not inspect.getargspec(fn)[2]:
530 if not inspect.getargspec(fn)[2]:
531 oldfn = fn
531 oldfn = fn
532 fn = lambda s, c, **kwargs: oldfn(s, c)
532 fn = lambda s, c, **kwargs: oldfn(s, c)
533 l.append((mf, fn, params))
533 l.append((mf, fn, params))
534 self.filterpats[filter] = l
534 self.filterpats[filter] = l
535
535
536 def _filter(self, filter, filename, data):
536 def _filter(self, filter, filename, data):
537 self._loadfilter(filter)
537 self._loadfilter(filter)
538
538
539 for mf, fn, cmd in self.filterpats[filter]:
539 for mf, fn, cmd in self.filterpats[filter]:
540 if mf(filename):
540 if mf(filename):
541 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
541 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
542 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
542 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
543 break
543 break
544
544
545 return data
545 return data
546
546
547 def adddatafilter(self, name, filter):
547 def adddatafilter(self, name, filter):
548 self._datafilters[name] = filter
548 self._datafilters[name] = filter
549
549
550 def wread(self, filename):
550 def wread(self, filename):
551 if self._link(filename):
551 if self._link(filename):
552 data = os.readlink(self.wjoin(filename))
552 data = os.readlink(self.wjoin(filename))
553 else:
553 else:
554 data = self.wopener(filename, 'r').read()
554 data = self.wopener(filename, 'r').read()
555 return self._filter("encode", filename, data)
555 return self._filter("encode", filename, data)
556
556
557 def wwrite(self, filename, data, flags):
557 def wwrite(self, filename, data, flags):
558 data = self._filter("decode", filename, data)
558 data = self._filter("decode", filename, data)
559 try:
559 try:
560 os.unlink(self.wjoin(filename))
560 os.unlink(self.wjoin(filename))
561 except OSError:
561 except OSError:
562 pass
562 pass
563 if 'l' in flags:
563 if 'l' in flags:
564 self.wopener.symlink(data, filename)
564 self.wopener.symlink(data, filename)
565 else:
565 else:
566 self.wopener(filename, 'w').write(data)
566 self.wopener(filename, 'w').write(data)
567 if 'x' in flags:
567 if 'x' in flags:
568 util.set_flags(self.wjoin(filename), False, True)
568 util.set_flags(self.wjoin(filename), False, True)
569
569
570 def wwritedata(self, filename, data):
570 def wwritedata(self, filename, data):
571 return self._filter("decode", filename, data)
571 return self._filter("decode", filename, data)
572
572
573 def transaction(self, desc):
573 def transaction(self, desc):
574 tr = self._transref and self._transref() or None
574 tr = self._transref and self._transref() or None
575 if tr and tr.running():
575 if tr and tr.running():
576 return tr.nest()
576 return tr.nest()
577
577
578 # abort here if the journal already exists
578 # abort here if the journal already exists
579 if os.path.exists(self.sjoin("journal")):
579 if os.path.exists(self.sjoin("journal")):
580 raise error.RepoError(
580 raise error.RepoError(
581 _("abandoned transaction found - run hg recover"))
581 _("abandoned transaction found - run hg recover"))
582
582
583 # save dirstate for rollback
583 # save dirstate for rollback
584 try:
584 try:
585 ds = self.opener("dirstate").read()
585 ds = self.opener("dirstate").read()
586 except IOError:
586 except IOError:
587 ds = ""
587 ds = ""
588 self.opener("journal.dirstate", "w").write(ds)
588 self.opener("journal.dirstate", "w").write(ds)
589 self.opener("journal.branch", "w").write(self.dirstate.branch())
589 self.opener("journal.branch", "w").write(self.dirstate.branch())
590 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
590 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
591
591
592 renames = [(self.sjoin("journal"), self.sjoin("undo")),
592 renames = [(self.sjoin("journal"), self.sjoin("undo")),
593 (self.join("journal.dirstate"), self.join("undo.dirstate")),
593 (self.join("journal.dirstate"), self.join("undo.dirstate")),
594 (self.join("journal.branch"), self.join("undo.branch")),
594 (self.join("journal.branch"), self.join("undo.branch")),
595 (self.join("journal.desc"), self.join("undo.desc"))]
595 (self.join("journal.desc"), self.join("undo.desc"))]
596 tr = transaction.transaction(self.ui.warn, self.sopener,
596 tr = transaction.transaction(self.ui.warn, self.sopener,
597 self.sjoin("journal"),
597 self.sjoin("journal"),
598 aftertrans(renames),
598 aftertrans(renames),
599 self.store.createmode)
599 self.store.createmode)
600 self._transref = weakref.ref(tr)
600 self._transref = weakref.ref(tr)
601 return tr
601 return tr
602
602
603 def recover(self):
603 def recover(self):
604 lock = self.lock()
604 lock = self.lock()
605 try:
605 try:
606 if os.path.exists(self.sjoin("journal")):
606 if os.path.exists(self.sjoin("journal")):
607 self.ui.status(_("rolling back interrupted transaction\n"))
607 self.ui.status(_("rolling back interrupted transaction\n"))
608 transaction.rollback(self.sopener, self.sjoin("journal"),
608 transaction.rollback(self.sopener, self.sjoin("journal"),
609 self.ui.warn)
609 self.ui.warn)
610 self.invalidate()
610 self.invalidate()
611 return True
611 return True
612 else:
612 else:
613 self.ui.warn(_("no interrupted transaction available\n"))
613 self.ui.warn(_("no interrupted transaction available\n"))
614 return False
614 return False
615 finally:
615 finally:
616 lock.release()
616 lock.release()
617
617
618 def rollback(self, dryrun=False):
618 def rollback(self, dryrun=False):
619 wlock = lock = None
619 wlock = lock = None
620 try:
620 try:
621 wlock = self.wlock()
621 wlock = self.wlock()
622 lock = self.lock()
622 lock = self.lock()
623 if os.path.exists(self.sjoin("undo")):
623 if os.path.exists(self.sjoin("undo")):
624 try:
624 try:
625 args = self.opener("undo.desc", "r").read().splitlines()
625 args = self.opener("undo.desc", "r").read().splitlines()
626 if len(args) >= 3 and self.ui.verbose:
626 if len(args) >= 3 and self.ui.verbose:
627 desc = _("rolling back to revision %s"
627 desc = _("rolling back to revision %s"
628 " (undo %s: %s)\n") % (
628 " (undo %s: %s)\n") % (
629 int(args[0]) - 1, args[1], args[2])
629 int(args[0]) - 1, args[1], args[2])
630 elif len(args) >= 2:
630 elif len(args) >= 2:
631 desc = _("rolling back to revision %s (undo %s)\n") % (
631 desc = _("rolling back to revision %s (undo %s)\n") % (
632 int(args[0]) - 1, args[1])
632 int(args[0]) - 1, args[1])
633 except IOError:
633 except IOError:
634 desc = _("rolling back unknown transaction\n")
634 desc = _("rolling back unknown transaction\n")
635 self.ui.status(desc)
635 self.ui.status(desc)
636 if dryrun:
636 if dryrun:
637 return
637 return
638 transaction.rollback(self.sopener, self.sjoin("undo"),
638 transaction.rollback(self.sopener, self.sjoin("undo"),
639 self.ui.warn)
639 self.ui.warn)
640 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
640 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
641 try:
641 try:
642 branch = self.opener("undo.branch").read()
642 branch = self.opener("undo.branch").read()
643 self.dirstate.setbranch(branch)
643 self.dirstate.setbranch(branch)
644 except IOError:
644 except IOError:
645 self.ui.warn(_("Named branch could not be reset, "
645 self.ui.warn(_("Named branch could not be reset, "
646 "current branch still is: %s\n")
646 "current branch still is: %s\n")
647 % encoding.tolocal(self.dirstate.branch()))
647 % encoding.tolocal(self.dirstate.branch()))
648 self.invalidate()
648 self.invalidate()
649 self.dirstate.invalidate()
649 self.dirstate.invalidate()
650 self.destroyed()
650 self.destroyed()
651 else:
651 else:
652 self.ui.warn(_("no rollback information available\n"))
652 self.ui.warn(_("no rollback information available\n"))
653 return 1
653 return 1
654 finally:
654 finally:
655 release(lock, wlock)
655 release(lock, wlock)
656
656
657 def invalidatecaches(self):
657 def invalidatecaches(self):
658 self._tags = None
658 self._tags = None
659 self._tagtypes = None
659 self._tagtypes = None
660 self.nodetagscache = None
660 self.nodetagscache = None
661 self._branchcache = None # in UTF-8
661 self._branchcache = None # in UTF-8
662 self._branchcachetip = None
662 self._branchcachetip = None
663
663
664 def invalidate(self):
664 def invalidate(self):
665 for a in "changelog manifest".split():
665 for a in "changelog manifest".split():
666 if a in self.__dict__:
666 if a in self.__dict__:
667 delattr(self, a)
667 delattr(self, a)
668 self.invalidatecaches()
668 self.invalidatecaches()
669
669
670 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
670 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
671 try:
671 try:
672 l = lock.lock(lockname, 0, releasefn, desc=desc)
672 l = lock.lock(lockname, 0, releasefn, desc=desc)
673 except error.LockHeld, inst:
673 except error.LockHeld, inst:
674 if not wait:
674 if not wait:
675 raise
675 raise
676 self.ui.warn(_("waiting for lock on %s held by %r\n") %
676 self.ui.warn(_("waiting for lock on %s held by %r\n") %
677 (desc, inst.locker))
677 (desc, inst.locker))
678 # default to 600 seconds timeout
678 # default to 600 seconds timeout
679 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
679 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
680 releasefn, desc=desc)
680 releasefn, desc=desc)
681 if acquirefn:
681 if acquirefn:
682 acquirefn()
682 acquirefn()
683 return l
683 return l
684
684
685 def lock(self, wait=True):
685 def lock(self, wait=True):
686 '''Lock the repository store (.hg/store) and return a weak reference
686 '''Lock the repository store (.hg/store) and return a weak reference
687 to the lock. Use this before modifying the store (e.g. committing or
687 to the lock. Use this before modifying the store (e.g. committing or
688 stripping). If you are opening a transaction, get a lock as well.)'''
688 stripping). If you are opening a transaction, get a lock as well.)'''
689 l = self._lockref and self._lockref()
689 l = self._lockref and self._lockref()
690 if l is not None and l.held:
690 if l is not None and l.held:
691 l.lock()
691 l.lock()
692 return l
692 return l
693
693
694 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
694 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
695 _('repository %s') % self.origroot)
695 _('repository %s') % self.origroot)
696 self._lockref = weakref.ref(l)
696 self._lockref = weakref.ref(l)
697 return l
697 return l
698
698
699 def wlock(self, wait=True):
699 def wlock(self, wait=True):
700 '''Lock the non-store parts of the repository (everything under
700 '''Lock the non-store parts of the repository (everything under
701 .hg except .hg/store) and return a weak reference to the lock.
701 .hg except .hg/store) and return a weak reference to the lock.
702 Use this before modifying files in .hg.'''
702 Use this before modifying files in .hg.'''
703 l = self._wlockref and self._wlockref()
703 l = self._wlockref and self._wlockref()
704 if l is not None and l.held:
704 if l is not None and l.held:
705 l.lock()
705 l.lock()
706 return l
706 return l
707
707
708 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
708 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
709 self.dirstate.invalidate, _('working directory of %s') %
709 self.dirstate.invalidate, _('working directory of %s') %
710 self.origroot)
710 self.origroot)
711 self._wlockref = weakref.ref(l)
711 self._wlockref = weakref.ref(l)
712 return l
712 return l
713
713
714 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
714 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
715 """
715 """
716 commit an individual file as part of a larger transaction
716 commit an individual file as part of a larger transaction
717 """
717 """
718
718
719 fname = fctx.path()
719 fname = fctx.path()
720 text = fctx.data()
720 text = fctx.data()
721 flog = self.file(fname)
721 flog = self.file(fname)
722 fparent1 = manifest1.get(fname, nullid)
722 fparent1 = manifest1.get(fname, nullid)
723 fparent2 = fparent2o = manifest2.get(fname, nullid)
723 fparent2 = fparent2o = manifest2.get(fname, nullid)
724
724
725 meta = {}
725 meta = {}
726 copy = fctx.renamed()
726 copy = fctx.renamed()
727 if copy and copy[0] != fname:
727 if copy and copy[0] != fname:
728 # Mark the new revision of this file as a copy of another
728 # Mark the new revision of this file as a copy of another
729 # file. This copy data will effectively act as a parent
729 # file. This copy data will effectively act as a parent
730 # of this new revision. If this is a merge, the first
730 # of this new revision. If this is a merge, the first
731 # parent will be the nullid (meaning "look up the copy data")
731 # parent will be the nullid (meaning "look up the copy data")
732 # and the second one will be the other parent. For example:
732 # and the second one will be the other parent. For example:
733 #
733 #
734 # 0 --- 1 --- 3 rev1 changes file foo
734 # 0 --- 1 --- 3 rev1 changes file foo
735 # \ / rev2 renames foo to bar and changes it
735 # \ / rev2 renames foo to bar and changes it
736 # \- 2 -/ rev3 should have bar with all changes and
736 # \- 2 -/ rev3 should have bar with all changes and
737 # should record that bar descends from
737 # should record that bar descends from
738 # bar in rev2 and foo in rev1
738 # bar in rev2 and foo in rev1
739 #
739 #
740 # this allows this merge to succeed:
740 # this allows this merge to succeed:
741 #
741 #
742 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
742 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
743 # \ / merging rev3 and rev4 should use bar@rev2
743 # \ / merging rev3 and rev4 should use bar@rev2
744 # \- 2 --- 4 as the merge base
744 # \- 2 --- 4 as the merge base
745 #
745 #
746
746
747 cfname = copy[0]
747 cfname = copy[0]
748 crev = manifest1.get(cfname)
748 crev = manifest1.get(cfname)
749 newfparent = fparent2
749 newfparent = fparent2
750
750
751 if manifest2: # branch merge
751 if manifest2: # branch merge
752 if fparent2 == nullid or crev is None: # copied on remote side
752 if fparent2 == nullid or crev is None: # copied on remote side
753 if cfname in manifest2:
753 if cfname in manifest2:
754 crev = manifest2[cfname]
754 crev = manifest2[cfname]
755 newfparent = fparent1
755 newfparent = fparent1
756
756
757 # find source in nearest ancestor if we've lost track
757 # find source in nearest ancestor if we've lost track
758 if not crev:
758 if not crev:
759 self.ui.debug(" %s: searching for copy revision for %s\n" %
759 self.ui.debug(" %s: searching for copy revision for %s\n" %
760 (fname, cfname))
760 (fname, cfname))
761 for ancestor in self['.'].ancestors():
761 for ancestor in self['.'].ancestors():
762 if cfname in ancestor:
762 if cfname in ancestor:
763 crev = ancestor[cfname].filenode()
763 crev = ancestor[cfname].filenode()
764 break
764 break
765
765
766 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
766 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
767 meta["copy"] = cfname
767 meta["copy"] = cfname
768 meta["copyrev"] = hex(crev)
768 meta["copyrev"] = hex(crev)
769 fparent1, fparent2 = nullid, newfparent
769 fparent1, fparent2 = nullid, newfparent
770 elif fparent2 != nullid:
770 elif fparent2 != nullid:
771 # is one parent an ancestor of the other?
771 # is one parent an ancestor of the other?
772 fparentancestor = flog.ancestor(fparent1, fparent2)
772 fparentancestor = flog.ancestor(fparent1, fparent2)
773 if fparentancestor == fparent1:
773 if fparentancestor == fparent1:
774 fparent1, fparent2 = fparent2, nullid
774 fparent1, fparent2 = fparent2, nullid
775 elif fparentancestor == fparent2:
775 elif fparentancestor == fparent2:
776 fparent2 = nullid
776 fparent2 = nullid
777
777
778 # is the file changed?
778 # is the file changed?
779 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
779 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
780 changelist.append(fname)
780 changelist.append(fname)
781 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
781 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
782
782
783 # are just the flags changed during merge?
783 # are just the flags changed during merge?
784 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
784 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
785 changelist.append(fname)
785 changelist.append(fname)
786
786
787 return fparent1
787 return fparent1
788
788
789 def commit(self, text="", user=None, date=None, match=None, force=False,
789 def commit(self, text="", user=None, date=None, match=None, force=False,
790 editor=False, extra={}):
790 editor=False, extra={}):
791 """Add a new revision to current repository.
791 """Add a new revision to current repository.
792
792
793 Revision information is gathered from the working directory,
793 Revision information is gathered from the working directory,
794 match can be used to filter the committed files. If editor is
794 match can be used to filter the committed files. If editor is
795 supplied, it is called to get a commit message.
795 supplied, it is called to get a commit message.
796 """
796 """
797
797
798 def fail(f, msg):
798 def fail(f, msg):
799 raise util.Abort('%s: %s' % (f, msg))
799 raise util.Abort('%s: %s' % (f, msg))
800
800
801 if not match:
801 if not match:
802 match = matchmod.always(self.root, '')
802 match = matchmod.always(self.root, '')
803
803
804 if not force:
804 if not force:
805 vdirs = []
805 vdirs = []
806 match.dir = vdirs.append
806 match.dir = vdirs.append
807 match.bad = fail
807 match.bad = fail
808
808
809 wlock = self.wlock()
809 wlock = self.wlock()
810 try:
810 try:
811 wctx = self[None]
811 wctx = self[None]
812 merge = len(wctx.parents()) > 1
812 merge = len(wctx.parents()) > 1
813
813
814 if (not force and merge and match and
814 if (not force and merge and match and
815 (match.files() or match.anypats())):
815 (match.files() or match.anypats())):
816 raise util.Abort(_('cannot partially commit a merge '
816 raise util.Abort(_('cannot partially commit a merge '
817 '(do not specify files or patterns)'))
817 '(do not specify files or patterns)'))
818
818
819 changes = self.status(match=match, clean=force)
819 changes = self.status(match=match, clean=force)
820 if force:
820 if force:
821 changes[0].extend(changes[6]) # mq may commit unchanged files
821 changes[0].extend(changes[6]) # mq may commit unchanged files
822
822
823 # check subrepos
823 # check subrepos
824 subs = []
824 subs = []
825 removedsubs = set()
825 removedsubs = set()
826 for p in wctx.parents():
826 for p in wctx.parents():
827 removedsubs.update(s for s in p.substate if match(s))
827 removedsubs.update(s for s in p.substate if match(s))
828 for s in wctx.substate:
828 for s in wctx.substate:
829 removedsubs.discard(s)
829 removedsubs.discard(s)
830 if match(s) and wctx.sub(s).dirty():
830 if match(s) and wctx.sub(s).dirty():
831 subs.append(s)
831 subs.append(s)
832 if (subs or removedsubs):
832 if (subs or removedsubs):
833 if (not match('.hgsub') and
833 if (not match('.hgsub') and
834 '.hgsub' in (wctx.modified() + wctx.added())):
834 '.hgsub' in (wctx.modified() + wctx.added())):
835 raise util.Abort(_("can't commit subrepos without .hgsub"))
835 raise util.Abort(_("can't commit subrepos without .hgsub"))
836 if '.hgsubstate' not in changes[0]:
836 if '.hgsubstate' not in changes[0]:
837 changes[0].insert(0, '.hgsubstate')
837 changes[0].insert(0, '.hgsubstate')
838
838
839 # make sure all explicit patterns are matched
839 # make sure all explicit patterns are matched
840 if not force and match.files():
840 if not force and match.files():
841 matched = set(changes[0] + changes[1] + changes[2])
841 matched = set(changes[0] + changes[1] + changes[2])
842
842
843 for f in match.files():
843 for f in match.files():
844 if f == '.' or f in matched or f in wctx.substate:
844 if f == '.' or f in matched or f in wctx.substate:
845 continue
845 continue
846 if f in changes[3]: # missing
846 if f in changes[3]: # missing
847 fail(f, _('file not found!'))
847 fail(f, _('file not found!'))
848 if f in vdirs: # visited directory
848 if f in vdirs: # visited directory
849 d = f + '/'
849 d = f + '/'
850 for mf in matched:
850 for mf in matched:
851 if mf.startswith(d):
851 if mf.startswith(d):
852 break
852 break
853 else:
853 else:
854 fail(f, _("no match under directory!"))
854 fail(f, _("no match under directory!"))
855 elif f not in self.dirstate:
855 elif f not in self.dirstate:
856 fail(f, _("file not tracked!"))
856 fail(f, _("file not tracked!"))
857
857
858 if (not force and not extra.get("close") and not merge
858 if (not force and not extra.get("close") and not merge
859 and not (changes[0] or changes[1] or changes[2])
859 and not (changes[0] or changes[1] or changes[2])
860 and wctx.branch() == wctx.p1().branch()):
860 and wctx.branch() == wctx.p1().branch()):
861 return None
861 return None
862
862
863 ms = mergemod.mergestate(self)
863 ms = mergemod.mergestate(self)
864 for f in changes[0]:
864 for f in changes[0]:
865 if f in ms and ms[f] == 'u':
865 if f in ms and ms[f] == 'u':
866 raise util.Abort(_("unresolved merge conflicts "
866 raise util.Abort(_("unresolved merge conflicts "
867 "(see hg resolve)"))
867 "(see hg resolve)"))
868
868
869 cctx = context.workingctx(self, text, user, date, extra, changes)
869 cctx = context.workingctx(self, text, user, date, extra, changes)
870 if editor:
870 if editor:
871 cctx._text = editor(self, cctx, subs)
871 cctx._text = editor(self, cctx, subs)
872 edited = (text != cctx._text)
872 edited = (text != cctx._text)
873
873
874 # commit subs
874 # commit subs
875 if subs or removedsubs:
875 if subs or removedsubs:
876 state = wctx.substate.copy()
876 state = wctx.substate.copy()
877 for s in subs:
877 for s in subs:
878 sub = wctx.sub(s)
878 sub = wctx.sub(s)
879 self.ui.status(_('committing subrepository %s\n') %
879 self.ui.status(_('committing subrepository %s\n') %
880 subrepo.relpath(sub))
880 subrepo.relpath(sub))
881 sr = sub.commit(cctx._text, user, date)
881 sr = sub.commit(cctx._text, user, date)
882 state[s] = (state[s][0], sr)
882 state[s] = (state[s][0], sr)
883 subrepo.writestate(self, state)
883 subrepo.writestate(self, state)
884
884
885 # Save commit message in case this transaction gets rolled back
885 # Save commit message in case this transaction gets rolled back
886 # (e.g. by a pretxncommit hook). Leave the content alone on
886 # (e.g. by a pretxncommit hook). Leave the content alone on
887 # the assumption that the user will use the same editor again.
887 # the assumption that the user will use the same editor again.
888 msgfile = self.opener('last-message.txt', 'wb')
888 msgfile = self.opener('last-message.txt', 'wb')
889 msgfile.write(cctx._text)
889 msgfile.write(cctx._text)
890 msgfile.close()
890 msgfile.close()
891
891
892 p1, p2 = self.dirstate.parents()
892 p1, p2 = self.dirstate.parents()
893 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
893 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
894 try:
894 try:
895 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
895 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
896 ret = self.commitctx(cctx, True)
896 ret = self.commitctx(cctx, True)
897 except:
897 except:
898 if edited:
898 if edited:
899 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
899 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
900 self.ui.write(
900 self.ui.write(
901 _('note: commit message saved in %s\n') % msgfn)
901 _('note: commit message saved in %s\n') % msgfn)
902 raise
902 raise
903
903
904 # update dirstate and mergestate
904 # update dirstate and mergestate
905 for f in changes[0] + changes[1]:
905 for f in changes[0] + changes[1]:
906 self.dirstate.normal(f)
906 self.dirstate.normal(f)
907 for f in changes[2]:
907 for f in changes[2]:
908 self.dirstate.forget(f)
908 self.dirstate.forget(f)
909 self.dirstate.setparents(ret)
909 self.dirstate.setparents(ret)
910 ms.reset()
910 ms.reset()
911 finally:
911 finally:
912 wlock.release()
912 wlock.release()
913
913
914 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
914 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
915 return ret
915 return ret
916
916
917 def commitctx(self, ctx, error=False):
917 def commitctx(self, ctx, error=False):
918 """Add a new revision to current repository.
918 """Add a new revision to current repository.
919 Revision information is passed via the context argument.
919 Revision information is passed via the context argument.
920 """
920 """
921
921
922 tr = lock = None
922 tr = lock = None
923 removed = ctx.removed()
923 removed = ctx.removed()
924 p1, p2 = ctx.p1(), ctx.p2()
924 p1, p2 = ctx.p1(), ctx.p2()
925 m1 = p1.manifest().copy()
925 m1 = p1.manifest().copy()
926 m2 = p2.manifest()
926 m2 = p2.manifest()
927 user = ctx.user()
927 user = ctx.user()
928
928
929 lock = self.lock()
929 lock = self.lock()
930 try:
930 try:
931 tr = self.transaction("commit")
931 tr = self.transaction("commit")
932 trp = weakref.proxy(tr)
932 trp = weakref.proxy(tr)
933
933
934 # check in files
934 # check in files
935 new = {}
935 new = {}
936 changed = []
936 changed = []
937 linkrev = len(self)
937 linkrev = len(self)
938 for f in sorted(ctx.modified() + ctx.added()):
938 for f in sorted(ctx.modified() + ctx.added()):
939 self.ui.note(f + "\n")
939 self.ui.note(f + "\n")
940 try:
940 try:
941 fctx = ctx[f]
941 fctx = ctx[f]
942 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
942 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
943 changed)
943 changed)
944 m1.set(f, fctx.flags())
944 m1.set(f, fctx.flags())
945 except OSError, inst:
945 except OSError, inst:
946 self.ui.warn(_("trouble committing %s!\n") % f)
946 self.ui.warn(_("trouble committing %s!\n") % f)
947 raise
947 raise
948 except IOError, inst:
948 except IOError, inst:
949 errcode = getattr(inst, 'errno', errno.ENOENT)
949 errcode = getattr(inst, 'errno', errno.ENOENT)
950 if error or errcode and errcode != errno.ENOENT:
950 if error or errcode and errcode != errno.ENOENT:
951 self.ui.warn(_("trouble committing %s!\n") % f)
951 self.ui.warn(_("trouble committing %s!\n") % f)
952 raise
952 raise
953 else:
953 else:
954 removed.append(f)
954 removed.append(f)
955
955
956 # update manifest
956 # update manifest
957 m1.update(new)
957 m1.update(new)
958 removed = [f for f in sorted(removed) if f in m1 or f in m2]
958 removed = [f for f in sorted(removed) if f in m1 or f in m2]
959 drop = [f for f in removed if f in m1]
959 drop = [f for f in removed if f in m1]
960 for f in drop:
960 for f in drop:
961 del m1[f]
961 del m1[f]
962 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
962 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
963 p2.manifestnode(), (new, drop))
963 p2.manifestnode(), (new, drop))
964
964
965 # update changelog
965 # update changelog
966 self.changelog.delayupdate()
966 self.changelog.delayupdate()
967 n = self.changelog.add(mn, changed + removed, ctx.description(),
967 n = self.changelog.add(mn, changed + removed, ctx.description(),
968 trp, p1.node(), p2.node(),
968 trp, p1.node(), p2.node(),
969 user, ctx.date(), ctx.extra().copy())
969 user, ctx.date(), ctx.extra().copy())
970 p = lambda: self.changelog.writepending() and self.root or ""
970 p = lambda: self.changelog.writepending() and self.root or ""
971 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
971 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
972 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
972 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
973 parent2=xp2, pending=p)
973 parent2=xp2, pending=p)
974 self.changelog.finalize(trp)
974 self.changelog.finalize(trp)
975 tr.close()
975 tr.close()
976
976
977 if self._branchcache:
977 if self._branchcache:
978 self.branchtags()
978 self.branchtags()
979 return n
979 return n
980 finally:
980 finally:
981 if tr:
981 if tr:
982 tr.release()
982 tr.release()
983 lock.release()
983 lock.release()
984
984
985 def destroyed(self):
985 def destroyed(self):
986 '''Inform the repository that nodes have been destroyed.
986 '''Inform the repository that nodes have been destroyed.
987 Intended for use by strip and rollback, so there's a common
987 Intended for use by strip and rollback, so there's a common
988 place for anything that has to be done after destroying history.'''
988 place for anything that has to be done after destroying history.'''
989 # XXX it might be nice if we could take the list of destroyed
989 # XXX it might be nice if we could take the list of destroyed
990 # nodes, but I don't see an easy way for rollback() to do that
990 # nodes, but I don't see an easy way for rollback() to do that
991
991
992 # Ensure the persistent tag cache is updated. Doing it now
992 # Ensure the persistent tag cache is updated. Doing it now
993 # means that the tag cache only has to worry about destroyed
993 # means that the tag cache only has to worry about destroyed
994 # heads immediately after a strip/rollback. That in turn
994 # heads immediately after a strip/rollback. That in turn
995 # guarantees that "cachetip == currenttip" (comparing both rev
995 # guarantees that "cachetip == currenttip" (comparing both rev
996 # and node) always means no nodes have been added or destroyed.
996 # and node) always means no nodes have been added or destroyed.
997
997
998 # XXX this is suboptimal when qrefresh'ing: we strip the current
998 # XXX this is suboptimal when qrefresh'ing: we strip the current
999 # head, refresh the tag cache, then immediately add a new head.
999 # head, refresh the tag cache, then immediately add a new head.
1000 # But I think doing it this way is necessary for the "instant
1000 # But I think doing it this way is necessary for the "instant
1001 # tag cache retrieval" case to work.
1001 # tag cache retrieval" case to work.
1002 self.invalidatecaches()
1002 self.invalidatecaches()
1003
1003
1004 def walk(self, match, node=None):
1004 def walk(self, match, node=None):
1005 '''
1005 '''
1006 walk recursively through the directory tree or a given
1006 walk recursively through the directory tree or a given
1007 changeset, finding all files matched by the match
1007 changeset, finding all files matched by the match
1008 function
1008 function
1009 '''
1009 '''
1010 return self[node].walk(match)
1010 return self[node].walk(match)
1011
1011
1012 def status(self, node1='.', node2=None, match=None,
1012 def status(self, node1='.', node2=None, match=None,
1013 ignored=False, clean=False, unknown=False):
1013 ignored=False, clean=False, unknown=False):
1014 """return status of files between two nodes or node and working directory
1014 """return status of files between two nodes or node and working directory
1015
1015
1016 If node1 is None, use the first dirstate parent instead.
1016 If node1 is None, use the first dirstate parent instead.
1017 If node2 is None, compare node1 with working directory.
1017 If node2 is None, compare node1 with working directory.
1018 """
1018 """
1019
1019
1020 def mfmatches(ctx):
1020 def mfmatches(ctx):
1021 mf = ctx.manifest().copy()
1021 mf = ctx.manifest().copy()
1022 for fn in mf.keys():
1022 for fn in mf.keys():
1023 if not match(fn):
1023 if not match(fn):
1024 del mf[fn]
1024 del mf[fn]
1025 return mf
1025 return mf
1026
1026
1027 if isinstance(node1, context.changectx):
1027 if isinstance(node1, context.changectx):
1028 ctx1 = node1
1028 ctx1 = node1
1029 else:
1029 else:
1030 ctx1 = self[node1]
1030 ctx1 = self[node1]
1031 if isinstance(node2, context.changectx):
1031 if isinstance(node2, context.changectx):
1032 ctx2 = node2
1032 ctx2 = node2
1033 else:
1033 else:
1034 ctx2 = self[node2]
1034 ctx2 = self[node2]
1035
1035
1036 working = ctx2.rev() is None
1036 working = ctx2.rev() is None
1037 parentworking = working and ctx1 == self['.']
1037 parentworking = working and ctx1 == self['.']
1038 match = match or matchmod.always(self.root, self.getcwd())
1038 match = match or matchmod.always(self.root, self.getcwd())
1039 listignored, listclean, listunknown = ignored, clean, unknown
1039 listignored, listclean, listunknown = ignored, clean, unknown
1040
1040
1041 # load earliest manifest first for caching reasons
1041 # load earliest manifest first for caching reasons
1042 if not working and ctx2.rev() < ctx1.rev():
1042 if not working and ctx2.rev() < ctx1.rev():
1043 ctx2.manifest()
1043 ctx2.manifest()
1044
1044
1045 if not parentworking:
1045 if not parentworking:
1046 def bad(f, msg):
1046 def bad(f, msg):
1047 if f not in ctx1:
1047 if f not in ctx1:
1048 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1048 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1049 match.bad = bad
1049 match.bad = bad
1050
1050
1051 if working: # we need to scan the working dir
1051 if working: # we need to scan the working dir
1052 subrepos = []
1052 subrepos = []
1053 if '.hgsub' in self.dirstate:
1053 if '.hgsub' in self.dirstate:
1054 subrepos = ctx1.substate.keys()
1054 subrepos = ctx1.substate.keys()
1055 s = self.dirstate.status(match, subrepos, listignored,
1055 s = self.dirstate.status(match, subrepos, listignored,
1056 listclean, listunknown)
1056 listclean, listunknown)
1057 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1057 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1058
1058
1059 # check for any possibly clean files
1059 # check for any possibly clean files
1060 if parentworking and cmp:
1060 if parentworking and cmp:
1061 fixup = []
1061 fixup = []
1062 # do a full compare of any files that might have changed
1062 # do a full compare of any files that might have changed
1063 for f in sorted(cmp):
1063 for f in sorted(cmp):
1064 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1064 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1065 or ctx1[f].cmp(ctx2[f].data())):
1065 or ctx1[f].cmp(ctx2[f])):
1066 modified.append(f)
1066 modified.append(f)
1067 else:
1067 else:
1068 fixup.append(f)
1068 fixup.append(f)
1069
1069
1070 # update dirstate for files that are actually clean
1070 # update dirstate for files that are actually clean
1071 if fixup:
1071 if fixup:
1072 if listclean:
1072 if listclean:
1073 clean += fixup
1073 clean += fixup
1074
1074
1075 try:
1075 try:
1076 # updating the dirstate is optional
1076 # updating the dirstate is optional
1077 # so we don't wait on the lock
1077 # so we don't wait on the lock
1078 wlock = self.wlock(False)
1078 wlock = self.wlock(False)
1079 try:
1079 try:
1080 for f in fixup:
1080 for f in fixup:
1081 self.dirstate.normal(f)
1081 self.dirstate.normal(f)
1082 finally:
1082 finally:
1083 wlock.release()
1083 wlock.release()
1084 except error.LockError:
1084 except error.LockError:
1085 pass
1085 pass
1086
1086
1087 if not parentworking:
1087 if not parentworking:
1088 mf1 = mfmatches(ctx1)
1088 mf1 = mfmatches(ctx1)
1089 if working:
1089 if working:
1090 # we are comparing working dir against non-parent
1090 # we are comparing working dir against non-parent
1091 # generate a pseudo-manifest for the working dir
1091 # generate a pseudo-manifest for the working dir
1092 mf2 = mfmatches(self['.'])
1092 mf2 = mfmatches(self['.'])
1093 for f in cmp + modified + added:
1093 for f in cmp + modified + added:
1094 mf2[f] = None
1094 mf2[f] = None
1095 mf2.set(f, ctx2.flags(f))
1095 mf2.set(f, ctx2.flags(f))
1096 for f in removed:
1096 for f in removed:
1097 if f in mf2:
1097 if f in mf2:
1098 del mf2[f]
1098 del mf2[f]
1099 else:
1099 else:
1100 # we are comparing two revisions
1100 # we are comparing two revisions
1101 deleted, unknown, ignored = [], [], []
1101 deleted, unknown, ignored = [], [], []
1102 mf2 = mfmatches(ctx2)
1102 mf2 = mfmatches(ctx2)
1103
1103
1104 modified, added, clean = [], [], []
1104 modified, added, clean = [], [], []
1105 for fn in mf2:
1105 for fn in mf2:
1106 if fn in mf1:
1106 if fn in mf1:
1107 if (mf1.flags(fn) != mf2.flags(fn) or
1107 if (mf1.flags(fn) != mf2.flags(fn) or
1108 (mf1[fn] != mf2[fn] and
1108 (mf1[fn] != mf2[fn] and
1109 (mf2[fn] or ctx1[fn].cmp(ctx2[fn].data())))):
1109 (mf2[fn] or ctx1[fn].cmp(ctx2[fn])))):
1110 modified.append(fn)
1110 modified.append(fn)
1111 elif listclean:
1111 elif listclean:
1112 clean.append(fn)
1112 clean.append(fn)
1113 del mf1[fn]
1113 del mf1[fn]
1114 else:
1114 else:
1115 added.append(fn)
1115 added.append(fn)
1116 removed = mf1.keys()
1116 removed = mf1.keys()
1117
1117
1118 r = modified, added, removed, deleted, unknown, ignored, clean
1118 r = modified, added, removed, deleted, unknown, ignored, clean
1119 [l.sort() for l in r]
1119 [l.sort() for l in r]
1120 return r
1120 return r
1121
1121
1122 def heads(self, start=None):
1122 def heads(self, start=None):
1123 heads = self.changelog.heads(start)
1123 heads = self.changelog.heads(start)
1124 # sort the output in rev descending order
1124 # sort the output in rev descending order
1125 heads = [(-self.changelog.rev(h), h) for h in heads]
1125 heads = [(-self.changelog.rev(h), h) for h in heads]
1126 return [n for (r, n) in sorted(heads)]
1126 return [n for (r, n) in sorted(heads)]
1127
1127
1128 def branchheads(self, branch=None, start=None, closed=False):
1128 def branchheads(self, branch=None, start=None, closed=False):
1129 '''return a (possibly filtered) list of heads for the given branch
1129 '''return a (possibly filtered) list of heads for the given branch
1130
1130
1131 Heads are returned in topological order, from newest to oldest.
1131 Heads are returned in topological order, from newest to oldest.
1132 If branch is None, use the dirstate branch.
1132 If branch is None, use the dirstate branch.
1133 If start is not None, return only heads reachable from start.
1133 If start is not None, return only heads reachable from start.
1134 If closed is True, return heads that are marked as closed as well.
1134 If closed is True, return heads that are marked as closed as well.
1135 '''
1135 '''
1136 if branch is None:
1136 if branch is None:
1137 branch = self[None].branch()
1137 branch = self[None].branch()
1138 branches = self.branchmap()
1138 branches = self.branchmap()
1139 if branch not in branches:
1139 if branch not in branches:
1140 return []
1140 return []
1141 # the cache returns heads ordered lowest to highest
1141 # the cache returns heads ordered lowest to highest
1142 bheads = list(reversed(branches[branch]))
1142 bheads = list(reversed(branches[branch]))
1143 if start is not None:
1143 if start is not None:
1144 # filter out the heads that cannot be reached from startrev
1144 # filter out the heads that cannot be reached from startrev
1145 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1145 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1146 bheads = [h for h in bheads if h in fbheads]
1146 bheads = [h for h in bheads if h in fbheads]
1147 if not closed:
1147 if not closed:
1148 bheads = [h for h in bheads if
1148 bheads = [h for h in bheads if
1149 ('close' not in self.changelog.read(h)[5])]
1149 ('close' not in self.changelog.read(h)[5])]
1150 return bheads
1150 return bheads
1151
1151
1152 def branches(self, nodes):
1152 def branches(self, nodes):
1153 if not nodes:
1153 if not nodes:
1154 nodes = [self.changelog.tip()]
1154 nodes = [self.changelog.tip()]
1155 b = []
1155 b = []
1156 for n in nodes:
1156 for n in nodes:
1157 t = n
1157 t = n
1158 while 1:
1158 while 1:
1159 p = self.changelog.parents(n)
1159 p = self.changelog.parents(n)
1160 if p[1] != nullid or p[0] == nullid:
1160 if p[1] != nullid or p[0] == nullid:
1161 b.append((t, n, p[0], p[1]))
1161 b.append((t, n, p[0], p[1]))
1162 break
1162 break
1163 n = p[0]
1163 n = p[0]
1164 return b
1164 return b
1165
1165
1166 def between(self, pairs):
1166 def between(self, pairs):
1167 r = []
1167 r = []
1168
1168
1169 for top, bottom in pairs:
1169 for top, bottom in pairs:
1170 n, l, i = top, [], 0
1170 n, l, i = top, [], 0
1171 f = 1
1171 f = 1
1172
1172
1173 while n != bottom and n != nullid:
1173 while n != bottom and n != nullid:
1174 p = self.changelog.parents(n)[0]
1174 p = self.changelog.parents(n)[0]
1175 if i == f:
1175 if i == f:
1176 l.append(n)
1176 l.append(n)
1177 f = f * 2
1177 f = f * 2
1178 n = p
1178 n = p
1179 i += 1
1179 i += 1
1180
1180
1181 r.append(l)
1181 r.append(l)
1182
1182
1183 return r
1183 return r
1184
1184
1185 def pull(self, remote, heads=None, force=False):
1185 def pull(self, remote, heads=None, force=False):
1186 lock = self.lock()
1186 lock = self.lock()
1187 try:
1187 try:
1188 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1188 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1189 force=force)
1189 force=force)
1190 common, fetch, rheads = tmp
1190 common, fetch, rheads = tmp
1191 if not fetch:
1191 if not fetch:
1192 self.ui.status(_("no changes found\n"))
1192 self.ui.status(_("no changes found\n"))
1193 return 0
1193 return 0
1194
1194
1195 if fetch == [nullid]:
1195 if fetch == [nullid]:
1196 self.ui.status(_("requesting all changes\n"))
1196 self.ui.status(_("requesting all changes\n"))
1197 elif heads is None and remote.capable('changegroupsubset'):
1197 elif heads is None and remote.capable('changegroupsubset'):
1198 # issue1320, avoid a race if remote changed after discovery
1198 # issue1320, avoid a race if remote changed after discovery
1199 heads = rheads
1199 heads = rheads
1200
1200
1201 if heads is None:
1201 if heads is None:
1202 cg = remote.changegroup(fetch, 'pull')
1202 cg = remote.changegroup(fetch, 'pull')
1203 else:
1203 else:
1204 if not remote.capable('changegroupsubset'):
1204 if not remote.capable('changegroupsubset'):
1205 raise util.Abort(_("Partial pull cannot be done because "
1205 raise util.Abort(_("Partial pull cannot be done because "
1206 "other repository doesn't support "
1206 "other repository doesn't support "
1207 "changegroupsubset."))
1207 "changegroupsubset."))
1208 cg = remote.changegroupsubset(fetch, heads, 'pull')
1208 cg = remote.changegroupsubset(fetch, heads, 'pull')
1209 return self.addchangegroup(cg, 'pull', remote.url(), lock=lock)
1209 return self.addchangegroup(cg, 'pull', remote.url(), lock=lock)
1210 finally:
1210 finally:
1211 lock.release()
1211 lock.release()
1212
1212
1213 def push(self, remote, force=False, revs=None, newbranch=False):
1213 def push(self, remote, force=False, revs=None, newbranch=False):
1214 '''Push outgoing changesets (limited by revs) from the current
1214 '''Push outgoing changesets (limited by revs) from the current
1215 repository to remote. Return an integer:
1215 repository to remote. Return an integer:
1216 - 0 means HTTP error *or* nothing to push
1216 - 0 means HTTP error *or* nothing to push
1217 - 1 means we pushed and remote head count is unchanged *or*
1217 - 1 means we pushed and remote head count is unchanged *or*
1218 we have outgoing changesets but refused to push
1218 we have outgoing changesets but refused to push
1219 - other values as described by addchangegroup()
1219 - other values as described by addchangegroup()
1220 '''
1220 '''
1221 # there are two ways to push to remote repo:
1221 # there are two ways to push to remote repo:
1222 #
1222 #
1223 # addchangegroup assumes local user can lock remote
1223 # addchangegroup assumes local user can lock remote
1224 # repo (local filesystem, old ssh servers).
1224 # repo (local filesystem, old ssh servers).
1225 #
1225 #
1226 # unbundle assumes local user cannot lock remote repo (new ssh
1226 # unbundle assumes local user cannot lock remote repo (new ssh
1227 # servers, http servers).
1227 # servers, http servers).
1228
1228
1229 lock = None
1229 lock = None
1230 unbundle = remote.capable('unbundle')
1230 unbundle = remote.capable('unbundle')
1231 if not unbundle:
1231 if not unbundle:
1232 lock = remote.lock()
1232 lock = remote.lock()
1233 try:
1233 try:
1234 ret = discovery.prepush(self, remote, force, revs, newbranch)
1234 ret = discovery.prepush(self, remote, force, revs, newbranch)
1235 if ret[0] is None:
1235 if ret[0] is None:
1236 # and here we return 0 for "nothing to push" or 1 for
1236 # and here we return 0 for "nothing to push" or 1 for
1237 # "something to push but I refuse"
1237 # "something to push but I refuse"
1238 return ret[1]
1238 return ret[1]
1239
1239
1240 cg, remote_heads = ret
1240 cg, remote_heads = ret
1241 if unbundle:
1241 if unbundle:
1242 # local repo finds heads on server, finds out what revs it must
1242 # local repo finds heads on server, finds out what revs it must
1243 # push. once revs transferred, if server finds it has
1243 # push. once revs transferred, if server finds it has
1244 # different heads (someone else won commit/push race), server
1244 # different heads (someone else won commit/push race), server
1245 # aborts.
1245 # aborts.
1246 if force:
1246 if force:
1247 remote_heads = ['force']
1247 remote_heads = ['force']
1248 # ssh: return remote's addchangegroup()
1248 # ssh: return remote's addchangegroup()
1249 # http: return remote's addchangegroup() or 0 for error
1249 # http: return remote's addchangegroup() or 0 for error
1250 return remote.unbundle(cg, remote_heads, 'push')
1250 return remote.unbundle(cg, remote_heads, 'push')
1251 else:
1251 else:
1252 # we return an integer indicating remote head count change
1252 # we return an integer indicating remote head count change
1253 return remote.addchangegroup(cg, 'push', self.url(), lock=lock)
1253 return remote.addchangegroup(cg, 'push', self.url(), lock=lock)
1254 finally:
1254 finally:
1255 if lock is not None:
1255 if lock is not None:
1256 lock.release()
1256 lock.release()
1257
1257
1258 def changegroupinfo(self, nodes, source):
1258 def changegroupinfo(self, nodes, source):
1259 if self.ui.verbose or source == 'bundle':
1259 if self.ui.verbose or source == 'bundle':
1260 self.ui.status(_("%d changesets found\n") % len(nodes))
1260 self.ui.status(_("%d changesets found\n") % len(nodes))
1261 if self.ui.debugflag:
1261 if self.ui.debugflag:
1262 self.ui.debug("list of changesets:\n")
1262 self.ui.debug("list of changesets:\n")
1263 for node in nodes:
1263 for node in nodes:
1264 self.ui.debug("%s\n" % hex(node))
1264 self.ui.debug("%s\n" % hex(node))
1265
1265
1266 def changegroupsubset(self, bases, heads, source, extranodes=None):
1266 def changegroupsubset(self, bases, heads, source, extranodes=None):
1267 """Compute a changegroup consisting of all the nodes that are
1267 """Compute a changegroup consisting of all the nodes that are
1268 descendents of any of the bases and ancestors of any of the heads.
1268 descendents of any of the bases and ancestors of any of the heads.
1269 Return a chunkbuffer object whose read() method will return
1269 Return a chunkbuffer object whose read() method will return
1270 successive changegroup chunks.
1270 successive changegroup chunks.
1271
1271
1272 It is fairly complex as determining which filenodes and which
1272 It is fairly complex as determining which filenodes and which
1273 manifest nodes need to be included for the changeset to be complete
1273 manifest nodes need to be included for the changeset to be complete
1274 is non-trivial.
1274 is non-trivial.
1275
1275
1276 Another wrinkle is doing the reverse, figuring out which changeset in
1276 Another wrinkle is doing the reverse, figuring out which changeset in
1277 the changegroup a particular filenode or manifestnode belongs to.
1277 the changegroup a particular filenode or manifestnode belongs to.
1278
1278
1279 The caller can specify some nodes that must be included in the
1279 The caller can specify some nodes that must be included in the
1280 changegroup using the extranodes argument. It should be a dict
1280 changegroup using the extranodes argument. It should be a dict
1281 where the keys are the filenames (or 1 for the manifest), and the
1281 where the keys are the filenames (or 1 for the manifest), and the
1282 values are lists of (node, linknode) tuples, where node is a wanted
1282 values are lists of (node, linknode) tuples, where node is a wanted
1283 node and linknode is the changelog node that should be transmitted as
1283 node and linknode is the changelog node that should be transmitted as
1284 the linkrev.
1284 the linkrev.
1285 """
1285 """
1286
1286
1287 # Set up some initial variables
1287 # Set up some initial variables
1288 # Make it easy to refer to self.changelog
1288 # Make it easy to refer to self.changelog
1289 cl = self.changelog
1289 cl = self.changelog
1290 # Compute the list of changesets in this changegroup.
1290 # Compute the list of changesets in this changegroup.
1291 # Some bases may turn out to be superfluous, and some heads may be
1291 # Some bases may turn out to be superfluous, and some heads may be
1292 # too. nodesbetween will return the minimal set of bases and heads
1292 # too. nodesbetween will return the minimal set of bases and heads
1293 # necessary to re-create the changegroup.
1293 # necessary to re-create the changegroup.
1294 if not bases:
1294 if not bases:
1295 bases = [nullid]
1295 bases = [nullid]
1296 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1296 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1297
1297
1298 if extranodes is None:
1298 if extranodes is None:
1299 # can we go through the fast path ?
1299 # can we go through the fast path ?
1300 heads.sort()
1300 heads.sort()
1301 allheads = self.heads()
1301 allheads = self.heads()
1302 allheads.sort()
1302 allheads.sort()
1303 if heads == allheads:
1303 if heads == allheads:
1304 return self._changegroup(msng_cl_lst, source)
1304 return self._changegroup(msng_cl_lst, source)
1305
1305
1306 # slow path
1306 # slow path
1307 self.hook('preoutgoing', throw=True, source=source)
1307 self.hook('preoutgoing', throw=True, source=source)
1308
1308
1309 self.changegroupinfo(msng_cl_lst, source)
1309 self.changegroupinfo(msng_cl_lst, source)
1310
1310
1311 # We assume that all ancestors of bases are known
1311 # We assume that all ancestors of bases are known
1312 commonrevs = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1312 commonrevs = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1313
1313
1314 # Make it easy to refer to self.manifest
1314 # Make it easy to refer to self.manifest
1315 mnfst = self.manifest
1315 mnfst = self.manifest
1316 # We don't know which manifests are missing yet
1316 # We don't know which manifests are missing yet
1317 msng_mnfst_set = {}
1317 msng_mnfst_set = {}
1318 # Nor do we know which filenodes are missing.
1318 # Nor do we know which filenodes are missing.
1319 msng_filenode_set = {}
1319 msng_filenode_set = {}
1320
1320
1321 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1321 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1322 junk = None
1322 junk = None
1323
1323
1324 # A changeset always belongs to itself, so the changenode lookup
1324 # A changeset always belongs to itself, so the changenode lookup
1325 # function for a changenode is identity.
1325 # function for a changenode is identity.
1326 def identity(x):
1326 def identity(x):
1327 return x
1327 return x
1328
1328
1329 # A function generating function that sets up the initial environment
1329 # A function generating function that sets up the initial environment
1330 # the inner function.
1330 # the inner function.
1331 def filenode_collector(changedfiles):
1331 def filenode_collector(changedfiles):
1332 # This gathers information from each manifestnode included in the
1332 # This gathers information from each manifestnode included in the
1333 # changegroup about which filenodes the manifest node references
1333 # changegroup about which filenodes the manifest node references
1334 # so we can include those in the changegroup too.
1334 # so we can include those in the changegroup too.
1335 #
1335 #
1336 # It also remembers which changenode each filenode belongs to. It
1336 # It also remembers which changenode each filenode belongs to. It
1337 # does this by assuming the a filenode belongs to the changenode
1337 # does this by assuming the a filenode belongs to the changenode
1338 # the first manifest that references it belongs to.
1338 # the first manifest that references it belongs to.
1339 def collect_msng_filenodes(mnfstnode):
1339 def collect_msng_filenodes(mnfstnode):
1340 r = mnfst.rev(mnfstnode)
1340 r = mnfst.rev(mnfstnode)
1341 if r - 1 in mnfst.parentrevs(r):
1341 if r - 1 in mnfst.parentrevs(r):
1342 # If the previous rev is one of the parents,
1342 # If the previous rev is one of the parents,
1343 # we only need to see a diff.
1343 # we only need to see a diff.
1344 deltamf = mnfst.readdelta(mnfstnode)
1344 deltamf = mnfst.readdelta(mnfstnode)
1345 # For each line in the delta
1345 # For each line in the delta
1346 for f, fnode in deltamf.iteritems():
1346 for f, fnode in deltamf.iteritems():
1347 # And if the file is in the list of files we care
1347 # And if the file is in the list of files we care
1348 # about.
1348 # about.
1349 if f in changedfiles:
1349 if f in changedfiles:
1350 # Get the changenode this manifest belongs to
1350 # Get the changenode this manifest belongs to
1351 clnode = msng_mnfst_set[mnfstnode]
1351 clnode = msng_mnfst_set[mnfstnode]
1352 # Create the set of filenodes for the file if
1352 # Create the set of filenodes for the file if
1353 # there isn't one already.
1353 # there isn't one already.
1354 ndset = msng_filenode_set.setdefault(f, {})
1354 ndset = msng_filenode_set.setdefault(f, {})
1355 # And set the filenode's changelog node to the
1355 # And set the filenode's changelog node to the
1356 # manifest's if it hasn't been set already.
1356 # manifest's if it hasn't been set already.
1357 ndset.setdefault(fnode, clnode)
1357 ndset.setdefault(fnode, clnode)
1358 else:
1358 else:
1359 # Otherwise we need a full manifest.
1359 # Otherwise we need a full manifest.
1360 m = mnfst.read(mnfstnode)
1360 m = mnfst.read(mnfstnode)
1361 # For every file in we care about.
1361 # For every file in we care about.
1362 for f in changedfiles:
1362 for f in changedfiles:
1363 fnode = m.get(f, None)
1363 fnode = m.get(f, None)
1364 # If it's in the manifest
1364 # If it's in the manifest
1365 if fnode is not None:
1365 if fnode is not None:
1366 # See comments above.
1366 # See comments above.
1367 clnode = msng_mnfst_set[mnfstnode]
1367 clnode = msng_mnfst_set[mnfstnode]
1368 ndset = msng_filenode_set.setdefault(f, {})
1368 ndset = msng_filenode_set.setdefault(f, {})
1369 ndset.setdefault(fnode, clnode)
1369 ndset.setdefault(fnode, clnode)
1370 return collect_msng_filenodes
1370 return collect_msng_filenodes
1371
1371
1372 # If we determine that a particular file or manifest node must be a
1372 # If we determine that a particular file or manifest node must be a
1373 # node that the recipient of the changegroup will already have, we can
1373 # node that the recipient of the changegroup will already have, we can
1374 # also assume the recipient will have all the parents. This function
1374 # also assume the recipient will have all the parents. This function
1375 # prunes them from the set of missing nodes.
1375 # prunes them from the set of missing nodes.
1376 def prune(revlog, missingnodes):
1376 def prune(revlog, missingnodes):
1377 hasset = set()
1377 hasset = set()
1378 # If a 'missing' filenode thinks it belongs to a changenode we
1378 # If a 'missing' filenode thinks it belongs to a changenode we
1379 # assume the recipient must have, then the recipient must have
1379 # assume the recipient must have, then the recipient must have
1380 # that filenode.
1380 # that filenode.
1381 for n in missingnodes:
1381 for n in missingnodes:
1382 clrev = revlog.linkrev(revlog.rev(n))
1382 clrev = revlog.linkrev(revlog.rev(n))
1383 if clrev in commonrevs:
1383 if clrev in commonrevs:
1384 hasset.add(n)
1384 hasset.add(n)
1385 for n in hasset:
1385 for n in hasset:
1386 missingnodes.pop(n, None)
1386 missingnodes.pop(n, None)
1387 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1387 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1388 missingnodes.pop(revlog.node(r), None)
1388 missingnodes.pop(revlog.node(r), None)
1389
1389
1390 # Add the nodes that were explicitly requested.
1390 # Add the nodes that were explicitly requested.
1391 def add_extra_nodes(name, nodes):
1391 def add_extra_nodes(name, nodes):
1392 if not extranodes or name not in extranodes:
1392 if not extranodes or name not in extranodes:
1393 return
1393 return
1394
1394
1395 for node, linknode in extranodes[name]:
1395 for node, linknode in extranodes[name]:
1396 if node not in nodes:
1396 if node not in nodes:
1397 nodes[node] = linknode
1397 nodes[node] = linknode
1398
1398
1399 # Now that we have all theses utility functions to help out and
1399 # Now that we have all theses utility functions to help out and
1400 # logically divide up the task, generate the group.
1400 # logically divide up the task, generate the group.
1401 def gengroup():
1401 def gengroup():
1402 # The set of changed files starts empty.
1402 # The set of changed files starts empty.
1403 changedfiles = set()
1403 changedfiles = set()
1404 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1404 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1405
1405
1406 # Create a changenode group generator that will call our functions
1406 # Create a changenode group generator that will call our functions
1407 # back to lookup the owning changenode and collect information.
1407 # back to lookup the owning changenode and collect information.
1408 group = cl.group(msng_cl_lst, identity, collect)
1408 group = cl.group(msng_cl_lst, identity, collect)
1409 for cnt, chnk in enumerate(group):
1409 for cnt, chnk in enumerate(group):
1410 yield chnk
1410 yield chnk
1411 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1411 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1412 self.ui.progress(_('bundling changes'), None)
1412 self.ui.progress(_('bundling changes'), None)
1413
1413
1414 prune(mnfst, msng_mnfst_set)
1414 prune(mnfst, msng_mnfst_set)
1415 add_extra_nodes(1, msng_mnfst_set)
1415 add_extra_nodes(1, msng_mnfst_set)
1416 msng_mnfst_lst = msng_mnfst_set.keys()
1416 msng_mnfst_lst = msng_mnfst_set.keys()
1417 # Sort the manifestnodes by revision number.
1417 # Sort the manifestnodes by revision number.
1418 msng_mnfst_lst.sort(key=mnfst.rev)
1418 msng_mnfst_lst.sort(key=mnfst.rev)
1419 # Create a generator for the manifestnodes that calls our lookup
1419 # Create a generator for the manifestnodes that calls our lookup
1420 # and data collection functions back.
1420 # and data collection functions back.
1421 group = mnfst.group(msng_mnfst_lst,
1421 group = mnfst.group(msng_mnfst_lst,
1422 lambda mnode: msng_mnfst_set[mnode],
1422 lambda mnode: msng_mnfst_set[mnode],
1423 filenode_collector(changedfiles))
1423 filenode_collector(changedfiles))
1424 for cnt, chnk in enumerate(group):
1424 for cnt, chnk in enumerate(group):
1425 yield chnk
1425 yield chnk
1426 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1426 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1427 self.ui.progress(_('bundling manifests'), None)
1427 self.ui.progress(_('bundling manifests'), None)
1428
1428
1429 # These are no longer needed, dereference and toss the memory for
1429 # These are no longer needed, dereference and toss the memory for
1430 # them.
1430 # them.
1431 msng_mnfst_lst = None
1431 msng_mnfst_lst = None
1432 msng_mnfst_set.clear()
1432 msng_mnfst_set.clear()
1433
1433
1434 if extranodes:
1434 if extranodes:
1435 for fname in extranodes:
1435 for fname in extranodes:
1436 if isinstance(fname, int):
1436 if isinstance(fname, int):
1437 continue
1437 continue
1438 msng_filenode_set.setdefault(fname, {})
1438 msng_filenode_set.setdefault(fname, {})
1439 changedfiles.add(fname)
1439 changedfiles.add(fname)
1440 # Go through all our files in order sorted by name.
1440 # Go through all our files in order sorted by name.
1441 cnt = 0
1441 cnt = 0
1442 for fname in sorted(changedfiles):
1442 for fname in sorted(changedfiles):
1443 filerevlog = self.file(fname)
1443 filerevlog = self.file(fname)
1444 if not len(filerevlog):
1444 if not len(filerevlog):
1445 raise util.Abort(_("empty or missing revlog for %s") % fname)
1445 raise util.Abort(_("empty or missing revlog for %s") % fname)
1446 # Toss out the filenodes that the recipient isn't really
1446 # Toss out the filenodes that the recipient isn't really
1447 # missing.
1447 # missing.
1448 missingfnodes = msng_filenode_set.pop(fname, {})
1448 missingfnodes = msng_filenode_set.pop(fname, {})
1449 prune(filerevlog, missingfnodes)
1449 prune(filerevlog, missingfnodes)
1450 add_extra_nodes(fname, missingfnodes)
1450 add_extra_nodes(fname, missingfnodes)
1451 # If any filenodes are left, generate the group for them,
1451 # If any filenodes are left, generate the group for them,
1452 # otherwise don't bother.
1452 # otherwise don't bother.
1453 if missingfnodes:
1453 if missingfnodes:
1454 yield changegroup.chunkheader(len(fname))
1454 yield changegroup.chunkheader(len(fname))
1455 yield fname
1455 yield fname
1456 # Sort the filenodes by their revision # (topological order)
1456 # Sort the filenodes by their revision # (topological order)
1457 nodeiter = list(missingfnodes)
1457 nodeiter = list(missingfnodes)
1458 nodeiter.sort(key=filerevlog.rev)
1458 nodeiter.sort(key=filerevlog.rev)
1459 # Create a group generator and only pass in a changenode
1459 # Create a group generator and only pass in a changenode
1460 # lookup function as we need to collect no information
1460 # lookup function as we need to collect no information
1461 # from filenodes.
1461 # from filenodes.
1462 group = filerevlog.group(nodeiter,
1462 group = filerevlog.group(nodeiter,
1463 lambda fnode: missingfnodes[fnode])
1463 lambda fnode: missingfnodes[fnode])
1464 for chnk in group:
1464 for chnk in group:
1465 self.ui.progress(
1465 self.ui.progress(
1466 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1466 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1467 cnt += 1
1467 cnt += 1
1468 yield chnk
1468 yield chnk
1469 # Signal that no more groups are left.
1469 # Signal that no more groups are left.
1470 yield changegroup.closechunk()
1470 yield changegroup.closechunk()
1471 self.ui.progress(_('bundling files'), None)
1471 self.ui.progress(_('bundling files'), None)
1472
1472
1473 if msng_cl_lst:
1473 if msng_cl_lst:
1474 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1474 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1475
1475
1476 return util.chunkbuffer(gengroup())
1476 return util.chunkbuffer(gengroup())
1477
1477
1478 def changegroup(self, basenodes, source):
1478 def changegroup(self, basenodes, source):
1479 # to avoid a race we use changegroupsubset() (issue1320)
1479 # to avoid a race we use changegroupsubset() (issue1320)
1480 return self.changegroupsubset(basenodes, self.heads(), source)
1480 return self.changegroupsubset(basenodes, self.heads(), source)
1481
1481
1482 def _changegroup(self, nodes, source):
1482 def _changegroup(self, nodes, source):
1483 """Compute the changegroup of all nodes that we have that a recipient
1483 """Compute the changegroup of all nodes that we have that a recipient
1484 doesn't. Return a chunkbuffer object whose read() method will return
1484 doesn't. Return a chunkbuffer object whose read() method will return
1485 successive changegroup chunks.
1485 successive changegroup chunks.
1486
1486
1487 This is much easier than the previous function as we can assume that
1487 This is much easier than the previous function as we can assume that
1488 the recipient has any changenode we aren't sending them.
1488 the recipient has any changenode we aren't sending them.
1489
1489
1490 nodes is the set of nodes to send"""
1490 nodes is the set of nodes to send"""
1491
1491
1492 self.hook('preoutgoing', throw=True, source=source)
1492 self.hook('preoutgoing', throw=True, source=source)
1493
1493
1494 cl = self.changelog
1494 cl = self.changelog
1495 revset = set([cl.rev(n) for n in nodes])
1495 revset = set([cl.rev(n) for n in nodes])
1496 self.changegroupinfo(nodes, source)
1496 self.changegroupinfo(nodes, source)
1497
1497
1498 def identity(x):
1498 def identity(x):
1499 return x
1499 return x
1500
1500
1501 def gennodelst(log):
1501 def gennodelst(log):
1502 for r in log:
1502 for r in log:
1503 if log.linkrev(r) in revset:
1503 if log.linkrev(r) in revset:
1504 yield log.node(r)
1504 yield log.node(r)
1505
1505
1506 def lookuplinkrev_func(revlog):
1506 def lookuplinkrev_func(revlog):
1507 def lookuplinkrev(n):
1507 def lookuplinkrev(n):
1508 return cl.node(revlog.linkrev(revlog.rev(n)))
1508 return cl.node(revlog.linkrev(revlog.rev(n)))
1509 return lookuplinkrev
1509 return lookuplinkrev
1510
1510
1511 def gengroup():
1511 def gengroup():
1512 '''yield a sequence of changegroup chunks (strings)'''
1512 '''yield a sequence of changegroup chunks (strings)'''
1513 # construct a list of all changed files
1513 # construct a list of all changed files
1514 changedfiles = set()
1514 changedfiles = set()
1515 mmfs = {}
1515 mmfs = {}
1516 collect = changegroup.collector(cl, mmfs, changedfiles)
1516 collect = changegroup.collector(cl, mmfs, changedfiles)
1517
1517
1518 for cnt, chnk in enumerate(cl.group(nodes, identity, collect)):
1518 for cnt, chnk in enumerate(cl.group(nodes, identity, collect)):
1519 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1519 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1520 yield chnk
1520 yield chnk
1521 self.ui.progress(_('bundling changes'), None)
1521 self.ui.progress(_('bundling changes'), None)
1522
1522
1523 mnfst = self.manifest
1523 mnfst = self.manifest
1524 nodeiter = gennodelst(mnfst)
1524 nodeiter = gennodelst(mnfst)
1525 for cnt, chnk in enumerate(mnfst.group(nodeiter,
1525 for cnt, chnk in enumerate(mnfst.group(nodeiter,
1526 lookuplinkrev_func(mnfst))):
1526 lookuplinkrev_func(mnfst))):
1527 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1527 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1528 yield chnk
1528 yield chnk
1529 self.ui.progress(_('bundling manifests'), None)
1529 self.ui.progress(_('bundling manifests'), None)
1530
1530
1531 cnt = 0
1531 cnt = 0
1532 for fname in sorted(changedfiles):
1532 for fname in sorted(changedfiles):
1533 filerevlog = self.file(fname)
1533 filerevlog = self.file(fname)
1534 if not len(filerevlog):
1534 if not len(filerevlog):
1535 raise util.Abort(_("empty or missing revlog for %s") % fname)
1535 raise util.Abort(_("empty or missing revlog for %s") % fname)
1536 nodeiter = gennodelst(filerevlog)
1536 nodeiter = gennodelst(filerevlog)
1537 nodeiter = list(nodeiter)
1537 nodeiter = list(nodeiter)
1538 if nodeiter:
1538 if nodeiter:
1539 yield changegroup.chunkheader(len(fname))
1539 yield changegroup.chunkheader(len(fname))
1540 yield fname
1540 yield fname
1541 lookup = lookuplinkrev_func(filerevlog)
1541 lookup = lookuplinkrev_func(filerevlog)
1542 for chnk in filerevlog.group(nodeiter, lookup):
1542 for chnk in filerevlog.group(nodeiter, lookup):
1543 self.ui.progress(
1543 self.ui.progress(
1544 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1544 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1545 cnt += 1
1545 cnt += 1
1546 yield chnk
1546 yield chnk
1547 self.ui.progress(_('bundling files'), None)
1547 self.ui.progress(_('bundling files'), None)
1548
1548
1549 yield changegroup.closechunk()
1549 yield changegroup.closechunk()
1550
1550
1551 if nodes:
1551 if nodes:
1552 self.hook('outgoing', node=hex(nodes[0]), source=source)
1552 self.hook('outgoing', node=hex(nodes[0]), source=source)
1553
1553
1554 return util.chunkbuffer(gengroup())
1554 return util.chunkbuffer(gengroup())
1555
1555
1556 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1556 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1557 """Add the changegroup returned by source.read() to this repo.
1557 """Add the changegroup returned by source.read() to this repo.
1558 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1558 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1559 the URL of the repo where this changegroup is coming from.
1559 the URL of the repo where this changegroup is coming from.
1560
1560
1561 Return an integer summarizing the change to this repo:
1561 Return an integer summarizing the change to this repo:
1562 - nothing changed or no source: 0
1562 - nothing changed or no source: 0
1563 - more heads than before: 1+added heads (2..n)
1563 - more heads than before: 1+added heads (2..n)
1564 - fewer heads than before: -1-removed heads (-2..-n)
1564 - fewer heads than before: -1-removed heads (-2..-n)
1565 - number of heads stays the same: 1
1565 - number of heads stays the same: 1
1566 """
1566 """
1567 def csmap(x):
1567 def csmap(x):
1568 self.ui.debug("add changeset %s\n" % short(x))
1568 self.ui.debug("add changeset %s\n" % short(x))
1569 return len(cl)
1569 return len(cl)
1570
1570
1571 def revmap(x):
1571 def revmap(x):
1572 return cl.rev(x)
1572 return cl.rev(x)
1573
1573
1574 if not source:
1574 if not source:
1575 return 0
1575 return 0
1576
1576
1577 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1577 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1578
1578
1579 changesets = files = revisions = 0
1579 changesets = files = revisions = 0
1580 efiles = set()
1580 efiles = set()
1581
1581
1582 # write changelog data to temp files so concurrent readers will not see
1582 # write changelog data to temp files so concurrent readers will not see
1583 # inconsistent view
1583 # inconsistent view
1584 cl = self.changelog
1584 cl = self.changelog
1585 cl.delayupdate()
1585 cl.delayupdate()
1586 oldheads = len(cl.heads())
1586 oldheads = len(cl.heads())
1587
1587
1588 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
1588 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
1589 try:
1589 try:
1590 trp = weakref.proxy(tr)
1590 trp = weakref.proxy(tr)
1591 # pull off the changeset group
1591 # pull off the changeset group
1592 self.ui.status(_("adding changesets\n"))
1592 self.ui.status(_("adding changesets\n"))
1593 clstart = len(cl)
1593 clstart = len(cl)
1594 class prog(object):
1594 class prog(object):
1595 step = _('changesets')
1595 step = _('changesets')
1596 count = 1
1596 count = 1
1597 ui = self.ui
1597 ui = self.ui
1598 total = None
1598 total = None
1599 def __call__(self):
1599 def __call__(self):
1600 self.ui.progress(self.step, self.count, unit=_('chunks'),
1600 self.ui.progress(self.step, self.count, unit=_('chunks'),
1601 total=self.total)
1601 total=self.total)
1602 self.count += 1
1602 self.count += 1
1603 pr = prog()
1603 pr = prog()
1604 chunkiter = changegroup.chunkiter(source, progress=pr)
1604 chunkiter = changegroup.chunkiter(source, progress=pr)
1605 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
1605 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
1606 raise util.Abort(_("received changelog group is empty"))
1606 raise util.Abort(_("received changelog group is empty"))
1607 clend = len(cl)
1607 clend = len(cl)
1608 changesets = clend - clstart
1608 changesets = clend - clstart
1609 for c in xrange(clstart, clend):
1609 for c in xrange(clstart, clend):
1610 efiles.update(self[c].files())
1610 efiles.update(self[c].files())
1611 efiles = len(efiles)
1611 efiles = len(efiles)
1612 self.ui.progress(_('changesets'), None)
1612 self.ui.progress(_('changesets'), None)
1613
1613
1614 # pull off the manifest group
1614 # pull off the manifest group
1615 self.ui.status(_("adding manifests\n"))
1615 self.ui.status(_("adding manifests\n"))
1616 pr.step = _('manifests')
1616 pr.step = _('manifests')
1617 pr.count = 1
1617 pr.count = 1
1618 pr.total = changesets # manifests <= changesets
1618 pr.total = changesets # manifests <= changesets
1619 chunkiter = changegroup.chunkiter(source, progress=pr)
1619 chunkiter = changegroup.chunkiter(source, progress=pr)
1620 # no need to check for empty manifest group here:
1620 # no need to check for empty manifest group here:
1621 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1621 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1622 # no new manifest will be created and the manifest group will
1622 # no new manifest will be created and the manifest group will
1623 # be empty during the pull
1623 # be empty during the pull
1624 self.manifest.addgroup(chunkiter, revmap, trp)
1624 self.manifest.addgroup(chunkiter, revmap, trp)
1625 self.ui.progress(_('manifests'), None)
1625 self.ui.progress(_('manifests'), None)
1626
1626
1627 needfiles = {}
1627 needfiles = {}
1628 if self.ui.configbool('server', 'validate', default=False):
1628 if self.ui.configbool('server', 'validate', default=False):
1629 # validate incoming csets have their manifests
1629 # validate incoming csets have their manifests
1630 for cset in xrange(clstart, clend):
1630 for cset in xrange(clstart, clend):
1631 mfest = self.changelog.read(self.changelog.node(cset))[0]
1631 mfest = self.changelog.read(self.changelog.node(cset))[0]
1632 mfest = self.manifest.readdelta(mfest)
1632 mfest = self.manifest.readdelta(mfest)
1633 # store file nodes we must see
1633 # store file nodes we must see
1634 for f, n in mfest.iteritems():
1634 for f, n in mfest.iteritems():
1635 needfiles.setdefault(f, set()).add(n)
1635 needfiles.setdefault(f, set()).add(n)
1636
1636
1637 # process the files
1637 # process the files
1638 self.ui.status(_("adding file changes\n"))
1638 self.ui.status(_("adding file changes\n"))
1639 pr.step = 'files'
1639 pr.step = 'files'
1640 pr.count = 1
1640 pr.count = 1
1641 pr.total = efiles
1641 pr.total = efiles
1642 while 1:
1642 while 1:
1643 f = changegroup.getchunk(source)
1643 f = changegroup.getchunk(source)
1644 if not f:
1644 if not f:
1645 break
1645 break
1646 self.ui.debug("adding %s revisions\n" % f)
1646 self.ui.debug("adding %s revisions\n" % f)
1647 pr()
1647 pr()
1648 fl = self.file(f)
1648 fl = self.file(f)
1649 o = len(fl)
1649 o = len(fl)
1650 chunkiter = changegroup.chunkiter(source)
1650 chunkiter = changegroup.chunkiter(source)
1651 if fl.addgroup(chunkiter, revmap, trp) is None:
1651 if fl.addgroup(chunkiter, revmap, trp) is None:
1652 raise util.Abort(_("received file revlog group is empty"))
1652 raise util.Abort(_("received file revlog group is empty"))
1653 revisions += len(fl) - o
1653 revisions += len(fl) - o
1654 files += 1
1654 files += 1
1655 if f in needfiles:
1655 if f in needfiles:
1656 needs = needfiles[f]
1656 needs = needfiles[f]
1657 for new in xrange(o, len(fl)):
1657 for new in xrange(o, len(fl)):
1658 n = fl.node(new)
1658 n = fl.node(new)
1659 if n in needs:
1659 if n in needs:
1660 needs.remove(n)
1660 needs.remove(n)
1661 if not needs:
1661 if not needs:
1662 del needfiles[f]
1662 del needfiles[f]
1663 self.ui.progress(_('files'), None)
1663 self.ui.progress(_('files'), None)
1664
1664
1665 for f, needs in needfiles.iteritems():
1665 for f, needs in needfiles.iteritems():
1666 fl = self.file(f)
1666 fl = self.file(f)
1667 for n in needs:
1667 for n in needs:
1668 try:
1668 try:
1669 fl.rev(n)
1669 fl.rev(n)
1670 except error.LookupError:
1670 except error.LookupError:
1671 raise util.Abort(
1671 raise util.Abort(
1672 _('missing file data for %s:%s - run hg verify') %
1672 _('missing file data for %s:%s - run hg verify') %
1673 (f, hex(n)))
1673 (f, hex(n)))
1674
1674
1675 newheads = len(cl.heads())
1675 newheads = len(cl.heads())
1676 heads = ""
1676 heads = ""
1677 if oldheads and newheads != oldheads:
1677 if oldheads and newheads != oldheads:
1678 heads = _(" (%+d heads)") % (newheads - oldheads)
1678 heads = _(" (%+d heads)") % (newheads - oldheads)
1679
1679
1680 self.ui.status(_("added %d changesets"
1680 self.ui.status(_("added %d changesets"
1681 " with %d changes to %d files%s\n")
1681 " with %d changes to %d files%s\n")
1682 % (changesets, revisions, files, heads))
1682 % (changesets, revisions, files, heads))
1683
1683
1684 if changesets > 0:
1684 if changesets > 0:
1685 p = lambda: cl.writepending() and self.root or ""
1685 p = lambda: cl.writepending() and self.root or ""
1686 self.hook('pretxnchangegroup', throw=True,
1686 self.hook('pretxnchangegroup', throw=True,
1687 node=hex(cl.node(clstart)), source=srctype,
1687 node=hex(cl.node(clstart)), source=srctype,
1688 url=url, pending=p)
1688 url=url, pending=p)
1689
1689
1690 # make changelog see real files again
1690 # make changelog see real files again
1691 cl.finalize(trp)
1691 cl.finalize(trp)
1692
1692
1693 tr.close()
1693 tr.close()
1694 finally:
1694 finally:
1695 tr.release()
1695 tr.release()
1696 if lock:
1696 if lock:
1697 lock.release()
1697 lock.release()
1698
1698
1699 if changesets > 0:
1699 if changesets > 0:
1700 # forcefully update the on-disk branch cache
1700 # forcefully update the on-disk branch cache
1701 self.ui.debug("updating the branch cache\n")
1701 self.ui.debug("updating the branch cache\n")
1702 self.branchtags()
1702 self.branchtags()
1703 self.hook("changegroup", node=hex(cl.node(clstart)),
1703 self.hook("changegroup", node=hex(cl.node(clstart)),
1704 source=srctype, url=url)
1704 source=srctype, url=url)
1705
1705
1706 for i in xrange(clstart, clend):
1706 for i in xrange(clstart, clend):
1707 self.hook("incoming", node=hex(cl.node(i)),
1707 self.hook("incoming", node=hex(cl.node(i)),
1708 source=srctype, url=url)
1708 source=srctype, url=url)
1709
1709
1710 # never return 0 here:
1710 # never return 0 here:
1711 if newheads < oldheads:
1711 if newheads < oldheads:
1712 return newheads - oldheads - 1
1712 return newheads - oldheads - 1
1713 else:
1713 else:
1714 return newheads - oldheads + 1
1714 return newheads - oldheads + 1
1715
1715
1716
1716
1717 def stream_in(self, remote):
1717 def stream_in(self, remote):
1718 fp = remote.stream_out()
1718 fp = remote.stream_out()
1719 l = fp.readline()
1719 l = fp.readline()
1720 try:
1720 try:
1721 resp = int(l)
1721 resp = int(l)
1722 except ValueError:
1722 except ValueError:
1723 raise error.ResponseError(
1723 raise error.ResponseError(
1724 _('Unexpected response from remote server:'), l)
1724 _('Unexpected response from remote server:'), l)
1725 if resp == 1:
1725 if resp == 1:
1726 raise util.Abort(_('operation forbidden by server'))
1726 raise util.Abort(_('operation forbidden by server'))
1727 elif resp == 2:
1727 elif resp == 2:
1728 raise util.Abort(_('locking the remote repository failed'))
1728 raise util.Abort(_('locking the remote repository failed'))
1729 elif resp != 0:
1729 elif resp != 0:
1730 raise util.Abort(_('the server sent an unknown error code'))
1730 raise util.Abort(_('the server sent an unknown error code'))
1731 self.ui.status(_('streaming all changes\n'))
1731 self.ui.status(_('streaming all changes\n'))
1732 l = fp.readline()
1732 l = fp.readline()
1733 try:
1733 try:
1734 total_files, total_bytes = map(int, l.split(' ', 1))
1734 total_files, total_bytes = map(int, l.split(' ', 1))
1735 except (ValueError, TypeError):
1735 except (ValueError, TypeError):
1736 raise error.ResponseError(
1736 raise error.ResponseError(
1737 _('Unexpected response from remote server:'), l)
1737 _('Unexpected response from remote server:'), l)
1738 self.ui.status(_('%d files to transfer, %s of data\n') %
1738 self.ui.status(_('%d files to transfer, %s of data\n') %
1739 (total_files, util.bytecount(total_bytes)))
1739 (total_files, util.bytecount(total_bytes)))
1740 start = time.time()
1740 start = time.time()
1741 for i in xrange(total_files):
1741 for i in xrange(total_files):
1742 # XXX doesn't support '\n' or '\r' in filenames
1742 # XXX doesn't support '\n' or '\r' in filenames
1743 l = fp.readline()
1743 l = fp.readline()
1744 try:
1744 try:
1745 name, size = l.split('\0', 1)
1745 name, size = l.split('\0', 1)
1746 size = int(size)
1746 size = int(size)
1747 except (ValueError, TypeError):
1747 except (ValueError, TypeError):
1748 raise error.ResponseError(
1748 raise error.ResponseError(
1749 _('Unexpected response from remote server:'), l)
1749 _('Unexpected response from remote server:'), l)
1750 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1750 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1751 # for backwards compat, name was partially encoded
1751 # for backwards compat, name was partially encoded
1752 ofp = self.sopener(store.decodedir(name), 'w')
1752 ofp = self.sopener(store.decodedir(name), 'w')
1753 for chunk in util.filechunkiter(fp, limit=size):
1753 for chunk in util.filechunkiter(fp, limit=size):
1754 ofp.write(chunk)
1754 ofp.write(chunk)
1755 ofp.close()
1755 ofp.close()
1756 elapsed = time.time() - start
1756 elapsed = time.time() - start
1757 if elapsed <= 0:
1757 if elapsed <= 0:
1758 elapsed = 0.001
1758 elapsed = 0.001
1759 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1759 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1760 (util.bytecount(total_bytes), elapsed,
1760 (util.bytecount(total_bytes), elapsed,
1761 util.bytecount(total_bytes / elapsed)))
1761 util.bytecount(total_bytes / elapsed)))
1762 self.invalidate()
1762 self.invalidate()
1763 return len(self.heads()) + 1
1763 return len(self.heads()) + 1
1764
1764
1765 def clone(self, remote, heads=[], stream=False):
1765 def clone(self, remote, heads=[], stream=False):
1766 '''clone remote repository.
1766 '''clone remote repository.
1767
1767
1768 keyword arguments:
1768 keyword arguments:
1769 heads: list of revs to clone (forces use of pull)
1769 heads: list of revs to clone (forces use of pull)
1770 stream: use streaming clone if possible'''
1770 stream: use streaming clone if possible'''
1771
1771
1772 # now, all clients that can request uncompressed clones can
1772 # now, all clients that can request uncompressed clones can
1773 # read repo formats supported by all servers that can serve
1773 # read repo formats supported by all servers that can serve
1774 # them.
1774 # them.
1775
1775
1776 # if revlog format changes, client will have to check version
1776 # if revlog format changes, client will have to check version
1777 # and format flags on "stream" capability, and use
1777 # and format flags on "stream" capability, and use
1778 # uncompressed only if compatible.
1778 # uncompressed only if compatible.
1779
1779
1780 if stream and not heads and remote.capable('stream'):
1780 if stream and not heads and remote.capable('stream'):
1781 return self.stream_in(remote)
1781 return self.stream_in(remote)
1782 return self.pull(remote, heads)
1782 return self.pull(remote, heads)
1783
1783
1784 def pushkey(self, namespace, key, old, new):
1784 def pushkey(self, namespace, key, old, new):
1785 return pushkey.push(self, namespace, key, old, new)
1785 return pushkey.push(self, namespace, key, old, new)
1786
1786
1787 def listkeys(self, namespace):
1787 def listkeys(self, namespace):
1788 return pushkey.list(self, namespace)
1788 return pushkey.list(self, namespace)
1789
1789
1790 # used to avoid circular references so destructors work
1790 # used to avoid circular references so destructors work
1791 def aftertrans(files):
1791 def aftertrans(files):
1792 renamefiles = [tuple(t) for t in files]
1792 renamefiles = [tuple(t) for t in files]
1793 def a():
1793 def a():
1794 for src, dest in renamefiles:
1794 for src, dest in renamefiles:
1795 util.rename(src, dest)
1795 util.rename(src, dest)
1796 return a
1796 return a
1797
1797
1798 def instance(ui, path, create):
1798 def instance(ui, path, create):
1799 return localrepository(ui, util.drop_scheme('file', path), create)
1799 return localrepository(ui, util.drop_scheme('file', path), create)
1800
1800
1801 def islocal(path):
1801 def islocal(path):
1802 return True
1802 return True
@@ -1,527 +1,527 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 util, filemerge, copies, subrepo
10 import 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._read()
17 self._read()
18 def reset(self, node=None):
18 def reset(self, node=None):
19 self._state = {}
19 self._state = {}
20 if node:
20 if node:
21 self._local = node
21 self._local = node
22 shutil.rmtree(self._repo.join("merge"), True)
22 shutil.rmtree(self._repo.join("merge"), True)
23 def _read(self):
23 def _read(self):
24 self._state = {}
24 self._state = {}
25 try:
25 try:
26 f = self._repo.opener("merge/state")
26 f = self._repo.opener("merge/state")
27 for i, l in enumerate(f):
27 for i, l in enumerate(f):
28 if i == 0:
28 if i == 0:
29 self._local = bin(l[:-1])
29 self._local = bin(l[:-1])
30 else:
30 else:
31 bits = l[:-1].split("\0")
31 bits = l[:-1].split("\0")
32 self._state[bits[0]] = bits[1:]
32 self._state[bits[0]] = bits[1:]
33 except IOError, err:
33 except IOError, err:
34 if err.errno != errno.ENOENT:
34 if err.errno != errno.ENOENT:
35 raise
35 raise
36 def _write(self):
36 def _write(self):
37 f = self._repo.opener("merge/state", "w")
37 f = self._repo.opener("merge/state", "w")
38 f.write(hex(self._local) + "\n")
38 f.write(hex(self._local) + "\n")
39 for d, v in self._state.iteritems():
39 for d, v in self._state.iteritems():
40 f.write("\0".join([d] + v) + "\n")
40 f.write("\0".join([d] + v) + "\n")
41 def add(self, fcl, fco, fca, fd, flags):
41 def add(self, fcl, fco, fca, fd, flags):
42 hash = util.sha1(fcl.path()).hexdigest()
42 hash = util.sha1(fcl.path()).hexdigest()
43 self._repo.opener("merge/" + hash, "w").write(fcl.data())
43 self._repo.opener("merge/" + hash, "w").write(fcl.data())
44 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
44 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
45 hex(fca.filenode()), fco.path(), flags]
45 hex(fca.filenode()), fco.path(), flags]
46 self._write()
46 self._write()
47 def __contains__(self, dfile):
47 def __contains__(self, dfile):
48 return dfile in self._state
48 return dfile in self._state
49 def __getitem__(self, dfile):
49 def __getitem__(self, dfile):
50 return self._state[dfile][0]
50 return self._state[dfile][0]
51 def __iter__(self):
51 def __iter__(self):
52 l = self._state.keys()
52 l = self._state.keys()
53 l.sort()
53 l.sort()
54 for f in l:
54 for f in l:
55 yield f
55 yield f
56 def mark(self, dfile, state):
56 def mark(self, dfile, state):
57 self._state[dfile][0] = state
57 self._state[dfile][0] = state
58 self._write()
58 self._write()
59 def resolve(self, dfile, wctx, octx):
59 def resolve(self, dfile, wctx, octx):
60 if self[dfile] == 'r':
60 if self[dfile] == 'r':
61 return 0
61 return 0
62 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
62 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
63 f = self._repo.opener("merge/" + hash)
63 f = self._repo.opener("merge/" + hash)
64 self._repo.wwrite(dfile, f.read(), flags)
64 self._repo.wwrite(dfile, f.read(), flags)
65 fcd = wctx[dfile]
65 fcd = wctx[dfile]
66 fco = octx[ofile]
66 fco = octx[ofile]
67 fca = self._repo.filectx(afile, fileid=anode)
67 fca = self._repo.filectx(afile, fileid=anode)
68 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
68 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
69 if not r:
69 if not r:
70 self.mark(dfile, 'r')
70 self.mark(dfile, 'r')
71 return r
71 return r
72
72
73 def _checkunknown(wctx, mctx):
73 def _checkunknown(wctx, mctx):
74 "check for collisions between unknown files and files in mctx"
74 "check for collisions between unknown files and files in mctx"
75 for f in wctx.unknown():
75 for f in wctx.unknown():
76 if f in mctx and mctx[f].cmp(wctx[f].data()):
76 if f in mctx and mctx[f].cmp(wctx[f]):
77 raise util.Abort(_("untracked file in working directory differs"
77 raise util.Abort(_("untracked file in working directory differs"
78 " from file in requested revision: '%s'") % f)
78 " from file in requested revision: '%s'") % f)
79
79
80 def _checkcollision(mctx):
80 def _checkcollision(mctx):
81 "check for case folding collisions in the destination context"
81 "check for case folding collisions in the destination context"
82 folded = {}
82 folded = {}
83 for fn in mctx:
83 for fn in mctx:
84 fold = fn.lower()
84 fold = fn.lower()
85 if fold in folded:
85 if fold in folded:
86 raise util.Abort(_("case-folding collision between %s and %s")
86 raise util.Abort(_("case-folding collision between %s and %s")
87 % (fn, folded[fold]))
87 % (fn, folded[fold]))
88 folded[fold] = fn
88 folded[fold] = fn
89
89
90 def _forgetremoved(wctx, mctx, branchmerge):
90 def _forgetremoved(wctx, mctx, branchmerge):
91 """
91 """
92 Forget removed files
92 Forget removed files
93
93
94 If we're jumping between revisions (as opposed to merging), and if
94 If we're jumping between revisions (as opposed to merging), and if
95 neither the working directory nor the target rev has the file,
95 neither the working directory nor the target rev has the file,
96 then we need to remove it from the dirstate, to prevent the
96 then we need to remove it from the dirstate, to prevent the
97 dirstate from listing the file when it is no longer in the
97 dirstate from listing the file when it is no longer in the
98 manifest.
98 manifest.
99
99
100 If we're merging, and the other revision has removed a file
100 If we're merging, and the other revision has removed a file
101 that is not present in the working directory, we need to mark it
101 that is not present in the working directory, we need to mark it
102 as removed.
102 as removed.
103 """
103 """
104
104
105 action = []
105 action = []
106 state = branchmerge and 'r' or 'f'
106 state = branchmerge and 'r' or 'f'
107 for f in wctx.deleted():
107 for f in wctx.deleted():
108 if f not in mctx:
108 if f not in mctx:
109 action.append((f, state))
109 action.append((f, state))
110
110
111 if not branchmerge:
111 if not branchmerge:
112 for f in wctx.removed():
112 for f in wctx.removed():
113 if f not in mctx:
113 if f not in mctx:
114 action.append((f, "f"))
114 action.append((f, "f"))
115
115
116 return action
116 return action
117
117
118 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
118 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
119 """
119 """
120 Merge p1 and p2 with ancestor ma and generate merge action list
120 Merge p1 and p2 with ancestor ma and generate merge action list
121
121
122 overwrite = whether we clobber working files
122 overwrite = whether we clobber working files
123 partial = function to filter file lists
123 partial = function to filter file lists
124 """
124 """
125
125
126 def fmerge(f, f2, fa):
126 def fmerge(f, f2, fa):
127 """merge flags"""
127 """merge flags"""
128 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
128 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
129 if m == n: # flags agree
129 if m == n: # flags agree
130 return m # unchanged
130 return m # unchanged
131 if m and n and not a: # flags set, don't agree, differ from parent
131 if m and n and not a: # flags set, don't agree, differ from parent
132 r = repo.ui.promptchoice(
132 r = repo.ui.promptchoice(
133 _(" conflicting flags for %s\n"
133 _(" conflicting flags for %s\n"
134 "(n)one, e(x)ec or sym(l)ink?") % f,
134 "(n)one, e(x)ec or sym(l)ink?") % f,
135 (_("&None"), _("E&xec"), _("Sym&link")), 0)
135 (_("&None"), _("E&xec"), _("Sym&link")), 0)
136 if r == 1:
136 if r == 1:
137 return "x" # Exec
137 return "x" # Exec
138 if r == 2:
138 if r == 2:
139 return "l" # Symlink
139 return "l" # Symlink
140 return ""
140 return ""
141 if m and m != a: # changed from a to m
141 if m and m != a: # changed from a to m
142 return m
142 return m
143 if n and n != a: # changed from a to n
143 if n and n != a: # changed from a to n
144 return n
144 return n
145 return '' # flag was cleared
145 return '' # flag was cleared
146
146
147 def act(msg, m, f, *args):
147 def act(msg, m, f, *args):
148 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
148 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
149 action.append((f, m) + args)
149 action.append((f, m) + args)
150
150
151 action, copy = [], {}
151 action, copy = [], {}
152
152
153 if overwrite:
153 if overwrite:
154 pa = p1
154 pa = p1
155 elif pa == p2: # backwards
155 elif pa == p2: # backwards
156 pa = p1.p1()
156 pa = p1.p1()
157 elif pa and repo.ui.configbool("merge", "followcopies", True):
157 elif pa and repo.ui.configbool("merge", "followcopies", True):
158 dirs = repo.ui.configbool("merge", "followdirs", True)
158 dirs = repo.ui.configbool("merge", "followdirs", True)
159 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
159 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
160 for of, fl in diverge.iteritems():
160 for of, fl in diverge.iteritems():
161 act("divergent renames", "dr", of, fl)
161 act("divergent renames", "dr", of, fl)
162
162
163 repo.ui.note(_("resolving manifests\n"))
163 repo.ui.note(_("resolving manifests\n"))
164 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
164 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
165 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
165 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
166
166
167 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
167 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
168 copied = set(copy.values())
168 copied = set(copy.values())
169
169
170 if '.hgsubstate' in m1:
170 if '.hgsubstate' in m1:
171 # check whether sub state is modified
171 # check whether sub state is modified
172 for s in p1.substate:
172 for s in p1.substate:
173 if p1.sub(s).dirty():
173 if p1.sub(s).dirty():
174 m1['.hgsubstate'] += "+"
174 m1['.hgsubstate'] += "+"
175 break
175 break
176
176
177 # Compare manifests
177 # Compare manifests
178 for f, n in m1.iteritems():
178 for f, n in m1.iteritems():
179 if partial and not partial(f):
179 if partial and not partial(f):
180 continue
180 continue
181 if f in m2:
181 if f in m2:
182 rflags = fmerge(f, f, f)
182 rflags = fmerge(f, f, f)
183 a = ma.get(f, nullid)
183 a = ma.get(f, nullid)
184 if n == m2[f] or m2[f] == a: # same or local newer
184 if n == m2[f] or m2[f] == a: # same or local newer
185 # is file locally modified or flags need changing?
185 # is file locally modified or flags need changing?
186 # dirstate flags may need to be made current
186 # dirstate flags may need to be made current
187 if m1.flags(f) != rflags or n[20:]:
187 if m1.flags(f) != rflags or n[20:]:
188 act("update permissions", "e", f, rflags)
188 act("update permissions", "e", f, rflags)
189 elif n == a: # remote newer
189 elif n == a: # remote newer
190 act("remote is newer", "g", f, rflags)
190 act("remote is newer", "g", f, rflags)
191 else: # both changed
191 else: # both changed
192 act("versions differ", "m", f, f, f, rflags, False)
192 act("versions differ", "m", f, f, f, rflags, False)
193 elif f in copied: # files we'll deal with on m2 side
193 elif f in copied: # files we'll deal with on m2 side
194 pass
194 pass
195 elif f in copy:
195 elif f in copy:
196 f2 = copy[f]
196 f2 = copy[f]
197 if f2 not in m2: # directory rename
197 if f2 not in m2: # directory rename
198 act("remote renamed directory to " + f2, "d",
198 act("remote renamed directory to " + f2, "d",
199 f, None, f2, m1.flags(f))
199 f, None, f2, m1.flags(f))
200 else: # case 2 A,B/B/B or case 4,21 A/B/B
200 else: # case 2 A,B/B/B or case 4,21 A/B/B
201 act("local copied/moved to " + f2, "m",
201 act("local copied/moved to " + f2, "m",
202 f, f2, f, fmerge(f, f2, f2), False)
202 f, f2, f, fmerge(f, f2, f2), False)
203 elif f in ma: # clean, a different, no remote
203 elif f in ma: # clean, a different, no remote
204 if n != ma[f]:
204 if n != ma[f]:
205 if repo.ui.promptchoice(
205 if repo.ui.promptchoice(
206 _(" local changed %s which remote deleted\n"
206 _(" local changed %s which remote deleted\n"
207 "use (c)hanged version or (d)elete?") % f,
207 "use (c)hanged version or (d)elete?") % f,
208 (_("&Changed"), _("&Delete")), 0):
208 (_("&Changed"), _("&Delete")), 0):
209 act("prompt delete", "r", f)
209 act("prompt delete", "r", f)
210 else:
210 else:
211 act("prompt keep", "a", f)
211 act("prompt keep", "a", f)
212 elif n[20:] == "a": # added, no remote
212 elif n[20:] == "a": # added, no remote
213 act("remote deleted", "f", f)
213 act("remote deleted", "f", f)
214 elif n[20:] != "u":
214 elif n[20:] != "u":
215 act("other deleted", "r", f)
215 act("other deleted", "r", f)
216
216
217 for f, n in m2.iteritems():
217 for f, n in m2.iteritems():
218 if partial and not partial(f):
218 if partial and not partial(f):
219 continue
219 continue
220 if f in m1 or f in copied: # files already visited
220 if f in m1 or f in copied: # files already visited
221 continue
221 continue
222 if f in copy:
222 if f in copy:
223 f2 = copy[f]
223 f2 = copy[f]
224 if f2 not in m1: # directory rename
224 if f2 not in m1: # directory rename
225 act("local renamed directory to " + f2, "d",
225 act("local renamed directory to " + f2, "d",
226 None, f, f2, m2.flags(f))
226 None, f, f2, m2.flags(f))
227 elif f2 in m2: # rename case 1, A/A,B/A
227 elif f2 in m2: # rename case 1, A/A,B/A
228 act("remote copied to " + f, "m",
228 act("remote copied to " + f, "m",
229 f2, f, f, fmerge(f2, f, f2), False)
229 f2, f, f, fmerge(f2, f, f2), False)
230 else: # case 3,20 A/B/A
230 else: # case 3,20 A/B/A
231 act("remote moved to " + f, "m",
231 act("remote moved to " + f, "m",
232 f2, f, f, fmerge(f2, f, f2), True)
232 f2, f, f, fmerge(f2, f, f2), True)
233 elif f not in ma:
233 elif f not in ma:
234 act("remote created", "g", f, m2.flags(f))
234 act("remote created", "g", f, m2.flags(f))
235 elif n != ma[f]:
235 elif n != ma[f]:
236 if repo.ui.promptchoice(
236 if repo.ui.promptchoice(
237 _("remote changed %s which local deleted\n"
237 _("remote changed %s which local deleted\n"
238 "use (c)hanged version or leave (d)eleted?") % f,
238 "use (c)hanged version or leave (d)eleted?") % f,
239 (_("&Changed"), _("&Deleted")), 0) == 0:
239 (_("&Changed"), _("&Deleted")), 0) == 0:
240 act("prompt recreating", "g", f, m2.flags(f))
240 act("prompt recreating", "g", f, m2.flags(f))
241
241
242 return action
242 return action
243
243
244 def actionkey(a):
244 def actionkey(a):
245 return a[1] == 'r' and -1 or 0, a
245 return a[1] == 'r' and -1 or 0, a
246
246
247 def applyupdates(repo, action, wctx, mctx, actx):
247 def applyupdates(repo, action, wctx, mctx, actx):
248 """apply the merge action list to the working directory
248 """apply the merge action list to the working directory
249
249
250 wctx is the working copy context
250 wctx is the working copy context
251 mctx is the context to be merged into the working copy
251 mctx is the context to be merged into the working copy
252 actx is the context of the common ancestor
252 actx is the context of the common ancestor
253 """
253 """
254
254
255 updated, merged, removed, unresolved = 0, 0, 0, 0
255 updated, merged, removed, unresolved = 0, 0, 0, 0
256 ms = mergestate(repo)
256 ms = mergestate(repo)
257 ms.reset(wctx.parents()[0].node())
257 ms.reset(wctx.parents()[0].node())
258 moves = []
258 moves = []
259 action.sort(key=actionkey)
259 action.sort(key=actionkey)
260 substate = wctx.substate # prime
260 substate = wctx.substate # prime
261
261
262 # prescan for merges
262 # prescan for merges
263 u = repo.ui
263 u = repo.ui
264 for a in action:
264 for a in action:
265 f, m = a[:2]
265 f, m = a[:2]
266 if m == 'm': # merge
266 if m == 'm': # merge
267 f2, fd, flags, move = a[2:]
267 f2, fd, flags, move = a[2:]
268 if f == '.hgsubstate': # merged internally
268 if f == '.hgsubstate': # merged internally
269 continue
269 continue
270 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
270 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
271 fcl = wctx[f]
271 fcl = wctx[f]
272 fco = mctx[f2]
272 fco = mctx[f2]
273 fca = fcl.ancestor(fco, actx) or repo.filectx(f, fileid=nullrev)
273 fca = fcl.ancestor(fco, actx) or repo.filectx(f, fileid=nullrev)
274 ms.add(fcl, fco, fca, fd, flags)
274 ms.add(fcl, fco, fca, fd, flags)
275 if f != fd and move:
275 if f != fd and move:
276 moves.append(f)
276 moves.append(f)
277
277
278 # remove renamed files after safely stored
278 # remove renamed files after safely stored
279 for f in moves:
279 for f in moves:
280 if util.lexists(repo.wjoin(f)):
280 if util.lexists(repo.wjoin(f)):
281 repo.ui.debug("removing %s\n" % f)
281 repo.ui.debug("removing %s\n" % f)
282 os.unlink(repo.wjoin(f))
282 os.unlink(repo.wjoin(f))
283
283
284 audit_path = util.path_auditor(repo.root)
284 audit_path = util.path_auditor(repo.root)
285
285
286 numupdates = len(action)
286 numupdates = len(action)
287 for i, a in enumerate(action):
287 for i, a in enumerate(action):
288 f, m = a[:2]
288 f, m = a[:2]
289 u.progress('update', i + 1, item=f, total=numupdates, unit='files')
289 u.progress('update', i + 1, item=f, total=numupdates, unit='files')
290 if f and f[0] == "/":
290 if f and f[0] == "/":
291 continue
291 continue
292 if m == "r": # remove
292 if m == "r": # remove
293 repo.ui.note(_("removing %s\n") % f)
293 repo.ui.note(_("removing %s\n") % f)
294 audit_path(f)
294 audit_path(f)
295 if f == '.hgsubstate': # subrepo states need updating
295 if f == '.hgsubstate': # subrepo states need updating
296 subrepo.submerge(repo, wctx, mctx, wctx)
296 subrepo.submerge(repo, wctx, mctx, wctx)
297 try:
297 try:
298 util.unlink(repo.wjoin(f))
298 util.unlink(repo.wjoin(f))
299 except OSError, inst:
299 except OSError, inst:
300 if inst.errno != errno.ENOENT:
300 if inst.errno != errno.ENOENT:
301 repo.ui.warn(_("update failed to remove %s: %s!\n") %
301 repo.ui.warn(_("update failed to remove %s: %s!\n") %
302 (f, inst.strerror))
302 (f, inst.strerror))
303 removed += 1
303 removed += 1
304 elif m == "m": # merge
304 elif m == "m": # merge
305 if f == '.hgsubstate': # subrepo states need updating
305 if f == '.hgsubstate': # subrepo states need updating
306 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx))
306 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx))
307 continue
307 continue
308 f2, fd, flags, move = a[2:]
308 f2, fd, flags, move = a[2:]
309 r = ms.resolve(fd, wctx, mctx)
309 r = ms.resolve(fd, wctx, mctx)
310 if r is not None and r > 0:
310 if r is not None and r > 0:
311 unresolved += 1
311 unresolved += 1
312 else:
312 else:
313 if r is None:
313 if r is None:
314 updated += 1
314 updated += 1
315 else:
315 else:
316 merged += 1
316 merged += 1
317 util.set_flags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
317 util.set_flags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
318 if f != fd and move and util.lexists(repo.wjoin(f)):
318 if f != fd and move and util.lexists(repo.wjoin(f)):
319 repo.ui.debug("removing %s\n" % f)
319 repo.ui.debug("removing %s\n" % f)
320 os.unlink(repo.wjoin(f))
320 os.unlink(repo.wjoin(f))
321 elif m == "g": # get
321 elif m == "g": # get
322 flags = a[2]
322 flags = a[2]
323 repo.ui.note(_("getting %s\n") % f)
323 repo.ui.note(_("getting %s\n") % f)
324 t = mctx.filectx(f).data()
324 t = mctx.filectx(f).data()
325 repo.wwrite(f, t, flags)
325 repo.wwrite(f, t, flags)
326 updated += 1
326 updated += 1
327 if f == '.hgsubstate': # subrepo states need updating
327 if f == '.hgsubstate': # subrepo states need updating
328 subrepo.submerge(repo, wctx, mctx, wctx)
328 subrepo.submerge(repo, wctx, mctx, wctx)
329 elif m == "d": # directory rename
329 elif m == "d": # directory rename
330 f2, fd, flags = a[2:]
330 f2, fd, flags = a[2:]
331 if f:
331 if f:
332 repo.ui.note(_("moving %s to %s\n") % (f, fd))
332 repo.ui.note(_("moving %s to %s\n") % (f, fd))
333 t = wctx.filectx(f).data()
333 t = wctx.filectx(f).data()
334 repo.wwrite(fd, t, flags)
334 repo.wwrite(fd, t, flags)
335 util.unlink(repo.wjoin(f))
335 util.unlink(repo.wjoin(f))
336 if f2:
336 if f2:
337 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
337 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
338 t = mctx.filectx(f2).data()
338 t = mctx.filectx(f2).data()
339 repo.wwrite(fd, t, flags)
339 repo.wwrite(fd, t, flags)
340 updated += 1
340 updated += 1
341 elif m == "dr": # divergent renames
341 elif m == "dr": # divergent renames
342 fl = a[2]
342 fl = a[2]
343 repo.ui.warn(_("warning: detected divergent renames of %s to:\n") % f)
343 repo.ui.warn(_("warning: detected divergent renames of %s to:\n") % f)
344 for nf in fl:
344 for nf in fl:
345 repo.ui.warn(" %s\n" % nf)
345 repo.ui.warn(" %s\n" % nf)
346 elif m == "e": # exec
346 elif m == "e": # exec
347 flags = a[2]
347 flags = a[2]
348 util.set_flags(repo.wjoin(f), 'l' in flags, 'x' in flags)
348 util.set_flags(repo.wjoin(f), 'l' in flags, 'x' in flags)
349 u.progress('update', None, total=numupdates, unit='files')
349 u.progress('update', None, total=numupdates, unit='files')
350
350
351 return updated, merged, removed, unresolved
351 return updated, merged, removed, unresolved
352
352
353 def recordupdates(repo, action, branchmerge):
353 def recordupdates(repo, action, branchmerge):
354 "record merge actions to the dirstate"
354 "record merge actions to the dirstate"
355
355
356 for a in action:
356 for a in action:
357 f, m = a[:2]
357 f, m = a[:2]
358 if m == "r": # remove
358 if m == "r": # remove
359 if branchmerge:
359 if branchmerge:
360 repo.dirstate.remove(f)
360 repo.dirstate.remove(f)
361 else:
361 else:
362 repo.dirstate.forget(f)
362 repo.dirstate.forget(f)
363 elif m == "a": # re-add
363 elif m == "a": # re-add
364 if not branchmerge:
364 if not branchmerge:
365 repo.dirstate.add(f)
365 repo.dirstate.add(f)
366 elif m == "f": # forget
366 elif m == "f": # forget
367 repo.dirstate.forget(f)
367 repo.dirstate.forget(f)
368 elif m == "e": # exec change
368 elif m == "e": # exec change
369 repo.dirstate.normallookup(f)
369 repo.dirstate.normallookup(f)
370 elif m == "g": # get
370 elif m == "g": # get
371 if branchmerge:
371 if branchmerge:
372 repo.dirstate.otherparent(f)
372 repo.dirstate.otherparent(f)
373 else:
373 else:
374 repo.dirstate.normal(f)
374 repo.dirstate.normal(f)
375 elif m == "m": # merge
375 elif m == "m": # merge
376 f2, fd, flag, move = a[2:]
376 f2, fd, flag, move = a[2:]
377 if branchmerge:
377 if branchmerge:
378 # We've done a branch merge, mark this file as merged
378 # We've done a branch merge, mark this file as merged
379 # so that we properly record the merger later
379 # so that we properly record the merger later
380 repo.dirstate.merge(fd)
380 repo.dirstate.merge(fd)
381 if f != f2: # copy/rename
381 if f != f2: # copy/rename
382 if move:
382 if move:
383 repo.dirstate.remove(f)
383 repo.dirstate.remove(f)
384 if f != fd:
384 if f != fd:
385 repo.dirstate.copy(f, fd)
385 repo.dirstate.copy(f, fd)
386 else:
386 else:
387 repo.dirstate.copy(f2, fd)
387 repo.dirstate.copy(f2, fd)
388 else:
388 else:
389 # We've update-merged a locally modified file, so
389 # We've update-merged a locally modified file, so
390 # we set the dirstate to emulate a normal checkout
390 # we set the dirstate to emulate a normal checkout
391 # of that file some time in the past. Thus our
391 # of that file some time in the past. Thus our
392 # merge will appear as a normal local file
392 # merge will appear as a normal local file
393 # modification.
393 # modification.
394 if f2 == fd: # file not locally copied/moved
394 if f2 == fd: # file not locally copied/moved
395 repo.dirstate.normallookup(fd)
395 repo.dirstate.normallookup(fd)
396 if move:
396 if move:
397 repo.dirstate.forget(f)
397 repo.dirstate.forget(f)
398 elif m == "d": # directory rename
398 elif m == "d": # directory rename
399 f2, fd, flag = a[2:]
399 f2, fd, flag = a[2:]
400 if not f2 and f not in repo.dirstate:
400 if not f2 and f not in repo.dirstate:
401 # untracked file moved
401 # untracked file moved
402 continue
402 continue
403 if branchmerge:
403 if branchmerge:
404 repo.dirstate.add(fd)
404 repo.dirstate.add(fd)
405 if f:
405 if f:
406 repo.dirstate.remove(f)
406 repo.dirstate.remove(f)
407 repo.dirstate.copy(f, fd)
407 repo.dirstate.copy(f, fd)
408 if f2:
408 if f2:
409 repo.dirstate.copy(f2, fd)
409 repo.dirstate.copy(f2, fd)
410 else:
410 else:
411 repo.dirstate.normal(fd)
411 repo.dirstate.normal(fd)
412 if f:
412 if f:
413 repo.dirstate.forget(f)
413 repo.dirstate.forget(f)
414
414
415 def update(repo, node, branchmerge, force, partial):
415 def update(repo, node, branchmerge, force, partial):
416 """
416 """
417 Perform a merge between the working directory and the given node
417 Perform a merge between the working directory and the given node
418
418
419 node = the node to update to, or None if unspecified
419 node = the node to update to, or None if unspecified
420 branchmerge = whether to merge between branches
420 branchmerge = whether to merge between branches
421 force = whether to force branch merging or file overwriting
421 force = whether to force branch merging or file overwriting
422 partial = a function to filter file lists (dirstate not updated)
422 partial = a function to filter file lists (dirstate not updated)
423
423
424 The table below shows all the behaviors of the update command
424 The table below shows all the behaviors of the update command
425 given the -c and -C or no options, whether the working directory
425 given the -c and -C or no options, whether the working directory
426 is dirty, whether a revision is specified, and the relationship of
426 is dirty, whether a revision is specified, and the relationship of
427 the parent rev to the target rev (linear, on the same named
427 the parent rev to the target rev (linear, on the same named
428 branch, or on another named branch).
428 branch, or on another named branch).
429
429
430 This logic is tested by test-update-branches.
430 This logic is tested by test-update-branches.
431
431
432 -c -C dirty rev | linear same cross
432 -c -C dirty rev | linear same cross
433 n n n n | ok (1) x
433 n n n n | ok (1) x
434 n n n y | ok ok ok
434 n n n y | ok ok ok
435 n n y * | merge (2) (2)
435 n n y * | merge (2) (2)
436 n y * * | --- discard ---
436 n y * * | --- discard ---
437 y n y * | --- (3) ---
437 y n y * | --- (3) ---
438 y n n * | --- ok ---
438 y n n * | --- ok ---
439 y y * * | --- (4) ---
439 y y * * | --- (4) ---
440
440
441 x = can't happen
441 x = can't happen
442 * = don't-care
442 * = don't-care
443 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
443 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
444 2 = abort: crosses branches (use 'hg merge' to merge or
444 2 = abort: crosses branches (use 'hg merge' to merge or
445 use 'hg update -C' to discard changes)
445 use 'hg update -C' to discard changes)
446 3 = abort: uncommitted local changes
446 3 = abort: uncommitted local changes
447 4 = incompatible options (checked in commands.py)
447 4 = incompatible options (checked in commands.py)
448 """
448 """
449
449
450 onode = node
450 onode = node
451 wlock = repo.wlock()
451 wlock = repo.wlock()
452 try:
452 try:
453 wc = repo[None]
453 wc = repo[None]
454 if node is None:
454 if node is None:
455 # tip of current branch
455 # tip of current branch
456 try:
456 try:
457 node = repo.branchtags()[wc.branch()]
457 node = repo.branchtags()[wc.branch()]
458 except KeyError:
458 except KeyError:
459 if wc.branch() == "default": # no default branch!
459 if wc.branch() == "default": # no default branch!
460 node = repo.lookup("tip") # update to tip
460 node = repo.lookup("tip") # update to tip
461 else:
461 else:
462 raise util.Abort(_("branch %s not found") % wc.branch())
462 raise util.Abort(_("branch %s not found") % wc.branch())
463 overwrite = force and not branchmerge
463 overwrite = force and not branchmerge
464 pl = wc.parents()
464 pl = wc.parents()
465 p1, p2 = pl[0], repo[node]
465 p1, p2 = pl[0], repo[node]
466 pa = p1.ancestor(p2)
466 pa = p1.ancestor(p2)
467 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
467 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
468 fastforward = False
468 fastforward = False
469
469
470 ### check phase
470 ### check phase
471 if not overwrite and len(pl) > 1:
471 if not overwrite and len(pl) > 1:
472 raise util.Abort(_("outstanding uncommitted merges"))
472 raise util.Abort(_("outstanding uncommitted merges"))
473 if branchmerge:
473 if branchmerge:
474 if pa == p2:
474 if pa == p2:
475 raise util.Abort(_("merging with a working directory ancestor"
475 raise util.Abort(_("merging with a working directory ancestor"
476 " has no effect"))
476 " has no effect"))
477 elif pa == p1:
477 elif pa == p1:
478 if p1.branch() != p2.branch():
478 if p1.branch() != p2.branch():
479 fastforward = True
479 fastforward = True
480 else:
480 else:
481 raise util.Abort(_("nothing to merge (use 'hg update'"
481 raise util.Abort(_("nothing to merge (use 'hg update'"
482 " or check 'hg heads')"))
482 " or check 'hg heads')"))
483 if not force and (wc.files() or wc.deleted()):
483 if not force and (wc.files() or wc.deleted()):
484 raise util.Abort(_("outstanding uncommitted changes "
484 raise util.Abort(_("outstanding uncommitted changes "
485 "(use 'hg status' to list changes)"))
485 "(use 'hg status' to list changes)"))
486 elif not overwrite:
486 elif not overwrite:
487 if pa == p1 or pa == p2: # linear
487 if pa == p1 or pa == p2: # linear
488 pass # all good
488 pass # all good
489 elif wc.files() or wc.deleted():
489 elif wc.files() or wc.deleted():
490 raise util.Abort(_("crosses branches (use 'hg merge' to merge "
490 raise util.Abort(_("crosses branches (use 'hg merge' to merge "
491 "or use 'hg update -C' to discard changes)"))
491 "or use 'hg update -C' to discard changes)"))
492 elif onode is None:
492 elif onode is None:
493 raise util.Abort(_("crosses branches (use 'hg merge' or use "
493 raise util.Abort(_("crosses branches (use 'hg merge' or use "
494 "'hg update -c')"))
494 "'hg update -c')"))
495 else:
495 else:
496 # Allow jumping branches if clean and specific rev given
496 # Allow jumping branches if clean and specific rev given
497 overwrite = True
497 overwrite = True
498
498
499 ### calculate phase
499 ### calculate phase
500 action = []
500 action = []
501 wc.status(unknown=True) # prime cache
501 wc.status(unknown=True) # prime cache
502 if not force:
502 if not force:
503 _checkunknown(wc, p2)
503 _checkunknown(wc, p2)
504 if not util.checkcase(repo.path):
504 if not util.checkcase(repo.path):
505 _checkcollision(p2)
505 _checkcollision(p2)
506 action += _forgetremoved(wc, p2, branchmerge)
506 action += _forgetremoved(wc, p2, branchmerge)
507 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
507 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
508
508
509 ### apply phase
509 ### apply phase
510 if not branchmerge: # just jump to the new rev
510 if not branchmerge: # just jump to the new rev
511 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
511 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
512 if not partial:
512 if not partial:
513 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
513 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
514
514
515 stats = applyupdates(repo, action, wc, p2, pa)
515 stats = applyupdates(repo, action, wc, p2, pa)
516
516
517 if not partial:
517 if not partial:
518 repo.dirstate.setparents(fp1, fp2)
518 repo.dirstate.setparents(fp1, fp2)
519 recordupdates(repo, action, branchmerge)
519 recordupdates(repo, action, branchmerge)
520 if not branchmerge and not fastforward:
520 if not branchmerge and not fastforward:
521 repo.dirstate.setbranch(p2.branch())
521 repo.dirstate.setbranch(p2.branch())
522 finally:
522 finally:
523 wlock.release()
523 wlock.release()
524
524
525 if not partial:
525 if not partial:
526 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
526 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
527 return stats
527 return stats
General Comments 0
You need to be logged in to leave comments. Login now