##// END OF EJS Templates
phases: fix verify with secret csets...
Matt Mackall -
r16018:ed9f40bc stable
parent child Browse files
Show More
@@ -1,584 +1,584 b''
1 # hg.py - repository classes for mercurial
1 # hg.py - repository classes for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from i18n import _
9 from i18n import _
10 from lock import release
10 from lock import release
11 from node import hex, nullid
11 from node import hex, nullid
12 import localrepo, bundlerepo, httprepo, sshrepo, statichttprepo, bookmarks
12 import localrepo, bundlerepo, httprepo, sshrepo, statichttprepo, bookmarks
13 import lock, util, extensions, error, node, scmutil
13 import lock, util, extensions, error, node, scmutil
14 import cmdutil, discovery
14 import cmdutil, discovery
15 import merge as mergemod
15 import merge as mergemod
16 import verify as verifymod
16 import verify as verifymod
17 import errno, os, shutil
17 import errno, os, shutil
18
18
19 def _local(path):
19 def _local(path):
20 path = util.expandpath(util.urllocalpath(path))
20 path = util.expandpath(util.urllocalpath(path))
21 return (os.path.isfile(path) and bundlerepo or localrepo)
21 return (os.path.isfile(path) and bundlerepo or localrepo)
22
22
23 def addbranchrevs(lrepo, repo, branches, revs):
23 def addbranchrevs(lrepo, repo, branches, revs):
24 hashbranch, branches = branches
24 hashbranch, branches = branches
25 if not hashbranch and not branches:
25 if not hashbranch and not branches:
26 return revs or None, revs and revs[0] or None
26 return revs or None, revs and revs[0] or None
27 revs = revs and list(revs) or []
27 revs = revs and list(revs) or []
28 if not repo.capable('branchmap'):
28 if not repo.capable('branchmap'):
29 if branches:
29 if branches:
30 raise util.Abort(_("remote branch lookup not supported"))
30 raise util.Abort(_("remote branch lookup not supported"))
31 revs.append(hashbranch)
31 revs.append(hashbranch)
32 return revs, revs[0]
32 return revs, revs[0]
33 branchmap = repo.branchmap()
33 branchmap = repo.branchmap()
34
34
35 def primary(branch):
35 def primary(branch):
36 if branch == '.':
36 if branch == '.':
37 if not lrepo or not lrepo.local():
37 if not lrepo or not lrepo.local():
38 raise util.Abort(_("dirstate branch not accessible"))
38 raise util.Abort(_("dirstate branch not accessible"))
39 branch = lrepo.dirstate.branch()
39 branch = lrepo.dirstate.branch()
40 if branch in branchmap:
40 if branch in branchmap:
41 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
41 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
42 return True
42 return True
43 else:
43 else:
44 return False
44 return False
45
45
46 for branch in branches:
46 for branch in branches:
47 if not primary(branch):
47 if not primary(branch):
48 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
48 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
49 if hashbranch:
49 if hashbranch:
50 if not primary(hashbranch):
50 if not primary(hashbranch):
51 revs.append(hashbranch)
51 revs.append(hashbranch)
52 return revs, revs[0]
52 return revs, revs[0]
53
53
54 def parseurl(path, branches=None):
54 def parseurl(path, branches=None):
55 '''parse url#branch, returning (url, (branch, branches))'''
55 '''parse url#branch, returning (url, (branch, branches))'''
56
56
57 u = util.url(path)
57 u = util.url(path)
58 branch = None
58 branch = None
59 if u.fragment:
59 if u.fragment:
60 branch = u.fragment
60 branch = u.fragment
61 u.fragment = None
61 u.fragment = None
62 return str(u), (branch, branches or [])
62 return str(u), (branch, branches or [])
63
63
64 schemes = {
64 schemes = {
65 'bundle': bundlerepo,
65 'bundle': bundlerepo,
66 'file': _local,
66 'file': _local,
67 'http': httprepo,
67 'http': httprepo,
68 'https': httprepo,
68 'https': httprepo,
69 'ssh': sshrepo,
69 'ssh': sshrepo,
70 'static-http': statichttprepo,
70 'static-http': statichttprepo,
71 }
71 }
72
72
73 def _peerlookup(path):
73 def _peerlookup(path):
74 u = util.url(path)
74 u = util.url(path)
75 scheme = u.scheme or 'file'
75 scheme = u.scheme or 'file'
76 thing = schemes.get(scheme) or schemes['file']
76 thing = schemes.get(scheme) or schemes['file']
77 try:
77 try:
78 return thing(path)
78 return thing(path)
79 except TypeError:
79 except TypeError:
80 return thing
80 return thing
81
81
82 def islocal(repo):
82 def islocal(repo):
83 '''return true if repo or path is local'''
83 '''return true if repo or path is local'''
84 if isinstance(repo, str):
84 if isinstance(repo, str):
85 try:
85 try:
86 return _peerlookup(repo).islocal(repo)
86 return _peerlookup(repo).islocal(repo)
87 except AttributeError:
87 except AttributeError:
88 return False
88 return False
89 return repo.local()
89 return repo.local()
90
90
91 def repository(ui, path='', create=False):
91 def repository(ui, path='', create=False):
92 """return a repository object for the specified path"""
92 """return a repository object for the specified path"""
93 repo = _peerlookup(path).instance(ui, path, create)
93 repo = _peerlookup(path).instance(ui, path, create)
94 ui = getattr(repo, "ui", ui)
94 ui = getattr(repo, "ui", ui)
95 for name, module in extensions.extensions():
95 for name, module in extensions.extensions():
96 hook = getattr(module, 'reposetup', None)
96 hook = getattr(module, 'reposetup', None)
97 if hook:
97 if hook:
98 hook(ui, repo)
98 hook(ui, repo)
99 return repo
99 return repo
100
100
101 def peer(uiorrepo, opts, path, create=False):
101 def peer(uiorrepo, opts, path, create=False):
102 '''return a repository peer for the specified path'''
102 '''return a repository peer for the specified path'''
103 rui = remoteui(uiorrepo, opts)
103 rui = remoteui(uiorrepo, opts)
104 return repository(rui, path, create)
104 return repository(rui, path, create)
105
105
106 def defaultdest(source):
106 def defaultdest(source):
107 '''return default destination of clone if none is given'''
107 '''return default destination of clone if none is given'''
108 return os.path.basename(os.path.normpath(source))
108 return os.path.basename(os.path.normpath(source))
109
109
110 def share(ui, source, dest=None, update=True):
110 def share(ui, source, dest=None, update=True):
111 '''create a shared repository'''
111 '''create a shared repository'''
112
112
113 if not islocal(source):
113 if not islocal(source):
114 raise util.Abort(_('can only share local repositories'))
114 raise util.Abort(_('can only share local repositories'))
115
115
116 if not dest:
116 if not dest:
117 dest = defaultdest(source)
117 dest = defaultdest(source)
118 else:
118 else:
119 dest = ui.expandpath(dest)
119 dest = ui.expandpath(dest)
120
120
121 if isinstance(source, str):
121 if isinstance(source, str):
122 origsource = ui.expandpath(source)
122 origsource = ui.expandpath(source)
123 source, branches = parseurl(origsource)
123 source, branches = parseurl(origsource)
124 srcrepo = repository(ui, source)
124 srcrepo = repository(ui, source)
125 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
125 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
126 else:
126 else:
127 srcrepo = source
127 srcrepo = source
128 origsource = source = srcrepo.url()
128 origsource = source = srcrepo.url()
129 checkout = None
129 checkout = None
130
130
131 sharedpath = srcrepo.sharedpath # if our source is already sharing
131 sharedpath = srcrepo.sharedpath # if our source is already sharing
132
132
133 root = os.path.realpath(dest)
133 root = os.path.realpath(dest)
134 roothg = os.path.join(root, '.hg')
134 roothg = os.path.join(root, '.hg')
135
135
136 if os.path.exists(roothg):
136 if os.path.exists(roothg):
137 raise util.Abort(_('destination already exists'))
137 raise util.Abort(_('destination already exists'))
138
138
139 if not os.path.isdir(root):
139 if not os.path.isdir(root):
140 os.mkdir(root)
140 os.mkdir(root)
141 util.makedir(roothg, notindexed=True)
141 util.makedir(roothg, notindexed=True)
142
142
143 requirements = ''
143 requirements = ''
144 try:
144 try:
145 requirements = srcrepo.opener.read('requires')
145 requirements = srcrepo.opener.read('requires')
146 except IOError, inst:
146 except IOError, inst:
147 if inst.errno != errno.ENOENT:
147 if inst.errno != errno.ENOENT:
148 raise
148 raise
149
149
150 requirements += 'shared\n'
150 requirements += 'shared\n'
151 util.writefile(os.path.join(roothg, 'requires'), requirements)
151 util.writefile(os.path.join(roothg, 'requires'), requirements)
152 util.writefile(os.path.join(roothg, 'sharedpath'), sharedpath)
152 util.writefile(os.path.join(roothg, 'sharedpath'), sharedpath)
153
153
154 r = repository(ui, root)
154 r = repository(ui, root)
155
155
156 default = srcrepo.ui.config('paths', 'default')
156 default = srcrepo.ui.config('paths', 'default')
157 if default:
157 if default:
158 fp = r.opener("hgrc", "w", text=True)
158 fp = r.opener("hgrc", "w", text=True)
159 fp.write("[paths]\n")
159 fp.write("[paths]\n")
160 fp.write("default = %s\n" % default)
160 fp.write("default = %s\n" % default)
161 fp.close()
161 fp.close()
162
162
163 if update:
163 if update:
164 r.ui.status(_("updating working directory\n"))
164 r.ui.status(_("updating working directory\n"))
165 if update is not True:
165 if update is not True:
166 checkout = update
166 checkout = update
167 for test in (checkout, 'default', 'tip'):
167 for test in (checkout, 'default', 'tip'):
168 if test is None:
168 if test is None:
169 continue
169 continue
170 try:
170 try:
171 uprev = r.lookup(test)
171 uprev = r.lookup(test)
172 break
172 break
173 except error.RepoLookupError:
173 except error.RepoLookupError:
174 continue
174 continue
175 _update(r, uprev)
175 _update(r, uprev)
176
176
177 def copystore(ui, srcrepo, destpath):
177 def copystore(ui, srcrepo, destpath):
178 '''copy files from store of srcrepo in destpath
178 '''copy files from store of srcrepo in destpath
179
179
180 returns destlock
180 returns destlock
181 '''
181 '''
182 destlock = None
182 destlock = None
183 try:
183 try:
184 hardlink = None
184 hardlink = None
185 num = 0
185 num = 0
186 srcpublishing = srcrepo.ui.configbool('phases', 'publish', True)
186 srcpublishing = srcrepo.ui.configbool('phases', 'publish', True)
187 for f in srcrepo.store.copylist():
187 for f in srcrepo.store.copylist():
188 if srcpublishing and f.endswith('phaseroots'):
188 if srcpublishing and f.endswith('phaseroots'):
189 continue
189 continue
190 src = os.path.join(srcrepo.sharedpath, f)
190 src = os.path.join(srcrepo.sharedpath, f)
191 dst = os.path.join(destpath, f)
191 dst = os.path.join(destpath, f)
192 dstbase = os.path.dirname(dst)
192 dstbase = os.path.dirname(dst)
193 if dstbase and not os.path.exists(dstbase):
193 if dstbase and not os.path.exists(dstbase):
194 os.mkdir(dstbase)
194 os.mkdir(dstbase)
195 if os.path.exists(src):
195 if os.path.exists(src):
196 if dst.endswith('data'):
196 if dst.endswith('data'):
197 # lock to avoid premature writing to the target
197 # lock to avoid premature writing to the target
198 destlock = lock.lock(os.path.join(dstbase, "lock"))
198 destlock = lock.lock(os.path.join(dstbase, "lock"))
199 hardlink, n = util.copyfiles(src, dst, hardlink)
199 hardlink, n = util.copyfiles(src, dst, hardlink)
200 num += n
200 num += n
201 if hardlink:
201 if hardlink:
202 ui.debug("linked %d files\n" % num)
202 ui.debug("linked %d files\n" % num)
203 else:
203 else:
204 ui.debug("copied %d files\n" % num)
204 ui.debug("copied %d files\n" % num)
205 return destlock
205 return destlock
206 except:
206 except:
207 release(destlock)
207 release(destlock)
208 raise
208 raise
209
209
210 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
210 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
211 update=True, stream=False, branch=None):
211 update=True, stream=False, branch=None):
212 """Make a copy of an existing repository.
212 """Make a copy of an existing repository.
213
213
214 Create a copy of an existing repository in a new directory. The
214 Create a copy of an existing repository in a new directory. The
215 source and destination are URLs, as passed to the repository
215 source and destination are URLs, as passed to the repository
216 function. Returns a pair of repository objects, the source and
216 function. Returns a pair of repository objects, the source and
217 newly created destination.
217 newly created destination.
218
218
219 The location of the source is added to the new repository's
219 The location of the source is added to the new repository's
220 .hg/hgrc file, as the default to be used for future pulls and
220 .hg/hgrc file, as the default to be used for future pulls and
221 pushes.
221 pushes.
222
222
223 If an exception is raised, the partly cloned/updated destination
223 If an exception is raised, the partly cloned/updated destination
224 repository will be deleted.
224 repository will be deleted.
225
225
226 Arguments:
226 Arguments:
227
227
228 source: repository object or URL
228 source: repository object or URL
229
229
230 dest: URL of destination repository to create (defaults to base
230 dest: URL of destination repository to create (defaults to base
231 name of source repository)
231 name of source repository)
232
232
233 pull: always pull from source repository, even in local case
233 pull: always pull from source repository, even in local case
234
234
235 stream: stream raw data uncompressed from repository (fast over
235 stream: stream raw data uncompressed from repository (fast over
236 LAN, slow over WAN)
236 LAN, slow over WAN)
237
237
238 rev: revision to clone up to (implies pull=True)
238 rev: revision to clone up to (implies pull=True)
239
239
240 update: update working directory after clone completes, if
240 update: update working directory after clone completes, if
241 destination is local repository (True means update to default rev,
241 destination is local repository (True means update to default rev,
242 anything else is treated as a revision)
242 anything else is treated as a revision)
243
243
244 branch: branches to clone
244 branch: branches to clone
245 """
245 """
246
246
247 if isinstance(source, str):
247 if isinstance(source, str):
248 origsource = ui.expandpath(source)
248 origsource = ui.expandpath(source)
249 source, branch = parseurl(origsource, branch)
249 source, branch = parseurl(origsource, branch)
250 srcrepo = repository(remoteui(ui, peeropts), source)
250 srcrepo = repository(remoteui(ui, peeropts), source)
251 else:
251 else:
252 srcrepo = source
252 srcrepo = source
253 branch = (None, branch or [])
253 branch = (None, branch or [])
254 origsource = source = srcrepo.url()
254 origsource = source = srcrepo.url()
255 rev, checkout = addbranchrevs(srcrepo, srcrepo, branch, rev)
255 rev, checkout = addbranchrevs(srcrepo, srcrepo, branch, rev)
256
256
257 if dest is None:
257 if dest is None:
258 dest = defaultdest(source)
258 dest = defaultdest(source)
259 ui.status(_("destination directory: %s\n") % dest)
259 ui.status(_("destination directory: %s\n") % dest)
260 else:
260 else:
261 dest = ui.expandpath(dest)
261 dest = ui.expandpath(dest)
262
262
263 dest = util.urllocalpath(dest)
263 dest = util.urllocalpath(dest)
264 source = util.urllocalpath(source)
264 source = util.urllocalpath(source)
265
265
266 if os.path.exists(dest):
266 if os.path.exists(dest):
267 if not os.path.isdir(dest):
267 if not os.path.isdir(dest):
268 raise util.Abort(_("destination '%s' already exists") % dest)
268 raise util.Abort(_("destination '%s' already exists") % dest)
269 elif os.listdir(dest):
269 elif os.listdir(dest):
270 raise util.Abort(_("destination '%s' is not empty") % dest)
270 raise util.Abort(_("destination '%s' is not empty") % dest)
271
271
272 class DirCleanup(object):
272 class DirCleanup(object):
273 def __init__(self, dir_):
273 def __init__(self, dir_):
274 self.rmtree = shutil.rmtree
274 self.rmtree = shutil.rmtree
275 self.dir_ = dir_
275 self.dir_ = dir_
276 def close(self):
276 def close(self):
277 self.dir_ = None
277 self.dir_ = None
278 def cleanup(self):
278 def cleanup(self):
279 if self.dir_:
279 if self.dir_:
280 self.rmtree(self.dir_, True)
280 self.rmtree(self.dir_, True)
281
281
282 srclock = destlock = dircleanup = None
282 srclock = destlock = dircleanup = None
283 try:
283 try:
284 abspath = origsource
284 abspath = origsource
285 if islocal(origsource):
285 if islocal(origsource):
286 abspath = os.path.abspath(util.urllocalpath(origsource))
286 abspath = os.path.abspath(util.urllocalpath(origsource))
287
287
288 if islocal(dest):
288 if islocal(dest):
289 dircleanup = DirCleanup(dest)
289 dircleanup = DirCleanup(dest)
290
290
291 copy = False
291 copy = False
292 if srcrepo.cancopy() and islocal(dest):
292 if srcrepo.cancopy() and islocal(dest) and not srcrepo.revs("secret()"):
293 copy = not pull and not rev
293 copy = not pull and not rev
294
294
295 if copy:
295 if copy:
296 try:
296 try:
297 # we use a lock here because if we race with commit, we
297 # we use a lock here because if we race with commit, we
298 # can end up with extra data in the cloned revlogs that's
298 # can end up with extra data in the cloned revlogs that's
299 # not pointed to by changesets, thus causing verify to
299 # not pointed to by changesets, thus causing verify to
300 # fail
300 # fail
301 srclock = srcrepo.lock(wait=False)
301 srclock = srcrepo.lock(wait=False)
302 except error.LockError:
302 except error.LockError:
303 copy = False
303 copy = False
304
304
305 if copy:
305 if copy:
306 srcrepo.hook('preoutgoing', throw=True, source='clone')
306 srcrepo.hook('preoutgoing', throw=True, source='clone')
307 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
307 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
308 if not os.path.exists(dest):
308 if not os.path.exists(dest):
309 os.mkdir(dest)
309 os.mkdir(dest)
310 else:
310 else:
311 # only clean up directories we create ourselves
311 # only clean up directories we create ourselves
312 dircleanup.dir_ = hgdir
312 dircleanup.dir_ = hgdir
313 try:
313 try:
314 destpath = hgdir
314 destpath = hgdir
315 util.makedir(destpath, notindexed=True)
315 util.makedir(destpath, notindexed=True)
316 except OSError, inst:
316 except OSError, inst:
317 if inst.errno == errno.EEXIST:
317 if inst.errno == errno.EEXIST:
318 dircleanup.close()
318 dircleanup.close()
319 raise util.Abort(_("destination '%s' already exists")
319 raise util.Abort(_("destination '%s' already exists")
320 % dest)
320 % dest)
321 raise
321 raise
322
322
323 destlock = copystore(ui, srcrepo, destpath)
323 destlock = copystore(ui, srcrepo, destpath)
324
324
325 # we need to re-init the repo after manually copying the data
325 # we need to re-init the repo after manually copying the data
326 # into it
326 # into it
327 destrepo = repository(remoteui(ui, peeropts), dest)
327 destrepo = repository(remoteui(ui, peeropts), dest)
328 srcrepo.hook('outgoing', source='clone',
328 srcrepo.hook('outgoing', source='clone',
329 node=node.hex(node.nullid))
329 node=node.hex(node.nullid))
330 else:
330 else:
331 try:
331 try:
332 destrepo = repository(remoteui(ui, peeropts), dest,
332 destrepo = repository(remoteui(ui, peeropts), dest,
333 create=True)
333 create=True)
334 except OSError, inst:
334 except OSError, inst:
335 if inst.errno == errno.EEXIST:
335 if inst.errno == errno.EEXIST:
336 dircleanup.close()
336 dircleanup.close()
337 raise util.Abort(_("destination '%s' already exists")
337 raise util.Abort(_("destination '%s' already exists")
338 % dest)
338 % dest)
339 raise
339 raise
340
340
341 revs = None
341 revs = None
342 if rev:
342 if rev:
343 if not srcrepo.capable('lookup'):
343 if not srcrepo.capable('lookup'):
344 raise util.Abort(_("src repository does not support "
344 raise util.Abort(_("src repository does not support "
345 "revision lookup and so doesn't "
345 "revision lookup and so doesn't "
346 "support clone by revision"))
346 "support clone by revision"))
347 revs = [srcrepo.lookup(r) for r in rev]
347 revs = [srcrepo.lookup(r) for r in rev]
348 checkout = revs[0]
348 checkout = revs[0]
349 if destrepo.local():
349 if destrepo.local():
350 destrepo.clone(srcrepo, heads=revs, stream=stream)
350 destrepo.clone(srcrepo, heads=revs, stream=stream)
351 elif srcrepo.local():
351 elif srcrepo.local():
352 srcrepo.push(destrepo, revs=revs)
352 srcrepo.push(destrepo, revs=revs)
353 else:
353 else:
354 raise util.Abort(_("clone from remote to remote not supported"))
354 raise util.Abort(_("clone from remote to remote not supported"))
355
355
356 if dircleanup:
356 if dircleanup:
357 dircleanup.close()
357 dircleanup.close()
358
358
359 # clone all bookmarks
359 # clone all bookmarks
360 if destrepo.local() and srcrepo.capable("pushkey"):
360 if destrepo.local() and srcrepo.capable("pushkey"):
361 rb = srcrepo.listkeys('bookmarks')
361 rb = srcrepo.listkeys('bookmarks')
362 for k, n in rb.iteritems():
362 for k, n in rb.iteritems():
363 try:
363 try:
364 m = destrepo.lookup(n)
364 m = destrepo.lookup(n)
365 destrepo._bookmarks[k] = m
365 destrepo._bookmarks[k] = m
366 except error.RepoLookupError:
366 except error.RepoLookupError:
367 pass
367 pass
368 if rb:
368 if rb:
369 bookmarks.write(destrepo)
369 bookmarks.write(destrepo)
370 elif srcrepo.local() and destrepo.capable("pushkey"):
370 elif srcrepo.local() and destrepo.capable("pushkey"):
371 for k, n in srcrepo._bookmarks.iteritems():
371 for k, n in srcrepo._bookmarks.iteritems():
372 destrepo.pushkey('bookmarks', k, '', hex(n))
372 destrepo.pushkey('bookmarks', k, '', hex(n))
373
373
374 if destrepo.local():
374 if destrepo.local():
375 fp = destrepo.opener("hgrc", "w", text=True)
375 fp = destrepo.opener("hgrc", "w", text=True)
376 fp.write("[paths]\n")
376 fp.write("[paths]\n")
377 u = util.url(abspath)
377 u = util.url(abspath)
378 u.passwd = None
378 u.passwd = None
379 defaulturl = str(u)
379 defaulturl = str(u)
380 fp.write("default = %s\n" % defaulturl)
380 fp.write("default = %s\n" % defaulturl)
381 fp.close()
381 fp.close()
382
382
383 destrepo.ui.setconfig('paths', 'default', defaulturl)
383 destrepo.ui.setconfig('paths', 'default', defaulturl)
384
384
385 if update:
385 if update:
386 if update is not True:
386 if update is not True:
387 checkout = update
387 checkout = update
388 if srcrepo.local():
388 if srcrepo.local():
389 checkout = srcrepo.lookup(update)
389 checkout = srcrepo.lookup(update)
390 for test in (checkout, 'default', 'tip'):
390 for test in (checkout, 'default', 'tip'):
391 if test is None:
391 if test is None:
392 continue
392 continue
393 try:
393 try:
394 uprev = destrepo.lookup(test)
394 uprev = destrepo.lookup(test)
395 break
395 break
396 except error.RepoLookupError:
396 except error.RepoLookupError:
397 continue
397 continue
398 bn = destrepo[uprev].branch()
398 bn = destrepo[uprev].branch()
399 destrepo.ui.status(_("updating to branch %s\n") % bn)
399 destrepo.ui.status(_("updating to branch %s\n") % bn)
400 _update(destrepo, uprev)
400 _update(destrepo, uprev)
401
401
402 return srcrepo, destrepo
402 return srcrepo, destrepo
403 finally:
403 finally:
404 release(srclock, destlock)
404 release(srclock, destlock)
405 if dircleanup is not None:
405 if dircleanup is not None:
406 dircleanup.cleanup()
406 dircleanup.cleanup()
407
407
408 def _showstats(repo, stats):
408 def _showstats(repo, stats):
409 repo.ui.status(_("%d files updated, %d files merged, "
409 repo.ui.status(_("%d files updated, %d files merged, "
410 "%d files removed, %d files unresolved\n") % stats)
410 "%d files removed, %d files unresolved\n") % stats)
411
411
412 def update(repo, node):
412 def update(repo, node):
413 """update the working directory to node, merging linear changes"""
413 """update the working directory to node, merging linear changes"""
414 stats = mergemod.update(repo, node, False, False, None)
414 stats = mergemod.update(repo, node, False, False, None)
415 _showstats(repo, stats)
415 _showstats(repo, stats)
416 if stats[3]:
416 if stats[3]:
417 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
417 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
418 return stats[3] > 0
418 return stats[3] > 0
419
419
420 # naming conflict in clone()
420 # naming conflict in clone()
421 _update = update
421 _update = update
422
422
423 def clean(repo, node, show_stats=True):
423 def clean(repo, node, show_stats=True):
424 """forcibly switch the working directory to node, clobbering changes"""
424 """forcibly switch the working directory to node, clobbering changes"""
425 stats = mergemod.update(repo, node, False, True, None)
425 stats = mergemod.update(repo, node, False, True, None)
426 if show_stats:
426 if show_stats:
427 _showstats(repo, stats)
427 _showstats(repo, stats)
428 return stats[3] > 0
428 return stats[3] > 0
429
429
430 def merge(repo, node, force=None, remind=True):
430 def merge(repo, node, force=None, remind=True):
431 """Branch merge with node, resolving changes. Return true if any
431 """Branch merge with node, resolving changes. Return true if any
432 unresolved conflicts."""
432 unresolved conflicts."""
433 stats = mergemod.update(repo, node, True, force, False)
433 stats = mergemod.update(repo, node, True, force, False)
434 _showstats(repo, stats)
434 _showstats(repo, stats)
435 if stats[3]:
435 if stats[3]:
436 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
436 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
437 "or 'hg update -C .' to abandon\n"))
437 "or 'hg update -C .' to abandon\n"))
438 elif remind:
438 elif remind:
439 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
439 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
440 return stats[3] > 0
440 return stats[3] > 0
441
441
442 def _incoming(displaychlist, subreporecurse, ui, repo, source,
442 def _incoming(displaychlist, subreporecurse, ui, repo, source,
443 opts, buffered=False):
443 opts, buffered=False):
444 """
444 """
445 Helper for incoming / gincoming.
445 Helper for incoming / gincoming.
446 displaychlist gets called with
446 displaychlist gets called with
447 (remoterepo, incomingchangesetlist, displayer) parameters,
447 (remoterepo, incomingchangesetlist, displayer) parameters,
448 and is supposed to contain only code that can't be unified.
448 and is supposed to contain only code that can't be unified.
449 """
449 """
450 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
450 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
451 other = peer(repo, opts, source)
451 other = peer(repo, opts, source)
452 ui.status(_('comparing with %s\n') % util.hidepassword(source))
452 ui.status(_('comparing with %s\n') % util.hidepassword(source))
453 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
453 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
454
454
455 if revs:
455 if revs:
456 revs = [other.lookup(rev) for rev in revs]
456 revs = [other.lookup(rev) for rev in revs]
457 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
457 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
458 revs, opts["bundle"], opts["force"])
458 revs, opts["bundle"], opts["force"])
459 try:
459 try:
460 if not chlist:
460 if not chlist:
461 ui.status(_("no changes found\n"))
461 ui.status(_("no changes found\n"))
462 return subreporecurse()
462 return subreporecurse()
463
463
464 displayer = cmdutil.show_changeset(ui, other, opts, buffered)
464 displayer = cmdutil.show_changeset(ui, other, opts, buffered)
465
465
466 # XXX once graphlog extension makes it into core,
466 # XXX once graphlog extension makes it into core,
467 # should be replaced by a if graph/else
467 # should be replaced by a if graph/else
468 displaychlist(other, chlist, displayer)
468 displaychlist(other, chlist, displayer)
469
469
470 displayer.close()
470 displayer.close()
471 finally:
471 finally:
472 cleanupfn()
472 cleanupfn()
473 subreporecurse()
473 subreporecurse()
474 return 0 # exit code is zero since we found incoming changes
474 return 0 # exit code is zero since we found incoming changes
475
475
476 def incoming(ui, repo, source, opts):
476 def incoming(ui, repo, source, opts):
477 def subreporecurse():
477 def subreporecurse():
478 ret = 1
478 ret = 1
479 if opts.get('subrepos'):
479 if opts.get('subrepos'):
480 ctx = repo[None]
480 ctx = repo[None]
481 for subpath in sorted(ctx.substate):
481 for subpath in sorted(ctx.substate):
482 sub = ctx.sub(subpath)
482 sub = ctx.sub(subpath)
483 ret = min(ret, sub.incoming(ui, source, opts))
483 ret = min(ret, sub.incoming(ui, source, opts))
484 return ret
484 return ret
485
485
486 def display(other, chlist, displayer):
486 def display(other, chlist, displayer):
487 limit = cmdutil.loglimit(opts)
487 limit = cmdutil.loglimit(opts)
488 if opts.get('newest_first'):
488 if opts.get('newest_first'):
489 chlist.reverse()
489 chlist.reverse()
490 count = 0
490 count = 0
491 for n in chlist:
491 for n in chlist:
492 if limit is not None and count >= limit:
492 if limit is not None and count >= limit:
493 break
493 break
494 parents = [p for p in other.changelog.parents(n) if p != nullid]
494 parents = [p for p in other.changelog.parents(n) if p != nullid]
495 if opts.get('no_merges') and len(parents) == 2:
495 if opts.get('no_merges') and len(parents) == 2:
496 continue
496 continue
497 count += 1
497 count += 1
498 displayer.show(other[n])
498 displayer.show(other[n])
499 return _incoming(display, subreporecurse, ui, repo, source, opts)
499 return _incoming(display, subreporecurse, ui, repo, source, opts)
500
500
501 def _outgoing(ui, repo, dest, opts):
501 def _outgoing(ui, repo, dest, opts):
502 dest = ui.expandpath(dest or 'default-push', dest or 'default')
502 dest = ui.expandpath(dest or 'default-push', dest or 'default')
503 dest, branches = parseurl(dest, opts.get('branch'))
503 dest, branches = parseurl(dest, opts.get('branch'))
504 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
504 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
505 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
505 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
506 if revs:
506 if revs:
507 revs = [repo.lookup(rev) for rev in revs]
507 revs = [repo.lookup(rev) for rev in revs]
508
508
509 other = peer(repo, opts, dest)
509 other = peer(repo, opts, dest)
510 outgoing = discovery.findcommonoutgoing(repo, other, revs,
510 outgoing = discovery.findcommonoutgoing(repo, other, revs,
511 force=opts.get('force'))
511 force=opts.get('force'))
512 o = outgoing.missing
512 o = outgoing.missing
513 if not o:
513 if not o:
514 scmutil.nochangesfound(repo.ui, outgoing.excluded)
514 scmutil.nochangesfound(repo.ui, outgoing.excluded)
515 return None
515 return None
516 return o
516 return o
517
517
518 def outgoing(ui, repo, dest, opts):
518 def outgoing(ui, repo, dest, opts):
519 def recurse():
519 def recurse():
520 ret = 1
520 ret = 1
521 if opts.get('subrepos'):
521 if opts.get('subrepos'):
522 ctx = repo[None]
522 ctx = repo[None]
523 for subpath in sorted(ctx.substate):
523 for subpath in sorted(ctx.substate):
524 sub = ctx.sub(subpath)
524 sub = ctx.sub(subpath)
525 ret = min(ret, sub.outgoing(ui, dest, opts))
525 ret = min(ret, sub.outgoing(ui, dest, opts))
526 return ret
526 return ret
527
527
528 limit = cmdutil.loglimit(opts)
528 limit = cmdutil.loglimit(opts)
529 o = _outgoing(ui, repo, dest, opts)
529 o = _outgoing(ui, repo, dest, opts)
530 if o is None:
530 if o is None:
531 return recurse()
531 return recurse()
532
532
533 if opts.get('newest_first'):
533 if opts.get('newest_first'):
534 o.reverse()
534 o.reverse()
535 displayer = cmdutil.show_changeset(ui, repo, opts)
535 displayer = cmdutil.show_changeset(ui, repo, opts)
536 count = 0
536 count = 0
537 for n in o:
537 for n in o:
538 if limit is not None and count >= limit:
538 if limit is not None and count >= limit:
539 break
539 break
540 parents = [p for p in repo.changelog.parents(n) if p != nullid]
540 parents = [p for p in repo.changelog.parents(n) if p != nullid]
541 if opts.get('no_merges') and len(parents) == 2:
541 if opts.get('no_merges') and len(parents) == 2:
542 continue
542 continue
543 count += 1
543 count += 1
544 displayer.show(repo[n])
544 displayer.show(repo[n])
545 displayer.close()
545 displayer.close()
546 recurse()
546 recurse()
547 return 0 # exit code is zero since we found outgoing changes
547 return 0 # exit code is zero since we found outgoing changes
548
548
549 def revert(repo, node, choose):
549 def revert(repo, node, choose):
550 """revert changes to revision in node without updating dirstate"""
550 """revert changes to revision in node without updating dirstate"""
551 return mergemod.update(repo, node, False, True, choose)[3] > 0
551 return mergemod.update(repo, node, False, True, choose)[3] > 0
552
552
553 def verify(repo):
553 def verify(repo):
554 """verify the consistency of a repository"""
554 """verify the consistency of a repository"""
555 return verifymod.verify(repo)
555 return verifymod.verify(repo)
556
556
557 def remoteui(src, opts):
557 def remoteui(src, opts):
558 'build a remote ui from ui or repo and opts'
558 'build a remote ui from ui or repo and opts'
559 if util.safehasattr(src, 'baseui'): # looks like a repository
559 if util.safehasattr(src, 'baseui'): # looks like a repository
560 dst = src.baseui.copy() # drop repo-specific config
560 dst = src.baseui.copy() # drop repo-specific config
561 src = src.ui # copy target options from repo
561 src = src.ui # copy target options from repo
562 else: # assume it's a global ui object
562 else: # assume it's a global ui object
563 dst = src.copy() # keep all global options
563 dst = src.copy() # keep all global options
564
564
565 # copy ssh-specific options
565 # copy ssh-specific options
566 for o in 'ssh', 'remotecmd':
566 for o in 'ssh', 'remotecmd':
567 v = opts.get(o) or src.config('ui', o)
567 v = opts.get(o) or src.config('ui', o)
568 if v:
568 if v:
569 dst.setconfig("ui", o, v)
569 dst.setconfig("ui", o, v)
570
570
571 # copy bundle-specific options
571 # copy bundle-specific options
572 r = src.config('bundle', 'mainreporoot')
572 r = src.config('bundle', 'mainreporoot')
573 if r:
573 if r:
574 dst.setconfig('bundle', 'mainreporoot', r)
574 dst.setconfig('bundle', 'mainreporoot', r)
575
575
576 # copy selected local settings to the remote ui
576 # copy selected local settings to the remote ui
577 for sect in ('auth', 'hostfingerprints', 'http_proxy'):
577 for sect in ('auth', 'hostfingerprints', 'http_proxy'):
578 for key, val in src.configitems(sect):
578 for key, val in src.configitems(sect):
579 dst.setconfig(sect, key, val)
579 dst.setconfig(sect, key, val)
580 v = src.config('web', 'cacerts')
580 v = src.config('web', 'cacerts')
581 if v:
581 if v:
582 dst.setconfig('web', 'cacerts', util.expandpath(v))
582 dst.setconfig('web', 'cacerts', util.expandpath(v))
583
583
584 return dst
584 return dst
@@ -1,2314 +1,2310 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup, subrepo, discovery, pushkey
10 import repo, changegroup, subrepo, discovery, pushkey
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
12 import lock, transaction, store, encoding
12 import lock, transaction, store, encoding
13 import scmutil, util, extensions, hook, error, revset
13 import scmutil, util, extensions, hook, error, revset
14 import match as matchmod
14 import match as matchmod
15 import merge as mergemod
15 import merge as mergemod
16 import tags as tagsmod
16 import tags as tagsmod
17 from lock import release
17 from lock import release
18 import weakref, errno, os, time, inspect
18 import weakref, errno, os, time, inspect
19 propertycache = util.propertycache
19 propertycache = util.propertycache
20 filecache = scmutil.filecache
20 filecache = scmutil.filecache
21
21
22 class localrepository(repo.repository):
22 class localrepository(repo.repository):
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey',
24 'known', 'getbundle'))
24 'known', 'getbundle'))
25 supportedformats = set(('revlogv1', 'generaldelta'))
25 supportedformats = set(('revlogv1', 'generaldelta'))
26 supported = supportedformats | set(('store', 'fncache', 'shared',
26 supported = supportedformats | set(('store', 'fncache', 'shared',
27 'dotencode'))
27 'dotencode'))
28
28
29 def __init__(self, baseui, path=None, create=False):
29 def __init__(self, baseui, path=None, create=False):
30 repo.repository.__init__(self)
30 repo.repository.__init__(self)
31 self.root = os.path.realpath(util.expandpath(path))
31 self.root = os.path.realpath(util.expandpath(path))
32 self.path = os.path.join(self.root, ".hg")
32 self.path = os.path.join(self.root, ".hg")
33 self.origroot = path
33 self.origroot = path
34 self.auditor = scmutil.pathauditor(self.root, self._checknested)
34 self.auditor = scmutil.pathauditor(self.root, self._checknested)
35 self.opener = scmutil.opener(self.path)
35 self.opener = scmutil.opener(self.path)
36 self.wopener = scmutil.opener(self.root)
36 self.wopener = scmutil.opener(self.root)
37 self.baseui = baseui
37 self.baseui = baseui
38 self.ui = baseui.copy()
38 self.ui = baseui.copy()
39 self._dirtyphases = False
39 self._dirtyphases = False
40 # A list of callback to shape the phase if no data were found.
40 # A list of callback to shape the phase if no data were found.
41 # Callback are in the form: func(repo, roots) --> processed root.
41 # Callback are in the form: func(repo, roots) --> processed root.
42 # This list it to be filled by extension during repo setup
42 # This list it to be filled by extension during repo setup
43 self._phasedefaults = []
43 self._phasedefaults = []
44
44
45 try:
45 try:
46 self.ui.readconfig(self.join("hgrc"), self.root)
46 self.ui.readconfig(self.join("hgrc"), self.root)
47 extensions.loadall(self.ui)
47 extensions.loadall(self.ui)
48 except IOError:
48 except IOError:
49 pass
49 pass
50
50
51 if not os.path.isdir(self.path):
51 if not os.path.isdir(self.path):
52 if create:
52 if create:
53 if not os.path.exists(path):
53 if not os.path.exists(path):
54 util.makedirs(path)
54 util.makedirs(path)
55 util.makedir(self.path, notindexed=True)
55 util.makedir(self.path, notindexed=True)
56 requirements = ["revlogv1"]
56 requirements = ["revlogv1"]
57 if self.ui.configbool('format', 'usestore', True):
57 if self.ui.configbool('format', 'usestore', True):
58 os.mkdir(os.path.join(self.path, "store"))
58 os.mkdir(os.path.join(self.path, "store"))
59 requirements.append("store")
59 requirements.append("store")
60 if self.ui.configbool('format', 'usefncache', True):
60 if self.ui.configbool('format', 'usefncache', True):
61 requirements.append("fncache")
61 requirements.append("fncache")
62 if self.ui.configbool('format', 'dotencode', True):
62 if self.ui.configbool('format', 'dotencode', True):
63 requirements.append('dotencode')
63 requirements.append('dotencode')
64 # create an invalid changelog
64 # create an invalid changelog
65 self.opener.append(
65 self.opener.append(
66 "00changelog.i",
66 "00changelog.i",
67 '\0\0\0\2' # represents revlogv2
67 '\0\0\0\2' # represents revlogv2
68 ' dummy changelog to prevent using the old repo layout'
68 ' dummy changelog to prevent using the old repo layout'
69 )
69 )
70 if self.ui.configbool('format', 'generaldelta', False):
70 if self.ui.configbool('format', 'generaldelta', False):
71 requirements.append("generaldelta")
71 requirements.append("generaldelta")
72 requirements = set(requirements)
72 requirements = set(requirements)
73 else:
73 else:
74 raise error.RepoError(_("repository %s not found") % path)
74 raise error.RepoError(_("repository %s not found") % path)
75 elif create:
75 elif create:
76 raise error.RepoError(_("repository %s already exists") % path)
76 raise error.RepoError(_("repository %s already exists") % path)
77 else:
77 else:
78 try:
78 try:
79 requirements = scmutil.readrequires(self.opener, self.supported)
79 requirements = scmutil.readrequires(self.opener, self.supported)
80 except IOError, inst:
80 except IOError, inst:
81 if inst.errno != errno.ENOENT:
81 if inst.errno != errno.ENOENT:
82 raise
82 raise
83 requirements = set()
83 requirements = set()
84
84
85 self.sharedpath = self.path
85 self.sharedpath = self.path
86 try:
86 try:
87 s = os.path.realpath(self.opener.read("sharedpath").rstrip('\n'))
87 s = os.path.realpath(self.opener.read("sharedpath").rstrip('\n'))
88 if not os.path.exists(s):
88 if not os.path.exists(s):
89 raise error.RepoError(
89 raise error.RepoError(
90 _('.hg/sharedpath points to nonexistent directory %s') % s)
90 _('.hg/sharedpath points to nonexistent directory %s') % s)
91 self.sharedpath = s
91 self.sharedpath = s
92 except IOError, inst:
92 except IOError, inst:
93 if inst.errno != errno.ENOENT:
93 if inst.errno != errno.ENOENT:
94 raise
94 raise
95
95
96 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
96 self.store = store.store(requirements, self.sharedpath, scmutil.opener)
97 self.spath = self.store.path
97 self.spath = self.store.path
98 self.sopener = self.store.opener
98 self.sopener = self.store.opener
99 self.sjoin = self.store.join
99 self.sjoin = self.store.join
100 self.opener.createmode = self.store.createmode
100 self.opener.createmode = self.store.createmode
101 self._applyrequirements(requirements)
101 self._applyrequirements(requirements)
102 if create:
102 if create:
103 self._writerequirements()
103 self._writerequirements()
104
104
105
105
106 self._branchcache = None
106 self._branchcache = None
107 self._branchcachetip = None
107 self._branchcachetip = None
108 self.filterpats = {}
108 self.filterpats = {}
109 self._datafilters = {}
109 self._datafilters = {}
110 self._transref = self._lockref = self._wlockref = None
110 self._transref = self._lockref = self._wlockref = None
111
111
112 # A cache for various files under .hg/ that tracks file changes,
112 # A cache for various files under .hg/ that tracks file changes,
113 # (used by the filecache decorator)
113 # (used by the filecache decorator)
114 #
114 #
115 # Maps a property name to its util.filecacheentry
115 # Maps a property name to its util.filecacheentry
116 self._filecache = {}
116 self._filecache = {}
117
117
118 def _applyrequirements(self, requirements):
118 def _applyrequirements(self, requirements):
119 self.requirements = requirements
119 self.requirements = requirements
120 openerreqs = set(('revlogv1', 'generaldelta'))
120 openerreqs = set(('revlogv1', 'generaldelta'))
121 self.sopener.options = dict((r, 1) for r in requirements
121 self.sopener.options = dict((r, 1) for r in requirements
122 if r in openerreqs)
122 if r in openerreqs)
123
123
124 def _writerequirements(self):
124 def _writerequirements(self):
125 reqfile = self.opener("requires", "w")
125 reqfile = self.opener("requires", "w")
126 for r in self.requirements:
126 for r in self.requirements:
127 reqfile.write("%s\n" % r)
127 reqfile.write("%s\n" % r)
128 reqfile.close()
128 reqfile.close()
129
129
130 def _checknested(self, path):
130 def _checknested(self, path):
131 """Determine if path is a legal nested repository."""
131 """Determine if path is a legal nested repository."""
132 if not path.startswith(self.root):
132 if not path.startswith(self.root):
133 return False
133 return False
134 subpath = path[len(self.root) + 1:]
134 subpath = path[len(self.root) + 1:]
135 normsubpath = util.pconvert(subpath)
135 normsubpath = util.pconvert(subpath)
136
136
137 # XXX: Checking against the current working copy is wrong in
137 # XXX: Checking against the current working copy is wrong in
138 # the sense that it can reject things like
138 # the sense that it can reject things like
139 #
139 #
140 # $ hg cat -r 10 sub/x.txt
140 # $ hg cat -r 10 sub/x.txt
141 #
141 #
142 # if sub/ is no longer a subrepository in the working copy
142 # if sub/ is no longer a subrepository in the working copy
143 # parent revision.
143 # parent revision.
144 #
144 #
145 # However, it can of course also allow things that would have
145 # However, it can of course also allow things that would have
146 # been rejected before, such as the above cat command if sub/
146 # been rejected before, such as the above cat command if sub/
147 # is a subrepository now, but was a normal directory before.
147 # is a subrepository now, but was a normal directory before.
148 # The old path auditor would have rejected by mistake since it
148 # The old path auditor would have rejected by mistake since it
149 # panics when it sees sub/.hg/.
149 # panics when it sees sub/.hg/.
150 #
150 #
151 # All in all, checking against the working copy seems sensible
151 # All in all, checking against the working copy seems sensible
152 # since we want to prevent access to nested repositories on
152 # since we want to prevent access to nested repositories on
153 # the filesystem *now*.
153 # the filesystem *now*.
154 ctx = self[None]
154 ctx = self[None]
155 parts = util.splitpath(subpath)
155 parts = util.splitpath(subpath)
156 while parts:
156 while parts:
157 prefix = '/'.join(parts)
157 prefix = '/'.join(parts)
158 if prefix in ctx.substate:
158 if prefix in ctx.substate:
159 if prefix == normsubpath:
159 if prefix == normsubpath:
160 return True
160 return True
161 else:
161 else:
162 sub = ctx.sub(prefix)
162 sub = ctx.sub(prefix)
163 return sub.checknested(subpath[len(prefix) + 1:])
163 return sub.checknested(subpath[len(prefix) + 1:])
164 else:
164 else:
165 parts.pop()
165 parts.pop()
166 return False
166 return False
167
167
168 @filecache('bookmarks')
168 @filecache('bookmarks')
169 def _bookmarks(self):
169 def _bookmarks(self):
170 return bookmarks.read(self)
170 return bookmarks.read(self)
171
171
172 @filecache('bookmarks.current')
172 @filecache('bookmarks.current')
173 def _bookmarkcurrent(self):
173 def _bookmarkcurrent(self):
174 return bookmarks.readcurrent(self)
174 return bookmarks.readcurrent(self)
175
175
176 def _writebookmarks(self, marks):
176 def _writebookmarks(self, marks):
177 bookmarks.write(self)
177 bookmarks.write(self)
178
178
179 @filecache('phaseroots', True)
179 @filecache('phaseroots', True)
180 def _phaseroots(self):
180 def _phaseroots(self):
181 self._dirtyphases = False
181 self._dirtyphases = False
182 phaseroots = phases.readroots(self)
182 phaseroots = phases.readroots(self)
183 phases.filterunknown(self, phaseroots)
183 phases.filterunknown(self, phaseroots)
184 return phaseroots
184 return phaseroots
185
185
186 @propertycache
186 @propertycache
187 def _phaserev(self):
187 def _phaserev(self):
188 cache = [phases.public] * len(self)
188 cache = [phases.public] * len(self)
189 for phase in phases.trackedphases:
189 for phase in phases.trackedphases:
190 roots = map(self.changelog.rev, self._phaseroots[phase])
190 roots = map(self.changelog.rev, self._phaseroots[phase])
191 if roots:
191 if roots:
192 for rev in roots:
192 for rev in roots:
193 cache[rev] = phase
193 cache[rev] = phase
194 for rev in self.changelog.descendants(*roots):
194 for rev in self.changelog.descendants(*roots):
195 cache[rev] = phase
195 cache[rev] = phase
196 return cache
196 return cache
197
197
198 @filecache('00changelog.i', True)
198 @filecache('00changelog.i', True)
199 def changelog(self):
199 def changelog(self):
200 c = changelog.changelog(self.sopener)
200 c = changelog.changelog(self.sopener)
201 if 'HG_PENDING' in os.environ:
201 if 'HG_PENDING' in os.environ:
202 p = os.environ['HG_PENDING']
202 p = os.environ['HG_PENDING']
203 if p.startswith(self.root):
203 if p.startswith(self.root):
204 c.readpending('00changelog.i.a')
204 c.readpending('00changelog.i.a')
205 return c
205 return c
206
206
207 @filecache('00manifest.i', True)
207 @filecache('00manifest.i', True)
208 def manifest(self):
208 def manifest(self):
209 return manifest.manifest(self.sopener)
209 return manifest.manifest(self.sopener)
210
210
211 @filecache('dirstate')
211 @filecache('dirstate')
212 def dirstate(self):
212 def dirstate(self):
213 warned = [0]
213 warned = [0]
214 def validate(node):
214 def validate(node):
215 try:
215 try:
216 self.changelog.rev(node)
216 self.changelog.rev(node)
217 return node
217 return node
218 except error.LookupError:
218 except error.LookupError:
219 if not warned[0]:
219 if not warned[0]:
220 warned[0] = True
220 warned[0] = True
221 self.ui.warn(_("warning: ignoring unknown"
221 self.ui.warn(_("warning: ignoring unknown"
222 " working parent %s!\n") % short(node))
222 " working parent %s!\n") % short(node))
223 return nullid
223 return nullid
224
224
225 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
225 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
226
226
227 def __getitem__(self, changeid):
227 def __getitem__(self, changeid):
228 if changeid is None:
228 if changeid is None:
229 return context.workingctx(self)
229 return context.workingctx(self)
230 return context.changectx(self, changeid)
230 return context.changectx(self, changeid)
231
231
232 def __contains__(self, changeid):
232 def __contains__(self, changeid):
233 try:
233 try:
234 return bool(self.lookup(changeid))
234 return bool(self.lookup(changeid))
235 except error.RepoLookupError:
235 except error.RepoLookupError:
236 return False
236 return False
237
237
238 def __nonzero__(self):
238 def __nonzero__(self):
239 return True
239 return True
240
240
241 def __len__(self):
241 def __len__(self):
242 return len(self.changelog)
242 return len(self.changelog)
243
243
244 def __iter__(self):
244 def __iter__(self):
245 for i in xrange(len(self)):
245 for i in xrange(len(self)):
246 yield i
246 yield i
247
247
248 def revs(self, expr, *args):
248 def revs(self, expr, *args):
249 '''Return a list of revisions matching the given revset'''
249 '''Return a list of revisions matching the given revset'''
250 expr = revset.formatspec(expr, *args)
250 expr = revset.formatspec(expr, *args)
251 m = revset.match(None, expr)
251 m = revset.match(None, expr)
252 return [r for r in m(self, range(len(self)))]
252 return [r for r in m(self, range(len(self)))]
253
253
254 def set(self, expr, *args):
254 def set(self, expr, *args):
255 '''
255 '''
256 Yield a context for each matching revision, after doing arg
256 Yield a context for each matching revision, after doing arg
257 replacement via revset.formatspec
257 replacement via revset.formatspec
258 '''
258 '''
259 for r in self.revs(expr, *args):
259 for r in self.revs(expr, *args):
260 yield self[r]
260 yield self[r]
261
261
262 def url(self):
262 def url(self):
263 return 'file:' + self.root
263 return 'file:' + self.root
264
264
265 def hook(self, name, throw=False, **args):
265 def hook(self, name, throw=False, **args):
266 return hook.hook(self.ui, self, name, throw, **args)
266 return hook.hook(self.ui, self, name, throw, **args)
267
267
268 tag_disallowed = ':\r\n'
268 tag_disallowed = ':\r\n'
269
269
270 def _tag(self, names, node, message, local, user, date, extra={}):
270 def _tag(self, names, node, message, local, user, date, extra={}):
271 if isinstance(names, str):
271 if isinstance(names, str):
272 allchars = names
272 allchars = names
273 names = (names,)
273 names = (names,)
274 else:
274 else:
275 allchars = ''.join(names)
275 allchars = ''.join(names)
276 for c in self.tag_disallowed:
276 for c in self.tag_disallowed:
277 if c in allchars:
277 if c in allchars:
278 raise util.Abort(_('%r cannot be used in a tag name') % c)
278 raise util.Abort(_('%r cannot be used in a tag name') % c)
279
279
280 branches = self.branchmap()
280 branches = self.branchmap()
281 for name in names:
281 for name in names:
282 self.hook('pretag', throw=True, node=hex(node), tag=name,
282 self.hook('pretag', throw=True, node=hex(node), tag=name,
283 local=local)
283 local=local)
284 if name in branches:
284 if name in branches:
285 self.ui.warn(_("warning: tag %s conflicts with existing"
285 self.ui.warn(_("warning: tag %s conflicts with existing"
286 " branch name\n") % name)
286 " branch name\n") % name)
287
287
288 def writetags(fp, names, munge, prevtags):
288 def writetags(fp, names, munge, prevtags):
289 fp.seek(0, 2)
289 fp.seek(0, 2)
290 if prevtags and prevtags[-1] != '\n':
290 if prevtags and prevtags[-1] != '\n':
291 fp.write('\n')
291 fp.write('\n')
292 for name in names:
292 for name in names:
293 m = munge and munge(name) or name
293 m = munge and munge(name) or name
294 if self._tagscache.tagtypes and name in self._tagscache.tagtypes:
294 if self._tagscache.tagtypes and name in self._tagscache.tagtypes:
295 old = self.tags().get(name, nullid)
295 old = self.tags().get(name, nullid)
296 fp.write('%s %s\n' % (hex(old), m))
296 fp.write('%s %s\n' % (hex(old), m))
297 fp.write('%s %s\n' % (hex(node), m))
297 fp.write('%s %s\n' % (hex(node), m))
298 fp.close()
298 fp.close()
299
299
300 prevtags = ''
300 prevtags = ''
301 if local:
301 if local:
302 try:
302 try:
303 fp = self.opener('localtags', 'r+')
303 fp = self.opener('localtags', 'r+')
304 except IOError:
304 except IOError:
305 fp = self.opener('localtags', 'a')
305 fp = self.opener('localtags', 'a')
306 else:
306 else:
307 prevtags = fp.read()
307 prevtags = fp.read()
308
308
309 # local tags are stored in the current charset
309 # local tags are stored in the current charset
310 writetags(fp, names, None, prevtags)
310 writetags(fp, names, None, prevtags)
311 for name in names:
311 for name in names:
312 self.hook('tag', node=hex(node), tag=name, local=local)
312 self.hook('tag', node=hex(node), tag=name, local=local)
313 return
313 return
314
314
315 try:
315 try:
316 fp = self.wfile('.hgtags', 'rb+')
316 fp = self.wfile('.hgtags', 'rb+')
317 except IOError, e:
317 except IOError, e:
318 if e.errno != errno.ENOENT:
318 if e.errno != errno.ENOENT:
319 raise
319 raise
320 fp = self.wfile('.hgtags', 'ab')
320 fp = self.wfile('.hgtags', 'ab')
321 else:
321 else:
322 prevtags = fp.read()
322 prevtags = fp.read()
323
323
324 # committed tags are stored in UTF-8
324 # committed tags are stored in UTF-8
325 writetags(fp, names, encoding.fromlocal, prevtags)
325 writetags(fp, names, encoding.fromlocal, prevtags)
326
326
327 fp.close()
327 fp.close()
328
328
329 self.invalidatecaches()
329 self.invalidatecaches()
330
330
331 if '.hgtags' not in self.dirstate:
331 if '.hgtags' not in self.dirstate:
332 self[None].add(['.hgtags'])
332 self[None].add(['.hgtags'])
333
333
334 m = matchmod.exact(self.root, '', ['.hgtags'])
334 m = matchmod.exact(self.root, '', ['.hgtags'])
335 tagnode = self.commit(message, user, date, extra=extra, match=m)
335 tagnode = self.commit(message, user, date, extra=extra, match=m)
336
336
337 for name in names:
337 for name in names:
338 self.hook('tag', node=hex(node), tag=name, local=local)
338 self.hook('tag', node=hex(node), tag=name, local=local)
339
339
340 return tagnode
340 return tagnode
341
341
342 def tag(self, names, node, message, local, user, date):
342 def tag(self, names, node, message, local, user, date):
343 '''tag a revision with one or more symbolic names.
343 '''tag a revision with one or more symbolic names.
344
344
345 names is a list of strings or, when adding a single tag, names may be a
345 names is a list of strings or, when adding a single tag, names may be a
346 string.
346 string.
347
347
348 if local is True, the tags are stored in a per-repository file.
348 if local is True, the tags are stored in a per-repository file.
349 otherwise, they are stored in the .hgtags file, and a new
349 otherwise, they are stored in the .hgtags file, and a new
350 changeset is committed with the change.
350 changeset is committed with the change.
351
351
352 keyword arguments:
352 keyword arguments:
353
353
354 local: whether to store tags in non-version-controlled file
354 local: whether to store tags in non-version-controlled file
355 (default False)
355 (default False)
356
356
357 message: commit message to use if committing
357 message: commit message to use if committing
358
358
359 user: name of user to use if committing
359 user: name of user to use if committing
360
360
361 date: date tuple to use if committing'''
361 date: date tuple to use if committing'''
362
362
363 if not local:
363 if not local:
364 for x in self.status()[:5]:
364 for x in self.status()[:5]:
365 if '.hgtags' in x:
365 if '.hgtags' in x:
366 raise util.Abort(_('working copy of .hgtags is changed '
366 raise util.Abort(_('working copy of .hgtags is changed '
367 '(please commit .hgtags manually)'))
367 '(please commit .hgtags manually)'))
368
368
369 self.tags() # instantiate the cache
369 self.tags() # instantiate the cache
370 self._tag(names, node, message, local, user, date)
370 self._tag(names, node, message, local, user, date)
371
371
372 @propertycache
372 @propertycache
373 def _tagscache(self):
373 def _tagscache(self):
374 '''Returns a tagscache object that contains various tags related caches.'''
374 '''Returns a tagscache object that contains various tags related caches.'''
375
375
376 # This simplifies its cache management by having one decorated
376 # This simplifies its cache management by having one decorated
377 # function (this one) and the rest simply fetch things from it.
377 # function (this one) and the rest simply fetch things from it.
378 class tagscache(object):
378 class tagscache(object):
379 def __init__(self):
379 def __init__(self):
380 # These two define the set of tags for this repository. tags
380 # These two define the set of tags for this repository. tags
381 # maps tag name to node; tagtypes maps tag name to 'global' or
381 # maps tag name to node; tagtypes maps tag name to 'global' or
382 # 'local'. (Global tags are defined by .hgtags across all
382 # 'local'. (Global tags are defined by .hgtags across all
383 # heads, and local tags are defined in .hg/localtags.)
383 # heads, and local tags are defined in .hg/localtags.)
384 # They constitute the in-memory cache of tags.
384 # They constitute the in-memory cache of tags.
385 self.tags = self.tagtypes = None
385 self.tags = self.tagtypes = None
386
386
387 self.nodetagscache = self.tagslist = None
387 self.nodetagscache = self.tagslist = None
388
388
389 cache = tagscache()
389 cache = tagscache()
390 cache.tags, cache.tagtypes = self._findtags()
390 cache.tags, cache.tagtypes = self._findtags()
391
391
392 return cache
392 return cache
393
393
394 def tags(self):
394 def tags(self):
395 '''return a mapping of tag to node'''
395 '''return a mapping of tag to node'''
396 return self._tagscache.tags
396 return self._tagscache.tags
397
397
398 def _findtags(self):
398 def _findtags(self):
399 '''Do the hard work of finding tags. Return a pair of dicts
399 '''Do the hard work of finding tags. Return a pair of dicts
400 (tags, tagtypes) where tags maps tag name to node, and tagtypes
400 (tags, tagtypes) where tags maps tag name to node, and tagtypes
401 maps tag name to a string like \'global\' or \'local\'.
401 maps tag name to a string like \'global\' or \'local\'.
402 Subclasses or extensions are free to add their own tags, but
402 Subclasses or extensions are free to add their own tags, but
403 should be aware that the returned dicts will be retained for the
403 should be aware that the returned dicts will be retained for the
404 duration of the localrepo object.'''
404 duration of the localrepo object.'''
405
405
406 # XXX what tagtype should subclasses/extensions use? Currently
406 # XXX what tagtype should subclasses/extensions use? Currently
407 # mq and bookmarks add tags, but do not set the tagtype at all.
407 # mq and bookmarks add tags, but do not set the tagtype at all.
408 # Should each extension invent its own tag type? Should there
408 # Should each extension invent its own tag type? Should there
409 # be one tagtype for all such "virtual" tags? Or is the status
409 # be one tagtype for all such "virtual" tags? Or is the status
410 # quo fine?
410 # quo fine?
411
411
412 alltags = {} # map tag name to (node, hist)
412 alltags = {} # map tag name to (node, hist)
413 tagtypes = {}
413 tagtypes = {}
414
414
415 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
415 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
416 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
416 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
417
417
418 # Build the return dicts. Have to re-encode tag names because
418 # Build the return dicts. Have to re-encode tag names because
419 # the tags module always uses UTF-8 (in order not to lose info
419 # the tags module always uses UTF-8 (in order not to lose info
420 # writing to the cache), but the rest of Mercurial wants them in
420 # writing to the cache), but the rest of Mercurial wants them in
421 # local encoding.
421 # local encoding.
422 tags = {}
422 tags = {}
423 for (name, (node, hist)) in alltags.iteritems():
423 for (name, (node, hist)) in alltags.iteritems():
424 if node != nullid:
424 if node != nullid:
425 try:
425 try:
426 # ignore tags to unknown nodes
426 # ignore tags to unknown nodes
427 self.changelog.lookup(node)
427 self.changelog.lookup(node)
428 tags[encoding.tolocal(name)] = node
428 tags[encoding.tolocal(name)] = node
429 except error.LookupError:
429 except error.LookupError:
430 pass
430 pass
431 tags['tip'] = self.changelog.tip()
431 tags['tip'] = self.changelog.tip()
432 tagtypes = dict([(encoding.tolocal(name), value)
432 tagtypes = dict([(encoding.tolocal(name), value)
433 for (name, value) in tagtypes.iteritems()])
433 for (name, value) in tagtypes.iteritems()])
434 return (tags, tagtypes)
434 return (tags, tagtypes)
435
435
436 def tagtype(self, tagname):
436 def tagtype(self, tagname):
437 '''
437 '''
438 return the type of the given tag. result can be:
438 return the type of the given tag. result can be:
439
439
440 'local' : a local tag
440 'local' : a local tag
441 'global' : a global tag
441 'global' : a global tag
442 None : tag does not exist
442 None : tag does not exist
443 '''
443 '''
444
444
445 return self._tagscache.tagtypes.get(tagname)
445 return self._tagscache.tagtypes.get(tagname)
446
446
447 def tagslist(self):
447 def tagslist(self):
448 '''return a list of tags ordered by revision'''
448 '''return a list of tags ordered by revision'''
449 if not self._tagscache.tagslist:
449 if not self._tagscache.tagslist:
450 l = []
450 l = []
451 for t, n in self.tags().iteritems():
451 for t, n in self.tags().iteritems():
452 r = self.changelog.rev(n)
452 r = self.changelog.rev(n)
453 l.append((r, t, n))
453 l.append((r, t, n))
454 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
454 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
455
455
456 return self._tagscache.tagslist
456 return self._tagscache.tagslist
457
457
458 def nodetags(self, node):
458 def nodetags(self, node):
459 '''return the tags associated with a node'''
459 '''return the tags associated with a node'''
460 if not self._tagscache.nodetagscache:
460 if not self._tagscache.nodetagscache:
461 nodetagscache = {}
461 nodetagscache = {}
462 for t, n in self.tags().iteritems():
462 for t, n in self.tags().iteritems():
463 nodetagscache.setdefault(n, []).append(t)
463 nodetagscache.setdefault(n, []).append(t)
464 for tags in nodetagscache.itervalues():
464 for tags in nodetagscache.itervalues():
465 tags.sort()
465 tags.sort()
466 self._tagscache.nodetagscache = nodetagscache
466 self._tagscache.nodetagscache = nodetagscache
467 return self._tagscache.nodetagscache.get(node, [])
467 return self._tagscache.nodetagscache.get(node, [])
468
468
469 def nodebookmarks(self, node):
469 def nodebookmarks(self, node):
470 marks = []
470 marks = []
471 for bookmark, n in self._bookmarks.iteritems():
471 for bookmark, n in self._bookmarks.iteritems():
472 if n == node:
472 if n == node:
473 marks.append(bookmark)
473 marks.append(bookmark)
474 return sorted(marks)
474 return sorted(marks)
475
475
476 def _branchtags(self, partial, lrev):
476 def _branchtags(self, partial, lrev):
477 # TODO: rename this function?
477 # TODO: rename this function?
478 tiprev = len(self) - 1
478 tiprev = len(self) - 1
479 if lrev != tiprev:
479 if lrev != tiprev:
480 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
480 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
481 self._updatebranchcache(partial, ctxgen)
481 self._updatebranchcache(partial, ctxgen)
482 self._writebranchcache(partial, self.changelog.tip(), tiprev)
482 self._writebranchcache(partial, self.changelog.tip(), tiprev)
483
483
484 return partial
484 return partial
485
485
486 def updatebranchcache(self):
486 def updatebranchcache(self):
487 tip = self.changelog.tip()
487 tip = self.changelog.tip()
488 if self._branchcache is not None and self._branchcachetip == tip:
488 if self._branchcache is not None and self._branchcachetip == tip:
489 return
489 return
490
490
491 oldtip = self._branchcachetip
491 oldtip = self._branchcachetip
492 self._branchcachetip = tip
492 self._branchcachetip = tip
493 if oldtip is None or oldtip not in self.changelog.nodemap:
493 if oldtip is None or oldtip not in self.changelog.nodemap:
494 partial, last, lrev = self._readbranchcache()
494 partial, last, lrev = self._readbranchcache()
495 else:
495 else:
496 lrev = self.changelog.rev(oldtip)
496 lrev = self.changelog.rev(oldtip)
497 partial = self._branchcache
497 partial = self._branchcache
498
498
499 self._branchtags(partial, lrev)
499 self._branchtags(partial, lrev)
500 # this private cache holds all heads (not just tips)
500 # this private cache holds all heads (not just tips)
501 self._branchcache = partial
501 self._branchcache = partial
502
502
503 def branchmap(self):
503 def branchmap(self):
504 '''returns a dictionary {branch: [branchheads]}'''
504 '''returns a dictionary {branch: [branchheads]}'''
505 self.updatebranchcache()
505 self.updatebranchcache()
506 return self._branchcache
506 return self._branchcache
507
507
508 def branchtags(self):
508 def branchtags(self):
509 '''return a dict where branch names map to the tipmost head of
509 '''return a dict where branch names map to the tipmost head of
510 the branch, open heads come before closed'''
510 the branch, open heads come before closed'''
511 bt = {}
511 bt = {}
512 for bn, heads in self.branchmap().iteritems():
512 for bn, heads in self.branchmap().iteritems():
513 tip = heads[-1]
513 tip = heads[-1]
514 for h in reversed(heads):
514 for h in reversed(heads):
515 if 'close' not in self.changelog.read(h)[5]:
515 if 'close' not in self.changelog.read(h)[5]:
516 tip = h
516 tip = h
517 break
517 break
518 bt[bn] = tip
518 bt[bn] = tip
519 return bt
519 return bt
520
520
521 def _readbranchcache(self):
521 def _readbranchcache(self):
522 partial = {}
522 partial = {}
523 try:
523 try:
524 f = self.opener("cache/branchheads")
524 f = self.opener("cache/branchheads")
525 lines = f.read().split('\n')
525 lines = f.read().split('\n')
526 f.close()
526 f.close()
527 except (IOError, OSError):
527 except (IOError, OSError):
528 return {}, nullid, nullrev
528 return {}, nullid, nullrev
529
529
530 try:
530 try:
531 last, lrev = lines.pop(0).split(" ", 1)
531 last, lrev = lines.pop(0).split(" ", 1)
532 last, lrev = bin(last), int(lrev)
532 last, lrev = bin(last), int(lrev)
533 if lrev >= len(self) or self[lrev].node() != last:
533 if lrev >= len(self) or self[lrev].node() != last:
534 # invalidate the cache
534 # invalidate the cache
535 raise ValueError('invalidating branch cache (tip differs)')
535 raise ValueError('invalidating branch cache (tip differs)')
536 for l in lines:
536 for l in lines:
537 if not l:
537 if not l:
538 continue
538 continue
539 node, label = l.split(" ", 1)
539 node, label = l.split(" ", 1)
540 label = encoding.tolocal(label.strip())
540 label = encoding.tolocal(label.strip())
541 partial.setdefault(label, []).append(bin(node))
541 partial.setdefault(label, []).append(bin(node))
542 except KeyboardInterrupt:
542 except KeyboardInterrupt:
543 raise
543 raise
544 except Exception, inst:
544 except Exception, inst:
545 if self.ui.debugflag:
545 if self.ui.debugflag:
546 self.ui.warn(str(inst), '\n')
546 self.ui.warn(str(inst), '\n')
547 partial, last, lrev = {}, nullid, nullrev
547 partial, last, lrev = {}, nullid, nullrev
548 return partial, last, lrev
548 return partial, last, lrev
549
549
550 def _writebranchcache(self, branches, tip, tiprev):
550 def _writebranchcache(self, branches, tip, tiprev):
551 try:
551 try:
552 f = self.opener("cache/branchheads", "w", atomictemp=True)
552 f = self.opener("cache/branchheads", "w", atomictemp=True)
553 f.write("%s %s\n" % (hex(tip), tiprev))
553 f.write("%s %s\n" % (hex(tip), tiprev))
554 for label, nodes in branches.iteritems():
554 for label, nodes in branches.iteritems():
555 for node in nodes:
555 for node in nodes:
556 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
556 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
557 f.close()
557 f.close()
558 except (IOError, OSError):
558 except (IOError, OSError):
559 pass
559 pass
560
560
561 def _updatebranchcache(self, partial, ctxgen):
561 def _updatebranchcache(self, partial, ctxgen):
562 # collect new branch entries
562 # collect new branch entries
563 newbranches = {}
563 newbranches = {}
564 for c in ctxgen:
564 for c in ctxgen:
565 newbranches.setdefault(c.branch(), []).append(c.node())
565 newbranches.setdefault(c.branch(), []).append(c.node())
566 # if older branchheads are reachable from new ones, they aren't
566 # if older branchheads are reachable from new ones, they aren't
567 # really branchheads. Note checking parents is insufficient:
567 # really branchheads. Note checking parents is insufficient:
568 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
568 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
569 for branch, newnodes in newbranches.iteritems():
569 for branch, newnodes in newbranches.iteritems():
570 bheads = partial.setdefault(branch, [])
570 bheads = partial.setdefault(branch, [])
571 bheads.extend(newnodes)
571 bheads.extend(newnodes)
572 if len(bheads) <= 1:
572 if len(bheads) <= 1:
573 continue
573 continue
574 bheads = sorted(bheads, key=lambda x: self[x].rev())
574 bheads = sorted(bheads, key=lambda x: self[x].rev())
575 # starting from tip means fewer passes over reachable
575 # starting from tip means fewer passes over reachable
576 while newnodes:
576 while newnodes:
577 latest = newnodes.pop()
577 latest = newnodes.pop()
578 if latest not in bheads:
578 if latest not in bheads:
579 continue
579 continue
580 minbhrev = self[bheads[0]].node()
580 minbhrev = self[bheads[0]].node()
581 reachable = self.changelog.reachable(latest, minbhrev)
581 reachable = self.changelog.reachable(latest, minbhrev)
582 reachable.remove(latest)
582 reachable.remove(latest)
583 if reachable:
583 if reachable:
584 bheads = [b for b in bheads if b not in reachable]
584 bheads = [b for b in bheads if b not in reachable]
585 partial[branch] = bheads
585 partial[branch] = bheads
586
586
587 def lookup(self, key):
587 def lookup(self, key):
588 if isinstance(key, int):
588 if isinstance(key, int):
589 return self.changelog.node(key)
589 return self.changelog.node(key)
590 elif key == '.':
590 elif key == '.':
591 return self.dirstate.p1()
591 return self.dirstate.p1()
592 elif key == 'null':
592 elif key == 'null':
593 return nullid
593 return nullid
594 elif key == 'tip':
594 elif key == 'tip':
595 return self.changelog.tip()
595 return self.changelog.tip()
596 n = self.changelog._match(key)
596 n = self.changelog._match(key)
597 if n:
597 if n:
598 return n
598 return n
599 if key in self._bookmarks:
599 if key in self._bookmarks:
600 return self._bookmarks[key]
600 return self._bookmarks[key]
601 if key in self.tags():
601 if key in self.tags():
602 return self.tags()[key]
602 return self.tags()[key]
603 if key in self.branchtags():
603 if key in self.branchtags():
604 return self.branchtags()[key]
604 return self.branchtags()[key]
605 n = self.changelog._partialmatch(key)
605 n = self.changelog._partialmatch(key)
606 if n:
606 if n:
607 return n
607 return n
608
608
609 # can't find key, check if it might have come from damaged dirstate
609 # can't find key, check if it might have come from damaged dirstate
610 if key in self.dirstate.parents():
610 if key in self.dirstate.parents():
611 raise error.Abort(_("working directory has unknown parent '%s'!")
611 raise error.Abort(_("working directory has unknown parent '%s'!")
612 % short(key))
612 % short(key))
613 try:
613 try:
614 if len(key) == 20:
614 if len(key) == 20:
615 key = hex(key)
615 key = hex(key)
616 except TypeError:
616 except TypeError:
617 pass
617 pass
618 raise error.RepoLookupError(_("unknown revision '%s'") % key)
618 raise error.RepoLookupError(_("unknown revision '%s'") % key)
619
619
620 def lookupbranch(self, key, remote=None):
620 def lookupbranch(self, key, remote=None):
621 repo = remote or self
621 repo = remote or self
622 if key in repo.branchmap():
622 if key in repo.branchmap():
623 return key
623 return key
624
624
625 repo = (remote and remote.local()) and remote or self
625 repo = (remote and remote.local()) and remote or self
626 return repo[key].branch()
626 return repo[key].branch()
627
627
628 def known(self, nodes):
628 def known(self, nodes):
629 nm = self.changelog.nodemap
629 nm = self.changelog.nodemap
630 result = []
630 result = []
631 for n in nodes:
631 for n in nodes:
632 r = nm.get(n)
632 r = nm.get(n)
633 resp = not (r is None or self._phaserev[r] >= phases.secret)
633 resp = not (r is None or self._phaserev[r] >= phases.secret)
634 result.append(resp)
634 result.append(resp)
635 return result
635 return result
636
636
637 def local(self):
637 def local(self):
638 return self
638 return self
639
639
640 def cancopy(self):
641 return (repo.repository.cancopy(self)
642 and not self._phaseroots[phases.secret])
643
644 def join(self, f):
640 def join(self, f):
645 return os.path.join(self.path, f)
641 return os.path.join(self.path, f)
646
642
647 def wjoin(self, f):
643 def wjoin(self, f):
648 return os.path.join(self.root, f)
644 return os.path.join(self.root, f)
649
645
650 def file(self, f):
646 def file(self, f):
651 if f[0] == '/':
647 if f[0] == '/':
652 f = f[1:]
648 f = f[1:]
653 return filelog.filelog(self.sopener, f)
649 return filelog.filelog(self.sopener, f)
654
650
655 def changectx(self, changeid):
651 def changectx(self, changeid):
656 return self[changeid]
652 return self[changeid]
657
653
658 def parents(self, changeid=None):
654 def parents(self, changeid=None):
659 '''get list of changectxs for parents of changeid'''
655 '''get list of changectxs for parents of changeid'''
660 return self[changeid].parents()
656 return self[changeid].parents()
661
657
662 def filectx(self, path, changeid=None, fileid=None):
658 def filectx(self, path, changeid=None, fileid=None):
663 """changeid can be a changeset revision, node, or tag.
659 """changeid can be a changeset revision, node, or tag.
664 fileid can be a file revision or node."""
660 fileid can be a file revision or node."""
665 return context.filectx(self, path, changeid, fileid)
661 return context.filectx(self, path, changeid, fileid)
666
662
667 def getcwd(self):
663 def getcwd(self):
668 return self.dirstate.getcwd()
664 return self.dirstate.getcwd()
669
665
670 def pathto(self, f, cwd=None):
666 def pathto(self, f, cwd=None):
671 return self.dirstate.pathto(f, cwd)
667 return self.dirstate.pathto(f, cwd)
672
668
673 def wfile(self, f, mode='r'):
669 def wfile(self, f, mode='r'):
674 return self.wopener(f, mode)
670 return self.wopener(f, mode)
675
671
676 def _link(self, f):
672 def _link(self, f):
677 return os.path.islink(self.wjoin(f))
673 return os.path.islink(self.wjoin(f))
678
674
679 def _loadfilter(self, filter):
675 def _loadfilter(self, filter):
680 if filter not in self.filterpats:
676 if filter not in self.filterpats:
681 l = []
677 l = []
682 for pat, cmd in self.ui.configitems(filter):
678 for pat, cmd in self.ui.configitems(filter):
683 if cmd == '!':
679 if cmd == '!':
684 continue
680 continue
685 mf = matchmod.match(self.root, '', [pat])
681 mf = matchmod.match(self.root, '', [pat])
686 fn = None
682 fn = None
687 params = cmd
683 params = cmd
688 for name, filterfn in self._datafilters.iteritems():
684 for name, filterfn in self._datafilters.iteritems():
689 if cmd.startswith(name):
685 if cmd.startswith(name):
690 fn = filterfn
686 fn = filterfn
691 params = cmd[len(name):].lstrip()
687 params = cmd[len(name):].lstrip()
692 break
688 break
693 if not fn:
689 if not fn:
694 fn = lambda s, c, **kwargs: util.filter(s, c)
690 fn = lambda s, c, **kwargs: util.filter(s, c)
695 # Wrap old filters not supporting keyword arguments
691 # Wrap old filters not supporting keyword arguments
696 if not inspect.getargspec(fn)[2]:
692 if not inspect.getargspec(fn)[2]:
697 oldfn = fn
693 oldfn = fn
698 fn = lambda s, c, **kwargs: oldfn(s, c)
694 fn = lambda s, c, **kwargs: oldfn(s, c)
699 l.append((mf, fn, params))
695 l.append((mf, fn, params))
700 self.filterpats[filter] = l
696 self.filterpats[filter] = l
701 return self.filterpats[filter]
697 return self.filterpats[filter]
702
698
703 def _filter(self, filterpats, filename, data):
699 def _filter(self, filterpats, filename, data):
704 for mf, fn, cmd in filterpats:
700 for mf, fn, cmd in filterpats:
705 if mf(filename):
701 if mf(filename):
706 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
702 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
707 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
703 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
708 break
704 break
709
705
710 return data
706 return data
711
707
712 @propertycache
708 @propertycache
713 def _encodefilterpats(self):
709 def _encodefilterpats(self):
714 return self._loadfilter('encode')
710 return self._loadfilter('encode')
715
711
716 @propertycache
712 @propertycache
717 def _decodefilterpats(self):
713 def _decodefilterpats(self):
718 return self._loadfilter('decode')
714 return self._loadfilter('decode')
719
715
720 def adddatafilter(self, name, filter):
716 def adddatafilter(self, name, filter):
721 self._datafilters[name] = filter
717 self._datafilters[name] = filter
722
718
723 def wread(self, filename):
719 def wread(self, filename):
724 if self._link(filename):
720 if self._link(filename):
725 data = os.readlink(self.wjoin(filename))
721 data = os.readlink(self.wjoin(filename))
726 else:
722 else:
727 data = self.wopener.read(filename)
723 data = self.wopener.read(filename)
728 return self._filter(self._encodefilterpats, filename, data)
724 return self._filter(self._encodefilterpats, filename, data)
729
725
730 def wwrite(self, filename, data, flags):
726 def wwrite(self, filename, data, flags):
731 data = self._filter(self._decodefilterpats, filename, data)
727 data = self._filter(self._decodefilterpats, filename, data)
732 if 'l' in flags:
728 if 'l' in flags:
733 self.wopener.symlink(data, filename)
729 self.wopener.symlink(data, filename)
734 else:
730 else:
735 self.wopener.write(filename, data)
731 self.wopener.write(filename, data)
736 if 'x' in flags:
732 if 'x' in flags:
737 util.setflags(self.wjoin(filename), False, True)
733 util.setflags(self.wjoin(filename), False, True)
738
734
739 def wwritedata(self, filename, data):
735 def wwritedata(self, filename, data):
740 return self._filter(self._decodefilterpats, filename, data)
736 return self._filter(self._decodefilterpats, filename, data)
741
737
742 def transaction(self, desc):
738 def transaction(self, desc):
743 tr = self._transref and self._transref() or None
739 tr = self._transref and self._transref() or None
744 if tr and tr.running():
740 if tr and tr.running():
745 return tr.nest()
741 return tr.nest()
746
742
747 # abort here if the journal already exists
743 # abort here if the journal already exists
748 if os.path.exists(self.sjoin("journal")):
744 if os.path.exists(self.sjoin("journal")):
749 raise error.RepoError(
745 raise error.RepoError(
750 _("abandoned transaction found - run hg recover"))
746 _("abandoned transaction found - run hg recover"))
751
747
752 journalfiles = self._writejournal(desc)
748 journalfiles = self._writejournal(desc)
753 renames = [(x, undoname(x)) for x in journalfiles]
749 renames = [(x, undoname(x)) for x in journalfiles]
754
750
755 tr = transaction.transaction(self.ui.warn, self.sopener,
751 tr = transaction.transaction(self.ui.warn, self.sopener,
756 self.sjoin("journal"),
752 self.sjoin("journal"),
757 aftertrans(renames),
753 aftertrans(renames),
758 self.store.createmode)
754 self.store.createmode)
759 self._transref = weakref.ref(tr)
755 self._transref = weakref.ref(tr)
760 return tr
756 return tr
761
757
762 def _writejournal(self, desc):
758 def _writejournal(self, desc):
763 # save dirstate for rollback
759 # save dirstate for rollback
764 try:
760 try:
765 ds = self.opener.read("dirstate")
761 ds = self.opener.read("dirstate")
766 except IOError:
762 except IOError:
767 ds = ""
763 ds = ""
768 self.opener.write("journal.dirstate", ds)
764 self.opener.write("journal.dirstate", ds)
769 self.opener.write("journal.branch",
765 self.opener.write("journal.branch",
770 encoding.fromlocal(self.dirstate.branch()))
766 encoding.fromlocal(self.dirstate.branch()))
771 self.opener.write("journal.desc",
767 self.opener.write("journal.desc",
772 "%d\n%s\n" % (len(self), desc))
768 "%d\n%s\n" % (len(self), desc))
773
769
774 bkname = self.join('bookmarks')
770 bkname = self.join('bookmarks')
775 if os.path.exists(bkname):
771 if os.path.exists(bkname):
776 util.copyfile(bkname, self.join('journal.bookmarks'))
772 util.copyfile(bkname, self.join('journal.bookmarks'))
777 else:
773 else:
778 self.opener.write('journal.bookmarks', '')
774 self.opener.write('journal.bookmarks', '')
779 phasesname = self.sjoin('phaseroots')
775 phasesname = self.sjoin('phaseroots')
780 if os.path.exists(phasesname):
776 if os.path.exists(phasesname):
781 util.copyfile(phasesname, self.sjoin('journal.phaseroots'))
777 util.copyfile(phasesname, self.sjoin('journal.phaseroots'))
782 else:
778 else:
783 self.sopener.write('journal.phaseroots', '')
779 self.sopener.write('journal.phaseroots', '')
784
780
785 return (self.sjoin('journal'), self.join('journal.dirstate'),
781 return (self.sjoin('journal'), self.join('journal.dirstate'),
786 self.join('journal.branch'), self.join('journal.desc'),
782 self.join('journal.branch'), self.join('journal.desc'),
787 self.join('journal.bookmarks'),
783 self.join('journal.bookmarks'),
788 self.sjoin('journal.phaseroots'))
784 self.sjoin('journal.phaseroots'))
789
785
790 def recover(self):
786 def recover(self):
791 lock = self.lock()
787 lock = self.lock()
792 try:
788 try:
793 if os.path.exists(self.sjoin("journal")):
789 if os.path.exists(self.sjoin("journal")):
794 self.ui.status(_("rolling back interrupted transaction\n"))
790 self.ui.status(_("rolling back interrupted transaction\n"))
795 transaction.rollback(self.sopener, self.sjoin("journal"),
791 transaction.rollback(self.sopener, self.sjoin("journal"),
796 self.ui.warn)
792 self.ui.warn)
797 self.invalidate()
793 self.invalidate()
798 return True
794 return True
799 else:
795 else:
800 self.ui.warn(_("no interrupted transaction available\n"))
796 self.ui.warn(_("no interrupted transaction available\n"))
801 return False
797 return False
802 finally:
798 finally:
803 lock.release()
799 lock.release()
804
800
805 def rollback(self, dryrun=False, force=False):
801 def rollback(self, dryrun=False, force=False):
806 wlock = lock = None
802 wlock = lock = None
807 try:
803 try:
808 wlock = self.wlock()
804 wlock = self.wlock()
809 lock = self.lock()
805 lock = self.lock()
810 if os.path.exists(self.sjoin("undo")):
806 if os.path.exists(self.sjoin("undo")):
811 return self._rollback(dryrun, force)
807 return self._rollback(dryrun, force)
812 else:
808 else:
813 self.ui.warn(_("no rollback information available\n"))
809 self.ui.warn(_("no rollback information available\n"))
814 return 1
810 return 1
815 finally:
811 finally:
816 release(lock, wlock)
812 release(lock, wlock)
817
813
818 def _rollback(self, dryrun, force):
814 def _rollback(self, dryrun, force):
819 ui = self.ui
815 ui = self.ui
820 try:
816 try:
821 args = self.opener.read('undo.desc').splitlines()
817 args = self.opener.read('undo.desc').splitlines()
822 (oldlen, desc, detail) = (int(args[0]), args[1], None)
818 (oldlen, desc, detail) = (int(args[0]), args[1], None)
823 if len(args) >= 3:
819 if len(args) >= 3:
824 detail = args[2]
820 detail = args[2]
825 oldtip = oldlen - 1
821 oldtip = oldlen - 1
826
822
827 if detail and ui.verbose:
823 if detail and ui.verbose:
828 msg = (_('repository tip rolled back to revision %s'
824 msg = (_('repository tip rolled back to revision %s'
829 ' (undo %s: %s)\n')
825 ' (undo %s: %s)\n')
830 % (oldtip, desc, detail))
826 % (oldtip, desc, detail))
831 else:
827 else:
832 msg = (_('repository tip rolled back to revision %s'
828 msg = (_('repository tip rolled back to revision %s'
833 ' (undo %s)\n')
829 ' (undo %s)\n')
834 % (oldtip, desc))
830 % (oldtip, desc))
835 except IOError:
831 except IOError:
836 msg = _('rolling back unknown transaction\n')
832 msg = _('rolling back unknown transaction\n')
837 desc = None
833 desc = None
838
834
839 if not force and self['.'] != self['tip'] and desc == 'commit':
835 if not force and self['.'] != self['tip'] and desc == 'commit':
840 raise util.Abort(
836 raise util.Abort(
841 _('rollback of last commit while not checked out '
837 _('rollback of last commit while not checked out '
842 'may lose data'), hint=_('use -f to force'))
838 'may lose data'), hint=_('use -f to force'))
843
839
844 ui.status(msg)
840 ui.status(msg)
845 if dryrun:
841 if dryrun:
846 return 0
842 return 0
847
843
848 parents = self.dirstate.parents()
844 parents = self.dirstate.parents()
849 transaction.rollback(self.sopener, self.sjoin('undo'), ui.warn)
845 transaction.rollback(self.sopener, self.sjoin('undo'), ui.warn)
850 if os.path.exists(self.join('undo.bookmarks')):
846 if os.path.exists(self.join('undo.bookmarks')):
851 util.rename(self.join('undo.bookmarks'),
847 util.rename(self.join('undo.bookmarks'),
852 self.join('bookmarks'))
848 self.join('bookmarks'))
853 if os.path.exists(self.sjoin('undo.phaseroots')):
849 if os.path.exists(self.sjoin('undo.phaseroots')):
854 util.rename(self.sjoin('undo.phaseroots'),
850 util.rename(self.sjoin('undo.phaseroots'),
855 self.sjoin('phaseroots'))
851 self.sjoin('phaseroots'))
856 self.invalidate()
852 self.invalidate()
857
853
858 parentgone = (parents[0] not in self.changelog.nodemap or
854 parentgone = (parents[0] not in self.changelog.nodemap or
859 parents[1] not in self.changelog.nodemap)
855 parents[1] not in self.changelog.nodemap)
860 if parentgone:
856 if parentgone:
861 util.rename(self.join('undo.dirstate'), self.join('dirstate'))
857 util.rename(self.join('undo.dirstate'), self.join('dirstate'))
862 try:
858 try:
863 branch = self.opener.read('undo.branch')
859 branch = self.opener.read('undo.branch')
864 self.dirstate.setbranch(branch)
860 self.dirstate.setbranch(branch)
865 except IOError:
861 except IOError:
866 ui.warn(_('named branch could not be reset: '
862 ui.warn(_('named branch could not be reset: '
867 'current branch is still \'%s\'\n')
863 'current branch is still \'%s\'\n')
868 % self.dirstate.branch())
864 % self.dirstate.branch())
869
865
870 self.dirstate.invalidate()
866 self.dirstate.invalidate()
871 parents = tuple([p.rev() for p in self.parents()])
867 parents = tuple([p.rev() for p in self.parents()])
872 if len(parents) > 1:
868 if len(parents) > 1:
873 ui.status(_('working directory now based on '
869 ui.status(_('working directory now based on '
874 'revisions %d and %d\n') % parents)
870 'revisions %d and %d\n') % parents)
875 else:
871 else:
876 ui.status(_('working directory now based on '
872 ui.status(_('working directory now based on '
877 'revision %d\n') % parents)
873 'revision %d\n') % parents)
878 self.destroyed()
874 self.destroyed()
879 return 0
875 return 0
880
876
881 def invalidatecaches(self):
877 def invalidatecaches(self):
882 def delcache(name):
878 def delcache(name):
883 try:
879 try:
884 delattr(self, name)
880 delattr(self, name)
885 except AttributeError:
881 except AttributeError:
886 pass
882 pass
887
883
888 delcache('_tagscache')
884 delcache('_tagscache')
889 delcache('_phaserev')
885 delcache('_phaserev')
890
886
891 self._branchcache = None # in UTF-8
887 self._branchcache = None # in UTF-8
892 self._branchcachetip = None
888 self._branchcachetip = None
893
889
894 def invalidatedirstate(self):
890 def invalidatedirstate(self):
895 '''Invalidates the dirstate, causing the next call to dirstate
891 '''Invalidates the dirstate, causing the next call to dirstate
896 to check if it was modified since the last time it was read,
892 to check if it was modified since the last time it was read,
897 rereading it if it has.
893 rereading it if it has.
898
894
899 This is different to dirstate.invalidate() that it doesn't always
895 This is different to dirstate.invalidate() that it doesn't always
900 rereads the dirstate. Use dirstate.invalidate() if you want to
896 rereads the dirstate. Use dirstate.invalidate() if you want to
901 explicitly read the dirstate again (i.e. restoring it to a previous
897 explicitly read the dirstate again (i.e. restoring it to a previous
902 known good state).'''
898 known good state).'''
903 try:
899 try:
904 delattr(self, 'dirstate')
900 delattr(self, 'dirstate')
905 except AttributeError:
901 except AttributeError:
906 pass
902 pass
907
903
908 def invalidate(self):
904 def invalidate(self):
909 for k in self._filecache:
905 for k in self._filecache:
910 # dirstate is invalidated separately in invalidatedirstate()
906 # dirstate is invalidated separately in invalidatedirstate()
911 if k == 'dirstate':
907 if k == 'dirstate':
912 continue
908 continue
913
909
914 try:
910 try:
915 delattr(self, k)
911 delattr(self, k)
916 except AttributeError:
912 except AttributeError:
917 pass
913 pass
918 self.invalidatecaches()
914 self.invalidatecaches()
919
915
920 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
916 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
921 try:
917 try:
922 l = lock.lock(lockname, 0, releasefn, desc=desc)
918 l = lock.lock(lockname, 0, releasefn, desc=desc)
923 except error.LockHeld, inst:
919 except error.LockHeld, inst:
924 if not wait:
920 if not wait:
925 raise
921 raise
926 self.ui.warn(_("waiting for lock on %s held by %r\n") %
922 self.ui.warn(_("waiting for lock on %s held by %r\n") %
927 (desc, inst.locker))
923 (desc, inst.locker))
928 # default to 600 seconds timeout
924 # default to 600 seconds timeout
929 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
925 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
930 releasefn, desc=desc)
926 releasefn, desc=desc)
931 if acquirefn:
927 if acquirefn:
932 acquirefn()
928 acquirefn()
933 return l
929 return l
934
930
935 def _afterlock(self, callback):
931 def _afterlock(self, callback):
936 """add a callback to the current repository lock.
932 """add a callback to the current repository lock.
937
933
938 The callback will be executed on lock release."""
934 The callback will be executed on lock release."""
939 l = self._lockref and self._lockref()
935 l = self._lockref and self._lockref()
940 if l:
936 if l:
941 l.postrelease.append(callback)
937 l.postrelease.append(callback)
942
938
943 def lock(self, wait=True):
939 def lock(self, wait=True):
944 '''Lock the repository store (.hg/store) and return a weak reference
940 '''Lock the repository store (.hg/store) and return a weak reference
945 to the lock. Use this before modifying the store (e.g. committing or
941 to the lock. Use this before modifying the store (e.g. committing or
946 stripping). If you are opening a transaction, get a lock as well.)'''
942 stripping). If you are opening a transaction, get a lock as well.)'''
947 l = self._lockref and self._lockref()
943 l = self._lockref and self._lockref()
948 if l is not None and l.held:
944 if l is not None and l.held:
949 l.lock()
945 l.lock()
950 return l
946 return l
951
947
952 def unlock():
948 def unlock():
953 self.store.write()
949 self.store.write()
954 if self._dirtyphases:
950 if self._dirtyphases:
955 phases.writeroots(self)
951 phases.writeroots(self)
956 for k, ce in self._filecache.items():
952 for k, ce in self._filecache.items():
957 if k == 'dirstate':
953 if k == 'dirstate':
958 continue
954 continue
959 ce.refresh()
955 ce.refresh()
960
956
961 l = self._lock(self.sjoin("lock"), wait, unlock,
957 l = self._lock(self.sjoin("lock"), wait, unlock,
962 self.invalidate, _('repository %s') % self.origroot)
958 self.invalidate, _('repository %s') % self.origroot)
963 self._lockref = weakref.ref(l)
959 self._lockref = weakref.ref(l)
964 return l
960 return l
965
961
966 def wlock(self, wait=True):
962 def wlock(self, wait=True):
967 '''Lock the non-store parts of the repository (everything under
963 '''Lock the non-store parts of the repository (everything under
968 .hg except .hg/store) and return a weak reference to the lock.
964 .hg except .hg/store) and return a weak reference to the lock.
969 Use this before modifying files in .hg.'''
965 Use this before modifying files in .hg.'''
970 l = self._wlockref and self._wlockref()
966 l = self._wlockref and self._wlockref()
971 if l is not None and l.held:
967 if l is not None and l.held:
972 l.lock()
968 l.lock()
973 return l
969 return l
974
970
975 def unlock():
971 def unlock():
976 self.dirstate.write()
972 self.dirstate.write()
977 ce = self._filecache.get('dirstate')
973 ce = self._filecache.get('dirstate')
978 if ce:
974 if ce:
979 ce.refresh()
975 ce.refresh()
980
976
981 l = self._lock(self.join("wlock"), wait, unlock,
977 l = self._lock(self.join("wlock"), wait, unlock,
982 self.invalidatedirstate, _('working directory of %s') %
978 self.invalidatedirstate, _('working directory of %s') %
983 self.origroot)
979 self.origroot)
984 self._wlockref = weakref.ref(l)
980 self._wlockref = weakref.ref(l)
985 return l
981 return l
986
982
987 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
983 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
988 """
984 """
989 commit an individual file as part of a larger transaction
985 commit an individual file as part of a larger transaction
990 """
986 """
991
987
992 fname = fctx.path()
988 fname = fctx.path()
993 text = fctx.data()
989 text = fctx.data()
994 flog = self.file(fname)
990 flog = self.file(fname)
995 fparent1 = manifest1.get(fname, nullid)
991 fparent1 = manifest1.get(fname, nullid)
996 fparent2 = fparent2o = manifest2.get(fname, nullid)
992 fparent2 = fparent2o = manifest2.get(fname, nullid)
997
993
998 meta = {}
994 meta = {}
999 copy = fctx.renamed()
995 copy = fctx.renamed()
1000 if copy and copy[0] != fname:
996 if copy and copy[0] != fname:
1001 # Mark the new revision of this file as a copy of another
997 # Mark the new revision of this file as a copy of another
1002 # file. This copy data will effectively act as a parent
998 # file. This copy data will effectively act as a parent
1003 # of this new revision. If this is a merge, the first
999 # of this new revision. If this is a merge, the first
1004 # parent will be the nullid (meaning "look up the copy data")
1000 # parent will be the nullid (meaning "look up the copy data")
1005 # and the second one will be the other parent. For example:
1001 # and the second one will be the other parent. For example:
1006 #
1002 #
1007 # 0 --- 1 --- 3 rev1 changes file foo
1003 # 0 --- 1 --- 3 rev1 changes file foo
1008 # \ / rev2 renames foo to bar and changes it
1004 # \ / rev2 renames foo to bar and changes it
1009 # \- 2 -/ rev3 should have bar with all changes and
1005 # \- 2 -/ rev3 should have bar with all changes and
1010 # should record that bar descends from
1006 # should record that bar descends from
1011 # bar in rev2 and foo in rev1
1007 # bar in rev2 and foo in rev1
1012 #
1008 #
1013 # this allows this merge to succeed:
1009 # this allows this merge to succeed:
1014 #
1010 #
1015 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1011 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1016 # \ / merging rev3 and rev4 should use bar@rev2
1012 # \ / merging rev3 and rev4 should use bar@rev2
1017 # \- 2 --- 4 as the merge base
1013 # \- 2 --- 4 as the merge base
1018 #
1014 #
1019
1015
1020 cfname = copy[0]
1016 cfname = copy[0]
1021 crev = manifest1.get(cfname)
1017 crev = manifest1.get(cfname)
1022 newfparent = fparent2
1018 newfparent = fparent2
1023
1019
1024 if manifest2: # branch merge
1020 if manifest2: # branch merge
1025 if fparent2 == nullid or crev is None: # copied on remote side
1021 if fparent2 == nullid or crev is None: # copied on remote side
1026 if cfname in manifest2:
1022 if cfname in manifest2:
1027 crev = manifest2[cfname]
1023 crev = manifest2[cfname]
1028 newfparent = fparent1
1024 newfparent = fparent1
1029
1025
1030 # find source in nearest ancestor if we've lost track
1026 # find source in nearest ancestor if we've lost track
1031 if not crev:
1027 if not crev:
1032 self.ui.debug(" %s: searching for copy revision for %s\n" %
1028 self.ui.debug(" %s: searching for copy revision for %s\n" %
1033 (fname, cfname))
1029 (fname, cfname))
1034 for ancestor in self[None].ancestors():
1030 for ancestor in self[None].ancestors():
1035 if cfname in ancestor:
1031 if cfname in ancestor:
1036 crev = ancestor[cfname].filenode()
1032 crev = ancestor[cfname].filenode()
1037 break
1033 break
1038
1034
1039 if crev:
1035 if crev:
1040 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1036 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1041 meta["copy"] = cfname
1037 meta["copy"] = cfname
1042 meta["copyrev"] = hex(crev)
1038 meta["copyrev"] = hex(crev)
1043 fparent1, fparent2 = nullid, newfparent
1039 fparent1, fparent2 = nullid, newfparent
1044 else:
1040 else:
1045 self.ui.warn(_("warning: can't find ancestor for '%s' "
1041 self.ui.warn(_("warning: can't find ancestor for '%s' "
1046 "copied from '%s'!\n") % (fname, cfname))
1042 "copied from '%s'!\n") % (fname, cfname))
1047
1043
1048 elif fparent2 != nullid:
1044 elif fparent2 != nullid:
1049 # is one parent an ancestor of the other?
1045 # is one parent an ancestor of the other?
1050 fparentancestor = flog.ancestor(fparent1, fparent2)
1046 fparentancestor = flog.ancestor(fparent1, fparent2)
1051 if fparentancestor == fparent1:
1047 if fparentancestor == fparent1:
1052 fparent1, fparent2 = fparent2, nullid
1048 fparent1, fparent2 = fparent2, nullid
1053 elif fparentancestor == fparent2:
1049 elif fparentancestor == fparent2:
1054 fparent2 = nullid
1050 fparent2 = nullid
1055
1051
1056 # is the file changed?
1052 # is the file changed?
1057 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1053 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1058 changelist.append(fname)
1054 changelist.append(fname)
1059 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1055 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1060
1056
1061 # are just the flags changed during merge?
1057 # are just the flags changed during merge?
1062 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1058 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1063 changelist.append(fname)
1059 changelist.append(fname)
1064
1060
1065 return fparent1
1061 return fparent1
1066
1062
1067 def commit(self, text="", user=None, date=None, match=None, force=False,
1063 def commit(self, text="", user=None, date=None, match=None, force=False,
1068 editor=False, extra={}):
1064 editor=False, extra={}):
1069 """Add a new revision to current repository.
1065 """Add a new revision to current repository.
1070
1066
1071 Revision information is gathered from the working directory,
1067 Revision information is gathered from the working directory,
1072 match can be used to filter the committed files. If editor is
1068 match can be used to filter the committed files. If editor is
1073 supplied, it is called to get a commit message.
1069 supplied, it is called to get a commit message.
1074 """
1070 """
1075
1071
1076 def fail(f, msg):
1072 def fail(f, msg):
1077 raise util.Abort('%s: %s' % (f, msg))
1073 raise util.Abort('%s: %s' % (f, msg))
1078
1074
1079 if not match:
1075 if not match:
1080 match = matchmod.always(self.root, '')
1076 match = matchmod.always(self.root, '')
1081
1077
1082 if not force:
1078 if not force:
1083 vdirs = []
1079 vdirs = []
1084 match.dir = vdirs.append
1080 match.dir = vdirs.append
1085 match.bad = fail
1081 match.bad = fail
1086
1082
1087 wlock = self.wlock()
1083 wlock = self.wlock()
1088 try:
1084 try:
1089 wctx = self[None]
1085 wctx = self[None]
1090 merge = len(wctx.parents()) > 1
1086 merge = len(wctx.parents()) > 1
1091
1087
1092 if (not force and merge and match and
1088 if (not force and merge and match and
1093 (match.files() or match.anypats())):
1089 (match.files() or match.anypats())):
1094 raise util.Abort(_('cannot partially commit a merge '
1090 raise util.Abort(_('cannot partially commit a merge '
1095 '(do not specify files or patterns)'))
1091 '(do not specify files or patterns)'))
1096
1092
1097 changes = self.status(match=match, clean=force)
1093 changes = self.status(match=match, clean=force)
1098 if force:
1094 if force:
1099 changes[0].extend(changes[6]) # mq may commit unchanged files
1095 changes[0].extend(changes[6]) # mq may commit unchanged files
1100
1096
1101 # check subrepos
1097 # check subrepos
1102 subs = []
1098 subs = []
1103 removedsubs = set()
1099 removedsubs = set()
1104 if '.hgsub' in wctx:
1100 if '.hgsub' in wctx:
1105 # only manage subrepos and .hgsubstate if .hgsub is present
1101 # only manage subrepos and .hgsubstate if .hgsub is present
1106 for p in wctx.parents():
1102 for p in wctx.parents():
1107 removedsubs.update(s for s in p.substate if match(s))
1103 removedsubs.update(s for s in p.substate if match(s))
1108 for s in wctx.substate:
1104 for s in wctx.substate:
1109 removedsubs.discard(s)
1105 removedsubs.discard(s)
1110 if match(s) and wctx.sub(s).dirty():
1106 if match(s) and wctx.sub(s).dirty():
1111 subs.append(s)
1107 subs.append(s)
1112 if (subs or removedsubs):
1108 if (subs or removedsubs):
1113 if (not match('.hgsub') and
1109 if (not match('.hgsub') and
1114 '.hgsub' in (wctx.modified() + wctx.added())):
1110 '.hgsub' in (wctx.modified() + wctx.added())):
1115 raise util.Abort(
1111 raise util.Abort(
1116 _("can't commit subrepos without .hgsub"))
1112 _("can't commit subrepos without .hgsub"))
1117 if '.hgsubstate' not in changes[0]:
1113 if '.hgsubstate' not in changes[0]:
1118 changes[0].insert(0, '.hgsubstate')
1114 changes[0].insert(0, '.hgsubstate')
1119 if '.hgsubstate' in changes[2]:
1115 if '.hgsubstate' in changes[2]:
1120 changes[2].remove('.hgsubstate')
1116 changes[2].remove('.hgsubstate')
1121 elif '.hgsub' in changes[2]:
1117 elif '.hgsub' in changes[2]:
1122 # clean up .hgsubstate when .hgsub is removed
1118 # clean up .hgsubstate when .hgsub is removed
1123 if ('.hgsubstate' in wctx and
1119 if ('.hgsubstate' in wctx and
1124 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1120 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1125 changes[2].insert(0, '.hgsubstate')
1121 changes[2].insert(0, '.hgsubstate')
1126
1122
1127 if subs and not self.ui.configbool('ui', 'commitsubrepos', False):
1123 if subs and not self.ui.configbool('ui', 'commitsubrepos', False):
1128 changedsubs = [s for s in subs if wctx.sub(s).dirty(True)]
1124 changedsubs = [s for s in subs if wctx.sub(s).dirty(True)]
1129 if changedsubs:
1125 if changedsubs:
1130 raise util.Abort(_("uncommitted changes in subrepo %s")
1126 raise util.Abort(_("uncommitted changes in subrepo %s")
1131 % changedsubs[0],
1127 % changedsubs[0],
1132 hint=_("use --subrepos for recursive commit"))
1128 hint=_("use --subrepos for recursive commit"))
1133
1129
1134 # make sure all explicit patterns are matched
1130 # make sure all explicit patterns are matched
1135 if not force and match.files():
1131 if not force and match.files():
1136 matched = set(changes[0] + changes[1] + changes[2])
1132 matched = set(changes[0] + changes[1] + changes[2])
1137
1133
1138 for f in match.files():
1134 for f in match.files():
1139 if f == '.' or f in matched or f in wctx.substate:
1135 if f == '.' or f in matched or f in wctx.substate:
1140 continue
1136 continue
1141 if f in changes[3]: # missing
1137 if f in changes[3]: # missing
1142 fail(f, _('file not found!'))
1138 fail(f, _('file not found!'))
1143 if f in vdirs: # visited directory
1139 if f in vdirs: # visited directory
1144 d = f + '/'
1140 d = f + '/'
1145 for mf in matched:
1141 for mf in matched:
1146 if mf.startswith(d):
1142 if mf.startswith(d):
1147 break
1143 break
1148 else:
1144 else:
1149 fail(f, _("no match under directory!"))
1145 fail(f, _("no match under directory!"))
1150 elif f not in self.dirstate:
1146 elif f not in self.dirstate:
1151 fail(f, _("file not tracked!"))
1147 fail(f, _("file not tracked!"))
1152
1148
1153 if (not force and not extra.get("close") and not merge
1149 if (not force and not extra.get("close") and not merge
1154 and not (changes[0] or changes[1] or changes[2])
1150 and not (changes[0] or changes[1] or changes[2])
1155 and wctx.branch() == wctx.p1().branch()):
1151 and wctx.branch() == wctx.p1().branch()):
1156 return None
1152 return None
1157
1153
1158 ms = mergemod.mergestate(self)
1154 ms = mergemod.mergestate(self)
1159 for f in changes[0]:
1155 for f in changes[0]:
1160 if f in ms and ms[f] == 'u':
1156 if f in ms and ms[f] == 'u':
1161 raise util.Abort(_("unresolved merge conflicts "
1157 raise util.Abort(_("unresolved merge conflicts "
1162 "(see hg help resolve)"))
1158 "(see hg help resolve)"))
1163
1159
1164 cctx = context.workingctx(self, text, user, date, extra, changes)
1160 cctx = context.workingctx(self, text, user, date, extra, changes)
1165 if editor:
1161 if editor:
1166 cctx._text = editor(self, cctx, subs)
1162 cctx._text = editor(self, cctx, subs)
1167 edited = (text != cctx._text)
1163 edited = (text != cctx._text)
1168
1164
1169 # commit subs
1165 # commit subs
1170 if subs or removedsubs:
1166 if subs or removedsubs:
1171 state = wctx.substate.copy()
1167 state = wctx.substate.copy()
1172 for s in sorted(subs):
1168 for s in sorted(subs):
1173 sub = wctx.sub(s)
1169 sub = wctx.sub(s)
1174 self.ui.status(_('committing subrepository %s\n') %
1170 self.ui.status(_('committing subrepository %s\n') %
1175 subrepo.subrelpath(sub))
1171 subrepo.subrelpath(sub))
1176 sr = sub.commit(cctx._text, user, date)
1172 sr = sub.commit(cctx._text, user, date)
1177 state[s] = (state[s][0], sr)
1173 state[s] = (state[s][0], sr)
1178 subrepo.writestate(self, state)
1174 subrepo.writestate(self, state)
1179
1175
1180 # Save commit message in case this transaction gets rolled back
1176 # Save commit message in case this transaction gets rolled back
1181 # (e.g. by a pretxncommit hook). Leave the content alone on
1177 # (e.g. by a pretxncommit hook). Leave the content alone on
1182 # the assumption that the user will use the same editor again.
1178 # the assumption that the user will use the same editor again.
1183 msgfn = self.savecommitmessage(cctx._text)
1179 msgfn = self.savecommitmessage(cctx._text)
1184
1180
1185 p1, p2 = self.dirstate.parents()
1181 p1, p2 = self.dirstate.parents()
1186 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1182 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1187 try:
1183 try:
1188 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1184 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1189 ret = self.commitctx(cctx, True)
1185 ret = self.commitctx(cctx, True)
1190 except:
1186 except:
1191 if edited:
1187 if edited:
1192 self.ui.write(
1188 self.ui.write(
1193 _('note: commit message saved in %s\n') % msgfn)
1189 _('note: commit message saved in %s\n') % msgfn)
1194 raise
1190 raise
1195
1191
1196 # update bookmarks, dirstate and mergestate
1192 # update bookmarks, dirstate and mergestate
1197 bookmarks.update(self, p1, ret)
1193 bookmarks.update(self, p1, ret)
1198 for f in changes[0] + changes[1]:
1194 for f in changes[0] + changes[1]:
1199 self.dirstate.normal(f)
1195 self.dirstate.normal(f)
1200 for f in changes[2]:
1196 for f in changes[2]:
1201 self.dirstate.drop(f)
1197 self.dirstate.drop(f)
1202 self.dirstate.setparents(ret)
1198 self.dirstate.setparents(ret)
1203 ms.reset()
1199 ms.reset()
1204 finally:
1200 finally:
1205 wlock.release()
1201 wlock.release()
1206
1202
1207 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1203 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1208 return ret
1204 return ret
1209
1205
1210 def commitctx(self, ctx, error=False):
1206 def commitctx(self, ctx, error=False):
1211 """Add a new revision to current repository.
1207 """Add a new revision to current repository.
1212 Revision information is passed via the context argument.
1208 Revision information is passed via the context argument.
1213 """
1209 """
1214
1210
1215 tr = lock = None
1211 tr = lock = None
1216 removed = list(ctx.removed())
1212 removed = list(ctx.removed())
1217 p1, p2 = ctx.p1(), ctx.p2()
1213 p1, p2 = ctx.p1(), ctx.p2()
1218 user = ctx.user()
1214 user = ctx.user()
1219
1215
1220 lock = self.lock()
1216 lock = self.lock()
1221 try:
1217 try:
1222 tr = self.transaction("commit")
1218 tr = self.transaction("commit")
1223 trp = weakref.proxy(tr)
1219 trp = weakref.proxy(tr)
1224
1220
1225 if ctx.files():
1221 if ctx.files():
1226 m1 = p1.manifest().copy()
1222 m1 = p1.manifest().copy()
1227 m2 = p2.manifest()
1223 m2 = p2.manifest()
1228
1224
1229 # check in files
1225 # check in files
1230 new = {}
1226 new = {}
1231 changed = []
1227 changed = []
1232 linkrev = len(self)
1228 linkrev = len(self)
1233 for f in sorted(ctx.modified() + ctx.added()):
1229 for f in sorted(ctx.modified() + ctx.added()):
1234 self.ui.note(f + "\n")
1230 self.ui.note(f + "\n")
1235 try:
1231 try:
1236 fctx = ctx[f]
1232 fctx = ctx[f]
1237 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1233 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1238 changed)
1234 changed)
1239 m1.set(f, fctx.flags())
1235 m1.set(f, fctx.flags())
1240 except OSError, inst:
1236 except OSError, inst:
1241 self.ui.warn(_("trouble committing %s!\n") % f)
1237 self.ui.warn(_("trouble committing %s!\n") % f)
1242 raise
1238 raise
1243 except IOError, inst:
1239 except IOError, inst:
1244 errcode = getattr(inst, 'errno', errno.ENOENT)
1240 errcode = getattr(inst, 'errno', errno.ENOENT)
1245 if error or errcode and errcode != errno.ENOENT:
1241 if error or errcode and errcode != errno.ENOENT:
1246 self.ui.warn(_("trouble committing %s!\n") % f)
1242 self.ui.warn(_("trouble committing %s!\n") % f)
1247 raise
1243 raise
1248 else:
1244 else:
1249 removed.append(f)
1245 removed.append(f)
1250
1246
1251 # update manifest
1247 # update manifest
1252 m1.update(new)
1248 m1.update(new)
1253 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1249 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1254 drop = [f for f in removed if f in m1]
1250 drop = [f for f in removed if f in m1]
1255 for f in drop:
1251 for f in drop:
1256 del m1[f]
1252 del m1[f]
1257 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1253 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1258 p2.manifestnode(), (new, drop))
1254 p2.manifestnode(), (new, drop))
1259 files = changed + removed
1255 files = changed + removed
1260 else:
1256 else:
1261 mn = p1.manifestnode()
1257 mn = p1.manifestnode()
1262 files = []
1258 files = []
1263
1259
1264 # update changelog
1260 # update changelog
1265 self.changelog.delayupdate()
1261 self.changelog.delayupdate()
1266 n = self.changelog.add(mn, files, ctx.description(),
1262 n = self.changelog.add(mn, files, ctx.description(),
1267 trp, p1.node(), p2.node(),
1263 trp, p1.node(), p2.node(),
1268 user, ctx.date(), ctx.extra().copy())
1264 user, ctx.date(), ctx.extra().copy())
1269 p = lambda: self.changelog.writepending() and self.root or ""
1265 p = lambda: self.changelog.writepending() and self.root or ""
1270 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1266 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1271 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1267 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1272 parent2=xp2, pending=p)
1268 parent2=xp2, pending=p)
1273 self.changelog.finalize(trp)
1269 self.changelog.finalize(trp)
1274 # set the new commit is proper phase
1270 # set the new commit is proper phase
1275 targetphase = self.ui.configint('phases', 'new-commit',
1271 targetphase = self.ui.configint('phases', 'new-commit',
1276 phases.draft)
1272 phases.draft)
1277 if targetphase:
1273 if targetphase:
1278 # retract boundary do not alter parent changeset.
1274 # retract boundary do not alter parent changeset.
1279 # if a parent have higher the resulting phase will
1275 # if a parent have higher the resulting phase will
1280 # be compliant anyway
1276 # be compliant anyway
1281 #
1277 #
1282 # if minimal phase was 0 we don't need to retract anything
1278 # if minimal phase was 0 we don't need to retract anything
1283 phases.retractboundary(self, targetphase, [n])
1279 phases.retractboundary(self, targetphase, [n])
1284 tr.close()
1280 tr.close()
1285 self.updatebranchcache()
1281 self.updatebranchcache()
1286 return n
1282 return n
1287 finally:
1283 finally:
1288 if tr:
1284 if tr:
1289 tr.release()
1285 tr.release()
1290 lock.release()
1286 lock.release()
1291
1287
1292 def destroyed(self):
1288 def destroyed(self):
1293 '''Inform the repository that nodes have been destroyed.
1289 '''Inform the repository that nodes have been destroyed.
1294 Intended for use by strip and rollback, so there's a common
1290 Intended for use by strip and rollback, so there's a common
1295 place for anything that has to be done after destroying history.'''
1291 place for anything that has to be done after destroying history.'''
1296 # XXX it might be nice if we could take the list of destroyed
1292 # XXX it might be nice if we could take the list of destroyed
1297 # nodes, but I don't see an easy way for rollback() to do that
1293 # nodes, but I don't see an easy way for rollback() to do that
1298
1294
1299 # Ensure the persistent tag cache is updated. Doing it now
1295 # Ensure the persistent tag cache is updated. Doing it now
1300 # means that the tag cache only has to worry about destroyed
1296 # means that the tag cache only has to worry about destroyed
1301 # heads immediately after a strip/rollback. That in turn
1297 # heads immediately after a strip/rollback. That in turn
1302 # guarantees that "cachetip == currenttip" (comparing both rev
1298 # guarantees that "cachetip == currenttip" (comparing both rev
1303 # and node) always means no nodes have been added or destroyed.
1299 # and node) always means no nodes have been added or destroyed.
1304
1300
1305 # XXX this is suboptimal when qrefresh'ing: we strip the current
1301 # XXX this is suboptimal when qrefresh'ing: we strip the current
1306 # head, refresh the tag cache, then immediately add a new head.
1302 # head, refresh the tag cache, then immediately add a new head.
1307 # But I think doing it this way is necessary for the "instant
1303 # But I think doing it this way is necessary for the "instant
1308 # tag cache retrieval" case to work.
1304 # tag cache retrieval" case to work.
1309 self.invalidatecaches()
1305 self.invalidatecaches()
1310
1306
1311 def walk(self, match, node=None):
1307 def walk(self, match, node=None):
1312 '''
1308 '''
1313 walk recursively through the directory tree or a given
1309 walk recursively through the directory tree or a given
1314 changeset, finding all files matched by the match
1310 changeset, finding all files matched by the match
1315 function
1311 function
1316 '''
1312 '''
1317 return self[node].walk(match)
1313 return self[node].walk(match)
1318
1314
1319 def status(self, node1='.', node2=None, match=None,
1315 def status(self, node1='.', node2=None, match=None,
1320 ignored=False, clean=False, unknown=False,
1316 ignored=False, clean=False, unknown=False,
1321 listsubrepos=False):
1317 listsubrepos=False):
1322 """return status of files between two nodes or node and working directory
1318 """return status of files between two nodes or node and working directory
1323
1319
1324 If node1 is None, use the first dirstate parent instead.
1320 If node1 is None, use the first dirstate parent instead.
1325 If node2 is None, compare node1 with working directory.
1321 If node2 is None, compare node1 with working directory.
1326 """
1322 """
1327
1323
1328 def mfmatches(ctx):
1324 def mfmatches(ctx):
1329 mf = ctx.manifest().copy()
1325 mf = ctx.manifest().copy()
1330 for fn in mf.keys():
1326 for fn in mf.keys():
1331 if not match(fn):
1327 if not match(fn):
1332 del mf[fn]
1328 del mf[fn]
1333 return mf
1329 return mf
1334
1330
1335 if isinstance(node1, context.changectx):
1331 if isinstance(node1, context.changectx):
1336 ctx1 = node1
1332 ctx1 = node1
1337 else:
1333 else:
1338 ctx1 = self[node1]
1334 ctx1 = self[node1]
1339 if isinstance(node2, context.changectx):
1335 if isinstance(node2, context.changectx):
1340 ctx2 = node2
1336 ctx2 = node2
1341 else:
1337 else:
1342 ctx2 = self[node2]
1338 ctx2 = self[node2]
1343
1339
1344 working = ctx2.rev() is None
1340 working = ctx2.rev() is None
1345 parentworking = working and ctx1 == self['.']
1341 parentworking = working and ctx1 == self['.']
1346 match = match or matchmod.always(self.root, self.getcwd())
1342 match = match or matchmod.always(self.root, self.getcwd())
1347 listignored, listclean, listunknown = ignored, clean, unknown
1343 listignored, listclean, listunknown = ignored, clean, unknown
1348
1344
1349 # load earliest manifest first for caching reasons
1345 # load earliest manifest first for caching reasons
1350 if not working and ctx2.rev() < ctx1.rev():
1346 if not working and ctx2.rev() < ctx1.rev():
1351 ctx2.manifest()
1347 ctx2.manifest()
1352
1348
1353 if not parentworking:
1349 if not parentworking:
1354 def bad(f, msg):
1350 def bad(f, msg):
1355 if f not in ctx1:
1351 if f not in ctx1:
1356 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1352 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1357 match.bad = bad
1353 match.bad = bad
1358
1354
1359 if working: # we need to scan the working dir
1355 if working: # we need to scan the working dir
1360 subrepos = []
1356 subrepos = []
1361 if '.hgsub' in self.dirstate:
1357 if '.hgsub' in self.dirstate:
1362 subrepos = ctx2.substate.keys()
1358 subrepos = ctx2.substate.keys()
1363 s = self.dirstate.status(match, subrepos, listignored,
1359 s = self.dirstate.status(match, subrepos, listignored,
1364 listclean, listunknown)
1360 listclean, listunknown)
1365 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1361 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1366
1362
1367 # check for any possibly clean files
1363 # check for any possibly clean files
1368 if parentworking and cmp:
1364 if parentworking and cmp:
1369 fixup = []
1365 fixup = []
1370 # do a full compare of any files that might have changed
1366 # do a full compare of any files that might have changed
1371 for f in sorted(cmp):
1367 for f in sorted(cmp):
1372 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1368 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1373 or ctx1[f].cmp(ctx2[f])):
1369 or ctx1[f].cmp(ctx2[f])):
1374 modified.append(f)
1370 modified.append(f)
1375 else:
1371 else:
1376 fixup.append(f)
1372 fixup.append(f)
1377
1373
1378 # update dirstate for files that are actually clean
1374 # update dirstate for files that are actually clean
1379 if fixup:
1375 if fixup:
1380 if listclean:
1376 if listclean:
1381 clean += fixup
1377 clean += fixup
1382
1378
1383 try:
1379 try:
1384 # updating the dirstate is optional
1380 # updating the dirstate is optional
1385 # so we don't wait on the lock
1381 # so we don't wait on the lock
1386 wlock = self.wlock(False)
1382 wlock = self.wlock(False)
1387 try:
1383 try:
1388 for f in fixup:
1384 for f in fixup:
1389 self.dirstate.normal(f)
1385 self.dirstate.normal(f)
1390 finally:
1386 finally:
1391 wlock.release()
1387 wlock.release()
1392 except error.LockError:
1388 except error.LockError:
1393 pass
1389 pass
1394
1390
1395 if not parentworking:
1391 if not parentworking:
1396 mf1 = mfmatches(ctx1)
1392 mf1 = mfmatches(ctx1)
1397 if working:
1393 if working:
1398 # we are comparing working dir against non-parent
1394 # we are comparing working dir against non-parent
1399 # generate a pseudo-manifest for the working dir
1395 # generate a pseudo-manifest for the working dir
1400 mf2 = mfmatches(self['.'])
1396 mf2 = mfmatches(self['.'])
1401 for f in cmp + modified + added:
1397 for f in cmp + modified + added:
1402 mf2[f] = None
1398 mf2[f] = None
1403 mf2.set(f, ctx2.flags(f))
1399 mf2.set(f, ctx2.flags(f))
1404 for f in removed:
1400 for f in removed:
1405 if f in mf2:
1401 if f in mf2:
1406 del mf2[f]
1402 del mf2[f]
1407 else:
1403 else:
1408 # we are comparing two revisions
1404 # we are comparing two revisions
1409 deleted, unknown, ignored = [], [], []
1405 deleted, unknown, ignored = [], [], []
1410 mf2 = mfmatches(ctx2)
1406 mf2 = mfmatches(ctx2)
1411
1407
1412 modified, added, clean = [], [], []
1408 modified, added, clean = [], [], []
1413 for fn in mf2:
1409 for fn in mf2:
1414 if fn in mf1:
1410 if fn in mf1:
1415 if (fn not in deleted and
1411 if (fn not in deleted and
1416 (mf1.flags(fn) != mf2.flags(fn) or
1412 (mf1.flags(fn) != mf2.flags(fn) or
1417 (mf1[fn] != mf2[fn] and
1413 (mf1[fn] != mf2[fn] and
1418 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1414 (mf2[fn] or ctx1[fn].cmp(ctx2[fn]))))):
1419 modified.append(fn)
1415 modified.append(fn)
1420 elif listclean:
1416 elif listclean:
1421 clean.append(fn)
1417 clean.append(fn)
1422 del mf1[fn]
1418 del mf1[fn]
1423 elif fn not in deleted:
1419 elif fn not in deleted:
1424 added.append(fn)
1420 added.append(fn)
1425 removed = mf1.keys()
1421 removed = mf1.keys()
1426
1422
1427 if working and modified and not self.dirstate._checklink:
1423 if working and modified and not self.dirstate._checklink:
1428 # Symlink placeholders may get non-symlink-like contents
1424 # Symlink placeholders may get non-symlink-like contents
1429 # via user error or dereferencing by NFS or Samba servers,
1425 # via user error or dereferencing by NFS or Samba servers,
1430 # so we filter out any placeholders that don't look like a
1426 # so we filter out any placeholders that don't look like a
1431 # symlink
1427 # symlink
1432 sane = []
1428 sane = []
1433 for f in modified:
1429 for f in modified:
1434 if ctx2.flags(f) == 'l':
1430 if ctx2.flags(f) == 'l':
1435 d = ctx2[f].data()
1431 d = ctx2[f].data()
1436 if len(d) >= 1024 or '\n' in d or util.binary(d):
1432 if len(d) >= 1024 or '\n' in d or util.binary(d):
1437 self.ui.debug('ignoring suspect symlink placeholder'
1433 self.ui.debug('ignoring suspect symlink placeholder'
1438 ' "%s"\n' % f)
1434 ' "%s"\n' % f)
1439 continue
1435 continue
1440 sane.append(f)
1436 sane.append(f)
1441 modified = sane
1437 modified = sane
1442
1438
1443 r = modified, added, removed, deleted, unknown, ignored, clean
1439 r = modified, added, removed, deleted, unknown, ignored, clean
1444
1440
1445 if listsubrepos:
1441 if listsubrepos:
1446 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1442 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1447 if working:
1443 if working:
1448 rev2 = None
1444 rev2 = None
1449 else:
1445 else:
1450 rev2 = ctx2.substate[subpath][1]
1446 rev2 = ctx2.substate[subpath][1]
1451 try:
1447 try:
1452 submatch = matchmod.narrowmatcher(subpath, match)
1448 submatch = matchmod.narrowmatcher(subpath, match)
1453 s = sub.status(rev2, match=submatch, ignored=listignored,
1449 s = sub.status(rev2, match=submatch, ignored=listignored,
1454 clean=listclean, unknown=listunknown,
1450 clean=listclean, unknown=listunknown,
1455 listsubrepos=True)
1451 listsubrepos=True)
1456 for rfiles, sfiles in zip(r, s):
1452 for rfiles, sfiles in zip(r, s):
1457 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1453 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1458 except error.LookupError:
1454 except error.LookupError:
1459 self.ui.status(_("skipping missing subrepository: %s\n")
1455 self.ui.status(_("skipping missing subrepository: %s\n")
1460 % subpath)
1456 % subpath)
1461
1457
1462 for l in r:
1458 for l in r:
1463 l.sort()
1459 l.sort()
1464 return r
1460 return r
1465
1461
1466 def heads(self, start=None):
1462 def heads(self, start=None):
1467 heads = self.changelog.heads(start)
1463 heads = self.changelog.heads(start)
1468 # sort the output in rev descending order
1464 # sort the output in rev descending order
1469 return sorted(heads, key=self.changelog.rev, reverse=True)
1465 return sorted(heads, key=self.changelog.rev, reverse=True)
1470
1466
1471 def branchheads(self, branch=None, start=None, closed=False):
1467 def branchheads(self, branch=None, start=None, closed=False):
1472 '''return a (possibly filtered) list of heads for the given branch
1468 '''return a (possibly filtered) list of heads for the given branch
1473
1469
1474 Heads are returned in topological order, from newest to oldest.
1470 Heads are returned in topological order, from newest to oldest.
1475 If branch is None, use the dirstate branch.
1471 If branch is None, use the dirstate branch.
1476 If start is not None, return only heads reachable from start.
1472 If start is not None, return only heads reachable from start.
1477 If closed is True, return heads that are marked as closed as well.
1473 If closed is True, return heads that are marked as closed as well.
1478 '''
1474 '''
1479 if branch is None:
1475 if branch is None:
1480 branch = self[None].branch()
1476 branch = self[None].branch()
1481 branches = self.branchmap()
1477 branches = self.branchmap()
1482 if branch not in branches:
1478 if branch not in branches:
1483 return []
1479 return []
1484 # the cache returns heads ordered lowest to highest
1480 # the cache returns heads ordered lowest to highest
1485 bheads = list(reversed(branches[branch]))
1481 bheads = list(reversed(branches[branch]))
1486 if start is not None:
1482 if start is not None:
1487 # filter out the heads that cannot be reached from startrev
1483 # filter out the heads that cannot be reached from startrev
1488 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1484 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1489 bheads = [h for h in bheads if h in fbheads]
1485 bheads = [h for h in bheads if h in fbheads]
1490 if not closed:
1486 if not closed:
1491 bheads = [h for h in bheads if
1487 bheads = [h for h in bheads if
1492 ('close' not in self.changelog.read(h)[5])]
1488 ('close' not in self.changelog.read(h)[5])]
1493 return bheads
1489 return bheads
1494
1490
1495 def branches(self, nodes):
1491 def branches(self, nodes):
1496 if not nodes:
1492 if not nodes:
1497 nodes = [self.changelog.tip()]
1493 nodes = [self.changelog.tip()]
1498 b = []
1494 b = []
1499 for n in nodes:
1495 for n in nodes:
1500 t = n
1496 t = n
1501 while True:
1497 while True:
1502 p = self.changelog.parents(n)
1498 p = self.changelog.parents(n)
1503 if p[1] != nullid or p[0] == nullid:
1499 if p[1] != nullid or p[0] == nullid:
1504 b.append((t, n, p[0], p[1]))
1500 b.append((t, n, p[0], p[1]))
1505 break
1501 break
1506 n = p[0]
1502 n = p[0]
1507 return b
1503 return b
1508
1504
1509 def between(self, pairs):
1505 def between(self, pairs):
1510 r = []
1506 r = []
1511
1507
1512 for top, bottom in pairs:
1508 for top, bottom in pairs:
1513 n, l, i = top, [], 0
1509 n, l, i = top, [], 0
1514 f = 1
1510 f = 1
1515
1511
1516 while n != bottom and n != nullid:
1512 while n != bottom and n != nullid:
1517 p = self.changelog.parents(n)[0]
1513 p = self.changelog.parents(n)[0]
1518 if i == f:
1514 if i == f:
1519 l.append(n)
1515 l.append(n)
1520 f = f * 2
1516 f = f * 2
1521 n = p
1517 n = p
1522 i += 1
1518 i += 1
1523
1519
1524 r.append(l)
1520 r.append(l)
1525
1521
1526 return r
1522 return r
1527
1523
1528 def pull(self, remote, heads=None, force=False):
1524 def pull(self, remote, heads=None, force=False):
1529 lock = self.lock()
1525 lock = self.lock()
1530 try:
1526 try:
1531 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1527 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1532 force=force)
1528 force=force)
1533 common, fetch, rheads = tmp
1529 common, fetch, rheads = tmp
1534 if not fetch:
1530 if not fetch:
1535 self.ui.status(_("no changes found\n"))
1531 self.ui.status(_("no changes found\n"))
1536 added = []
1532 added = []
1537 result = 0
1533 result = 0
1538 else:
1534 else:
1539 if heads is None and list(common) == [nullid]:
1535 if heads is None and list(common) == [nullid]:
1540 self.ui.status(_("requesting all changes\n"))
1536 self.ui.status(_("requesting all changes\n"))
1541 elif heads is None and remote.capable('changegroupsubset'):
1537 elif heads is None and remote.capable('changegroupsubset'):
1542 # issue1320, avoid a race if remote changed after discovery
1538 # issue1320, avoid a race if remote changed after discovery
1543 heads = rheads
1539 heads = rheads
1544
1540
1545 if remote.capable('getbundle'):
1541 if remote.capable('getbundle'):
1546 cg = remote.getbundle('pull', common=common,
1542 cg = remote.getbundle('pull', common=common,
1547 heads=heads or rheads)
1543 heads=heads or rheads)
1548 elif heads is None:
1544 elif heads is None:
1549 cg = remote.changegroup(fetch, 'pull')
1545 cg = remote.changegroup(fetch, 'pull')
1550 elif not remote.capable('changegroupsubset'):
1546 elif not remote.capable('changegroupsubset'):
1551 raise util.Abort(_("partial pull cannot be done because "
1547 raise util.Abort(_("partial pull cannot be done because "
1552 "other repository doesn't support "
1548 "other repository doesn't support "
1553 "changegroupsubset."))
1549 "changegroupsubset."))
1554 else:
1550 else:
1555 cg = remote.changegroupsubset(fetch, heads, 'pull')
1551 cg = remote.changegroupsubset(fetch, heads, 'pull')
1556 clstart = len(self.changelog)
1552 clstart = len(self.changelog)
1557 result = self.addchangegroup(cg, 'pull', remote.url())
1553 result = self.addchangegroup(cg, 'pull', remote.url())
1558 clend = len(self.changelog)
1554 clend = len(self.changelog)
1559 added = [self.changelog.node(r) for r in xrange(clstart, clend)]
1555 added = [self.changelog.node(r) for r in xrange(clstart, clend)]
1560
1556
1561 # compute target subset
1557 # compute target subset
1562 if heads is None:
1558 if heads is None:
1563 # We pulled every thing possible
1559 # We pulled every thing possible
1564 # sync on everything common
1560 # sync on everything common
1565 subset = common + added
1561 subset = common + added
1566 else:
1562 else:
1567 # We pulled a specific subset
1563 # We pulled a specific subset
1568 # sync on this subset
1564 # sync on this subset
1569 subset = heads
1565 subset = heads
1570
1566
1571 # Get remote phases data from remote
1567 # Get remote phases data from remote
1572 remotephases = remote.listkeys('phases')
1568 remotephases = remote.listkeys('phases')
1573 publishing = bool(remotephases.get('publishing', False))
1569 publishing = bool(remotephases.get('publishing', False))
1574 if remotephases and not publishing:
1570 if remotephases and not publishing:
1575 # remote is new and unpublishing
1571 # remote is new and unpublishing
1576 pheads, _dr = phases.analyzeremotephases(self, subset,
1572 pheads, _dr = phases.analyzeremotephases(self, subset,
1577 remotephases)
1573 remotephases)
1578 phases.advanceboundary(self, phases.public, pheads)
1574 phases.advanceboundary(self, phases.public, pheads)
1579 phases.advanceboundary(self, phases.draft, subset)
1575 phases.advanceboundary(self, phases.draft, subset)
1580 else:
1576 else:
1581 # Remote is old or publishing all common changesets
1577 # Remote is old or publishing all common changesets
1582 # should be seen as public
1578 # should be seen as public
1583 phases.advanceboundary(self, phases.public, subset)
1579 phases.advanceboundary(self, phases.public, subset)
1584 finally:
1580 finally:
1585 lock.release()
1581 lock.release()
1586
1582
1587 return result
1583 return result
1588
1584
1589 def checkpush(self, force, revs):
1585 def checkpush(self, force, revs):
1590 """Extensions can override this function if additional checks have
1586 """Extensions can override this function if additional checks have
1591 to be performed before pushing, or call it if they override push
1587 to be performed before pushing, or call it if they override push
1592 command.
1588 command.
1593 """
1589 """
1594 pass
1590 pass
1595
1591
1596 def push(self, remote, force=False, revs=None, newbranch=False):
1592 def push(self, remote, force=False, revs=None, newbranch=False):
1597 '''Push outgoing changesets (limited by revs) from the current
1593 '''Push outgoing changesets (limited by revs) from the current
1598 repository to remote. Return an integer:
1594 repository to remote. Return an integer:
1599 - 0 means HTTP error *or* nothing to push
1595 - 0 means HTTP error *or* nothing to push
1600 - 1 means we pushed and remote head count is unchanged *or*
1596 - 1 means we pushed and remote head count is unchanged *or*
1601 we have outgoing changesets but refused to push
1597 we have outgoing changesets but refused to push
1602 - other values as described by addchangegroup()
1598 - other values as described by addchangegroup()
1603 '''
1599 '''
1604 # there are two ways to push to remote repo:
1600 # there are two ways to push to remote repo:
1605 #
1601 #
1606 # addchangegroup assumes local user can lock remote
1602 # addchangegroup assumes local user can lock remote
1607 # repo (local filesystem, old ssh servers).
1603 # repo (local filesystem, old ssh servers).
1608 #
1604 #
1609 # unbundle assumes local user cannot lock remote repo (new ssh
1605 # unbundle assumes local user cannot lock remote repo (new ssh
1610 # servers, http servers).
1606 # servers, http servers).
1611
1607
1612 # get local lock as we might write phase data
1608 # get local lock as we might write phase data
1613 locallock = self.lock()
1609 locallock = self.lock()
1614 try:
1610 try:
1615 self.checkpush(force, revs)
1611 self.checkpush(force, revs)
1616 lock = None
1612 lock = None
1617 unbundle = remote.capable('unbundle')
1613 unbundle = remote.capable('unbundle')
1618 if not unbundle:
1614 if not unbundle:
1619 lock = remote.lock()
1615 lock = remote.lock()
1620 try:
1616 try:
1621 # discovery
1617 # discovery
1622 fci = discovery.findcommonincoming
1618 fci = discovery.findcommonincoming
1623 commoninc = fci(self, remote, force=force)
1619 commoninc = fci(self, remote, force=force)
1624 common, inc, remoteheads = commoninc
1620 common, inc, remoteheads = commoninc
1625 fco = discovery.findcommonoutgoing
1621 fco = discovery.findcommonoutgoing
1626 outgoing = fco(self, remote, onlyheads=revs,
1622 outgoing = fco(self, remote, onlyheads=revs,
1627 commoninc=commoninc, force=force)
1623 commoninc=commoninc, force=force)
1628
1624
1629
1625
1630 if not outgoing.missing:
1626 if not outgoing.missing:
1631 # nothing to push
1627 # nothing to push
1632 scmutil.nochangesfound(self.ui, outgoing.excluded)
1628 scmutil.nochangesfound(self.ui, outgoing.excluded)
1633 ret = 1
1629 ret = 1
1634 else:
1630 else:
1635 # something to push
1631 # something to push
1636 if not force:
1632 if not force:
1637 discovery.checkheads(self, remote, outgoing,
1633 discovery.checkheads(self, remote, outgoing,
1638 remoteheads, newbranch,
1634 remoteheads, newbranch,
1639 bool(inc))
1635 bool(inc))
1640
1636
1641 # create a changegroup from local
1637 # create a changegroup from local
1642 if revs is None and not outgoing.excluded:
1638 if revs is None and not outgoing.excluded:
1643 # push everything,
1639 # push everything,
1644 # use the fast path, no race possible on push
1640 # use the fast path, no race possible on push
1645 cg = self._changegroup(outgoing.missing, 'push')
1641 cg = self._changegroup(outgoing.missing, 'push')
1646 else:
1642 else:
1647 cg = self.getlocalbundle('push', outgoing)
1643 cg = self.getlocalbundle('push', outgoing)
1648
1644
1649 # apply changegroup to remote
1645 # apply changegroup to remote
1650 if unbundle:
1646 if unbundle:
1651 # local repo finds heads on server, finds out what
1647 # local repo finds heads on server, finds out what
1652 # revs it must push. once revs transferred, if server
1648 # revs it must push. once revs transferred, if server
1653 # finds it has different heads (someone else won
1649 # finds it has different heads (someone else won
1654 # commit/push race), server aborts.
1650 # commit/push race), server aborts.
1655 if force:
1651 if force:
1656 remoteheads = ['force']
1652 remoteheads = ['force']
1657 # ssh: return remote's addchangegroup()
1653 # ssh: return remote's addchangegroup()
1658 # http: return remote's addchangegroup() or 0 for error
1654 # http: return remote's addchangegroup() or 0 for error
1659 ret = remote.unbundle(cg, remoteheads, 'push')
1655 ret = remote.unbundle(cg, remoteheads, 'push')
1660 else:
1656 else:
1661 # we return an integer indicating remote head count change
1657 # we return an integer indicating remote head count change
1662 ret = remote.addchangegroup(cg, 'push', self.url())
1658 ret = remote.addchangegroup(cg, 'push', self.url())
1663
1659
1664 if ret:
1660 if ret:
1665 # push succeed, synchonize target of the push
1661 # push succeed, synchonize target of the push
1666 cheads = outgoing.missingheads
1662 cheads = outgoing.missingheads
1667 elif revs is None:
1663 elif revs is None:
1668 # All out push fails. synchronize all common
1664 # All out push fails. synchronize all common
1669 cheads = outgoing.commonheads
1665 cheads = outgoing.commonheads
1670 else:
1666 else:
1671 # I want cheads = heads(::missingheads and ::commonheads)
1667 # I want cheads = heads(::missingheads and ::commonheads)
1672 # (missingheads is revs with secret changeset filtered out)
1668 # (missingheads is revs with secret changeset filtered out)
1673 #
1669 #
1674 # This can be expressed as:
1670 # This can be expressed as:
1675 # cheads = ( (missingheads and ::commonheads)
1671 # cheads = ( (missingheads and ::commonheads)
1676 # + (commonheads and ::missingheads))"
1672 # + (commonheads and ::missingheads))"
1677 # )
1673 # )
1678 #
1674 #
1679 # while trying to push we already computed the following:
1675 # while trying to push we already computed the following:
1680 # common = (::commonheads)
1676 # common = (::commonheads)
1681 # missing = ((commonheads::missingheads) - commonheads)
1677 # missing = ((commonheads::missingheads) - commonheads)
1682 #
1678 #
1683 # We can pick:
1679 # We can pick:
1684 # * missingheads part of comon (::commonheads)
1680 # * missingheads part of comon (::commonheads)
1685 common = set(outgoing.common)
1681 common = set(outgoing.common)
1686 cheads = [n for node in revs if n in common]
1682 cheads = [n for node in revs if n in common]
1687 # and
1683 # and
1688 # * commonheads parents on missing
1684 # * commonheads parents on missing
1689 rvset = repo.revset('%ln and parents(roots(%ln))',
1685 rvset = repo.revset('%ln and parents(roots(%ln))',
1690 outgoing.commonheads,
1686 outgoing.commonheads,
1691 outgoing.missing)
1687 outgoing.missing)
1692 cheads.extend(c.node() for c in rvset)
1688 cheads.extend(c.node() for c in rvset)
1693 # even when we don't push, exchanging phase data is useful
1689 # even when we don't push, exchanging phase data is useful
1694 remotephases = remote.listkeys('phases')
1690 remotephases = remote.listkeys('phases')
1695 if not remotephases: # old server or public only repo
1691 if not remotephases: # old server or public only repo
1696 phases.advanceboundary(self, phases.public, cheads)
1692 phases.advanceboundary(self, phases.public, cheads)
1697 # don't push any phase data as there is nothing to push
1693 # don't push any phase data as there is nothing to push
1698 else:
1694 else:
1699 ana = phases.analyzeremotephases(self, cheads, remotephases)
1695 ana = phases.analyzeremotephases(self, cheads, remotephases)
1700 pheads, droots = ana
1696 pheads, droots = ana
1701 ### Apply remote phase on local
1697 ### Apply remote phase on local
1702 if remotephases.get('publishing', False):
1698 if remotephases.get('publishing', False):
1703 phases.advanceboundary(self, phases.public, cheads)
1699 phases.advanceboundary(self, phases.public, cheads)
1704 else: # publish = False
1700 else: # publish = False
1705 phases.advanceboundary(self, phases.public, pheads)
1701 phases.advanceboundary(self, phases.public, pheads)
1706 phases.advanceboundary(self, phases.draft, cheads)
1702 phases.advanceboundary(self, phases.draft, cheads)
1707 ### Apply local phase on remote
1703 ### Apply local phase on remote
1708
1704
1709 # Get the list of all revs draft on remote by public here.
1705 # Get the list of all revs draft on remote by public here.
1710 # XXX Beware that revset break if droots is not strictly
1706 # XXX Beware that revset break if droots is not strictly
1711 # XXX root we may want to ensure it is but it is costly
1707 # XXX root we may want to ensure it is but it is costly
1712 outdated = self.set('heads((%ln::%ln) and public())',
1708 outdated = self.set('heads((%ln::%ln) and public())',
1713 droots, cheads)
1709 droots, cheads)
1714 for newremotehead in outdated:
1710 for newremotehead in outdated:
1715 r = remote.pushkey('phases',
1711 r = remote.pushkey('phases',
1716 newremotehead.hex(),
1712 newremotehead.hex(),
1717 str(phases.draft),
1713 str(phases.draft),
1718 str(phases.public))
1714 str(phases.public))
1719 if not r:
1715 if not r:
1720 self.ui.warn(_('updating %s to public failed!\n')
1716 self.ui.warn(_('updating %s to public failed!\n')
1721 % newremotehead)
1717 % newremotehead)
1722 finally:
1718 finally:
1723 if lock is not None:
1719 if lock is not None:
1724 lock.release()
1720 lock.release()
1725 finally:
1721 finally:
1726 locallock.release()
1722 locallock.release()
1727
1723
1728 self.ui.debug("checking for updated bookmarks\n")
1724 self.ui.debug("checking for updated bookmarks\n")
1729 rb = remote.listkeys('bookmarks')
1725 rb = remote.listkeys('bookmarks')
1730 for k in rb.keys():
1726 for k in rb.keys():
1731 if k in self._bookmarks:
1727 if k in self._bookmarks:
1732 nr, nl = rb[k], hex(self._bookmarks[k])
1728 nr, nl = rb[k], hex(self._bookmarks[k])
1733 if nr in self:
1729 if nr in self:
1734 cr = self[nr]
1730 cr = self[nr]
1735 cl = self[nl]
1731 cl = self[nl]
1736 if cl in cr.descendants():
1732 if cl in cr.descendants():
1737 r = remote.pushkey('bookmarks', k, nr, nl)
1733 r = remote.pushkey('bookmarks', k, nr, nl)
1738 if r:
1734 if r:
1739 self.ui.status(_("updating bookmark %s\n") % k)
1735 self.ui.status(_("updating bookmark %s\n") % k)
1740 else:
1736 else:
1741 self.ui.warn(_('updating bookmark %s'
1737 self.ui.warn(_('updating bookmark %s'
1742 ' failed!\n') % k)
1738 ' failed!\n') % k)
1743
1739
1744 return ret
1740 return ret
1745
1741
1746 def changegroupinfo(self, nodes, source):
1742 def changegroupinfo(self, nodes, source):
1747 if self.ui.verbose or source == 'bundle':
1743 if self.ui.verbose or source == 'bundle':
1748 self.ui.status(_("%d changesets found\n") % len(nodes))
1744 self.ui.status(_("%d changesets found\n") % len(nodes))
1749 if self.ui.debugflag:
1745 if self.ui.debugflag:
1750 self.ui.debug("list of changesets:\n")
1746 self.ui.debug("list of changesets:\n")
1751 for node in nodes:
1747 for node in nodes:
1752 self.ui.debug("%s\n" % hex(node))
1748 self.ui.debug("%s\n" % hex(node))
1753
1749
1754 def changegroupsubset(self, bases, heads, source):
1750 def changegroupsubset(self, bases, heads, source):
1755 """Compute a changegroup consisting of all the nodes that are
1751 """Compute a changegroup consisting of all the nodes that are
1756 descendants of any of the bases and ancestors of any of the heads.
1752 descendants of any of the bases and ancestors of any of the heads.
1757 Return a chunkbuffer object whose read() method will return
1753 Return a chunkbuffer object whose read() method will return
1758 successive changegroup chunks.
1754 successive changegroup chunks.
1759
1755
1760 It is fairly complex as determining which filenodes and which
1756 It is fairly complex as determining which filenodes and which
1761 manifest nodes need to be included for the changeset to be complete
1757 manifest nodes need to be included for the changeset to be complete
1762 is non-trivial.
1758 is non-trivial.
1763
1759
1764 Another wrinkle is doing the reverse, figuring out which changeset in
1760 Another wrinkle is doing the reverse, figuring out which changeset in
1765 the changegroup a particular filenode or manifestnode belongs to.
1761 the changegroup a particular filenode or manifestnode belongs to.
1766 """
1762 """
1767 cl = self.changelog
1763 cl = self.changelog
1768 if not bases:
1764 if not bases:
1769 bases = [nullid]
1765 bases = [nullid]
1770 csets, bases, heads = cl.nodesbetween(bases, heads)
1766 csets, bases, heads = cl.nodesbetween(bases, heads)
1771 # We assume that all ancestors of bases are known
1767 # We assume that all ancestors of bases are known
1772 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1768 common = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1773 return self._changegroupsubset(common, csets, heads, source)
1769 return self._changegroupsubset(common, csets, heads, source)
1774
1770
1775 def getlocalbundle(self, source, outgoing):
1771 def getlocalbundle(self, source, outgoing):
1776 """Like getbundle, but taking a discovery.outgoing as an argument.
1772 """Like getbundle, but taking a discovery.outgoing as an argument.
1777
1773
1778 This is only implemented for local repos and reuses potentially
1774 This is only implemented for local repos and reuses potentially
1779 precomputed sets in outgoing."""
1775 precomputed sets in outgoing."""
1780 if not outgoing.missing:
1776 if not outgoing.missing:
1781 return None
1777 return None
1782 return self._changegroupsubset(outgoing.common,
1778 return self._changegroupsubset(outgoing.common,
1783 outgoing.missing,
1779 outgoing.missing,
1784 outgoing.missingheads,
1780 outgoing.missingheads,
1785 source)
1781 source)
1786
1782
1787 def getbundle(self, source, heads=None, common=None):
1783 def getbundle(self, source, heads=None, common=None):
1788 """Like changegroupsubset, but returns the set difference between the
1784 """Like changegroupsubset, but returns the set difference between the
1789 ancestors of heads and the ancestors common.
1785 ancestors of heads and the ancestors common.
1790
1786
1791 If heads is None, use the local heads. If common is None, use [nullid].
1787 If heads is None, use the local heads. If common is None, use [nullid].
1792
1788
1793 The nodes in common might not all be known locally due to the way the
1789 The nodes in common might not all be known locally due to the way the
1794 current discovery protocol works.
1790 current discovery protocol works.
1795 """
1791 """
1796 cl = self.changelog
1792 cl = self.changelog
1797 if common:
1793 if common:
1798 nm = cl.nodemap
1794 nm = cl.nodemap
1799 common = [n for n in common if n in nm]
1795 common = [n for n in common if n in nm]
1800 else:
1796 else:
1801 common = [nullid]
1797 common = [nullid]
1802 if not heads:
1798 if not heads:
1803 heads = cl.heads()
1799 heads = cl.heads()
1804 return self.getlocalbundle(source,
1800 return self.getlocalbundle(source,
1805 discovery.outgoing(cl, common, heads))
1801 discovery.outgoing(cl, common, heads))
1806
1802
1807 def _changegroupsubset(self, commonrevs, csets, heads, source):
1803 def _changegroupsubset(self, commonrevs, csets, heads, source):
1808
1804
1809 cl = self.changelog
1805 cl = self.changelog
1810 mf = self.manifest
1806 mf = self.manifest
1811 mfs = {} # needed manifests
1807 mfs = {} # needed manifests
1812 fnodes = {} # needed file nodes
1808 fnodes = {} # needed file nodes
1813 changedfiles = set()
1809 changedfiles = set()
1814 fstate = ['', {}]
1810 fstate = ['', {}]
1815 count = [0]
1811 count = [0]
1816
1812
1817 # can we go through the fast path ?
1813 # can we go through the fast path ?
1818 heads.sort()
1814 heads.sort()
1819 if heads == sorted(self.heads()):
1815 if heads == sorted(self.heads()):
1820 return self._changegroup(csets, source)
1816 return self._changegroup(csets, source)
1821
1817
1822 # slow path
1818 # slow path
1823 self.hook('preoutgoing', throw=True, source=source)
1819 self.hook('preoutgoing', throw=True, source=source)
1824 self.changegroupinfo(csets, source)
1820 self.changegroupinfo(csets, source)
1825
1821
1826 # filter any nodes that claim to be part of the known set
1822 # filter any nodes that claim to be part of the known set
1827 def prune(revlog, missing):
1823 def prune(revlog, missing):
1828 return [n for n in missing
1824 return [n for n in missing
1829 if revlog.linkrev(revlog.rev(n)) not in commonrevs]
1825 if revlog.linkrev(revlog.rev(n)) not in commonrevs]
1830
1826
1831 def lookup(revlog, x):
1827 def lookup(revlog, x):
1832 if revlog == cl:
1828 if revlog == cl:
1833 c = cl.read(x)
1829 c = cl.read(x)
1834 changedfiles.update(c[3])
1830 changedfiles.update(c[3])
1835 mfs.setdefault(c[0], x)
1831 mfs.setdefault(c[0], x)
1836 count[0] += 1
1832 count[0] += 1
1837 self.ui.progress(_('bundling'), count[0],
1833 self.ui.progress(_('bundling'), count[0],
1838 unit=_('changesets'), total=len(csets))
1834 unit=_('changesets'), total=len(csets))
1839 return x
1835 return x
1840 elif revlog == mf:
1836 elif revlog == mf:
1841 clnode = mfs[x]
1837 clnode = mfs[x]
1842 mdata = mf.readfast(x)
1838 mdata = mf.readfast(x)
1843 for f in changedfiles:
1839 for f in changedfiles:
1844 if f in mdata:
1840 if f in mdata:
1845 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1841 fnodes.setdefault(f, {}).setdefault(mdata[f], clnode)
1846 count[0] += 1
1842 count[0] += 1
1847 self.ui.progress(_('bundling'), count[0],
1843 self.ui.progress(_('bundling'), count[0],
1848 unit=_('manifests'), total=len(mfs))
1844 unit=_('manifests'), total=len(mfs))
1849 return mfs[x]
1845 return mfs[x]
1850 else:
1846 else:
1851 self.ui.progress(
1847 self.ui.progress(
1852 _('bundling'), count[0], item=fstate[0],
1848 _('bundling'), count[0], item=fstate[0],
1853 unit=_('files'), total=len(changedfiles))
1849 unit=_('files'), total=len(changedfiles))
1854 return fstate[1][x]
1850 return fstate[1][x]
1855
1851
1856 bundler = changegroup.bundle10(lookup)
1852 bundler = changegroup.bundle10(lookup)
1857 reorder = self.ui.config('bundle', 'reorder', 'auto')
1853 reorder = self.ui.config('bundle', 'reorder', 'auto')
1858 if reorder == 'auto':
1854 if reorder == 'auto':
1859 reorder = None
1855 reorder = None
1860 else:
1856 else:
1861 reorder = util.parsebool(reorder)
1857 reorder = util.parsebool(reorder)
1862
1858
1863 def gengroup():
1859 def gengroup():
1864 # Create a changenode group generator that will call our functions
1860 # Create a changenode group generator that will call our functions
1865 # back to lookup the owning changenode and collect information.
1861 # back to lookup the owning changenode and collect information.
1866 for chunk in cl.group(csets, bundler, reorder=reorder):
1862 for chunk in cl.group(csets, bundler, reorder=reorder):
1867 yield chunk
1863 yield chunk
1868 self.ui.progress(_('bundling'), None)
1864 self.ui.progress(_('bundling'), None)
1869
1865
1870 # Create a generator for the manifestnodes that calls our lookup
1866 # Create a generator for the manifestnodes that calls our lookup
1871 # and data collection functions back.
1867 # and data collection functions back.
1872 count[0] = 0
1868 count[0] = 0
1873 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1869 for chunk in mf.group(prune(mf, mfs), bundler, reorder=reorder):
1874 yield chunk
1870 yield chunk
1875 self.ui.progress(_('bundling'), None)
1871 self.ui.progress(_('bundling'), None)
1876
1872
1877 mfs.clear()
1873 mfs.clear()
1878
1874
1879 # Go through all our files in order sorted by name.
1875 # Go through all our files in order sorted by name.
1880 count[0] = 0
1876 count[0] = 0
1881 for fname in sorted(changedfiles):
1877 for fname in sorted(changedfiles):
1882 filerevlog = self.file(fname)
1878 filerevlog = self.file(fname)
1883 if not len(filerevlog):
1879 if not len(filerevlog):
1884 raise util.Abort(_("empty or missing revlog for %s") % fname)
1880 raise util.Abort(_("empty or missing revlog for %s") % fname)
1885 fstate[0] = fname
1881 fstate[0] = fname
1886 fstate[1] = fnodes.pop(fname, {})
1882 fstate[1] = fnodes.pop(fname, {})
1887
1883
1888 nodelist = prune(filerevlog, fstate[1])
1884 nodelist = prune(filerevlog, fstate[1])
1889 if nodelist:
1885 if nodelist:
1890 count[0] += 1
1886 count[0] += 1
1891 yield bundler.fileheader(fname)
1887 yield bundler.fileheader(fname)
1892 for chunk in filerevlog.group(nodelist, bundler, reorder):
1888 for chunk in filerevlog.group(nodelist, bundler, reorder):
1893 yield chunk
1889 yield chunk
1894
1890
1895 # Signal that no more groups are left.
1891 # Signal that no more groups are left.
1896 yield bundler.close()
1892 yield bundler.close()
1897 self.ui.progress(_('bundling'), None)
1893 self.ui.progress(_('bundling'), None)
1898
1894
1899 if csets:
1895 if csets:
1900 self.hook('outgoing', node=hex(csets[0]), source=source)
1896 self.hook('outgoing', node=hex(csets[0]), source=source)
1901
1897
1902 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1898 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1903
1899
1904 def changegroup(self, basenodes, source):
1900 def changegroup(self, basenodes, source):
1905 # to avoid a race we use changegroupsubset() (issue1320)
1901 # to avoid a race we use changegroupsubset() (issue1320)
1906 return self.changegroupsubset(basenodes, self.heads(), source)
1902 return self.changegroupsubset(basenodes, self.heads(), source)
1907
1903
1908 def _changegroup(self, nodes, source):
1904 def _changegroup(self, nodes, source):
1909 """Compute the changegroup of all nodes that we have that a recipient
1905 """Compute the changegroup of all nodes that we have that a recipient
1910 doesn't. Return a chunkbuffer object whose read() method will return
1906 doesn't. Return a chunkbuffer object whose read() method will return
1911 successive changegroup chunks.
1907 successive changegroup chunks.
1912
1908
1913 This is much easier than the previous function as we can assume that
1909 This is much easier than the previous function as we can assume that
1914 the recipient has any changenode we aren't sending them.
1910 the recipient has any changenode we aren't sending them.
1915
1911
1916 nodes is the set of nodes to send"""
1912 nodes is the set of nodes to send"""
1917
1913
1918 cl = self.changelog
1914 cl = self.changelog
1919 mf = self.manifest
1915 mf = self.manifest
1920 mfs = {}
1916 mfs = {}
1921 changedfiles = set()
1917 changedfiles = set()
1922 fstate = ['']
1918 fstate = ['']
1923 count = [0]
1919 count = [0]
1924
1920
1925 self.hook('preoutgoing', throw=True, source=source)
1921 self.hook('preoutgoing', throw=True, source=source)
1926 self.changegroupinfo(nodes, source)
1922 self.changegroupinfo(nodes, source)
1927
1923
1928 revset = set([cl.rev(n) for n in nodes])
1924 revset = set([cl.rev(n) for n in nodes])
1929
1925
1930 def gennodelst(log):
1926 def gennodelst(log):
1931 return [log.node(r) for r in log if log.linkrev(r) in revset]
1927 return [log.node(r) for r in log if log.linkrev(r) in revset]
1932
1928
1933 def lookup(revlog, x):
1929 def lookup(revlog, x):
1934 if revlog == cl:
1930 if revlog == cl:
1935 c = cl.read(x)
1931 c = cl.read(x)
1936 changedfiles.update(c[3])
1932 changedfiles.update(c[3])
1937 mfs.setdefault(c[0], x)
1933 mfs.setdefault(c[0], x)
1938 count[0] += 1
1934 count[0] += 1
1939 self.ui.progress(_('bundling'), count[0],
1935 self.ui.progress(_('bundling'), count[0],
1940 unit=_('changesets'), total=len(nodes))
1936 unit=_('changesets'), total=len(nodes))
1941 return x
1937 return x
1942 elif revlog == mf:
1938 elif revlog == mf:
1943 count[0] += 1
1939 count[0] += 1
1944 self.ui.progress(_('bundling'), count[0],
1940 self.ui.progress(_('bundling'), count[0],
1945 unit=_('manifests'), total=len(mfs))
1941 unit=_('manifests'), total=len(mfs))
1946 return cl.node(revlog.linkrev(revlog.rev(x)))
1942 return cl.node(revlog.linkrev(revlog.rev(x)))
1947 else:
1943 else:
1948 self.ui.progress(
1944 self.ui.progress(
1949 _('bundling'), count[0], item=fstate[0],
1945 _('bundling'), count[0], item=fstate[0],
1950 total=len(changedfiles), unit=_('files'))
1946 total=len(changedfiles), unit=_('files'))
1951 return cl.node(revlog.linkrev(revlog.rev(x)))
1947 return cl.node(revlog.linkrev(revlog.rev(x)))
1952
1948
1953 bundler = changegroup.bundle10(lookup)
1949 bundler = changegroup.bundle10(lookup)
1954 reorder = self.ui.config('bundle', 'reorder', 'auto')
1950 reorder = self.ui.config('bundle', 'reorder', 'auto')
1955 if reorder == 'auto':
1951 if reorder == 'auto':
1956 reorder = None
1952 reorder = None
1957 else:
1953 else:
1958 reorder = util.parsebool(reorder)
1954 reorder = util.parsebool(reorder)
1959
1955
1960 def gengroup():
1956 def gengroup():
1961 '''yield a sequence of changegroup chunks (strings)'''
1957 '''yield a sequence of changegroup chunks (strings)'''
1962 # construct a list of all changed files
1958 # construct a list of all changed files
1963
1959
1964 for chunk in cl.group(nodes, bundler, reorder=reorder):
1960 for chunk in cl.group(nodes, bundler, reorder=reorder):
1965 yield chunk
1961 yield chunk
1966 self.ui.progress(_('bundling'), None)
1962 self.ui.progress(_('bundling'), None)
1967
1963
1968 count[0] = 0
1964 count[0] = 0
1969 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1965 for chunk in mf.group(gennodelst(mf), bundler, reorder=reorder):
1970 yield chunk
1966 yield chunk
1971 self.ui.progress(_('bundling'), None)
1967 self.ui.progress(_('bundling'), None)
1972
1968
1973 count[0] = 0
1969 count[0] = 0
1974 for fname in sorted(changedfiles):
1970 for fname in sorted(changedfiles):
1975 filerevlog = self.file(fname)
1971 filerevlog = self.file(fname)
1976 if not len(filerevlog):
1972 if not len(filerevlog):
1977 raise util.Abort(_("empty or missing revlog for %s") % fname)
1973 raise util.Abort(_("empty or missing revlog for %s") % fname)
1978 fstate[0] = fname
1974 fstate[0] = fname
1979 nodelist = gennodelst(filerevlog)
1975 nodelist = gennodelst(filerevlog)
1980 if nodelist:
1976 if nodelist:
1981 count[0] += 1
1977 count[0] += 1
1982 yield bundler.fileheader(fname)
1978 yield bundler.fileheader(fname)
1983 for chunk in filerevlog.group(nodelist, bundler, reorder):
1979 for chunk in filerevlog.group(nodelist, bundler, reorder):
1984 yield chunk
1980 yield chunk
1985 yield bundler.close()
1981 yield bundler.close()
1986 self.ui.progress(_('bundling'), None)
1982 self.ui.progress(_('bundling'), None)
1987
1983
1988 if nodes:
1984 if nodes:
1989 self.hook('outgoing', node=hex(nodes[0]), source=source)
1985 self.hook('outgoing', node=hex(nodes[0]), source=source)
1990
1986
1991 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1987 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1992
1988
1993 def addchangegroup(self, source, srctype, url, emptyok=False):
1989 def addchangegroup(self, source, srctype, url, emptyok=False):
1994 """Add the changegroup returned by source.read() to this repo.
1990 """Add the changegroup returned by source.read() to this repo.
1995 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1991 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1996 the URL of the repo where this changegroup is coming from.
1992 the URL of the repo where this changegroup is coming from.
1997
1993
1998 Return an integer summarizing the change to this repo:
1994 Return an integer summarizing the change to this repo:
1999 - nothing changed or no source: 0
1995 - nothing changed or no source: 0
2000 - more heads than before: 1+added heads (2..n)
1996 - more heads than before: 1+added heads (2..n)
2001 - fewer heads than before: -1-removed heads (-2..-n)
1997 - fewer heads than before: -1-removed heads (-2..-n)
2002 - number of heads stays the same: 1
1998 - number of heads stays the same: 1
2003 """
1999 """
2004 def csmap(x):
2000 def csmap(x):
2005 self.ui.debug("add changeset %s\n" % short(x))
2001 self.ui.debug("add changeset %s\n" % short(x))
2006 return len(cl)
2002 return len(cl)
2007
2003
2008 def revmap(x):
2004 def revmap(x):
2009 return cl.rev(x)
2005 return cl.rev(x)
2010
2006
2011 if not source:
2007 if not source:
2012 return 0
2008 return 0
2013
2009
2014 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2010 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2015
2011
2016 changesets = files = revisions = 0
2012 changesets = files = revisions = 0
2017 efiles = set()
2013 efiles = set()
2018
2014
2019 # write changelog data to temp files so concurrent readers will not see
2015 # write changelog data to temp files so concurrent readers will not see
2020 # inconsistent view
2016 # inconsistent view
2021 cl = self.changelog
2017 cl = self.changelog
2022 cl.delayupdate()
2018 cl.delayupdate()
2023 oldheads = cl.heads()
2019 oldheads = cl.heads()
2024
2020
2025 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2021 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
2026 try:
2022 try:
2027 trp = weakref.proxy(tr)
2023 trp = weakref.proxy(tr)
2028 # pull off the changeset group
2024 # pull off the changeset group
2029 self.ui.status(_("adding changesets\n"))
2025 self.ui.status(_("adding changesets\n"))
2030 clstart = len(cl)
2026 clstart = len(cl)
2031 class prog(object):
2027 class prog(object):
2032 step = _('changesets')
2028 step = _('changesets')
2033 count = 1
2029 count = 1
2034 ui = self.ui
2030 ui = self.ui
2035 total = None
2031 total = None
2036 def __call__(self):
2032 def __call__(self):
2037 self.ui.progress(self.step, self.count, unit=_('chunks'),
2033 self.ui.progress(self.step, self.count, unit=_('chunks'),
2038 total=self.total)
2034 total=self.total)
2039 self.count += 1
2035 self.count += 1
2040 pr = prog()
2036 pr = prog()
2041 source.callback = pr
2037 source.callback = pr
2042
2038
2043 source.changelogheader()
2039 source.changelogheader()
2044 srccontent = cl.addgroup(source, csmap, trp)
2040 srccontent = cl.addgroup(source, csmap, trp)
2045 if not (srccontent or emptyok):
2041 if not (srccontent or emptyok):
2046 raise util.Abort(_("received changelog group is empty"))
2042 raise util.Abort(_("received changelog group is empty"))
2047 clend = len(cl)
2043 clend = len(cl)
2048 changesets = clend - clstart
2044 changesets = clend - clstart
2049 for c in xrange(clstart, clend):
2045 for c in xrange(clstart, clend):
2050 efiles.update(self[c].files())
2046 efiles.update(self[c].files())
2051 efiles = len(efiles)
2047 efiles = len(efiles)
2052 self.ui.progress(_('changesets'), None)
2048 self.ui.progress(_('changesets'), None)
2053
2049
2054 # pull off the manifest group
2050 # pull off the manifest group
2055 self.ui.status(_("adding manifests\n"))
2051 self.ui.status(_("adding manifests\n"))
2056 pr.step = _('manifests')
2052 pr.step = _('manifests')
2057 pr.count = 1
2053 pr.count = 1
2058 pr.total = changesets # manifests <= changesets
2054 pr.total = changesets # manifests <= changesets
2059 # no need to check for empty manifest group here:
2055 # no need to check for empty manifest group here:
2060 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2056 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2061 # no new manifest will be created and the manifest group will
2057 # no new manifest will be created and the manifest group will
2062 # be empty during the pull
2058 # be empty during the pull
2063 source.manifestheader()
2059 source.manifestheader()
2064 self.manifest.addgroup(source, revmap, trp)
2060 self.manifest.addgroup(source, revmap, trp)
2065 self.ui.progress(_('manifests'), None)
2061 self.ui.progress(_('manifests'), None)
2066
2062
2067 needfiles = {}
2063 needfiles = {}
2068 if self.ui.configbool('server', 'validate', default=False):
2064 if self.ui.configbool('server', 'validate', default=False):
2069 # validate incoming csets have their manifests
2065 # validate incoming csets have their manifests
2070 for cset in xrange(clstart, clend):
2066 for cset in xrange(clstart, clend):
2071 mfest = self.changelog.read(self.changelog.node(cset))[0]
2067 mfest = self.changelog.read(self.changelog.node(cset))[0]
2072 mfest = self.manifest.readdelta(mfest)
2068 mfest = self.manifest.readdelta(mfest)
2073 # store file nodes we must see
2069 # store file nodes we must see
2074 for f, n in mfest.iteritems():
2070 for f, n in mfest.iteritems():
2075 needfiles.setdefault(f, set()).add(n)
2071 needfiles.setdefault(f, set()).add(n)
2076
2072
2077 # process the files
2073 # process the files
2078 self.ui.status(_("adding file changes\n"))
2074 self.ui.status(_("adding file changes\n"))
2079 pr.step = _('files')
2075 pr.step = _('files')
2080 pr.count = 1
2076 pr.count = 1
2081 pr.total = efiles
2077 pr.total = efiles
2082 source.callback = None
2078 source.callback = None
2083
2079
2084 while True:
2080 while True:
2085 chunkdata = source.filelogheader()
2081 chunkdata = source.filelogheader()
2086 if not chunkdata:
2082 if not chunkdata:
2087 break
2083 break
2088 f = chunkdata["filename"]
2084 f = chunkdata["filename"]
2089 self.ui.debug("adding %s revisions\n" % f)
2085 self.ui.debug("adding %s revisions\n" % f)
2090 pr()
2086 pr()
2091 fl = self.file(f)
2087 fl = self.file(f)
2092 o = len(fl)
2088 o = len(fl)
2093 if not fl.addgroup(source, revmap, trp):
2089 if not fl.addgroup(source, revmap, trp):
2094 raise util.Abort(_("received file revlog group is empty"))
2090 raise util.Abort(_("received file revlog group is empty"))
2095 revisions += len(fl) - o
2091 revisions += len(fl) - o
2096 files += 1
2092 files += 1
2097 if f in needfiles:
2093 if f in needfiles:
2098 needs = needfiles[f]
2094 needs = needfiles[f]
2099 for new in xrange(o, len(fl)):
2095 for new in xrange(o, len(fl)):
2100 n = fl.node(new)
2096 n = fl.node(new)
2101 if n in needs:
2097 if n in needs:
2102 needs.remove(n)
2098 needs.remove(n)
2103 if not needs:
2099 if not needs:
2104 del needfiles[f]
2100 del needfiles[f]
2105 self.ui.progress(_('files'), None)
2101 self.ui.progress(_('files'), None)
2106
2102
2107 for f, needs in needfiles.iteritems():
2103 for f, needs in needfiles.iteritems():
2108 fl = self.file(f)
2104 fl = self.file(f)
2109 for n in needs:
2105 for n in needs:
2110 try:
2106 try:
2111 fl.rev(n)
2107 fl.rev(n)
2112 except error.LookupError:
2108 except error.LookupError:
2113 raise util.Abort(
2109 raise util.Abort(
2114 _('missing file data for %s:%s - run hg verify') %
2110 _('missing file data for %s:%s - run hg verify') %
2115 (f, hex(n)))
2111 (f, hex(n)))
2116
2112
2117 dh = 0
2113 dh = 0
2118 if oldheads:
2114 if oldheads:
2119 heads = cl.heads()
2115 heads = cl.heads()
2120 dh = len(heads) - len(oldheads)
2116 dh = len(heads) - len(oldheads)
2121 for h in heads:
2117 for h in heads:
2122 if h not in oldheads and 'close' in self[h].extra():
2118 if h not in oldheads and 'close' in self[h].extra():
2123 dh -= 1
2119 dh -= 1
2124 htext = ""
2120 htext = ""
2125 if dh:
2121 if dh:
2126 htext = _(" (%+d heads)") % dh
2122 htext = _(" (%+d heads)") % dh
2127
2123
2128 self.ui.status(_("added %d changesets"
2124 self.ui.status(_("added %d changesets"
2129 " with %d changes to %d files%s\n")
2125 " with %d changes to %d files%s\n")
2130 % (changesets, revisions, files, htext))
2126 % (changesets, revisions, files, htext))
2131
2127
2132 if changesets > 0:
2128 if changesets > 0:
2133 p = lambda: cl.writepending() and self.root or ""
2129 p = lambda: cl.writepending() and self.root or ""
2134 self.hook('pretxnchangegroup', throw=True,
2130 self.hook('pretxnchangegroup', throw=True,
2135 node=hex(cl.node(clstart)), source=srctype,
2131 node=hex(cl.node(clstart)), source=srctype,
2136 url=url, pending=p)
2132 url=url, pending=p)
2137
2133
2138 added = [cl.node(r) for r in xrange(clstart, clend)]
2134 added = [cl.node(r) for r in xrange(clstart, clend)]
2139 publishing = self.ui.configbool('phases', 'publish', True)
2135 publishing = self.ui.configbool('phases', 'publish', True)
2140 if srctype == 'push':
2136 if srctype == 'push':
2141 # Old server can not push the boundary themself.
2137 # Old server can not push the boundary themself.
2142 # New server won't push the boundary if changeset already
2138 # New server won't push the boundary if changeset already
2143 # existed locally as secrete
2139 # existed locally as secrete
2144 #
2140 #
2145 # We should not use added here but the list of all change in
2141 # We should not use added here but the list of all change in
2146 # the bundle
2142 # the bundle
2147 if publishing:
2143 if publishing:
2148 phases.advanceboundary(self, phases.public, srccontent)
2144 phases.advanceboundary(self, phases.public, srccontent)
2149 else:
2145 else:
2150 phases.advanceboundary(self, phases.draft, srccontent)
2146 phases.advanceboundary(self, phases.draft, srccontent)
2151 phases.retractboundary(self, phases.draft, added)
2147 phases.retractboundary(self, phases.draft, added)
2152 elif srctype != 'strip':
2148 elif srctype != 'strip':
2153 # publishing only alter behavior during push
2149 # publishing only alter behavior during push
2154 #
2150 #
2155 # strip should not touch boundary at all
2151 # strip should not touch boundary at all
2156 phases.retractboundary(self, phases.draft, added)
2152 phases.retractboundary(self, phases.draft, added)
2157
2153
2158 # make changelog see real files again
2154 # make changelog see real files again
2159 cl.finalize(trp)
2155 cl.finalize(trp)
2160
2156
2161 tr.close()
2157 tr.close()
2162
2158
2163 if changesets > 0:
2159 if changesets > 0:
2164 def runhooks():
2160 def runhooks():
2165 # forcefully update the on-disk branch cache
2161 # forcefully update the on-disk branch cache
2166 self.ui.debug("updating the branch cache\n")
2162 self.ui.debug("updating the branch cache\n")
2167 self.updatebranchcache()
2163 self.updatebranchcache()
2168 self.hook("changegroup", node=hex(cl.node(clstart)),
2164 self.hook("changegroup", node=hex(cl.node(clstart)),
2169 source=srctype, url=url)
2165 source=srctype, url=url)
2170
2166
2171 for n in added:
2167 for n in added:
2172 self.hook("incoming", node=hex(n), source=srctype,
2168 self.hook("incoming", node=hex(n), source=srctype,
2173 url=url)
2169 url=url)
2174 self._afterlock(runhooks)
2170 self._afterlock(runhooks)
2175
2171
2176 finally:
2172 finally:
2177 tr.release()
2173 tr.release()
2178 # never return 0 here:
2174 # never return 0 here:
2179 if dh < 0:
2175 if dh < 0:
2180 return dh - 1
2176 return dh - 1
2181 else:
2177 else:
2182 return dh + 1
2178 return dh + 1
2183
2179
2184 def stream_in(self, remote, requirements):
2180 def stream_in(self, remote, requirements):
2185 lock = self.lock()
2181 lock = self.lock()
2186 try:
2182 try:
2187 fp = remote.stream_out()
2183 fp = remote.stream_out()
2188 l = fp.readline()
2184 l = fp.readline()
2189 try:
2185 try:
2190 resp = int(l)
2186 resp = int(l)
2191 except ValueError:
2187 except ValueError:
2192 raise error.ResponseError(
2188 raise error.ResponseError(
2193 _('Unexpected response from remote server:'), l)
2189 _('Unexpected response from remote server:'), l)
2194 if resp == 1:
2190 if resp == 1:
2195 raise util.Abort(_('operation forbidden by server'))
2191 raise util.Abort(_('operation forbidden by server'))
2196 elif resp == 2:
2192 elif resp == 2:
2197 raise util.Abort(_('locking the remote repository failed'))
2193 raise util.Abort(_('locking the remote repository failed'))
2198 elif resp != 0:
2194 elif resp != 0:
2199 raise util.Abort(_('the server sent an unknown error code'))
2195 raise util.Abort(_('the server sent an unknown error code'))
2200 self.ui.status(_('streaming all changes\n'))
2196 self.ui.status(_('streaming all changes\n'))
2201 l = fp.readline()
2197 l = fp.readline()
2202 try:
2198 try:
2203 total_files, total_bytes = map(int, l.split(' ', 1))
2199 total_files, total_bytes = map(int, l.split(' ', 1))
2204 except (ValueError, TypeError):
2200 except (ValueError, TypeError):
2205 raise error.ResponseError(
2201 raise error.ResponseError(
2206 _('Unexpected response from remote server:'), l)
2202 _('Unexpected response from remote server:'), l)
2207 self.ui.status(_('%d files to transfer, %s of data\n') %
2203 self.ui.status(_('%d files to transfer, %s of data\n') %
2208 (total_files, util.bytecount(total_bytes)))
2204 (total_files, util.bytecount(total_bytes)))
2209 start = time.time()
2205 start = time.time()
2210 for i in xrange(total_files):
2206 for i in xrange(total_files):
2211 # XXX doesn't support '\n' or '\r' in filenames
2207 # XXX doesn't support '\n' or '\r' in filenames
2212 l = fp.readline()
2208 l = fp.readline()
2213 try:
2209 try:
2214 name, size = l.split('\0', 1)
2210 name, size = l.split('\0', 1)
2215 size = int(size)
2211 size = int(size)
2216 except (ValueError, TypeError):
2212 except (ValueError, TypeError):
2217 raise error.ResponseError(
2213 raise error.ResponseError(
2218 _('Unexpected response from remote server:'), l)
2214 _('Unexpected response from remote server:'), l)
2219 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2215 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2220 # for backwards compat, name was partially encoded
2216 # for backwards compat, name was partially encoded
2221 ofp = self.sopener(store.decodedir(name), 'w')
2217 ofp = self.sopener(store.decodedir(name), 'w')
2222 for chunk in util.filechunkiter(fp, limit=size):
2218 for chunk in util.filechunkiter(fp, limit=size):
2223 ofp.write(chunk)
2219 ofp.write(chunk)
2224 ofp.close()
2220 ofp.close()
2225 elapsed = time.time() - start
2221 elapsed = time.time() - start
2226 if elapsed <= 0:
2222 if elapsed <= 0:
2227 elapsed = 0.001
2223 elapsed = 0.001
2228 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2224 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2229 (util.bytecount(total_bytes), elapsed,
2225 (util.bytecount(total_bytes), elapsed,
2230 util.bytecount(total_bytes / elapsed)))
2226 util.bytecount(total_bytes / elapsed)))
2231
2227
2232 # new requirements = old non-format requirements + new format-related
2228 # new requirements = old non-format requirements + new format-related
2233 # requirements from the streamed-in repository
2229 # requirements from the streamed-in repository
2234 requirements.update(set(self.requirements) - self.supportedformats)
2230 requirements.update(set(self.requirements) - self.supportedformats)
2235 self._applyrequirements(requirements)
2231 self._applyrequirements(requirements)
2236 self._writerequirements()
2232 self._writerequirements()
2237
2233
2238 self.invalidate()
2234 self.invalidate()
2239 return len(self.heads()) + 1
2235 return len(self.heads()) + 1
2240 finally:
2236 finally:
2241 lock.release()
2237 lock.release()
2242
2238
2243 def clone(self, remote, heads=[], stream=False):
2239 def clone(self, remote, heads=[], stream=False):
2244 '''clone remote repository.
2240 '''clone remote repository.
2245
2241
2246 keyword arguments:
2242 keyword arguments:
2247 heads: list of revs to clone (forces use of pull)
2243 heads: list of revs to clone (forces use of pull)
2248 stream: use streaming clone if possible'''
2244 stream: use streaming clone if possible'''
2249
2245
2250 # now, all clients that can request uncompressed clones can
2246 # now, all clients that can request uncompressed clones can
2251 # read repo formats supported by all servers that can serve
2247 # read repo formats supported by all servers that can serve
2252 # them.
2248 # them.
2253
2249
2254 # if revlog format changes, client will have to check version
2250 # if revlog format changes, client will have to check version
2255 # and format flags on "stream" capability, and use
2251 # and format flags on "stream" capability, and use
2256 # uncompressed only if compatible.
2252 # uncompressed only if compatible.
2257
2253
2258 if stream and not heads:
2254 if stream and not heads:
2259 # 'stream' means remote revlog format is revlogv1 only
2255 # 'stream' means remote revlog format is revlogv1 only
2260 if remote.capable('stream'):
2256 if remote.capable('stream'):
2261 return self.stream_in(remote, set(('revlogv1',)))
2257 return self.stream_in(remote, set(('revlogv1',)))
2262 # otherwise, 'streamreqs' contains the remote revlog format
2258 # otherwise, 'streamreqs' contains the remote revlog format
2263 streamreqs = remote.capable('streamreqs')
2259 streamreqs = remote.capable('streamreqs')
2264 if streamreqs:
2260 if streamreqs:
2265 streamreqs = set(streamreqs.split(','))
2261 streamreqs = set(streamreqs.split(','))
2266 # if we support it, stream in and adjust our requirements
2262 # if we support it, stream in and adjust our requirements
2267 if not streamreqs - self.supportedformats:
2263 if not streamreqs - self.supportedformats:
2268 return self.stream_in(remote, streamreqs)
2264 return self.stream_in(remote, streamreqs)
2269 return self.pull(remote, heads)
2265 return self.pull(remote, heads)
2270
2266
2271 def pushkey(self, namespace, key, old, new):
2267 def pushkey(self, namespace, key, old, new):
2272 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2268 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2273 old=old, new=new)
2269 old=old, new=new)
2274 ret = pushkey.push(self, namespace, key, old, new)
2270 ret = pushkey.push(self, namespace, key, old, new)
2275 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2271 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2276 ret=ret)
2272 ret=ret)
2277 return ret
2273 return ret
2278
2274
2279 def listkeys(self, namespace):
2275 def listkeys(self, namespace):
2280 self.hook('prelistkeys', throw=True, namespace=namespace)
2276 self.hook('prelistkeys', throw=True, namespace=namespace)
2281 values = pushkey.list(self, namespace)
2277 values = pushkey.list(self, namespace)
2282 self.hook('listkeys', namespace=namespace, values=values)
2278 self.hook('listkeys', namespace=namespace, values=values)
2283 return values
2279 return values
2284
2280
2285 def debugwireargs(self, one, two, three=None, four=None, five=None):
2281 def debugwireargs(self, one, two, three=None, four=None, five=None):
2286 '''used to test argument passing over the wire'''
2282 '''used to test argument passing over the wire'''
2287 return "%s %s %s %s %s" % (one, two, three, four, five)
2283 return "%s %s %s %s %s" % (one, two, three, four, five)
2288
2284
2289 def savecommitmessage(self, text):
2285 def savecommitmessage(self, text):
2290 fp = self.opener('last-message.txt', 'wb')
2286 fp = self.opener('last-message.txt', 'wb')
2291 try:
2287 try:
2292 fp.write(text)
2288 fp.write(text)
2293 finally:
2289 finally:
2294 fp.close()
2290 fp.close()
2295 return self.pathto(fp.name[len(self.root)+1:])
2291 return self.pathto(fp.name[len(self.root)+1:])
2296
2292
2297 # used to avoid circular references so destructors work
2293 # used to avoid circular references so destructors work
2298 def aftertrans(files):
2294 def aftertrans(files):
2299 renamefiles = [tuple(t) for t in files]
2295 renamefiles = [tuple(t) for t in files]
2300 def a():
2296 def a():
2301 for src, dest in renamefiles:
2297 for src, dest in renamefiles:
2302 util.rename(src, dest)
2298 util.rename(src, dest)
2303 return a
2299 return a
2304
2300
2305 def undoname(fn):
2301 def undoname(fn):
2306 base, name = os.path.split(fn)
2302 base, name = os.path.split(fn)
2307 assert name.startswith('journal')
2303 assert name.startswith('journal')
2308 return os.path.join(base, name.replace('journal', 'undo', 1))
2304 return os.path.join(base, name.replace('journal', 'undo', 1))
2309
2305
2310 def instance(ui, path, create):
2306 def instance(ui, path, create):
2311 return localrepository(ui, util.urllocalpath(path), create)
2307 return localrepository(ui, util.urllocalpath(path), create)
2312
2308
2313 def islocal(path):
2309 def islocal(path):
2314 return True
2310 return True
General Comments 0
You need to be logged in to leave comments. Login now