##// END OF EJS Templates
localrepository.push: propagate return value
Vadim Gelfer -
r2463:6ab016ed default
parent child Browse files
Show More
@@ -1,2145 +1,2144 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import os, util
8 import os, util
9 import filelog, manifest, changelog, dirstate, repo
9 import filelog, manifest, changelog, dirstate, repo
10 from node import *
10 from node import *
11 from i18n import gettext as _
11 from i18n import gettext as _
12 from demandload import *
12 from demandload import *
13 demandload(globals(), "appendfile changegroup")
13 demandload(globals(), "appendfile changegroup")
14 demandload(globals(), "re lock transaction tempfile stat mdiff errno ui")
14 demandload(globals(), "re lock transaction tempfile stat mdiff errno ui")
15 demandload(globals(), "revlog")
15 demandload(globals(), "revlog")
16
16
17 class localrepository(object):
17 class localrepository(object):
18 capabilities = ()
18 capabilities = ()
19
19
20 def __del__(self):
20 def __del__(self):
21 self.transhandle = None
21 self.transhandle = None
22 def __init__(self, parentui, path=None, create=0):
22 def __init__(self, parentui, path=None, create=0):
23 if not path:
23 if not path:
24 p = os.getcwd()
24 p = os.getcwd()
25 while not os.path.isdir(os.path.join(p, ".hg")):
25 while not os.path.isdir(os.path.join(p, ".hg")):
26 oldp = p
26 oldp = p
27 p = os.path.dirname(p)
27 p = os.path.dirname(p)
28 if p == oldp:
28 if p == oldp:
29 raise repo.RepoError(_("no repo found"))
29 raise repo.RepoError(_("no repo found"))
30 path = p
30 path = p
31 self.path = os.path.join(path, ".hg")
31 self.path = os.path.join(path, ".hg")
32
32
33 if not create and not os.path.isdir(self.path):
33 if not create and not os.path.isdir(self.path):
34 raise repo.RepoError(_("repository %s not found") % path)
34 raise repo.RepoError(_("repository %s not found") % path)
35
35
36 self.root = os.path.abspath(path)
36 self.root = os.path.abspath(path)
37 self.origroot = path
37 self.origroot = path
38 self.ui = ui.ui(parentui=parentui)
38 self.ui = ui.ui(parentui=parentui)
39 self.opener = util.opener(self.path)
39 self.opener = util.opener(self.path)
40 self.wopener = util.opener(self.root)
40 self.wopener = util.opener(self.root)
41
41
42 try:
42 try:
43 self.ui.readconfig(self.join("hgrc"), self.root)
43 self.ui.readconfig(self.join("hgrc"), self.root)
44 except IOError:
44 except IOError:
45 pass
45 pass
46
46
47 v = self.ui.revlogopts
47 v = self.ui.revlogopts
48 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
48 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
49 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
49 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
50 fl = v.get('flags', None)
50 fl = v.get('flags', None)
51 flags = 0
51 flags = 0
52 if fl != None:
52 if fl != None:
53 for x in fl.split():
53 for x in fl.split():
54 flags |= revlog.flagstr(x)
54 flags |= revlog.flagstr(x)
55 elif self.revlogv1:
55 elif self.revlogv1:
56 flags = revlog.REVLOG_DEFAULT_FLAGS
56 flags = revlog.REVLOG_DEFAULT_FLAGS
57
57
58 v = self.revlogversion | flags
58 v = self.revlogversion | flags
59 self.manifest = manifest.manifest(self.opener, v)
59 self.manifest = manifest.manifest(self.opener, v)
60 self.changelog = changelog.changelog(self.opener, v)
60 self.changelog = changelog.changelog(self.opener, v)
61
61
62 # the changelog might not have the inline index flag
62 # the changelog might not have the inline index flag
63 # on. If the format of the changelog is the same as found in
63 # on. If the format of the changelog is the same as found in
64 # .hgrc, apply any flags found in the .hgrc as well.
64 # .hgrc, apply any flags found in the .hgrc as well.
65 # Otherwise, just version from the changelog
65 # Otherwise, just version from the changelog
66 v = self.changelog.version
66 v = self.changelog.version
67 if v == self.revlogversion:
67 if v == self.revlogversion:
68 v |= flags
68 v |= flags
69 self.revlogversion = v
69 self.revlogversion = v
70
70
71 self.tagscache = None
71 self.tagscache = None
72 self.nodetagscache = None
72 self.nodetagscache = None
73 self.encodepats = None
73 self.encodepats = None
74 self.decodepats = None
74 self.decodepats = None
75 self.transhandle = None
75 self.transhandle = None
76
76
77 if create:
77 if create:
78 os.mkdir(self.path)
78 os.mkdir(self.path)
79 os.mkdir(self.join("data"))
79 os.mkdir(self.join("data"))
80
80
81 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
81 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
82
82
83 def hook(self, name, throw=False, **args):
83 def hook(self, name, throw=False, **args):
84 def callhook(hname, funcname):
84 def callhook(hname, funcname):
85 '''call python hook. hook is callable object, looked up as
85 '''call python hook. hook is callable object, looked up as
86 name in python module. if callable returns "true", hook
86 name in python module. if callable returns "true", hook
87 fails, else passes. if hook raises exception, treated as
87 fails, else passes. if hook raises exception, treated as
88 hook failure. exception propagates if throw is "true".
88 hook failure. exception propagates if throw is "true".
89
89
90 reason for "true" meaning "hook failed" is so that
90 reason for "true" meaning "hook failed" is so that
91 unmodified commands (e.g. mercurial.commands.update) can
91 unmodified commands (e.g. mercurial.commands.update) can
92 be run as hooks without wrappers to convert return values.'''
92 be run as hooks without wrappers to convert return values.'''
93
93
94 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
94 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
95 d = funcname.rfind('.')
95 d = funcname.rfind('.')
96 if d == -1:
96 if d == -1:
97 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
97 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
98 % (hname, funcname))
98 % (hname, funcname))
99 modname = funcname[:d]
99 modname = funcname[:d]
100 try:
100 try:
101 obj = __import__(modname)
101 obj = __import__(modname)
102 except ImportError:
102 except ImportError:
103 raise util.Abort(_('%s hook is invalid '
103 raise util.Abort(_('%s hook is invalid '
104 '(import of "%s" failed)') %
104 '(import of "%s" failed)') %
105 (hname, modname))
105 (hname, modname))
106 try:
106 try:
107 for p in funcname.split('.')[1:]:
107 for p in funcname.split('.')[1:]:
108 obj = getattr(obj, p)
108 obj = getattr(obj, p)
109 except AttributeError, err:
109 except AttributeError, err:
110 raise util.Abort(_('%s hook is invalid '
110 raise util.Abort(_('%s hook is invalid '
111 '("%s" is not defined)') %
111 '("%s" is not defined)') %
112 (hname, funcname))
112 (hname, funcname))
113 if not callable(obj):
113 if not callable(obj):
114 raise util.Abort(_('%s hook is invalid '
114 raise util.Abort(_('%s hook is invalid '
115 '("%s" is not callable)') %
115 '("%s" is not callable)') %
116 (hname, funcname))
116 (hname, funcname))
117 try:
117 try:
118 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
118 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
119 except (KeyboardInterrupt, util.SignalInterrupt):
119 except (KeyboardInterrupt, util.SignalInterrupt):
120 raise
120 raise
121 except Exception, exc:
121 except Exception, exc:
122 if isinstance(exc, util.Abort):
122 if isinstance(exc, util.Abort):
123 self.ui.warn(_('error: %s hook failed: %s\n') %
123 self.ui.warn(_('error: %s hook failed: %s\n') %
124 (hname, exc.args[0] % exc.args[1:]))
124 (hname, exc.args[0] % exc.args[1:]))
125 else:
125 else:
126 self.ui.warn(_('error: %s hook raised an exception: '
126 self.ui.warn(_('error: %s hook raised an exception: '
127 '%s\n') % (hname, exc))
127 '%s\n') % (hname, exc))
128 if throw:
128 if throw:
129 raise
129 raise
130 self.ui.print_exc()
130 self.ui.print_exc()
131 return True
131 return True
132 if r:
132 if r:
133 if throw:
133 if throw:
134 raise util.Abort(_('%s hook failed') % hname)
134 raise util.Abort(_('%s hook failed') % hname)
135 self.ui.warn(_('warning: %s hook failed\n') % hname)
135 self.ui.warn(_('warning: %s hook failed\n') % hname)
136 return r
136 return r
137
137
138 def runhook(name, cmd):
138 def runhook(name, cmd):
139 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
139 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
140 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
140 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
141 r = util.system(cmd, environ=env, cwd=self.root)
141 r = util.system(cmd, environ=env, cwd=self.root)
142 if r:
142 if r:
143 desc, r = util.explain_exit(r)
143 desc, r = util.explain_exit(r)
144 if throw:
144 if throw:
145 raise util.Abort(_('%s hook %s') % (name, desc))
145 raise util.Abort(_('%s hook %s') % (name, desc))
146 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
146 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
147 return r
147 return r
148
148
149 r = False
149 r = False
150 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
150 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
151 if hname.split(".", 1)[0] == name and cmd]
151 if hname.split(".", 1)[0] == name and cmd]
152 hooks.sort()
152 hooks.sort()
153 for hname, cmd in hooks:
153 for hname, cmd in hooks:
154 if cmd.startswith('python:'):
154 if cmd.startswith('python:'):
155 r = callhook(hname, cmd[7:].strip()) or r
155 r = callhook(hname, cmd[7:].strip()) or r
156 else:
156 else:
157 r = runhook(hname, cmd) or r
157 r = runhook(hname, cmd) or r
158 return r
158 return r
159
159
160 def tags(self):
160 def tags(self):
161 '''return a mapping of tag to node'''
161 '''return a mapping of tag to node'''
162 if not self.tagscache:
162 if not self.tagscache:
163 self.tagscache = {}
163 self.tagscache = {}
164
164
165 def parsetag(line, context):
165 def parsetag(line, context):
166 if not line:
166 if not line:
167 return
167 return
168 s = l.split(" ", 1)
168 s = l.split(" ", 1)
169 if len(s) != 2:
169 if len(s) != 2:
170 self.ui.warn(_("%s: cannot parse entry\n") % context)
170 self.ui.warn(_("%s: cannot parse entry\n") % context)
171 return
171 return
172 node, key = s
172 node, key = s
173 key = key.strip()
173 key = key.strip()
174 try:
174 try:
175 bin_n = bin(node)
175 bin_n = bin(node)
176 except TypeError:
176 except TypeError:
177 self.ui.warn(_("%s: node '%s' is not well formed\n") %
177 self.ui.warn(_("%s: node '%s' is not well formed\n") %
178 (context, node))
178 (context, node))
179 return
179 return
180 if bin_n not in self.changelog.nodemap:
180 if bin_n not in self.changelog.nodemap:
181 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
181 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
182 (context, key))
182 (context, key))
183 return
183 return
184 self.tagscache[key] = bin_n
184 self.tagscache[key] = bin_n
185
185
186 # read the tags file from each head, ending with the tip,
186 # read the tags file from each head, ending with the tip,
187 # and add each tag found to the map, with "newer" ones
187 # and add each tag found to the map, with "newer" ones
188 # taking precedence
188 # taking precedence
189 heads = self.heads()
189 heads = self.heads()
190 heads.reverse()
190 heads.reverse()
191 fl = self.file(".hgtags")
191 fl = self.file(".hgtags")
192 for node in heads:
192 for node in heads:
193 change = self.changelog.read(node)
193 change = self.changelog.read(node)
194 rev = self.changelog.rev(node)
194 rev = self.changelog.rev(node)
195 fn, ff = self.manifest.find(change[0], '.hgtags')
195 fn, ff = self.manifest.find(change[0], '.hgtags')
196 if fn is None: continue
196 if fn is None: continue
197 count = 0
197 count = 0
198 for l in fl.read(fn).splitlines():
198 for l in fl.read(fn).splitlines():
199 count += 1
199 count += 1
200 parsetag(l, _(".hgtags (rev %d:%s), line %d") %
200 parsetag(l, _(".hgtags (rev %d:%s), line %d") %
201 (rev, short(node), count))
201 (rev, short(node), count))
202 try:
202 try:
203 f = self.opener("localtags")
203 f = self.opener("localtags")
204 count = 0
204 count = 0
205 for l in f:
205 for l in f:
206 count += 1
206 count += 1
207 parsetag(l, _("localtags, line %d") % count)
207 parsetag(l, _("localtags, line %d") % count)
208 except IOError:
208 except IOError:
209 pass
209 pass
210
210
211 self.tagscache['tip'] = self.changelog.tip()
211 self.tagscache['tip'] = self.changelog.tip()
212
212
213 return self.tagscache
213 return self.tagscache
214
214
215 def tagslist(self):
215 def tagslist(self):
216 '''return a list of tags ordered by revision'''
216 '''return a list of tags ordered by revision'''
217 l = []
217 l = []
218 for t, n in self.tags().items():
218 for t, n in self.tags().items():
219 try:
219 try:
220 r = self.changelog.rev(n)
220 r = self.changelog.rev(n)
221 except:
221 except:
222 r = -2 # sort to the beginning of the list if unknown
222 r = -2 # sort to the beginning of the list if unknown
223 l.append((r, t, n))
223 l.append((r, t, n))
224 l.sort()
224 l.sort()
225 return [(t, n) for r, t, n in l]
225 return [(t, n) for r, t, n in l]
226
226
227 def nodetags(self, node):
227 def nodetags(self, node):
228 '''return the tags associated with a node'''
228 '''return the tags associated with a node'''
229 if not self.nodetagscache:
229 if not self.nodetagscache:
230 self.nodetagscache = {}
230 self.nodetagscache = {}
231 for t, n in self.tags().items():
231 for t, n in self.tags().items():
232 self.nodetagscache.setdefault(n, []).append(t)
232 self.nodetagscache.setdefault(n, []).append(t)
233 return self.nodetagscache.get(node, [])
233 return self.nodetagscache.get(node, [])
234
234
235 def lookup(self, key):
235 def lookup(self, key):
236 try:
236 try:
237 return self.tags()[key]
237 return self.tags()[key]
238 except KeyError:
238 except KeyError:
239 try:
239 try:
240 return self.changelog.lookup(key)
240 return self.changelog.lookup(key)
241 except:
241 except:
242 raise repo.RepoError(_("unknown revision '%s'") % key)
242 raise repo.RepoError(_("unknown revision '%s'") % key)
243
243
244 def dev(self):
244 def dev(self):
245 return os.lstat(self.path).st_dev
245 return os.lstat(self.path).st_dev
246
246
247 def local(self):
247 def local(self):
248 return True
248 return True
249
249
250 def join(self, f):
250 def join(self, f):
251 return os.path.join(self.path, f)
251 return os.path.join(self.path, f)
252
252
253 def wjoin(self, f):
253 def wjoin(self, f):
254 return os.path.join(self.root, f)
254 return os.path.join(self.root, f)
255
255
256 def file(self, f):
256 def file(self, f):
257 if f[0] == '/':
257 if f[0] == '/':
258 f = f[1:]
258 f = f[1:]
259 return filelog.filelog(self.opener, f, self.revlogversion)
259 return filelog.filelog(self.opener, f, self.revlogversion)
260
260
261 def getcwd(self):
261 def getcwd(self):
262 return self.dirstate.getcwd()
262 return self.dirstate.getcwd()
263
263
264 def wfile(self, f, mode='r'):
264 def wfile(self, f, mode='r'):
265 return self.wopener(f, mode)
265 return self.wopener(f, mode)
266
266
267 def wread(self, filename):
267 def wread(self, filename):
268 if self.encodepats == None:
268 if self.encodepats == None:
269 l = []
269 l = []
270 for pat, cmd in self.ui.configitems("encode"):
270 for pat, cmd in self.ui.configitems("encode"):
271 mf = util.matcher(self.root, "", [pat], [], [])[1]
271 mf = util.matcher(self.root, "", [pat], [], [])[1]
272 l.append((mf, cmd))
272 l.append((mf, cmd))
273 self.encodepats = l
273 self.encodepats = l
274
274
275 data = self.wopener(filename, 'r').read()
275 data = self.wopener(filename, 'r').read()
276
276
277 for mf, cmd in self.encodepats:
277 for mf, cmd in self.encodepats:
278 if mf(filename):
278 if mf(filename):
279 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
279 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
280 data = util.filter(data, cmd)
280 data = util.filter(data, cmd)
281 break
281 break
282
282
283 return data
283 return data
284
284
285 def wwrite(self, filename, data, fd=None):
285 def wwrite(self, filename, data, fd=None):
286 if self.decodepats == None:
286 if self.decodepats == None:
287 l = []
287 l = []
288 for pat, cmd in self.ui.configitems("decode"):
288 for pat, cmd in self.ui.configitems("decode"):
289 mf = util.matcher(self.root, "", [pat], [], [])[1]
289 mf = util.matcher(self.root, "", [pat], [], [])[1]
290 l.append((mf, cmd))
290 l.append((mf, cmd))
291 self.decodepats = l
291 self.decodepats = l
292
292
293 for mf, cmd in self.decodepats:
293 for mf, cmd in self.decodepats:
294 if mf(filename):
294 if mf(filename):
295 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
295 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
296 data = util.filter(data, cmd)
296 data = util.filter(data, cmd)
297 break
297 break
298
298
299 if fd:
299 if fd:
300 return fd.write(data)
300 return fd.write(data)
301 return self.wopener(filename, 'w').write(data)
301 return self.wopener(filename, 'w').write(data)
302
302
303 def transaction(self):
303 def transaction(self):
304 tr = self.transhandle
304 tr = self.transhandle
305 if tr != None and tr.running():
305 if tr != None and tr.running():
306 return tr.nest()
306 return tr.nest()
307
307
308 # save dirstate for rollback
308 # save dirstate for rollback
309 try:
309 try:
310 ds = self.opener("dirstate").read()
310 ds = self.opener("dirstate").read()
311 except IOError:
311 except IOError:
312 ds = ""
312 ds = ""
313 self.opener("journal.dirstate", "w").write(ds)
313 self.opener("journal.dirstate", "w").write(ds)
314
314
315 tr = transaction.transaction(self.ui.warn, self.opener,
315 tr = transaction.transaction(self.ui.warn, self.opener,
316 self.join("journal"),
316 self.join("journal"),
317 aftertrans(self.path))
317 aftertrans(self.path))
318 self.transhandle = tr
318 self.transhandle = tr
319 return tr
319 return tr
320
320
321 def recover(self):
321 def recover(self):
322 l = self.lock()
322 l = self.lock()
323 if os.path.exists(self.join("journal")):
323 if os.path.exists(self.join("journal")):
324 self.ui.status(_("rolling back interrupted transaction\n"))
324 self.ui.status(_("rolling back interrupted transaction\n"))
325 transaction.rollback(self.opener, self.join("journal"))
325 transaction.rollback(self.opener, self.join("journal"))
326 self.reload()
326 self.reload()
327 return True
327 return True
328 else:
328 else:
329 self.ui.warn(_("no interrupted transaction available\n"))
329 self.ui.warn(_("no interrupted transaction available\n"))
330 return False
330 return False
331
331
332 def rollback(self, wlock=None):
332 def rollback(self, wlock=None):
333 if not wlock:
333 if not wlock:
334 wlock = self.wlock()
334 wlock = self.wlock()
335 l = self.lock()
335 l = self.lock()
336 if os.path.exists(self.join("undo")):
336 if os.path.exists(self.join("undo")):
337 self.ui.status(_("rolling back last transaction\n"))
337 self.ui.status(_("rolling back last transaction\n"))
338 transaction.rollback(self.opener, self.join("undo"))
338 transaction.rollback(self.opener, self.join("undo"))
339 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
339 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
340 self.reload()
340 self.reload()
341 self.wreload()
341 self.wreload()
342 else:
342 else:
343 self.ui.warn(_("no rollback information available\n"))
343 self.ui.warn(_("no rollback information available\n"))
344
344
345 def wreload(self):
345 def wreload(self):
346 self.dirstate.read()
346 self.dirstate.read()
347
347
348 def reload(self):
348 def reload(self):
349 self.changelog.load()
349 self.changelog.load()
350 self.manifest.load()
350 self.manifest.load()
351 self.tagscache = None
351 self.tagscache = None
352 self.nodetagscache = None
352 self.nodetagscache = None
353
353
354 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
354 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
355 desc=None):
355 desc=None):
356 try:
356 try:
357 l = lock.lock(self.join(lockname), 0, releasefn, desc=desc)
357 l = lock.lock(self.join(lockname), 0, releasefn, desc=desc)
358 except lock.LockHeld, inst:
358 except lock.LockHeld, inst:
359 if not wait:
359 if not wait:
360 raise
360 raise
361 self.ui.warn(_("waiting for lock on %s held by %s\n") %
361 self.ui.warn(_("waiting for lock on %s held by %s\n") %
362 (desc, inst.args[0]))
362 (desc, inst.args[0]))
363 # default to 600 seconds timeout
363 # default to 600 seconds timeout
364 l = lock.lock(self.join(lockname),
364 l = lock.lock(self.join(lockname),
365 int(self.ui.config("ui", "timeout") or 600),
365 int(self.ui.config("ui", "timeout") or 600),
366 releasefn, desc=desc)
366 releasefn, desc=desc)
367 if acquirefn:
367 if acquirefn:
368 acquirefn()
368 acquirefn()
369 return l
369 return l
370
370
371 def lock(self, wait=1):
371 def lock(self, wait=1):
372 return self.do_lock("lock", wait, acquirefn=self.reload,
372 return self.do_lock("lock", wait, acquirefn=self.reload,
373 desc=_('repository %s') % self.origroot)
373 desc=_('repository %s') % self.origroot)
374
374
375 def wlock(self, wait=1):
375 def wlock(self, wait=1):
376 return self.do_lock("wlock", wait, self.dirstate.write,
376 return self.do_lock("wlock", wait, self.dirstate.write,
377 self.wreload,
377 self.wreload,
378 desc=_('working directory of %s') % self.origroot)
378 desc=_('working directory of %s') % self.origroot)
379
379
380 def checkfilemerge(self, filename, text, filelog, manifest1, manifest2):
380 def checkfilemerge(self, filename, text, filelog, manifest1, manifest2):
381 "determine whether a new filenode is needed"
381 "determine whether a new filenode is needed"
382 fp1 = manifest1.get(filename, nullid)
382 fp1 = manifest1.get(filename, nullid)
383 fp2 = manifest2.get(filename, nullid)
383 fp2 = manifest2.get(filename, nullid)
384
384
385 if fp2 != nullid:
385 if fp2 != nullid:
386 # is one parent an ancestor of the other?
386 # is one parent an ancestor of the other?
387 fpa = filelog.ancestor(fp1, fp2)
387 fpa = filelog.ancestor(fp1, fp2)
388 if fpa == fp1:
388 if fpa == fp1:
389 fp1, fp2 = fp2, nullid
389 fp1, fp2 = fp2, nullid
390 elif fpa == fp2:
390 elif fpa == fp2:
391 fp2 = nullid
391 fp2 = nullid
392
392
393 # is the file unmodified from the parent? report existing entry
393 # is the file unmodified from the parent? report existing entry
394 if fp2 == nullid and text == filelog.read(fp1):
394 if fp2 == nullid and text == filelog.read(fp1):
395 return (fp1, None, None)
395 return (fp1, None, None)
396
396
397 return (None, fp1, fp2)
397 return (None, fp1, fp2)
398
398
399 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
399 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
400 orig_parent = self.dirstate.parents()[0] or nullid
400 orig_parent = self.dirstate.parents()[0] or nullid
401 p1 = p1 or self.dirstate.parents()[0] or nullid
401 p1 = p1 or self.dirstate.parents()[0] or nullid
402 p2 = p2 or self.dirstate.parents()[1] or nullid
402 p2 = p2 or self.dirstate.parents()[1] or nullid
403 c1 = self.changelog.read(p1)
403 c1 = self.changelog.read(p1)
404 c2 = self.changelog.read(p2)
404 c2 = self.changelog.read(p2)
405 m1 = self.manifest.read(c1[0])
405 m1 = self.manifest.read(c1[0])
406 mf1 = self.manifest.readflags(c1[0])
406 mf1 = self.manifest.readflags(c1[0])
407 m2 = self.manifest.read(c2[0])
407 m2 = self.manifest.read(c2[0])
408 changed = []
408 changed = []
409
409
410 if orig_parent == p1:
410 if orig_parent == p1:
411 update_dirstate = 1
411 update_dirstate = 1
412 else:
412 else:
413 update_dirstate = 0
413 update_dirstate = 0
414
414
415 if not wlock:
415 if not wlock:
416 wlock = self.wlock()
416 wlock = self.wlock()
417 l = self.lock()
417 l = self.lock()
418 tr = self.transaction()
418 tr = self.transaction()
419 mm = m1.copy()
419 mm = m1.copy()
420 mfm = mf1.copy()
420 mfm = mf1.copy()
421 linkrev = self.changelog.count()
421 linkrev = self.changelog.count()
422 for f in files:
422 for f in files:
423 try:
423 try:
424 t = self.wread(f)
424 t = self.wread(f)
425 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
425 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
426 r = self.file(f)
426 r = self.file(f)
427 mfm[f] = tm
427 mfm[f] = tm
428
428
429 (entry, fp1, fp2) = self.checkfilemerge(f, t, r, m1, m2)
429 (entry, fp1, fp2) = self.checkfilemerge(f, t, r, m1, m2)
430 if entry:
430 if entry:
431 mm[f] = entry
431 mm[f] = entry
432 continue
432 continue
433
433
434 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
434 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
435 changed.append(f)
435 changed.append(f)
436 if update_dirstate:
436 if update_dirstate:
437 self.dirstate.update([f], "n")
437 self.dirstate.update([f], "n")
438 except IOError:
438 except IOError:
439 try:
439 try:
440 del mm[f]
440 del mm[f]
441 del mfm[f]
441 del mfm[f]
442 if update_dirstate:
442 if update_dirstate:
443 self.dirstate.forget([f])
443 self.dirstate.forget([f])
444 except:
444 except:
445 # deleted from p2?
445 # deleted from p2?
446 pass
446 pass
447
447
448 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
448 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
449 user = user or self.ui.username()
449 user = user or self.ui.username()
450 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
450 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
451 tr.close()
451 tr.close()
452 if update_dirstate:
452 if update_dirstate:
453 self.dirstate.setparents(n, nullid)
453 self.dirstate.setparents(n, nullid)
454
454
455 def commit(self, files=None, text="", user=None, date=None,
455 def commit(self, files=None, text="", user=None, date=None,
456 match=util.always, force=False, lock=None, wlock=None,
456 match=util.always, force=False, lock=None, wlock=None,
457 force_editor=False):
457 force_editor=False):
458 commit = []
458 commit = []
459 remove = []
459 remove = []
460 changed = []
460 changed = []
461
461
462 if files:
462 if files:
463 for f in files:
463 for f in files:
464 s = self.dirstate.state(f)
464 s = self.dirstate.state(f)
465 if s in 'nmai':
465 if s in 'nmai':
466 commit.append(f)
466 commit.append(f)
467 elif s == 'r':
467 elif s == 'r':
468 remove.append(f)
468 remove.append(f)
469 else:
469 else:
470 self.ui.warn(_("%s not tracked!\n") % f)
470 self.ui.warn(_("%s not tracked!\n") % f)
471 else:
471 else:
472 modified, added, removed, deleted, unknown = self.changes(match=match)
472 modified, added, removed, deleted, unknown = self.changes(match=match)
473 commit = modified + added
473 commit = modified + added
474 remove = removed
474 remove = removed
475
475
476 p1, p2 = self.dirstate.parents()
476 p1, p2 = self.dirstate.parents()
477 c1 = self.changelog.read(p1)
477 c1 = self.changelog.read(p1)
478 c2 = self.changelog.read(p2)
478 c2 = self.changelog.read(p2)
479 m1 = self.manifest.read(c1[0])
479 m1 = self.manifest.read(c1[0])
480 mf1 = self.manifest.readflags(c1[0])
480 mf1 = self.manifest.readflags(c1[0])
481 m2 = self.manifest.read(c2[0])
481 m2 = self.manifest.read(c2[0])
482
482
483 if not commit and not remove and not force and p2 == nullid:
483 if not commit and not remove and not force and p2 == nullid:
484 self.ui.status(_("nothing changed\n"))
484 self.ui.status(_("nothing changed\n"))
485 return None
485 return None
486
486
487 xp1 = hex(p1)
487 xp1 = hex(p1)
488 if p2 == nullid: xp2 = ''
488 if p2 == nullid: xp2 = ''
489 else: xp2 = hex(p2)
489 else: xp2 = hex(p2)
490
490
491 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
491 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
492
492
493 if not wlock:
493 if not wlock:
494 wlock = self.wlock()
494 wlock = self.wlock()
495 if not lock:
495 if not lock:
496 lock = self.lock()
496 lock = self.lock()
497 tr = self.transaction()
497 tr = self.transaction()
498
498
499 # check in files
499 # check in files
500 new = {}
500 new = {}
501 linkrev = self.changelog.count()
501 linkrev = self.changelog.count()
502 commit.sort()
502 commit.sort()
503 for f in commit:
503 for f in commit:
504 self.ui.note(f + "\n")
504 self.ui.note(f + "\n")
505 try:
505 try:
506 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
506 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
507 t = self.wread(f)
507 t = self.wread(f)
508 except IOError:
508 except IOError:
509 self.ui.warn(_("trouble committing %s!\n") % f)
509 self.ui.warn(_("trouble committing %s!\n") % f)
510 raise
510 raise
511
511
512 r = self.file(f)
512 r = self.file(f)
513
513
514 meta = {}
514 meta = {}
515 cp = self.dirstate.copied(f)
515 cp = self.dirstate.copied(f)
516 if cp:
516 if cp:
517 meta["copy"] = cp
517 meta["copy"] = cp
518 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
518 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
519 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
519 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
520 fp1, fp2 = nullid, nullid
520 fp1, fp2 = nullid, nullid
521 else:
521 else:
522 entry, fp1, fp2 = self.checkfilemerge(f, t, r, m1, m2)
522 entry, fp1, fp2 = self.checkfilemerge(f, t, r, m1, m2)
523 if entry:
523 if entry:
524 new[f] = entry
524 new[f] = entry
525 continue
525 continue
526
526
527 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
527 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
528 # remember what we've added so that we can later calculate
528 # remember what we've added so that we can later calculate
529 # the files to pull from a set of changesets
529 # the files to pull from a set of changesets
530 changed.append(f)
530 changed.append(f)
531
531
532 # update manifest
532 # update manifest
533 m1 = m1.copy()
533 m1 = m1.copy()
534 m1.update(new)
534 m1.update(new)
535 for f in remove:
535 for f in remove:
536 if f in m1:
536 if f in m1:
537 del m1[f]
537 del m1[f]
538 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
538 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
539 (new, remove))
539 (new, remove))
540
540
541 # add changeset
541 # add changeset
542 new = new.keys()
542 new = new.keys()
543 new.sort()
543 new.sort()
544
544
545 user = user or self.ui.username()
545 user = user or self.ui.username()
546 if not text or force_editor:
546 if not text or force_editor:
547 edittext = []
547 edittext = []
548 if text:
548 if text:
549 edittext.append(text)
549 edittext.append(text)
550 edittext.append("")
550 edittext.append("")
551 if p2 != nullid:
551 if p2 != nullid:
552 edittext.append("HG: branch merge")
552 edittext.append("HG: branch merge")
553 edittext.extend(["HG: changed %s" % f for f in changed])
553 edittext.extend(["HG: changed %s" % f for f in changed])
554 edittext.extend(["HG: removed %s" % f for f in remove])
554 edittext.extend(["HG: removed %s" % f for f in remove])
555 if not changed and not remove:
555 if not changed and not remove:
556 edittext.append("HG: no files changed")
556 edittext.append("HG: no files changed")
557 edittext.append("")
557 edittext.append("")
558 # run editor in the repository root
558 # run editor in the repository root
559 olddir = os.getcwd()
559 olddir = os.getcwd()
560 os.chdir(self.root)
560 os.chdir(self.root)
561 text = self.ui.edit("\n".join(edittext), user)
561 text = self.ui.edit("\n".join(edittext), user)
562 os.chdir(olddir)
562 os.chdir(olddir)
563
563
564 lines = [line.rstrip() for line in text.rstrip().splitlines()]
564 lines = [line.rstrip() for line in text.rstrip().splitlines()]
565 while lines and not lines[0]:
565 while lines and not lines[0]:
566 del lines[0]
566 del lines[0]
567 if not lines:
567 if not lines:
568 return None
568 return None
569 text = '\n'.join(lines)
569 text = '\n'.join(lines)
570 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
570 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
571 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
571 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
572 parent2=xp2)
572 parent2=xp2)
573 tr.close()
573 tr.close()
574
574
575 self.dirstate.setparents(n)
575 self.dirstate.setparents(n)
576 self.dirstate.update(new, "n")
576 self.dirstate.update(new, "n")
577 self.dirstate.forget(remove)
577 self.dirstate.forget(remove)
578
578
579 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
579 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
580 return n
580 return n
581
581
582 def walk(self, node=None, files=[], match=util.always, badmatch=None):
582 def walk(self, node=None, files=[], match=util.always, badmatch=None):
583 if node:
583 if node:
584 fdict = dict.fromkeys(files)
584 fdict = dict.fromkeys(files)
585 for fn in self.manifest.read(self.changelog.read(node)[0]):
585 for fn in self.manifest.read(self.changelog.read(node)[0]):
586 fdict.pop(fn, None)
586 fdict.pop(fn, None)
587 if match(fn):
587 if match(fn):
588 yield 'm', fn
588 yield 'm', fn
589 for fn in fdict:
589 for fn in fdict:
590 if badmatch and badmatch(fn):
590 if badmatch and badmatch(fn):
591 if match(fn):
591 if match(fn):
592 yield 'b', fn
592 yield 'b', fn
593 else:
593 else:
594 self.ui.warn(_('%s: No such file in rev %s\n') % (
594 self.ui.warn(_('%s: No such file in rev %s\n') % (
595 util.pathto(self.getcwd(), fn), short(node)))
595 util.pathto(self.getcwd(), fn), short(node)))
596 else:
596 else:
597 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
597 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
598 yield src, fn
598 yield src, fn
599
599
600 def changes(self, node1=None, node2=None, files=[], match=util.always,
600 def changes(self, node1=None, node2=None, files=[], match=util.always,
601 wlock=None, show_ignored=None):
601 wlock=None, show_ignored=None):
602 """return changes between two nodes or node and working directory
602 """return changes between two nodes or node and working directory
603
603
604 If node1 is None, use the first dirstate parent instead.
604 If node1 is None, use the first dirstate parent instead.
605 If node2 is None, compare node1 with working directory.
605 If node2 is None, compare node1 with working directory.
606 """
606 """
607
607
608 def fcmp(fn, mf):
608 def fcmp(fn, mf):
609 t1 = self.wread(fn)
609 t1 = self.wread(fn)
610 t2 = self.file(fn).read(mf.get(fn, nullid))
610 t2 = self.file(fn).read(mf.get(fn, nullid))
611 return cmp(t1, t2)
611 return cmp(t1, t2)
612
612
613 def mfmatches(node):
613 def mfmatches(node):
614 change = self.changelog.read(node)
614 change = self.changelog.read(node)
615 mf = dict(self.manifest.read(change[0]))
615 mf = dict(self.manifest.read(change[0]))
616 for fn in mf.keys():
616 for fn in mf.keys():
617 if not match(fn):
617 if not match(fn):
618 del mf[fn]
618 del mf[fn]
619 return mf
619 return mf
620
620
621 if node1:
621 if node1:
622 # read the manifest from node1 before the manifest from node2,
622 # read the manifest from node1 before the manifest from node2,
623 # so that we'll hit the manifest cache if we're going through
623 # so that we'll hit the manifest cache if we're going through
624 # all the revisions in parent->child order.
624 # all the revisions in parent->child order.
625 mf1 = mfmatches(node1)
625 mf1 = mfmatches(node1)
626
626
627 # are we comparing the working directory?
627 # are we comparing the working directory?
628 if not node2:
628 if not node2:
629 if not wlock:
629 if not wlock:
630 try:
630 try:
631 wlock = self.wlock(wait=0)
631 wlock = self.wlock(wait=0)
632 except lock.LockException:
632 except lock.LockException:
633 wlock = None
633 wlock = None
634 lookup, modified, added, removed, deleted, unknown, ignored = (
634 lookup, modified, added, removed, deleted, unknown, ignored = (
635 self.dirstate.changes(files, match, show_ignored))
635 self.dirstate.changes(files, match, show_ignored))
636
636
637 # are we comparing working dir against its parent?
637 # are we comparing working dir against its parent?
638 if not node1:
638 if not node1:
639 if lookup:
639 if lookup:
640 # do a full compare of any files that might have changed
640 # do a full compare of any files that might have changed
641 mf2 = mfmatches(self.dirstate.parents()[0])
641 mf2 = mfmatches(self.dirstate.parents()[0])
642 for f in lookup:
642 for f in lookup:
643 if fcmp(f, mf2):
643 if fcmp(f, mf2):
644 modified.append(f)
644 modified.append(f)
645 elif wlock is not None:
645 elif wlock is not None:
646 self.dirstate.update([f], "n")
646 self.dirstate.update([f], "n")
647 else:
647 else:
648 # we are comparing working dir against non-parent
648 # we are comparing working dir against non-parent
649 # generate a pseudo-manifest for the working dir
649 # generate a pseudo-manifest for the working dir
650 mf2 = mfmatches(self.dirstate.parents()[0])
650 mf2 = mfmatches(self.dirstate.parents()[0])
651 for f in lookup + modified + added:
651 for f in lookup + modified + added:
652 mf2[f] = ""
652 mf2[f] = ""
653 for f in removed:
653 for f in removed:
654 if f in mf2:
654 if f in mf2:
655 del mf2[f]
655 del mf2[f]
656 else:
656 else:
657 # we are comparing two revisions
657 # we are comparing two revisions
658 deleted, unknown, ignored = [], [], []
658 deleted, unknown, ignored = [], [], []
659 mf2 = mfmatches(node2)
659 mf2 = mfmatches(node2)
660
660
661 if node1:
661 if node1:
662 # flush lists from dirstate before comparing manifests
662 # flush lists from dirstate before comparing manifests
663 modified, added = [], []
663 modified, added = [], []
664
664
665 for fn in mf2:
665 for fn in mf2:
666 if mf1.has_key(fn):
666 if mf1.has_key(fn):
667 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
667 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
668 modified.append(fn)
668 modified.append(fn)
669 del mf1[fn]
669 del mf1[fn]
670 else:
670 else:
671 added.append(fn)
671 added.append(fn)
672
672
673 removed = mf1.keys()
673 removed = mf1.keys()
674
674
675 # sort and return results:
675 # sort and return results:
676 for l in modified, added, removed, deleted, unknown, ignored:
676 for l in modified, added, removed, deleted, unknown, ignored:
677 l.sort()
677 l.sort()
678 if show_ignored is None:
678 if show_ignored is None:
679 return (modified, added, removed, deleted, unknown)
679 return (modified, added, removed, deleted, unknown)
680 else:
680 else:
681 return (modified, added, removed, deleted, unknown, ignored)
681 return (modified, added, removed, deleted, unknown, ignored)
682
682
683 def add(self, list, wlock=None):
683 def add(self, list, wlock=None):
684 if not wlock:
684 if not wlock:
685 wlock = self.wlock()
685 wlock = self.wlock()
686 for f in list:
686 for f in list:
687 p = self.wjoin(f)
687 p = self.wjoin(f)
688 if not os.path.exists(p):
688 if not os.path.exists(p):
689 self.ui.warn(_("%s does not exist!\n") % f)
689 self.ui.warn(_("%s does not exist!\n") % f)
690 elif not os.path.isfile(p):
690 elif not os.path.isfile(p):
691 self.ui.warn(_("%s not added: only files supported currently\n")
691 self.ui.warn(_("%s not added: only files supported currently\n")
692 % f)
692 % f)
693 elif self.dirstate.state(f) in 'an':
693 elif self.dirstate.state(f) in 'an':
694 self.ui.warn(_("%s already tracked!\n") % f)
694 self.ui.warn(_("%s already tracked!\n") % f)
695 else:
695 else:
696 self.dirstate.update([f], "a")
696 self.dirstate.update([f], "a")
697
697
698 def forget(self, list, wlock=None):
698 def forget(self, list, wlock=None):
699 if not wlock:
699 if not wlock:
700 wlock = self.wlock()
700 wlock = self.wlock()
701 for f in list:
701 for f in list:
702 if self.dirstate.state(f) not in 'ai':
702 if self.dirstate.state(f) not in 'ai':
703 self.ui.warn(_("%s not added!\n") % f)
703 self.ui.warn(_("%s not added!\n") % f)
704 else:
704 else:
705 self.dirstate.forget([f])
705 self.dirstate.forget([f])
706
706
707 def remove(self, list, unlink=False, wlock=None):
707 def remove(self, list, unlink=False, wlock=None):
708 if unlink:
708 if unlink:
709 for f in list:
709 for f in list:
710 try:
710 try:
711 util.unlink(self.wjoin(f))
711 util.unlink(self.wjoin(f))
712 except OSError, inst:
712 except OSError, inst:
713 if inst.errno != errno.ENOENT:
713 if inst.errno != errno.ENOENT:
714 raise
714 raise
715 if not wlock:
715 if not wlock:
716 wlock = self.wlock()
716 wlock = self.wlock()
717 for f in list:
717 for f in list:
718 p = self.wjoin(f)
718 p = self.wjoin(f)
719 if os.path.exists(p):
719 if os.path.exists(p):
720 self.ui.warn(_("%s still exists!\n") % f)
720 self.ui.warn(_("%s still exists!\n") % f)
721 elif self.dirstate.state(f) == 'a':
721 elif self.dirstate.state(f) == 'a':
722 self.dirstate.forget([f])
722 self.dirstate.forget([f])
723 elif f not in self.dirstate:
723 elif f not in self.dirstate:
724 self.ui.warn(_("%s not tracked!\n") % f)
724 self.ui.warn(_("%s not tracked!\n") % f)
725 else:
725 else:
726 self.dirstate.update([f], "r")
726 self.dirstate.update([f], "r")
727
727
728 def undelete(self, list, wlock=None):
728 def undelete(self, list, wlock=None):
729 p = self.dirstate.parents()[0]
729 p = self.dirstate.parents()[0]
730 mn = self.changelog.read(p)[0]
730 mn = self.changelog.read(p)[0]
731 mf = self.manifest.readflags(mn)
731 mf = self.manifest.readflags(mn)
732 m = self.manifest.read(mn)
732 m = self.manifest.read(mn)
733 if not wlock:
733 if not wlock:
734 wlock = self.wlock()
734 wlock = self.wlock()
735 for f in list:
735 for f in list:
736 if self.dirstate.state(f) not in "r":
736 if self.dirstate.state(f) not in "r":
737 self.ui.warn("%s not removed!\n" % f)
737 self.ui.warn("%s not removed!\n" % f)
738 else:
738 else:
739 t = self.file(f).read(m[f])
739 t = self.file(f).read(m[f])
740 self.wwrite(f, t)
740 self.wwrite(f, t)
741 util.set_exec(self.wjoin(f), mf[f])
741 util.set_exec(self.wjoin(f), mf[f])
742 self.dirstate.update([f], "n")
742 self.dirstate.update([f], "n")
743
743
744 def copy(self, source, dest, wlock=None):
744 def copy(self, source, dest, wlock=None):
745 p = self.wjoin(dest)
745 p = self.wjoin(dest)
746 if not os.path.exists(p):
746 if not os.path.exists(p):
747 self.ui.warn(_("%s does not exist!\n") % dest)
747 self.ui.warn(_("%s does not exist!\n") % dest)
748 elif not os.path.isfile(p):
748 elif not os.path.isfile(p):
749 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
749 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
750 else:
750 else:
751 if not wlock:
751 if not wlock:
752 wlock = self.wlock()
752 wlock = self.wlock()
753 if self.dirstate.state(dest) == '?':
753 if self.dirstate.state(dest) == '?':
754 self.dirstate.update([dest], "a")
754 self.dirstate.update([dest], "a")
755 self.dirstate.copy(source, dest)
755 self.dirstate.copy(source, dest)
756
756
757 def heads(self, start=None):
757 def heads(self, start=None):
758 heads = self.changelog.heads(start)
758 heads = self.changelog.heads(start)
759 # sort the output in rev descending order
759 # sort the output in rev descending order
760 heads = [(-self.changelog.rev(h), h) for h in heads]
760 heads = [(-self.changelog.rev(h), h) for h in heads]
761 heads.sort()
761 heads.sort()
762 return [n for (r, n) in heads]
762 return [n for (r, n) in heads]
763
763
764 # branchlookup returns a dict giving a list of branches for
764 # branchlookup returns a dict giving a list of branches for
765 # each head. A branch is defined as the tag of a node or
765 # each head. A branch is defined as the tag of a node or
766 # the branch of the node's parents. If a node has multiple
766 # the branch of the node's parents. If a node has multiple
767 # branch tags, tags are eliminated if they are visible from other
767 # branch tags, tags are eliminated if they are visible from other
768 # branch tags.
768 # branch tags.
769 #
769 #
770 # So, for this graph: a->b->c->d->e
770 # So, for this graph: a->b->c->d->e
771 # \ /
771 # \ /
772 # aa -----/
772 # aa -----/
773 # a has tag 2.6.12
773 # a has tag 2.6.12
774 # d has tag 2.6.13
774 # d has tag 2.6.13
775 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
775 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
776 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
776 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
777 # from the list.
777 # from the list.
778 #
778 #
779 # It is possible that more than one head will have the same branch tag.
779 # It is possible that more than one head will have the same branch tag.
780 # callers need to check the result for multiple heads under the same
780 # callers need to check the result for multiple heads under the same
781 # branch tag if that is a problem for them (ie checkout of a specific
781 # branch tag if that is a problem for them (ie checkout of a specific
782 # branch).
782 # branch).
783 #
783 #
784 # passing in a specific branch will limit the depth of the search
784 # passing in a specific branch will limit the depth of the search
785 # through the parents. It won't limit the branches returned in the
785 # through the parents. It won't limit the branches returned in the
786 # result though.
786 # result though.
787 def branchlookup(self, heads=None, branch=None):
787 def branchlookup(self, heads=None, branch=None):
788 if not heads:
788 if not heads:
789 heads = self.heads()
789 heads = self.heads()
790 headt = [ h for h in heads ]
790 headt = [ h for h in heads ]
791 chlog = self.changelog
791 chlog = self.changelog
792 branches = {}
792 branches = {}
793 merges = []
793 merges = []
794 seenmerge = {}
794 seenmerge = {}
795
795
796 # traverse the tree once for each head, recording in the branches
796 # traverse the tree once for each head, recording in the branches
797 # dict which tags are visible from this head. The branches
797 # dict which tags are visible from this head. The branches
798 # dict also records which tags are visible from each tag
798 # dict also records which tags are visible from each tag
799 # while we traverse.
799 # while we traverse.
800 while headt or merges:
800 while headt or merges:
801 if merges:
801 if merges:
802 n, found = merges.pop()
802 n, found = merges.pop()
803 visit = [n]
803 visit = [n]
804 else:
804 else:
805 h = headt.pop()
805 h = headt.pop()
806 visit = [h]
806 visit = [h]
807 found = [h]
807 found = [h]
808 seen = {}
808 seen = {}
809 while visit:
809 while visit:
810 n = visit.pop()
810 n = visit.pop()
811 if n in seen:
811 if n in seen:
812 continue
812 continue
813 pp = chlog.parents(n)
813 pp = chlog.parents(n)
814 tags = self.nodetags(n)
814 tags = self.nodetags(n)
815 if tags:
815 if tags:
816 for x in tags:
816 for x in tags:
817 if x == 'tip':
817 if x == 'tip':
818 continue
818 continue
819 for f in found:
819 for f in found:
820 branches.setdefault(f, {})[n] = 1
820 branches.setdefault(f, {})[n] = 1
821 branches.setdefault(n, {})[n] = 1
821 branches.setdefault(n, {})[n] = 1
822 break
822 break
823 if n not in found:
823 if n not in found:
824 found.append(n)
824 found.append(n)
825 if branch in tags:
825 if branch in tags:
826 continue
826 continue
827 seen[n] = 1
827 seen[n] = 1
828 if pp[1] != nullid and n not in seenmerge:
828 if pp[1] != nullid and n not in seenmerge:
829 merges.append((pp[1], [x for x in found]))
829 merges.append((pp[1], [x for x in found]))
830 seenmerge[n] = 1
830 seenmerge[n] = 1
831 if pp[0] != nullid:
831 if pp[0] != nullid:
832 visit.append(pp[0])
832 visit.append(pp[0])
833 # traverse the branches dict, eliminating branch tags from each
833 # traverse the branches dict, eliminating branch tags from each
834 # head that are visible from another branch tag for that head.
834 # head that are visible from another branch tag for that head.
835 out = {}
835 out = {}
836 viscache = {}
836 viscache = {}
837 for h in heads:
837 for h in heads:
838 def visible(node):
838 def visible(node):
839 if node in viscache:
839 if node in viscache:
840 return viscache[node]
840 return viscache[node]
841 ret = {}
841 ret = {}
842 visit = [node]
842 visit = [node]
843 while visit:
843 while visit:
844 x = visit.pop()
844 x = visit.pop()
845 if x in viscache:
845 if x in viscache:
846 ret.update(viscache[x])
846 ret.update(viscache[x])
847 elif x not in ret:
847 elif x not in ret:
848 ret[x] = 1
848 ret[x] = 1
849 if x in branches:
849 if x in branches:
850 visit[len(visit):] = branches[x].keys()
850 visit[len(visit):] = branches[x].keys()
851 viscache[node] = ret
851 viscache[node] = ret
852 return ret
852 return ret
853 if h not in branches:
853 if h not in branches:
854 continue
854 continue
855 # O(n^2), but somewhat limited. This only searches the
855 # O(n^2), but somewhat limited. This only searches the
856 # tags visible from a specific head, not all the tags in the
856 # tags visible from a specific head, not all the tags in the
857 # whole repo.
857 # whole repo.
858 for b in branches[h]:
858 for b in branches[h]:
859 vis = False
859 vis = False
860 for bb in branches[h].keys():
860 for bb in branches[h].keys():
861 if b != bb:
861 if b != bb:
862 if b in visible(bb):
862 if b in visible(bb):
863 vis = True
863 vis = True
864 break
864 break
865 if not vis:
865 if not vis:
866 l = out.setdefault(h, [])
866 l = out.setdefault(h, [])
867 l[len(l):] = self.nodetags(b)
867 l[len(l):] = self.nodetags(b)
868 return out
868 return out
869
869
870 def branches(self, nodes):
870 def branches(self, nodes):
871 if not nodes:
871 if not nodes:
872 nodes = [self.changelog.tip()]
872 nodes = [self.changelog.tip()]
873 b = []
873 b = []
874 for n in nodes:
874 for n in nodes:
875 t = n
875 t = n
876 while 1:
876 while 1:
877 p = self.changelog.parents(n)
877 p = self.changelog.parents(n)
878 if p[1] != nullid or p[0] == nullid:
878 if p[1] != nullid or p[0] == nullid:
879 b.append((t, n, p[0], p[1]))
879 b.append((t, n, p[0], p[1]))
880 break
880 break
881 n = p[0]
881 n = p[0]
882 return b
882 return b
883
883
884 def between(self, pairs):
884 def between(self, pairs):
885 r = []
885 r = []
886
886
887 for top, bottom in pairs:
887 for top, bottom in pairs:
888 n, l, i = top, [], 0
888 n, l, i = top, [], 0
889 f = 1
889 f = 1
890
890
891 while n != bottom:
891 while n != bottom:
892 p = self.changelog.parents(n)[0]
892 p = self.changelog.parents(n)[0]
893 if i == f:
893 if i == f:
894 l.append(n)
894 l.append(n)
895 f = f * 2
895 f = f * 2
896 n = p
896 n = p
897 i += 1
897 i += 1
898
898
899 r.append(l)
899 r.append(l)
900
900
901 return r
901 return r
902
902
903 def findincoming(self, remote, base=None, heads=None, force=False):
903 def findincoming(self, remote, base=None, heads=None, force=False):
904 """Return list of roots of the subsets of missing nodes from remote
904 """Return list of roots of the subsets of missing nodes from remote
905
905
906 If base dict is specified, assume that these nodes and their parents
906 If base dict is specified, assume that these nodes and their parents
907 exist on the remote side and that no child of a node of base exists
907 exist on the remote side and that no child of a node of base exists
908 in both remote and self.
908 in both remote and self.
909 Furthermore base will be updated to include the nodes that exists
909 Furthermore base will be updated to include the nodes that exists
910 in self and remote but no children exists in self and remote.
910 in self and remote but no children exists in self and remote.
911 If a list of heads is specified, return only nodes which are heads
911 If a list of heads is specified, return only nodes which are heads
912 or ancestors of these heads.
912 or ancestors of these heads.
913
913
914 All the ancestors of base are in self and in remote.
914 All the ancestors of base are in self and in remote.
915 All the descendants of the list returned are missing in self.
915 All the descendants of the list returned are missing in self.
916 (and so we know that the rest of the nodes are missing in remote, see
916 (and so we know that the rest of the nodes are missing in remote, see
917 outgoing)
917 outgoing)
918 """
918 """
919 m = self.changelog.nodemap
919 m = self.changelog.nodemap
920 search = []
920 search = []
921 fetch = {}
921 fetch = {}
922 seen = {}
922 seen = {}
923 seenbranch = {}
923 seenbranch = {}
924 if base == None:
924 if base == None:
925 base = {}
925 base = {}
926
926
927 if not heads:
927 if not heads:
928 heads = remote.heads()
928 heads = remote.heads()
929
929
930 if self.changelog.tip() == nullid:
930 if self.changelog.tip() == nullid:
931 base[nullid] = 1
931 base[nullid] = 1
932 if heads != [nullid]:
932 if heads != [nullid]:
933 return [nullid]
933 return [nullid]
934 return []
934 return []
935
935
936 # assume we're closer to the tip than the root
936 # assume we're closer to the tip than the root
937 # and start by examining the heads
937 # and start by examining the heads
938 self.ui.status(_("searching for changes\n"))
938 self.ui.status(_("searching for changes\n"))
939
939
940 unknown = []
940 unknown = []
941 for h in heads:
941 for h in heads:
942 if h not in m:
942 if h not in m:
943 unknown.append(h)
943 unknown.append(h)
944 else:
944 else:
945 base[h] = 1
945 base[h] = 1
946
946
947 if not unknown:
947 if not unknown:
948 return []
948 return []
949
949
950 req = dict.fromkeys(unknown)
950 req = dict.fromkeys(unknown)
951 reqcnt = 0
951 reqcnt = 0
952
952
953 # search through remote branches
953 # search through remote branches
954 # a 'branch' here is a linear segment of history, with four parts:
954 # a 'branch' here is a linear segment of history, with four parts:
955 # head, root, first parent, second parent
955 # head, root, first parent, second parent
956 # (a branch always has two parents (or none) by definition)
956 # (a branch always has two parents (or none) by definition)
957 unknown = remote.branches(unknown)
957 unknown = remote.branches(unknown)
958 while unknown:
958 while unknown:
959 r = []
959 r = []
960 while unknown:
960 while unknown:
961 n = unknown.pop(0)
961 n = unknown.pop(0)
962 if n[0] in seen:
962 if n[0] in seen:
963 continue
963 continue
964
964
965 self.ui.debug(_("examining %s:%s\n")
965 self.ui.debug(_("examining %s:%s\n")
966 % (short(n[0]), short(n[1])))
966 % (short(n[0]), short(n[1])))
967 if n[0] == nullid: # found the end of the branch
967 if n[0] == nullid: # found the end of the branch
968 pass
968 pass
969 elif n in seenbranch:
969 elif n in seenbranch:
970 self.ui.debug(_("branch already found\n"))
970 self.ui.debug(_("branch already found\n"))
971 continue
971 continue
972 elif n[1] and n[1] in m: # do we know the base?
972 elif n[1] and n[1] in m: # do we know the base?
973 self.ui.debug(_("found incomplete branch %s:%s\n")
973 self.ui.debug(_("found incomplete branch %s:%s\n")
974 % (short(n[0]), short(n[1])))
974 % (short(n[0]), short(n[1])))
975 search.append(n) # schedule branch range for scanning
975 search.append(n) # schedule branch range for scanning
976 seenbranch[n] = 1
976 seenbranch[n] = 1
977 else:
977 else:
978 if n[1] not in seen and n[1] not in fetch:
978 if n[1] not in seen and n[1] not in fetch:
979 if n[2] in m and n[3] in m:
979 if n[2] in m and n[3] in m:
980 self.ui.debug(_("found new changeset %s\n") %
980 self.ui.debug(_("found new changeset %s\n") %
981 short(n[1]))
981 short(n[1]))
982 fetch[n[1]] = 1 # earliest unknown
982 fetch[n[1]] = 1 # earliest unknown
983 for p in n[2:4]:
983 for p in n[2:4]:
984 if p in m:
984 if p in m:
985 base[p] = 1 # latest known
985 base[p] = 1 # latest known
986
986
987 for p in n[2:4]:
987 for p in n[2:4]:
988 if p not in req and p not in m:
988 if p not in req and p not in m:
989 r.append(p)
989 r.append(p)
990 req[p] = 1
990 req[p] = 1
991 seen[n[0]] = 1
991 seen[n[0]] = 1
992
992
993 if r:
993 if r:
994 reqcnt += 1
994 reqcnt += 1
995 self.ui.debug(_("request %d: %s\n") %
995 self.ui.debug(_("request %d: %s\n") %
996 (reqcnt, " ".join(map(short, r))))
996 (reqcnt, " ".join(map(short, r))))
997 for p in range(0, len(r), 10):
997 for p in range(0, len(r), 10):
998 for b in remote.branches(r[p:p+10]):
998 for b in remote.branches(r[p:p+10]):
999 self.ui.debug(_("received %s:%s\n") %
999 self.ui.debug(_("received %s:%s\n") %
1000 (short(b[0]), short(b[1])))
1000 (short(b[0]), short(b[1])))
1001 unknown.append(b)
1001 unknown.append(b)
1002
1002
1003 # do binary search on the branches we found
1003 # do binary search on the branches we found
1004 while search:
1004 while search:
1005 n = search.pop(0)
1005 n = search.pop(0)
1006 reqcnt += 1
1006 reqcnt += 1
1007 l = remote.between([(n[0], n[1])])[0]
1007 l = remote.between([(n[0], n[1])])[0]
1008 l.append(n[1])
1008 l.append(n[1])
1009 p = n[0]
1009 p = n[0]
1010 f = 1
1010 f = 1
1011 for i in l:
1011 for i in l:
1012 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1012 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1013 if i in m:
1013 if i in m:
1014 if f <= 2:
1014 if f <= 2:
1015 self.ui.debug(_("found new branch changeset %s\n") %
1015 self.ui.debug(_("found new branch changeset %s\n") %
1016 short(p))
1016 short(p))
1017 fetch[p] = 1
1017 fetch[p] = 1
1018 base[i] = 1
1018 base[i] = 1
1019 else:
1019 else:
1020 self.ui.debug(_("narrowed branch search to %s:%s\n")
1020 self.ui.debug(_("narrowed branch search to %s:%s\n")
1021 % (short(p), short(i)))
1021 % (short(p), short(i)))
1022 search.append((p, i))
1022 search.append((p, i))
1023 break
1023 break
1024 p, f = i, f * 2
1024 p, f = i, f * 2
1025
1025
1026 # sanity check our fetch list
1026 # sanity check our fetch list
1027 for f in fetch.keys():
1027 for f in fetch.keys():
1028 if f in m:
1028 if f in m:
1029 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1029 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1030
1030
1031 if base.keys() == [nullid]:
1031 if base.keys() == [nullid]:
1032 if force:
1032 if force:
1033 self.ui.warn(_("warning: repository is unrelated\n"))
1033 self.ui.warn(_("warning: repository is unrelated\n"))
1034 else:
1034 else:
1035 raise util.Abort(_("repository is unrelated"))
1035 raise util.Abort(_("repository is unrelated"))
1036
1036
1037 self.ui.note(_("found new changesets starting at ") +
1037 self.ui.note(_("found new changesets starting at ") +
1038 " ".join([short(f) for f in fetch]) + "\n")
1038 " ".join([short(f) for f in fetch]) + "\n")
1039
1039
1040 self.ui.debug(_("%d total queries\n") % reqcnt)
1040 self.ui.debug(_("%d total queries\n") % reqcnt)
1041
1041
1042 return fetch.keys()
1042 return fetch.keys()
1043
1043
1044 def findoutgoing(self, remote, base=None, heads=None, force=False):
1044 def findoutgoing(self, remote, base=None, heads=None, force=False):
1045 """Return list of nodes that are roots of subsets not in remote
1045 """Return list of nodes that are roots of subsets not in remote
1046
1046
1047 If base dict is specified, assume that these nodes and their parents
1047 If base dict is specified, assume that these nodes and their parents
1048 exist on the remote side.
1048 exist on the remote side.
1049 If a list of heads is specified, return only nodes which are heads
1049 If a list of heads is specified, return only nodes which are heads
1050 or ancestors of these heads, and return a second element which
1050 or ancestors of these heads, and return a second element which
1051 contains all remote heads which get new children.
1051 contains all remote heads which get new children.
1052 """
1052 """
1053 if base == None:
1053 if base == None:
1054 base = {}
1054 base = {}
1055 self.findincoming(remote, base, heads, force=force)
1055 self.findincoming(remote, base, heads, force=force)
1056
1056
1057 self.ui.debug(_("common changesets up to ")
1057 self.ui.debug(_("common changesets up to ")
1058 + " ".join(map(short, base.keys())) + "\n")
1058 + " ".join(map(short, base.keys())) + "\n")
1059
1059
1060 remain = dict.fromkeys(self.changelog.nodemap)
1060 remain = dict.fromkeys(self.changelog.nodemap)
1061
1061
1062 # prune everything remote has from the tree
1062 # prune everything remote has from the tree
1063 del remain[nullid]
1063 del remain[nullid]
1064 remove = base.keys()
1064 remove = base.keys()
1065 while remove:
1065 while remove:
1066 n = remove.pop(0)
1066 n = remove.pop(0)
1067 if n in remain:
1067 if n in remain:
1068 del remain[n]
1068 del remain[n]
1069 for p in self.changelog.parents(n):
1069 for p in self.changelog.parents(n):
1070 remove.append(p)
1070 remove.append(p)
1071
1071
1072 # find every node whose parents have been pruned
1072 # find every node whose parents have been pruned
1073 subset = []
1073 subset = []
1074 # find every remote head that will get new children
1074 # find every remote head that will get new children
1075 updated_heads = {}
1075 updated_heads = {}
1076 for n in remain:
1076 for n in remain:
1077 p1, p2 = self.changelog.parents(n)
1077 p1, p2 = self.changelog.parents(n)
1078 if p1 not in remain and p2 not in remain:
1078 if p1 not in remain and p2 not in remain:
1079 subset.append(n)
1079 subset.append(n)
1080 if heads:
1080 if heads:
1081 if p1 in heads:
1081 if p1 in heads:
1082 updated_heads[p1] = True
1082 updated_heads[p1] = True
1083 if p2 in heads:
1083 if p2 in heads:
1084 updated_heads[p2] = True
1084 updated_heads[p2] = True
1085
1085
1086 # this is the set of all roots we have to push
1086 # this is the set of all roots we have to push
1087 if heads:
1087 if heads:
1088 return subset, updated_heads.keys()
1088 return subset, updated_heads.keys()
1089 else:
1089 else:
1090 return subset
1090 return subset
1091
1091
1092 def pull(self, remote, heads=None, force=False):
1092 def pull(self, remote, heads=None, force=False):
1093 l = self.lock()
1093 l = self.lock()
1094
1094
1095 fetch = self.findincoming(remote, force=force)
1095 fetch = self.findincoming(remote, force=force)
1096 if fetch == [nullid]:
1096 if fetch == [nullid]:
1097 self.ui.status(_("requesting all changes\n"))
1097 self.ui.status(_("requesting all changes\n"))
1098
1098
1099 if not fetch:
1099 if not fetch:
1100 self.ui.status(_("no changes found\n"))
1100 self.ui.status(_("no changes found\n"))
1101 return 0
1101 return 0
1102
1102
1103 if heads is None:
1103 if heads is None:
1104 cg = remote.changegroup(fetch, 'pull')
1104 cg = remote.changegroup(fetch, 'pull')
1105 else:
1105 else:
1106 cg = remote.changegroupsubset(fetch, heads, 'pull')
1106 cg = remote.changegroupsubset(fetch, heads, 'pull')
1107 return self.addchangegroup(cg, 'pull')
1107 return self.addchangegroup(cg, 'pull')
1108
1108
1109 def push(self, remote, force=False, revs=None):
1109 def push(self, remote, force=False, revs=None):
1110 # there are two ways to push to remote repo:
1110 # there are two ways to push to remote repo:
1111 #
1111 #
1112 # addchangegroup assumes local user can lock remote
1112 # addchangegroup assumes local user can lock remote
1113 # repo (local filesystem, old ssh servers).
1113 # repo (local filesystem, old ssh servers).
1114 #
1114 #
1115 # unbundle assumes local user cannot lock remote repo (new ssh
1115 # unbundle assumes local user cannot lock remote repo (new ssh
1116 # servers, http servers).
1116 # servers, http servers).
1117
1117
1118 if 'unbundle' in remote.capabilities:
1118 if 'unbundle' in remote.capabilities:
1119 self.push_unbundle(remote, force, revs)
1119 return self.push_unbundle(remote, force, revs)
1120 else:
1120 return self.push_addchangegroup(remote, force, revs)
1121 self.push_addchangegroup(remote, force, revs)
1122
1121
1123 def prepush(self, remote, force, revs):
1122 def prepush(self, remote, force, revs):
1124 base = {}
1123 base = {}
1125 remote_heads = remote.heads()
1124 remote_heads = remote.heads()
1126 inc = self.findincoming(remote, base, remote_heads, force=force)
1125 inc = self.findincoming(remote, base, remote_heads, force=force)
1127 if not force and inc:
1126 if not force and inc:
1128 self.ui.warn(_("abort: unsynced remote changes!\n"))
1127 self.ui.warn(_("abort: unsynced remote changes!\n"))
1129 self.ui.status(_("(did you forget to sync?"
1128 self.ui.status(_("(did you forget to sync?"
1130 " use push -f to force)\n"))
1129 " use push -f to force)\n"))
1131 return None, 1
1130 return None, 1
1132
1131
1133 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1132 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1134 if revs is not None:
1133 if revs is not None:
1135 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1134 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1136 else:
1135 else:
1137 bases, heads = update, self.changelog.heads()
1136 bases, heads = update, self.changelog.heads()
1138
1137
1139 if not bases:
1138 if not bases:
1140 self.ui.status(_("no changes found\n"))
1139 self.ui.status(_("no changes found\n"))
1141 return None, 1
1140 return None, 1
1142 elif not force:
1141 elif not force:
1143 # FIXME we don't properly detect creation of new heads
1142 # FIXME we don't properly detect creation of new heads
1144 # in the push -r case, assume the user knows what he's doing
1143 # in the push -r case, assume the user knows what he's doing
1145 if not revs and len(remote_heads) < len(heads) \
1144 if not revs and len(remote_heads) < len(heads) \
1146 and remote_heads != [nullid]:
1145 and remote_heads != [nullid]:
1147 self.ui.warn(_("abort: push creates new remote branches!\n"))
1146 self.ui.warn(_("abort: push creates new remote branches!\n"))
1148 self.ui.status(_("(did you forget to merge?"
1147 self.ui.status(_("(did you forget to merge?"
1149 " use push -f to force)\n"))
1148 " use push -f to force)\n"))
1150 return None, 1
1149 return None, 1
1151
1150
1152 if revs is None:
1151 if revs is None:
1153 cg = self.changegroup(update, 'push')
1152 cg = self.changegroup(update, 'push')
1154 else:
1153 else:
1155 cg = self.changegroupsubset(update, revs, 'push')
1154 cg = self.changegroupsubset(update, revs, 'push')
1156 return cg, remote_heads
1155 return cg, remote_heads
1157
1156
1158 def push_addchangegroup(self, remote, force, revs):
1157 def push_addchangegroup(self, remote, force, revs):
1159 lock = remote.lock()
1158 lock = remote.lock()
1160
1159
1161 ret = self.prepush(remote, force, revs)
1160 ret = self.prepush(remote, force, revs)
1162 if ret[0] is not None:
1161 if ret[0] is not None:
1163 cg, remote_heads = ret
1162 cg, remote_heads = ret
1164 return remote.addchangegroup(cg, 'push')
1163 return remote.addchangegroup(cg, 'push')
1165 return ret[1]
1164 return ret[1]
1166
1165
1167 def push_unbundle(self, remote, force, revs):
1166 def push_unbundle(self, remote, force, revs):
1168 # local repo finds heads on server, finds out what revs it
1167 # local repo finds heads on server, finds out what revs it
1169 # must push. once revs transferred, if server finds it has
1168 # must push. once revs transferred, if server finds it has
1170 # different heads (someone else won commit/push race), server
1169 # different heads (someone else won commit/push race), server
1171 # aborts.
1170 # aborts.
1172
1171
1173 ret = self.prepush(remote, force, revs)
1172 ret = self.prepush(remote, force, revs)
1174 if ret[0] is not None:
1173 if ret[0] is not None:
1175 cg, remote_heads = ret
1174 cg, remote_heads = ret
1176 if force: remote_heads = ['force']
1175 if force: remote_heads = ['force']
1177 return remote.unbundle(cg, remote_heads, 'push')
1176 return remote.unbundle(cg, remote_heads, 'push')
1178 return ret[1]
1177 return ret[1]
1179
1178
1180 def changegroupsubset(self, bases, heads, source):
1179 def changegroupsubset(self, bases, heads, source):
1181 """This function generates a changegroup consisting of all the nodes
1180 """This function generates a changegroup consisting of all the nodes
1182 that are descendents of any of the bases, and ancestors of any of
1181 that are descendents of any of the bases, and ancestors of any of
1183 the heads.
1182 the heads.
1184
1183
1185 It is fairly complex as determining which filenodes and which
1184 It is fairly complex as determining which filenodes and which
1186 manifest nodes need to be included for the changeset to be complete
1185 manifest nodes need to be included for the changeset to be complete
1187 is non-trivial.
1186 is non-trivial.
1188
1187
1189 Another wrinkle is doing the reverse, figuring out which changeset in
1188 Another wrinkle is doing the reverse, figuring out which changeset in
1190 the changegroup a particular filenode or manifestnode belongs to."""
1189 the changegroup a particular filenode or manifestnode belongs to."""
1191
1190
1192 self.hook('preoutgoing', throw=True, source=source)
1191 self.hook('preoutgoing', throw=True, source=source)
1193
1192
1194 # Set up some initial variables
1193 # Set up some initial variables
1195 # Make it easy to refer to self.changelog
1194 # Make it easy to refer to self.changelog
1196 cl = self.changelog
1195 cl = self.changelog
1197 # msng is short for missing - compute the list of changesets in this
1196 # msng is short for missing - compute the list of changesets in this
1198 # changegroup.
1197 # changegroup.
1199 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1198 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1200 # Some bases may turn out to be superfluous, and some heads may be
1199 # Some bases may turn out to be superfluous, and some heads may be
1201 # too. nodesbetween will return the minimal set of bases and heads
1200 # too. nodesbetween will return the minimal set of bases and heads
1202 # necessary to re-create the changegroup.
1201 # necessary to re-create the changegroup.
1203
1202
1204 # Known heads are the list of heads that it is assumed the recipient
1203 # Known heads are the list of heads that it is assumed the recipient
1205 # of this changegroup will know about.
1204 # of this changegroup will know about.
1206 knownheads = {}
1205 knownheads = {}
1207 # We assume that all parents of bases are known heads.
1206 # We assume that all parents of bases are known heads.
1208 for n in bases:
1207 for n in bases:
1209 for p in cl.parents(n):
1208 for p in cl.parents(n):
1210 if p != nullid:
1209 if p != nullid:
1211 knownheads[p] = 1
1210 knownheads[p] = 1
1212 knownheads = knownheads.keys()
1211 knownheads = knownheads.keys()
1213 if knownheads:
1212 if knownheads:
1214 # Now that we know what heads are known, we can compute which
1213 # Now that we know what heads are known, we can compute which
1215 # changesets are known. The recipient must know about all
1214 # changesets are known. The recipient must know about all
1216 # changesets required to reach the known heads from the null
1215 # changesets required to reach the known heads from the null
1217 # changeset.
1216 # changeset.
1218 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1217 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1219 junk = None
1218 junk = None
1220 # Transform the list into an ersatz set.
1219 # Transform the list into an ersatz set.
1221 has_cl_set = dict.fromkeys(has_cl_set)
1220 has_cl_set = dict.fromkeys(has_cl_set)
1222 else:
1221 else:
1223 # If there were no known heads, the recipient cannot be assumed to
1222 # If there were no known heads, the recipient cannot be assumed to
1224 # know about any changesets.
1223 # know about any changesets.
1225 has_cl_set = {}
1224 has_cl_set = {}
1226
1225
1227 # Make it easy to refer to self.manifest
1226 # Make it easy to refer to self.manifest
1228 mnfst = self.manifest
1227 mnfst = self.manifest
1229 # We don't know which manifests are missing yet
1228 # We don't know which manifests are missing yet
1230 msng_mnfst_set = {}
1229 msng_mnfst_set = {}
1231 # Nor do we know which filenodes are missing.
1230 # Nor do we know which filenodes are missing.
1232 msng_filenode_set = {}
1231 msng_filenode_set = {}
1233
1232
1234 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1233 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1235 junk = None
1234 junk = None
1236
1235
1237 # A changeset always belongs to itself, so the changenode lookup
1236 # A changeset always belongs to itself, so the changenode lookup
1238 # function for a changenode is identity.
1237 # function for a changenode is identity.
1239 def identity(x):
1238 def identity(x):
1240 return x
1239 return x
1241
1240
1242 # A function generating function. Sets up an environment for the
1241 # A function generating function. Sets up an environment for the
1243 # inner function.
1242 # inner function.
1244 def cmp_by_rev_func(revlog):
1243 def cmp_by_rev_func(revlog):
1245 # Compare two nodes by their revision number in the environment's
1244 # Compare two nodes by their revision number in the environment's
1246 # revision history. Since the revision number both represents the
1245 # revision history. Since the revision number both represents the
1247 # most efficient order to read the nodes in, and represents a
1246 # most efficient order to read the nodes in, and represents a
1248 # topological sorting of the nodes, this function is often useful.
1247 # topological sorting of the nodes, this function is often useful.
1249 def cmp_by_rev(a, b):
1248 def cmp_by_rev(a, b):
1250 return cmp(revlog.rev(a), revlog.rev(b))
1249 return cmp(revlog.rev(a), revlog.rev(b))
1251 return cmp_by_rev
1250 return cmp_by_rev
1252
1251
1253 # If we determine that a particular file or manifest node must be a
1252 # If we determine that a particular file or manifest node must be a
1254 # node that the recipient of the changegroup will already have, we can
1253 # node that the recipient of the changegroup will already have, we can
1255 # also assume the recipient will have all the parents. This function
1254 # also assume the recipient will have all the parents. This function
1256 # prunes them from the set of missing nodes.
1255 # prunes them from the set of missing nodes.
1257 def prune_parents(revlog, hasset, msngset):
1256 def prune_parents(revlog, hasset, msngset):
1258 haslst = hasset.keys()
1257 haslst = hasset.keys()
1259 haslst.sort(cmp_by_rev_func(revlog))
1258 haslst.sort(cmp_by_rev_func(revlog))
1260 for node in haslst:
1259 for node in haslst:
1261 parentlst = [p for p in revlog.parents(node) if p != nullid]
1260 parentlst = [p for p in revlog.parents(node) if p != nullid]
1262 while parentlst:
1261 while parentlst:
1263 n = parentlst.pop()
1262 n = parentlst.pop()
1264 if n not in hasset:
1263 if n not in hasset:
1265 hasset[n] = 1
1264 hasset[n] = 1
1266 p = [p for p in revlog.parents(n) if p != nullid]
1265 p = [p for p in revlog.parents(n) if p != nullid]
1267 parentlst.extend(p)
1266 parentlst.extend(p)
1268 for n in hasset:
1267 for n in hasset:
1269 msngset.pop(n, None)
1268 msngset.pop(n, None)
1270
1269
1271 # This is a function generating function used to set up an environment
1270 # This is a function generating function used to set up an environment
1272 # for the inner function to execute in.
1271 # for the inner function to execute in.
1273 def manifest_and_file_collector(changedfileset):
1272 def manifest_and_file_collector(changedfileset):
1274 # This is an information gathering function that gathers
1273 # This is an information gathering function that gathers
1275 # information from each changeset node that goes out as part of
1274 # information from each changeset node that goes out as part of
1276 # the changegroup. The information gathered is a list of which
1275 # the changegroup. The information gathered is a list of which
1277 # manifest nodes are potentially required (the recipient may
1276 # manifest nodes are potentially required (the recipient may
1278 # already have them) and total list of all files which were
1277 # already have them) and total list of all files which were
1279 # changed in any changeset in the changegroup.
1278 # changed in any changeset in the changegroup.
1280 #
1279 #
1281 # We also remember the first changenode we saw any manifest
1280 # We also remember the first changenode we saw any manifest
1282 # referenced by so we can later determine which changenode 'owns'
1281 # referenced by so we can later determine which changenode 'owns'
1283 # the manifest.
1282 # the manifest.
1284 def collect_manifests_and_files(clnode):
1283 def collect_manifests_and_files(clnode):
1285 c = cl.read(clnode)
1284 c = cl.read(clnode)
1286 for f in c[3]:
1285 for f in c[3]:
1287 # This is to make sure we only have one instance of each
1286 # This is to make sure we only have one instance of each
1288 # filename string for each filename.
1287 # filename string for each filename.
1289 changedfileset.setdefault(f, f)
1288 changedfileset.setdefault(f, f)
1290 msng_mnfst_set.setdefault(c[0], clnode)
1289 msng_mnfst_set.setdefault(c[0], clnode)
1291 return collect_manifests_and_files
1290 return collect_manifests_and_files
1292
1291
1293 # Figure out which manifest nodes (of the ones we think might be part
1292 # Figure out which manifest nodes (of the ones we think might be part
1294 # of the changegroup) the recipient must know about and remove them
1293 # of the changegroup) the recipient must know about and remove them
1295 # from the changegroup.
1294 # from the changegroup.
1296 def prune_manifests():
1295 def prune_manifests():
1297 has_mnfst_set = {}
1296 has_mnfst_set = {}
1298 for n in msng_mnfst_set:
1297 for n in msng_mnfst_set:
1299 # If a 'missing' manifest thinks it belongs to a changenode
1298 # If a 'missing' manifest thinks it belongs to a changenode
1300 # the recipient is assumed to have, obviously the recipient
1299 # the recipient is assumed to have, obviously the recipient
1301 # must have that manifest.
1300 # must have that manifest.
1302 linknode = cl.node(mnfst.linkrev(n))
1301 linknode = cl.node(mnfst.linkrev(n))
1303 if linknode in has_cl_set:
1302 if linknode in has_cl_set:
1304 has_mnfst_set[n] = 1
1303 has_mnfst_set[n] = 1
1305 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1304 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1306
1305
1307 # Use the information collected in collect_manifests_and_files to say
1306 # Use the information collected in collect_manifests_and_files to say
1308 # which changenode any manifestnode belongs to.
1307 # which changenode any manifestnode belongs to.
1309 def lookup_manifest_link(mnfstnode):
1308 def lookup_manifest_link(mnfstnode):
1310 return msng_mnfst_set[mnfstnode]
1309 return msng_mnfst_set[mnfstnode]
1311
1310
1312 # A function generating function that sets up the initial environment
1311 # A function generating function that sets up the initial environment
1313 # the inner function.
1312 # the inner function.
1314 def filenode_collector(changedfiles):
1313 def filenode_collector(changedfiles):
1315 next_rev = [0]
1314 next_rev = [0]
1316 # This gathers information from each manifestnode included in the
1315 # This gathers information from each manifestnode included in the
1317 # changegroup about which filenodes the manifest node references
1316 # changegroup about which filenodes the manifest node references
1318 # so we can include those in the changegroup too.
1317 # so we can include those in the changegroup too.
1319 #
1318 #
1320 # It also remembers which changenode each filenode belongs to. It
1319 # It also remembers which changenode each filenode belongs to. It
1321 # does this by assuming the a filenode belongs to the changenode
1320 # does this by assuming the a filenode belongs to the changenode
1322 # the first manifest that references it belongs to.
1321 # the first manifest that references it belongs to.
1323 def collect_msng_filenodes(mnfstnode):
1322 def collect_msng_filenodes(mnfstnode):
1324 r = mnfst.rev(mnfstnode)
1323 r = mnfst.rev(mnfstnode)
1325 if r == next_rev[0]:
1324 if r == next_rev[0]:
1326 # If the last rev we looked at was the one just previous,
1325 # If the last rev we looked at was the one just previous,
1327 # we only need to see a diff.
1326 # we only need to see a diff.
1328 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1327 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1329 # For each line in the delta
1328 # For each line in the delta
1330 for dline in delta.splitlines():
1329 for dline in delta.splitlines():
1331 # get the filename and filenode for that line
1330 # get the filename and filenode for that line
1332 f, fnode = dline.split('\0')
1331 f, fnode = dline.split('\0')
1333 fnode = bin(fnode[:40])
1332 fnode = bin(fnode[:40])
1334 f = changedfiles.get(f, None)
1333 f = changedfiles.get(f, None)
1335 # And if the file is in the list of files we care
1334 # And if the file is in the list of files we care
1336 # about.
1335 # about.
1337 if f is not None:
1336 if f is not None:
1338 # Get the changenode this manifest belongs to
1337 # Get the changenode this manifest belongs to
1339 clnode = msng_mnfst_set[mnfstnode]
1338 clnode = msng_mnfst_set[mnfstnode]
1340 # Create the set of filenodes for the file if
1339 # Create the set of filenodes for the file if
1341 # there isn't one already.
1340 # there isn't one already.
1342 ndset = msng_filenode_set.setdefault(f, {})
1341 ndset = msng_filenode_set.setdefault(f, {})
1343 # And set the filenode's changelog node to the
1342 # And set the filenode's changelog node to the
1344 # manifest's if it hasn't been set already.
1343 # manifest's if it hasn't been set already.
1345 ndset.setdefault(fnode, clnode)
1344 ndset.setdefault(fnode, clnode)
1346 else:
1345 else:
1347 # Otherwise we need a full manifest.
1346 # Otherwise we need a full manifest.
1348 m = mnfst.read(mnfstnode)
1347 m = mnfst.read(mnfstnode)
1349 # For every file in we care about.
1348 # For every file in we care about.
1350 for f in changedfiles:
1349 for f in changedfiles:
1351 fnode = m.get(f, None)
1350 fnode = m.get(f, None)
1352 # If it's in the manifest
1351 # If it's in the manifest
1353 if fnode is not None:
1352 if fnode is not None:
1354 # See comments above.
1353 # See comments above.
1355 clnode = msng_mnfst_set[mnfstnode]
1354 clnode = msng_mnfst_set[mnfstnode]
1356 ndset = msng_filenode_set.setdefault(f, {})
1355 ndset = msng_filenode_set.setdefault(f, {})
1357 ndset.setdefault(fnode, clnode)
1356 ndset.setdefault(fnode, clnode)
1358 # Remember the revision we hope to see next.
1357 # Remember the revision we hope to see next.
1359 next_rev[0] = r + 1
1358 next_rev[0] = r + 1
1360 return collect_msng_filenodes
1359 return collect_msng_filenodes
1361
1360
1362 # We have a list of filenodes we think we need for a file, lets remove
1361 # We have a list of filenodes we think we need for a file, lets remove
1363 # all those we now the recipient must have.
1362 # all those we now the recipient must have.
1364 def prune_filenodes(f, filerevlog):
1363 def prune_filenodes(f, filerevlog):
1365 msngset = msng_filenode_set[f]
1364 msngset = msng_filenode_set[f]
1366 hasset = {}
1365 hasset = {}
1367 # If a 'missing' filenode thinks it belongs to a changenode we
1366 # If a 'missing' filenode thinks it belongs to a changenode we
1368 # assume the recipient must have, then the recipient must have
1367 # assume the recipient must have, then the recipient must have
1369 # that filenode.
1368 # that filenode.
1370 for n in msngset:
1369 for n in msngset:
1371 clnode = cl.node(filerevlog.linkrev(n))
1370 clnode = cl.node(filerevlog.linkrev(n))
1372 if clnode in has_cl_set:
1371 if clnode in has_cl_set:
1373 hasset[n] = 1
1372 hasset[n] = 1
1374 prune_parents(filerevlog, hasset, msngset)
1373 prune_parents(filerevlog, hasset, msngset)
1375
1374
1376 # A function generator function that sets up the a context for the
1375 # A function generator function that sets up the a context for the
1377 # inner function.
1376 # inner function.
1378 def lookup_filenode_link_func(fname):
1377 def lookup_filenode_link_func(fname):
1379 msngset = msng_filenode_set[fname]
1378 msngset = msng_filenode_set[fname]
1380 # Lookup the changenode the filenode belongs to.
1379 # Lookup the changenode the filenode belongs to.
1381 def lookup_filenode_link(fnode):
1380 def lookup_filenode_link(fnode):
1382 return msngset[fnode]
1381 return msngset[fnode]
1383 return lookup_filenode_link
1382 return lookup_filenode_link
1384
1383
1385 # Now that we have all theses utility functions to help out and
1384 # Now that we have all theses utility functions to help out and
1386 # logically divide up the task, generate the group.
1385 # logically divide up the task, generate the group.
1387 def gengroup():
1386 def gengroup():
1388 # The set of changed files starts empty.
1387 # The set of changed files starts empty.
1389 changedfiles = {}
1388 changedfiles = {}
1390 # Create a changenode group generator that will call our functions
1389 # Create a changenode group generator that will call our functions
1391 # back to lookup the owning changenode and collect information.
1390 # back to lookup the owning changenode and collect information.
1392 group = cl.group(msng_cl_lst, identity,
1391 group = cl.group(msng_cl_lst, identity,
1393 manifest_and_file_collector(changedfiles))
1392 manifest_and_file_collector(changedfiles))
1394 for chnk in group:
1393 for chnk in group:
1395 yield chnk
1394 yield chnk
1396
1395
1397 # The list of manifests has been collected by the generator
1396 # The list of manifests has been collected by the generator
1398 # calling our functions back.
1397 # calling our functions back.
1399 prune_manifests()
1398 prune_manifests()
1400 msng_mnfst_lst = msng_mnfst_set.keys()
1399 msng_mnfst_lst = msng_mnfst_set.keys()
1401 # Sort the manifestnodes by revision number.
1400 # Sort the manifestnodes by revision number.
1402 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1401 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1403 # Create a generator for the manifestnodes that calls our lookup
1402 # Create a generator for the manifestnodes that calls our lookup
1404 # and data collection functions back.
1403 # and data collection functions back.
1405 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1404 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1406 filenode_collector(changedfiles))
1405 filenode_collector(changedfiles))
1407 for chnk in group:
1406 for chnk in group:
1408 yield chnk
1407 yield chnk
1409
1408
1410 # These are no longer needed, dereference and toss the memory for
1409 # These are no longer needed, dereference and toss the memory for
1411 # them.
1410 # them.
1412 msng_mnfst_lst = None
1411 msng_mnfst_lst = None
1413 msng_mnfst_set.clear()
1412 msng_mnfst_set.clear()
1414
1413
1415 changedfiles = changedfiles.keys()
1414 changedfiles = changedfiles.keys()
1416 changedfiles.sort()
1415 changedfiles.sort()
1417 # Go through all our files in order sorted by name.
1416 # Go through all our files in order sorted by name.
1418 for fname in changedfiles:
1417 for fname in changedfiles:
1419 filerevlog = self.file(fname)
1418 filerevlog = self.file(fname)
1420 # Toss out the filenodes that the recipient isn't really
1419 # Toss out the filenodes that the recipient isn't really
1421 # missing.
1420 # missing.
1422 if msng_filenode_set.has_key(fname):
1421 if msng_filenode_set.has_key(fname):
1423 prune_filenodes(fname, filerevlog)
1422 prune_filenodes(fname, filerevlog)
1424 msng_filenode_lst = msng_filenode_set[fname].keys()
1423 msng_filenode_lst = msng_filenode_set[fname].keys()
1425 else:
1424 else:
1426 msng_filenode_lst = []
1425 msng_filenode_lst = []
1427 # If any filenodes are left, generate the group for them,
1426 # If any filenodes are left, generate the group for them,
1428 # otherwise don't bother.
1427 # otherwise don't bother.
1429 if len(msng_filenode_lst) > 0:
1428 if len(msng_filenode_lst) > 0:
1430 yield changegroup.genchunk(fname)
1429 yield changegroup.genchunk(fname)
1431 # Sort the filenodes by their revision #
1430 # Sort the filenodes by their revision #
1432 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1431 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1433 # Create a group generator and only pass in a changenode
1432 # Create a group generator and only pass in a changenode
1434 # lookup function as we need to collect no information
1433 # lookup function as we need to collect no information
1435 # from filenodes.
1434 # from filenodes.
1436 group = filerevlog.group(msng_filenode_lst,
1435 group = filerevlog.group(msng_filenode_lst,
1437 lookup_filenode_link_func(fname))
1436 lookup_filenode_link_func(fname))
1438 for chnk in group:
1437 for chnk in group:
1439 yield chnk
1438 yield chnk
1440 if msng_filenode_set.has_key(fname):
1439 if msng_filenode_set.has_key(fname):
1441 # Don't need this anymore, toss it to free memory.
1440 # Don't need this anymore, toss it to free memory.
1442 del msng_filenode_set[fname]
1441 del msng_filenode_set[fname]
1443 # Signal that no more groups are left.
1442 # Signal that no more groups are left.
1444 yield changegroup.closechunk()
1443 yield changegroup.closechunk()
1445
1444
1446 if msng_cl_lst:
1445 if msng_cl_lst:
1447 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1446 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1448
1447
1449 return util.chunkbuffer(gengroup())
1448 return util.chunkbuffer(gengroup())
1450
1449
1451 def changegroup(self, basenodes, source):
1450 def changegroup(self, basenodes, source):
1452 """Generate a changegroup of all nodes that we have that a recipient
1451 """Generate a changegroup of all nodes that we have that a recipient
1453 doesn't.
1452 doesn't.
1454
1453
1455 This is much easier than the previous function as we can assume that
1454 This is much easier than the previous function as we can assume that
1456 the recipient has any changenode we aren't sending them."""
1455 the recipient has any changenode we aren't sending them."""
1457
1456
1458 self.hook('preoutgoing', throw=True, source=source)
1457 self.hook('preoutgoing', throw=True, source=source)
1459
1458
1460 cl = self.changelog
1459 cl = self.changelog
1461 nodes = cl.nodesbetween(basenodes, None)[0]
1460 nodes = cl.nodesbetween(basenodes, None)[0]
1462 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1461 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1463
1462
1464 def identity(x):
1463 def identity(x):
1465 return x
1464 return x
1466
1465
1467 def gennodelst(revlog):
1466 def gennodelst(revlog):
1468 for r in xrange(0, revlog.count()):
1467 for r in xrange(0, revlog.count()):
1469 n = revlog.node(r)
1468 n = revlog.node(r)
1470 if revlog.linkrev(n) in revset:
1469 if revlog.linkrev(n) in revset:
1471 yield n
1470 yield n
1472
1471
1473 def changed_file_collector(changedfileset):
1472 def changed_file_collector(changedfileset):
1474 def collect_changed_files(clnode):
1473 def collect_changed_files(clnode):
1475 c = cl.read(clnode)
1474 c = cl.read(clnode)
1476 for fname in c[3]:
1475 for fname in c[3]:
1477 changedfileset[fname] = 1
1476 changedfileset[fname] = 1
1478 return collect_changed_files
1477 return collect_changed_files
1479
1478
1480 def lookuprevlink_func(revlog):
1479 def lookuprevlink_func(revlog):
1481 def lookuprevlink(n):
1480 def lookuprevlink(n):
1482 return cl.node(revlog.linkrev(n))
1481 return cl.node(revlog.linkrev(n))
1483 return lookuprevlink
1482 return lookuprevlink
1484
1483
1485 def gengroup():
1484 def gengroup():
1486 # construct a list of all changed files
1485 # construct a list of all changed files
1487 changedfiles = {}
1486 changedfiles = {}
1488
1487
1489 for chnk in cl.group(nodes, identity,
1488 for chnk in cl.group(nodes, identity,
1490 changed_file_collector(changedfiles)):
1489 changed_file_collector(changedfiles)):
1491 yield chnk
1490 yield chnk
1492 changedfiles = changedfiles.keys()
1491 changedfiles = changedfiles.keys()
1493 changedfiles.sort()
1492 changedfiles.sort()
1494
1493
1495 mnfst = self.manifest
1494 mnfst = self.manifest
1496 nodeiter = gennodelst(mnfst)
1495 nodeiter = gennodelst(mnfst)
1497 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1496 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1498 yield chnk
1497 yield chnk
1499
1498
1500 for fname in changedfiles:
1499 for fname in changedfiles:
1501 filerevlog = self.file(fname)
1500 filerevlog = self.file(fname)
1502 nodeiter = gennodelst(filerevlog)
1501 nodeiter = gennodelst(filerevlog)
1503 nodeiter = list(nodeiter)
1502 nodeiter = list(nodeiter)
1504 if nodeiter:
1503 if nodeiter:
1505 yield changegroup.genchunk(fname)
1504 yield changegroup.genchunk(fname)
1506 lookup = lookuprevlink_func(filerevlog)
1505 lookup = lookuprevlink_func(filerevlog)
1507 for chnk in filerevlog.group(nodeiter, lookup):
1506 for chnk in filerevlog.group(nodeiter, lookup):
1508 yield chnk
1507 yield chnk
1509
1508
1510 yield changegroup.closechunk()
1509 yield changegroup.closechunk()
1511
1510
1512 if nodes:
1511 if nodes:
1513 self.hook('outgoing', node=hex(nodes[0]), source=source)
1512 self.hook('outgoing', node=hex(nodes[0]), source=source)
1514
1513
1515 return util.chunkbuffer(gengroup())
1514 return util.chunkbuffer(gengroup())
1516
1515
1517 def addchangegroup(self, source, srctype):
1516 def addchangegroup(self, source, srctype):
1518 """add changegroup to repo.
1517 """add changegroup to repo.
1519 returns number of heads modified or added + 1."""
1518 returns number of heads modified or added + 1."""
1520
1519
1521 def csmap(x):
1520 def csmap(x):
1522 self.ui.debug(_("add changeset %s\n") % short(x))
1521 self.ui.debug(_("add changeset %s\n") % short(x))
1523 return cl.count()
1522 return cl.count()
1524
1523
1525 def revmap(x):
1524 def revmap(x):
1526 return cl.rev(x)
1525 return cl.rev(x)
1527
1526
1528 if not source:
1527 if not source:
1529 return 0
1528 return 0
1530
1529
1531 self.hook('prechangegroup', throw=True, source=srctype)
1530 self.hook('prechangegroup', throw=True, source=srctype)
1532
1531
1533 changesets = files = revisions = 0
1532 changesets = files = revisions = 0
1534
1533
1535 tr = self.transaction()
1534 tr = self.transaction()
1536
1535
1537 # write changelog data to temp files so concurrent readers will not see
1536 # write changelog data to temp files so concurrent readers will not see
1538 # inconsistent view
1537 # inconsistent view
1539 cl = None
1538 cl = None
1540 try:
1539 try:
1541 cl = appendfile.appendchangelog(self.opener, self.changelog.version)
1540 cl = appendfile.appendchangelog(self.opener, self.changelog.version)
1542
1541
1543 oldheads = len(cl.heads())
1542 oldheads = len(cl.heads())
1544
1543
1545 # pull off the changeset group
1544 # pull off the changeset group
1546 self.ui.status(_("adding changesets\n"))
1545 self.ui.status(_("adding changesets\n"))
1547 cor = cl.count() - 1
1546 cor = cl.count() - 1
1548 chunkiter = changegroup.chunkiter(source)
1547 chunkiter = changegroup.chunkiter(source)
1549 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1548 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1550 raise util.Abort(_("received changelog group is empty"))
1549 raise util.Abort(_("received changelog group is empty"))
1551 cnr = cl.count() - 1
1550 cnr = cl.count() - 1
1552 changesets = cnr - cor
1551 changesets = cnr - cor
1553
1552
1554 # pull off the manifest group
1553 # pull off the manifest group
1555 self.ui.status(_("adding manifests\n"))
1554 self.ui.status(_("adding manifests\n"))
1556 chunkiter = changegroup.chunkiter(source)
1555 chunkiter = changegroup.chunkiter(source)
1557 # no need to check for empty manifest group here:
1556 # no need to check for empty manifest group here:
1558 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1557 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1559 # no new manifest will be created and the manifest group will
1558 # no new manifest will be created and the manifest group will
1560 # be empty during the pull
1559 # be empty during the pull
1561 self.manifest.addgroup(chunkiter, revmap, tr)
1560 self.manifest.addgroup(chunkiter, revmap, tr)
1562
1561
1563 # process the files
1562 # process the files
1564 self.ui.status(_("adding file changes\n"))
1563 self.ui.status(_("adding file changes\n"))
1565 while 1:
1564 while 1:
1566 f = changegroup.getchunk(source)
1565 f = changegroup.getchunk(source)
1567 if not f:
1566 if not f:
1568 break
1567 break
1569 self.ui.debug(_("adding %s revisions\n") % f)
1568 self.ui.debug(_("adding %s revisions\n") % f)
1570 fl = self.file(f)
1569 fl = self.file(f)
1571 o = fl.count()
1570 o = fl.count()
1572 chunkiter = changegroup.chunkiter(source)
1571 chunkiter = changegroup.chunkiter(source)
1573 if fl.addgroup(chunkiter, revmap, tr) is None:
1572 if fl.addgroup(chunkiter, revmap, tr) is None:
1574 raise util.Abort(_("received file revlog group is empty"))
1573 raise util.Abort(_("received file revlog group is empty"))
1575 revisions += fl.count() - o
1574 revisions += fl.count() - o
1576 files += 1
1575 files += 1
1577
1576
1578 cl.writedata()
1577 cl.writedata()
1579 finally:
1578 finally:
1580 if cl:
1579 if cl:
1581 cl.cleanup()
1580 cl.cleanup()
1582
1581
1583 # make changelog see real files again
1582 # make changelog see real files again
1584 self.changelog = changelog.changelog(self.opener, self.changelog.version)
1583 self.changelog = changelog.changelog(self.opener, self.changelog.version)
1585 self.changelog.checkinlinesize(tr)
1584 self.changelog.checkinlinesize(tr)
1586
1585
1587 newheads = len(self.changelog.heads())
1586 newheads = len(self.changelog.heads())
1588 heads = ""
1587 heads = ""
1589 if oldheads and newheads != oldheads:
1588 if oldheads and newheads != oldheads:
1590 heads = _(" (%+d heads)") % (newheads - oldheads)
1589 heads = _(" (%+d heads)") % (newheads - oldheads)
1591
1590
1592 self.ui.status(_("added %d changesets"
1591 self.ui.status(_("added %d changesets"
1593 " with %d changes to %d files%s\n")
1592 " with %d changes to %d files%s\n")
1594 % (changesets, revisions, files, heads))
1593 % (changesets, revisions, files, heads))
1595
1594
1596 if changesets > 0:
1595 if changesets > 0:
1597 self.hook('pretxnchangegroup', throw=True,
1596 self.hook('pretxnchangegroup', throw=True,
1598 node=hex(self.changelog.node(cor+1)), source=srctype)
1597 node=hex(self.changelog.node(cor+1)), source=srctype)
1599
1598
1600 tr.close()
1599 tr.close()
1601
1600
1602 if changesets > 0:
1601 if changesets > 0:
1603 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1602 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1604 source=srctype)
1603 source=srctype)
1605
1604
1606 for i in range(cor + 1, cnr + 1):
1605 for i in range(cor + 1, cnr + 1):
1607 self.hook("incoming", node=hex(self.changelog.node(i)),
1606 self.hook("incoming", node=hex(self.changelog.node(i)),
1608 source=srctype)
1607 source=srctype)
1609
1608
1610 return newheads - oldheads + 1
1609 return newheads - oldheads + 1
1611
1610
1612 def update(self, node, allow=False, force=False, choose=None,
1611 def update(self, node, allow=False, force=False, choose=None,
1613 moddirstate=True, forcemerge=False, wlock=None, show_stats=True):
1612 moddirstate=True, forcemerge=False, wlock=None, show_stats=True):
1614 pl = self.dirstate.parents()
1613 pl = self.dirstate.parents()
1615 if not force and pl[1] != nullid:
1614 if not force and pl[1] != nullid:
1616 raise util.Abort(_("outstanding uncommitted merges"))
1615 raise util.Abort(_("outstanding uncommitted merges"))
1617
1616
1618 err = False
1617 err = False
1619
1618
1620 p1, p2 = pl[0], node
1619 p1, p2 = pl[0], node
1621 pa = self.changelog.ancestor(p1, p2)
1620 pa = self.changelog.ancestor(p1, p2)
1622 m1n = self.changelog.read(p1)[0]
1621 m1n = self.changelog.read(p1)[0]
1623 m2n = self.changelog.read(p2)[0]
1622 m2n = self.changelog.read(p2)[0]
1624 man = self.manifest.ancestor(m1n, m2n)
1623 man = self.manifest.ancestor(m1n, m2n)
1625 m1 = self.manifest.read(m1n)
1624 m1 = self.manifest.read(m1n)
1626 mf1 = self.manifest.readflags(m1n)
1625 mf1 = self.manifest.readflags(m1n)
1627 m2 = self.manifest.read(m2n).copy()
1626 m2 = self.manifest.read(m2n).copy()
1628 mf2 = self.manifest.readflags(m2n)
1627 mf2 = self.manifest.readflags(m2n)
1629 ma = self.manifest.read(man)
1628 ma = self.manifest.read(man)
1630 mfa = self.manifest.readflags(man)
1629 mfa = self.manifest.readflags(man)
1631
1630
1632 modified, added, removed, deleted, unknown = self.changes()
1631 modified, added, removed, deleted, unknown = self.changes()
1633
1632
1634 # is this a jump, or a merge? i.e. is there a linear path
1633 # is this a jump, or a merge? i.e. is there a linear path
1635 # from p1 to p2?
1634 # from p1 to p2?
1636 linear_path = (pa == p1 or pa == p2)
1635 linear_path = (pa == p1 or pa == p2)
1637
1636
1638 if allow and linear_path:
1637 if allow and linear_path:
1639 raise util.Abort(_("there is nothing to merge, "
1638 raise util.Abort(_("there is nothing to merge, "
1640 "just use 'hg update'"))
1639 "just use 'hg update'"))
1641 if allow and not forcemerge:
1640 if allow and not forcemerge:
1642 if modified or added or removed:
1641 if modified or added or removed:
1643 raise util.Abort(_("outstanding uncommitted changes"))
1642 raise util.Abort(_("outstanding uncommitted changes"))
1644
1643
1645 if not forcemerge and not force:
1644 if not forcemerge and not force:
1646 for f in unknown:
1645 for f in unknown:
1647 if f in m2:
1646 if f in m2:
1648 t1 = self.wread(f)
1647 t1 = self.wread(f)
1649 t2 = self.file(f).read(m2[f])
1648 t2 = self.file(f).read(m2[f])
1650 if cmp(t1, t2) != 0:
1649 if cmp(t1, t2) != 0:
1651 raise util.Abort(_("'%s' already exists in the working"
1650 raise util.Abort(_("'%s' already exists in the working"
1652 " dir and differs from remote") % f)
1651 " dir and differs from remote") % f)
1653
1652
1654 # resolve the manifest to determine which files
1653 # resolve the manifest to determine which files
1655 # we care about merging
1654 # we care about merging
1656 self.ui.note(_("resolving manifests\n"))
1655 self.ui.note(_("resolving manifests\n"))
1657 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1656 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1658 (force, allow, moddirstate, linear_path))
1657 (force, allow, moddirstate, linear_path))
1659 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1658 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1660 (short(man), short(m1n), short(m2n)))
1659 (short(man), short(m1n), short(m2n)))
1661
1660
1662 merge = {}
1661 merge = {}
1663 get = {}
1662 get = {}
1664 remove = []
1663 remove = []
1665
1664
1666 # construct a working dir manifest
1665 # construct a working dir manifest
1667 mw = m1.copy()
1666 mw = m1.copy()
1668 mfw = mf1.copy()
1667 mfw = mf1.copy()
1669 umap = dict.fromkeys(unknown)
1668 umap = dict.fromkeys(unknown)
1670
1669
1671 for f in added + modified + unknown:
1670 for f in added + modified + unknown:
1672 mw[f] = ""
1671 mw[f] = ""
1673 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1672 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1674
1673
1675 if moddirstate and not wlock:
1674 if moddirstate and not wlock:
1676 wlock = self.wlock()
1675 wlock = self.wlock()
1677
1676
1678 for f in deleted + removed:
1677 for f in deleted + removed:
1679 if f in mw:
1678 if f in mw:
1680 del mw[f]
1679 del mw[f]
1681
1680
1682 # If we're jumping between revisions (as opposed to merging),
1681 # If we're jumping between revisions (as opposed to merging),
1683 # and if neither the working directory nor the target rev has
1682 # and if neither the working directory nor the target rev has
1684 # the file, then we need to remove it from the dirstate, to
1683 # the file, then we need to remove it from the dirstate, to
1685 # prevent the dirstate from listing the file when it is no
1684 # prevent the dirstate from listing the file when it is no
1686 # longer in the manifest.
1685 # longer in the manifest.
1687 if moddirstate and linear_path and f not in m2:
1686 if moddirstate and linear_path and f not in m2:
1688 self.dirstate.forget((f,))
1687 self.dirstate.forget((f,))
1689
1688
1690 # Compare manifests
1689 # Compare manifests
1691 for f, n in mw.iteritems():
1690 for f, n in mw.iteritems():
1692 if choose and not choose(f):
1691 if choose and not choose(f):
1693 continue
1692 continue
1694 if f in m2:
1693 if f in m2:
1695 s = 0
1694 s = 0
1696
1695
1697 # is the wfile new since m1, and match m2?
1696 # is the wfile new since m1, and match m2?
1698 if f not in m1:
1697 if f not in m1:
1699 t1 = self.wread(f)
1698 t1 = self.wread(f)
1700 t2 = self.file(f).read(m2[f])
1699 t2 = self.file(f).read(m2[f])
1701 if cmp(t1, t2) == 0:
1700 if cmp(t1, t2) == 0:
1702 n = m2[f]
1701 n = m2[f]
1703 del t1, t2
1702 del t1, t2
1704
1703
1705 # are files different?
1704 # are files different?
1706 if n != m2[f]:
1705 if n != m2[f]:
1707 a = ma.get(f, nullid)
1706 a = ma.get(f, nullid)
1708 # are both different from the ancestor?
1707 # are both different from the ancestor?
1709 if n != a and m2[f] != a:
1708 if n != a and m2[f] != a:
1710 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1709 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1711 # merge executable bits
1710 # merge executable bits
1712 # "if we changed or they changed, change in merge"
1711 # "if we changed or they changed, change in merge"
1713 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1712 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1714 mode = ((a^b) | (a^c)) ^ a
1713 mode = ((a^b) | (a^c)) ^ a
1715 merge[f] = (m1.get(f, nullid), m2[f], mode)
1714 merge[f] = (m1.get(f, nullid), m2[f], mode)
1716 s = 1
1715 s = 1
1717 # are we clobbering?
1716 # are we clobbering?
1718 # is remote's version newer?
1717 # is remote's version newer?
1719 # or are we going back in time?
1718 # or are we going back in time?
1720 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1719 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1721 self.ui.debug(_(" remote %s is newer, get\n") % f)
1720 self.ui.debug(_(" remote %s is newer, get\n") % f)
1722 get[f] = m2[f]
1721 get[f] = m2[f]
1723 s = 1
1722 s = 1
1724 elif f in umap or f in added:
1723 elif f in umap or f in added:
1725 # this unknown file is the same as the checkout
1724 # this unknown file is the same as the checkout
1726 # we need to reset the dirstate if the file was added
1725 # we need to reset the dirstate if the file was added
1727 get[f] = m2[f]
1726 get[f] = m2[f]
1728
1727
1729 if not s and mfw[f] != mf2[f]:
1728 if not s and mfw[f] != mf2[f]:
1730 if force:
1729 if force:
1731 self.ui.debug(_(" updating permissions for %s\n") % f)
1730 self.ui.debug(_(" updating permissions for %s\n") % f)
1732 util.set_exec(self.wjoin(f), mf2[f])
1731 util.set_exec(self.wjoin(f), mf2[f])
1733 else:
1732 else:
1734 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1733 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1735 mode = ((a^b) | (a^c)) ^ a
1734 mode = ((a^b) | (a^c)) ^ a
1736 if mode != b:
1735 if mode != b:
1737 self.ui.debug(_(" updating permissions for %s\n")
1736 self.ui.debug(_(" updating permissions for %s\n")
1738 % f)
1737 % f)
1739 util.set_exec(self.wjoin(f), mode)
1738 util.set_exec(self.wjoin(f), mode)
1740 del m2[f]
1739 del m2[f]
1741 elif f in ma:
1740 elif f in ma:
1742 if n != ma[f]:
1741 if n != ma[f]:
1743 r = _("d")
1742 r = _("d")
1744 if not force and (linear_path or allow):
1743 if not force and (linear_path or allow):
1745 r = self.ui.prompt(
1744 r = self.ui.prompt(
1746 (_(" local changed %s which remote deleted\n") % f) +
1745 (_(" local changed %s which remote deleted\n") % f) +
1747 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1746 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1748 if r == _("d"):
1747 if r == _("d"):
1749 remove.append(f)
1748 remove.append(f)
1750 else:
1749 else:
1751 self.ui.debug(_("other deleted %s\n") % f)
1750 self.ui.debug(_("other deleted %s\n") % f)
1752 remove.append(f) # other deleted it
1751 remove.append(f) # other deleted it
1753 else:
1752 else:
1754 # file is created on branch or in working directory
1753 # file is created on branch or in working directory
1755 if force and f not in umap:
1754 if force and f not in umap:
1756 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1755 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1757 remove.append(f)
1756 remove.append(f)
1758 elif n == m1.get(f, nullid): # same as parent
1757 elif n == m1.get(f, nullid): # same as parent
1759 if p2 == pa: # going backwards?
1758 if p2 == pa: # going backwards?
1760 self.ui.debug(_("remote deleted %s\n") % f)
1759 self.ui.debug(_("remote deleted %s\n") % f)
1761 remove.append(f)
1760 remove.append(f)
1762 else:
1761 else:
1763 self.ui.debug(_("local modified %s, keeping\n") % f)
1762 self.ui.debug(_("local modified %s, keeping\n") % f)
1764 else:
1763 else:
1765 self.ui.debug(_("working dir created %s, keeping\n") % f)
1764 self.ui.debug(_("working dir created %s, keeping\n") % f)
1766
1765
1767 for f, n in m2.iteritems():
1766 for f, n in m2.iteritems():
1768 if choose and not choose(f):
1767 if choose and not choose(f):
1769 continue
1768 continue
1770 if f[0] == "/":
1769 if f[0] == "/":
1771 continue
1770 continue
1772 if f in ma and n != ma[f]:
1771 if f in ma and n != ma[f]:
1773 r = _("k")
1772 r = _("k")
1774 if not force and (linear_path or allow):
1773 if not force and (linear_path or allow):
1775 r = self.ui.prompt(
1774 r = self.ui.prompt(
1776 (_("remote changed %s which local deleted\n") % f) +
1775 (_("remote changed %s which local deleted\n") % f) +
1777 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1776 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1778 if r == _("k"):
1777 if r == _("k"):
1779 get[f] = n
1778 get[f] = n
1780 elif f not in ma:
1779 elif f not in ma:
1781 self.ui.debug(_("remote created %s\n") % f)
1780 self.ui.debug(_("remote created %s\n") % f)
1782 get[f] = n
1781 get[f] = n
1783 else:
1782 else:
1784 if force or p2 == pa: # going backwards?
1783 if force or p2 == pa: # going backwards?
1785 self.ui.debug(_("local deleted %s, recreating\n") % f)
1784 self.ui.debug(_("local deleted %s, recreating\n") % f)
1786 get[f] = n
1785 get[f] = n
1787 else:
1786 else:
1788 self.ui.debug(_("local deleted %s\n") % f)
1787 self.ui.debug(_("local deleted %s\n") % f)
1789
1788
1790 del mw, m1, m2, ma
1789 del mw, m1, m2, ma
1791
1790
1792 if force:
1791 if force:
1793 for f in merge:
1792 for f in merge:
1794 get[f] = merge[f][1]
1793 get[f] = merge[f][1]
1795 merge = {}
1794 merge = {}
1796
1795
1797 if linear_path or force:
1796 if linear_path or force:
1798 # we don't need to do any magic, just jump to the new rev
1797 # we don't need to do any magic, just jump to the new rev
1799 branch_merge = False
1798 branch_merge = False
1800 p1, p2 = p2, nullid
1799 p1, p2 = p2, nullid
1801 else:
1800 else:
1802 if not allow:
1801 if not allow:
1803 self.ui.status(_("this update spans a branch"
1802 self.ui.status(_("this update spans a branch"
1804 " affecting the following files:\n"))
1803 " affecting the following files:\n"))
1805 fl = merge.keys() + get.keys()
1804 fl = merge.keys() + get.keys()
1806 fl.sort()
1805 fl.sort()
1807 for f in fl:
1806 for f in fl:
1808 cf = ""
1807 cf = ""
1809 if f in merge:
1808 if f in merge:
1810 cf = _(" (resolve)")
1809 cf = _(" (resolve)")
1811 self.ui.status(" %s%s\n" % (f, cf))
1810 self.ui.status(" %s%s\n" % (f, cf))
1812 self.ui.warn(_("aborting update spanning branches!\n"))
1811 self.ui.warn(_("aborting update spanning branches!\n"))
1813 self.ui.status(_("(use 'hg merge' to merge across branches"
1812 self.ui.status(_("(use 'hg merge' to merge across branches"
1814 " or 'hg update -C' to lose changes)\n"))
1813 " or 'hg update -C' to lose changes)\n"))
1815 return 1
1814 return 1
1816 branch_merge = True
1815 branch_merge = True
1817
1816
1818 xp1 = hex(p1)
1817 xp1 = hex(p1)
1819 xp2 = hex(p2)
1818 xp2 = hex(p2)
1820 if p2 == nullid: xxp2 = ''
1819 if p2 == nullid: xxp2 = ''
1821 else: xxp2 = xp2
1820 else: xxp2 = xp2
1822
1821
1823 self.hook('preupdate', throw=True, parent1=xp1, parent2=xxp2)
1822 self.hook('preupdate', throw=True, parent1=xp1, parent2=xxp2)
1824
1823
1825 # get the files we don't need to change
1824 # get the files we don't need to change
1826 files = get.keys()
1825 files = get.keys()
1827 files.sort()
1826 files.sort()
1828 for f in files:
1827 for f in files:
1829 if f[0] == "/":
1828 if f[0] == "/":
1830 continue
1829 continue
1831 self.ui.note(_("getting %s\n") % f)
1830 self.ui.note(_("getting %s\n") % f)
1832 t = self.file(f).read(get[f])
1831 t = self.file(f).read(get[f])
1833 self.wwrite(f, t)
1832 self.wwrite(f, t)
1834 util.set_exec(self.wjoin(f), mf2[f])
1833 util.set_exec(self.wjoin(f), mf2[f])
1835 if moddirstate:
1834 if moddirstate:
1836 if branch_merge:
1835 if branch_merge:
1837 self.dirstate.update([f], 'n', st_mtime=-1)
1836 self.dirstate.update([f], 'n', st_mtime=-1)
1838 else:
1837 else:
1839 self.dirstate.update([f], 'n')
1838 self.dirstate.update([f], 'n')
1840
1839
1841 # merge the tricky bits
1840 # merge the tricky bits
1842 failedmerge = []
1841 failedmerge = []
1843 files = merge.keys()
1842 files = merge.keys()
1844 files.sort()
1843 files.sort()
1845 for f in files:
1844 for f in files:
1846 self.ui.status(_("merging %s\n") % f)
1845 self.ui.status(_("merging %s\n") % f)
1847 my, other, flag = merge[f]
1846 my, other, flag = merge[f]
1848 ret = self.merge3(f, my, other, xp1, xp2)
1847 ret = self.merge3(f, my, other, xp1, xp2)
1849 if ret:
1848 if ret:
1850 err = True
1849 err = True
1851 failedmerge.append(f)
1850 failedmerge.append(f)
1852 util.set_exec(self.wjoin(f), flag)
1851 util.set_exec(self.wjoin(f), flag)
1853 if moddirstate:
1852 if moddirstate:
1854 if branch_merge:
1853 if branch_merge:
1855 # We've done a branch merge, mark this file as merged
1854 # We've done a branch merge, mark this file as merged
1856 # so that we properly record the merger later
1855 # so that we properly record the merger later
1857 self.dirstate.update([f], 'm')
1856 self.dirstate.update([f], 'm')
1858 else:
1857 else:
1859 # We've update-merged a locally modified file, so
1858 # We've update-merged a locally modified file, so
1860 # we set the dirstate to emulate a normal checkout
1859 # we set the dirstate to emulate a normal checkout
1861 # of that file some time in the past. Thus our
1860 # of that file some time in the past. Thus our
1862 # merge will appear as a normal local file
1861 # merge will appear as a normal local file
1863 # modification.
1862 # modification.
1864 f_len = len(self.file(f).read(other))
1863 f_len = len(self.file(f).read(other))
1865 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1864 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1866
1865
1867 remove.sort()
1866 remove.sort()
1868 for f in remove:
1867 for f in remove:
1869 self.ui.note(_("removing %s\n") % f)
1868 self.ui.note(_("removing %s\n") % f)
1870 util.audit_path(f)
1869 util.audit_path(f)
1871 try:
1870 try:
1872 util.unlink(self.wjoin(f))
1871 util.unlink(self.wjoin(f))
1873 except OSError, inst:
1872 except OSError, inst:
1874 if inst.errno != errno.ENOENT:
1873 if inst.errno != errno.ENOENT:
1875 self.ui.warn(_("update failed to remove %s: %s!\n") %
1874 self.ui.warn(_("update failed to remove %s: %s!\n") %
1876 (f, inst.strerror))
1875 (f, inst.strerror))
1877 if moddirstate:
1876 if moddirstate:
1878 if branch_merge:
1877 if branch_merge:
1879 self.dirstate.update(remove, 'r')
1878 self.dirstate.update(remove, 'r')
1880 else:
1879 else:
1881 self.dirstate.forget(remove)
1880 self.dirstate.forget(remove)
1882
1881
1883 if moddirstate:
1882 if moddirstate:
1884 self.dirstate.setparents(p1, p2)
1883 self.dirstate.setparents(p1, p2)
1885
1884
1886 if show_stats:
1885 if show_stats:
1887 stats = ((len(get), _("updated")),
1886 stats = ((len(get), _("updated")),
1888 (len(merge) - len(failedmerge), _("merged")),
1887 (len(merge) - len(failedmerge), _("merged")),
1889 (len(remove), _("removed")),
1888 (len(remove), _("removed")),
1890 (len(failedmerge), _("unresolved")))
1889 (len(failedmerge), _("unresolved")))
1891 note = ", ".join([_("%d files %s") % s for s in stats])
1890 note = ", ".join([_("%d files %s") % s for s in stats])
1892 self.ui.status("%s\n" % note)
1891 self.ui.status("%s\n" % note)
1893 if moddirstate:
1892 if moddirstate:
1894 if branch_merge:
1893 if branch_merge:
1895 if failedmerge:
1894 if failedmerge:
1896 self.ui.status(_("There are unresolved merges,"
1895 self.ui.status(_("There are unresolved merges,"
1897 " you can redo the full merge using:\n"
1896 " you can redo the full merge using:\n"
1898 " hg update -C %s\n"
1897 " hg update -C %s\n"
1899 " hg merge %s\n"
1898 " hg merge %s\n"
1900 % (self.changelog.rev(p1),
1899 % (self.changelog.rev(p1),
1901 self.changelog.rev(p2))))
1900 self.changelog.rev(p2))))
1902 else:
1901 else:
1903 self.ui.status(_("(branch merge, don't forget to commit)\n"))
1902 self.ui.status(_("(branch merge, don't forget to commit)\n"))
1904 elif failedmerge:
1903 elif failedmerge:
1905 self.ui.status(_("There are unresolved merges with"
1904 self.ui.status(_("There are unresolved merges with"
1906 " locally modified files.\n"))
1905 " locally modified files.\n"))
1907
1906
1908 self.hook('update', parent1=xp1, parent2=xxp2, error=int(err))
1907 self.hook('update', parent1=xp1, parent2=xxp2, error=int(err))
1909 return err
1908 return err
1910
1909
1911 def merge3(self, fn, my, other, p1, p2):
1910 def merge3(self, fn, my, other, p1, p2):
1912 """perform a 3-way merge in the working directory"""
1911 """perform a 3-way merge in the working directory"""
1913
1912
1914 def temp(prefix, node):
1913 def temp(prefix, node):
1915 pre = "%s~%s." % (os.path.basename(fn), prefix)
1914 pre = "%s~%s." % (os.path.basename(fn), prefix)
1916 (fd, name) = tempfile.mkstemp(prefix=pre)
1915 (fd, name) = tempfile.mkstemp(prefix=pre)
1917 f = os.fdopen(fd, "wb")
1916 f = os.fdopen(fd, "wb")
1918 self.wwrite(fn, fl.read(node), f)
1917 self.wwrite(fn, fl.read(node), f)
1919 f.close()
1918 f.close()
1920 return name
1919 return name
1921
1920
1922 fl = self.file(fn)
1921 fl = self.file(fn)
1923 base = fl.ancestor(my, other)
1922 base = fl.ancestor(my, other)
1924 a = self.wjoin(fn)
1923 a = self.wjoin(fn)
1925 b = temp("base", base)
1924 b = temp("base", base)
1926 c = temp("other", other)
1925 c = temp("other", other)
1927
1926
1928 self.ui.note(_("resolving %s\n") % fn)
1927 self.ui.note(_("resolving %s\n") % fn)
1929 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1928 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1930 (fn, short(my), short(other), short(base)))
1929 (fn, short(my), short(other), short(base)))
1931
1930
1932 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1931 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1933 or "hgmerge")
1932 or "hgmerge")
1934 r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=self.root,
1933 r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=self.root,
1935 environ={'HG_FILE': fn,
1934 environ={'HG_FILE': fn,
1936 'HG_MY_NODE': p1,
1935 'HG_MY_NODE': p1,
1937 'HG_OTHER_NODE': p2,
1936 'HG_OTHER_NODE': p2,
1938 'HG_FILE_MY_NODE': hex(my),
1937 'HG_FILE_MY_NODE': hex(my),
1939 'HG_FILE_OTHER_NODE': hex(other),
1938 'HG_FILE_OTHER_NODE': hex(other),
1940 'HG_FILE_BASE_NODE': hex(base)})
1939 'HG_FILE_BASE_NODE': hex(base)})
1941 if r:
1940 if r:
1942 self.ui.warn(_("merging %s failed!\n") % fn)
1941 self.ui.warn(_("merging %s failed!\n") % fn)
1943
1942
1944 os.unlink(b)
1943 os.unlink(b)
1945 os.unlink(c)
1944 os.unlink(c)
1946 return r
1945 return r
1947
1946
1948 def verify(self):
1947 def verify(self):
1949 filelinkrevs = {}
1948 filelinkrevs = {}
1950 filenodes = {}
1949 filenodes = {}
1951 changesets = revisions = files = 0
1950 changesets = revisions = files = 0
1952 errors = [0]
1951 errors = [0]
1953 warnings = [0]
1952 warnings = [0]
1954 neededmanifests = {}
1953 neededmanifests = {}
1955
1954
1956 def err(msg):
1955 def err(msg):
1957 self.ui.warn(msg + "\n")
1956 self.ui.warn(msg + "\n")
1958 errors[0] += 1
1957 errors[0] += 1
1959
1958
1960 def warn(msg):
1959 def warn(msg):
1961 self.ui.warn(msg + "\n")
1960 self.ui.warn(msg + "\n")
1962 warnings[0] += 1
1961 warnings[0] += 1
1963
1962
1964 def checksize(obj, name):
1963 def checksize(obj, name):
1965 d = obj.checksize()
1964 d = obj.checksize()
1966 if d[0]:
1965 if d[0]:
1967 err(_("%s data length off by %d bytes") % (name, d[0]))
1966 err(_("%s data length off by %d bytes") % (name, d[0]))
1968 if d[1]:
1967 if d[1]:
1969 err(_("%s index contains %d extra bytes") % (name, d[1]))
1968 err(_("%s index contains %d extra bytes") % (name, d[1]))
1970
1969
1971 def checkversion(obj, name):
1970 def checkversion(obj, name):
1972 if obj.version != revlog.REVLOGV0:
1971 if obj.version != revlog.REVLOGV0:
1973 if not revlogv1:
1972 if not revlogv1:
1974 warn(_("warning: `%s' uses revlog format 1") % name)
1973 warn(_("warning: `%s' uses revlog format 1") % name)
1975 elif revlogv1:
1974 elif revlogv1:
1976 warn(_("warning: `%s' uses revlog format 0") % name)
1975 warn(_("warning: `%s' uses revlog format 0") % name)
1977
1976
1978 revlogv1 = self.revlogversion != revlog.REVLOGV0
1977 revlogv1 = self.revlogversion != revlog.REVLOGV0
1979 if self.ui.verbose or revlogv1 != self.revlogv1:
1978 if self.ui.verbose or revlogv1 != self.revlogv1:
1980 self.ui.status(_("repository uses revlog format %d\n") %
1979 self.ui.status(_("repository uses revlog format %d\n") %
1981 (revlogv1 and 1 or 0))
1980 (revlogv1 and 1 or 0))
1982
1981
1983 seen = {}
1982 seen = {}
1984 self.ui.status(_("checking changesets\n"))
1983 self.ui.status(_("checking changesets\n"))
1985 checksize(self.changelog, "changelog")
1984 checksize(self.changelog, "changelog")
1986
1985
1987 for i in range(self.changelog.count()):
1986 for i in range(self.changelog.count()):
1988 changesets += 1
1987 changesets += 1
1989 n = self.changelog.node(i)
1988 n = self.changelog.node(i)
1990 l = self.changelog.linkrev(n)
1989 l = self.changelog.linkrev(n)
1991 if l != i:
1990 if l != i:
1992 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1991 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1993 if n in seen:
1992 if n in seen:
1994 err(_("duplicate changeset at revision %d") % i)
1993 err(_("duplicate changeset at revision %d") % i)
1995 seen[n] = 1
1994 seen[n] = 1
1996
1995
1997 for p in self.changelog.parents(n):
1996 for p in self.changelog.parents(n):
1998 if p not in self.changelog.nodemap:
1997 if p not in self.changelog.nodemap:
1999 err(_("changeset %s has unknown parent %s") %
1998 err(_("changeset %s has unknown parent %s") %
2000 (short(n), short(p)))
1999 (short(n), short(p)))
2001 try:
2000 try:
2002 changes = self.changelog.read(n)
2001 changes = self.changelog.read(n)
2003 except KeyboardInterrupt:
2002 except KeyboardInterrupt:
2004 self.ui.warn(_("interrupted"))
2003 self.ui.warn(_("interrupted"))
2005 raise
2004 raise
2006 except Exception, inst:
2005 except Exception, inst:
2007 err(_("unpacking changeset %s: %s") % (short(n), inst))
2006 err(_("unpacking changeset %s: %s") % (short(n), inst))
2008 continue
2007 continue
2009
2008
2010 neededmanifests[changes[0]] = n
2009 neededmanifests[changes[0]] = n
2011
2010
2012 for f in changes[3]:
2011 for f in changes[3]:
2013 filelinkrevs.setdefault(f, []).append(i)
2012 filelinkrevs.setdefault(f, []).append(i)
2014
2013
2015 seen = {}
2014 seen = {}
2016 self.ui.status(_("checking manifests\n"))
2015 self.ui.status(_("checking manifests\n"))
2017 checkversion(self.manifest, "manifest")
2016 checkversion(self.manifest, "manifest")
2018 checksize(self.manifest, "manifest")
2017 checksize(self.manifest, "manifest")
2019
2018
2020 for i in range(self.manifest.count()):
2019 for i in range(self.manifest.count()):
2021 n = self.manifest.node(i)
2020 n = self.manifest.node(i)
2022 l = self.manifest.linkrev(n)
2021 l = self.manifest.linkrev(n)
2023
2022
2024 if l < 0 or l >= self.changelog.count():
2023 if l < 0 or l >= self.changelog.count():
2025 err(_("bad manifest link (%d) at revision %d") % (l, i))
2024 err(_("bad manifest link (%d) at revision %d") % (l, i))
2026
2025
2027 if n in neededmanifests:
2026 if n in neededmanifests:
2028 del neededmanifests[n]
2027 del neededmanifests[n]
2029
2028
2030 if n in seen:
2029 if n in seen:
2031 err(_("duplicate manifest at revision %d") % i)
2030 err(_("duplicate manifest at revision %d") % i)
2032
2031
2033 seen[n] = 1
2032 seen[n] = 1
2034
2033
2035 for p in self.manifest.parents(n):
2034 for p in self.manifest.parents(n):
2036 if p not in self.manifest.nodemap:
2035 if p not in self.manifest.nodemap:
2037 err(_("manifest %s has unknown parent %s") %
2036 err(_("manifest %s has unknown parent %s") %
2038 (short(n), short(p)))
2037 (short(n), short(p)))
2039
2038
2040 try:
2039 try:
2041 delta = mdiff.patchtext(self.manifest.delta(n))
2040 delta = mdiff.patchtext(self.manifest.delta(n))
2042 except KeyboardInterrupt:
2041 except KeyboardInterrupt:
2043 self.ui.warn(_("interrupted"))
2042 self.ui.warn(_("interrupted"))
2044 raise
2043 raise
2045 except Exception, inst:
2044 except Exception, inst:
2046 err(_("unpacking manifest %s: %s") % (short(n), inst))
2045 err(_("unpacking manifest %s: %s") % (short(n), inst))
2047 continue
2046 continue
2048
2047
2049 try:
2048 try:
2050 ff = [ l.split('\0') for l in delta.splitlines() ]
2049 ff = [ l.split('\0') for l in delta.splitlines() ]
2051 for f, fn in ff:
2050 for f, fn in ff:
2052 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
2051 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
2053 except (ValueError, TypeError), inst:
2052 except (ValueError, TypeError), inst:
2054 err(_("broken delta in manifest %s: %s") % (short(n), inst))
2053 err(_("broken delta in manifest %s: %s") % (short(n), inst))
2055
2054
2056 self.ui.status(_("crosschecking files in changesets and manifests\n"))
2055 self.ui.status(_("crosschecking files in changesets and manifests\n"))
2057
2056
2058 for m, c in neededmanifests.items():
2057 for m, c in neededmanifests.items():
2059 err(_("Changeset %s refers to unknown manifest %s") %
2058 err(_("Changeset %s refers to unknown manifest %s") %
2060 (short(m), short(c)))
2059 (short(m), short(c)))
2061 del neededmanifests
2060 del neededmanifests
2062
2061
2063 for f in filenodes:
2062 for f in filenodes:
2064 if f not in filelinkrevs:
2063 if f not in filelinkrevs:
2065 err(_("file %s in manifest but not in changesets") % f)
2064 err(_("file %s in manifest but not in changesets") % f)
2066
2065
2067 for f in filelinkrevs:
2066 for f in filelinkrevs:
2068 if f not in filenodes:
2067 if f not in filenodes:
2069 err(_("file %s in changeset but not in manifest") % f)
2068 err(_("file %s in changeset but not in manifest") % f)
2070
2069
2071 self.ui.status(_("checking files\n"))
2070 self.ui.status(_("checking files\n"))
2072 ff = filenodes.keys()
2071 ff = filenodes.keys()
2073 ff.sort()
2072 ff.sort()
2074 for f in ff:
2073 for f in ff:
2075 if f == "/dev/null":
2074 if f == "/dev/null":
2076 continue
2075 continue
2077 files += 1
2076 files += 1
2078 if not f:
2077 if not f:
2079 err(_("file without name in manifest %s") % short(n))
2078 err(_("file without name in manifest %s") % short(n))
2080 continue
2079 continue
2081 fl = self.file(f)
2080 fl = self.file(f)
2082 checkversion(fl, f)
2081 checkversion(fl, f)
2083 checksize(fl, f)
2082 checksize(fl, f)
2084
2083
2085 nodes = {nullid: 1}
2084 nodes = {nullid: 1}
2086 seen = {}
2085 seen = {}
2087 for i in range(fl.count()):
2086 for i in range(fl.count()):
2088 revisions += 1
2087 revisions += 1
2089 n = fl.node(i)
2088 n = fl.node(i)
2090
2089
2091 if n in seen:
2090 if n in seen:
2092 err(_("%s: duplicate revision %d") % (f, i))
2091 err(_("%s: duplicate revision %d") % (f, i))
2093 if n not in filenodes[f]:
2092 if n not in filenodes[f]:
2094 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
2093 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
2095 else:
2094 else:
2096 del filenodes[f][n]
2095 del filenodes[f][n]
2097
2096
2098 flr = fl.linkrev(n)
2097 flr = fl.linkrev(n)
2099 if flr not in filelinkrevs.get(f, []):
2098 if flr not in filelinkrevs.get(f, []):
2100 err(_("%s:%s points to unexpected changeset %d")
2099 err(_("%s:%s points to unexpected changeset %d")
2101 % (f, short(n), flr))
2100 % (f, short(n), flr))
2102 else:
2101 else:
2103 filelinkrevs[f].remove(flr)
2102 filelinkrevs[f].remove(flr)
2104
2103
2105 # verify contents
2104 # verify contents
2106 try:
2105 try:
2107 t = fl.read(n)
2106 t = fl.read(n)
2108 except KeyboardInterrupt:
2107 except KeyboardInterrupt:
2109 self.ui.warn(_("interrupted"))
2108 self.ui.warn(_("interrupted"))
2110 raise
2109 raise
2111 except Exception, inst:
2110 except Exception, inst:
2112 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
2111 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
2113
2112
2114 # verify parents
2113 # verify parents
2115 (p1, p2) = fl.parents(n)
2114 (p1, p2) = fl.parents(n)
2116 if p1 not in nodes:
2115 if p1 not in nodes:
2117 err(_("file %s:%s unknown parent 1 %s") %
2116 err(_("file %s:%s unknown parent 1 %s") %
2118 (f, short(n), short(p1)))
2117 (f, short(n), short(p1)))
2119 if p2 not in nodes:
2118 if p2 not in nodes:
2120 err(_("file %s:%s unknown parent 2 %s") %
2119 err(_("file %s:%s unknown parent 2 %s") %
2121 (f, short(n), short(p1)))
2120 (f, short(n), short(p1)))
2122 nodes[n] = 1
2121 nodes[n] = 1
2123
2122
2124 # cross-check
2123 # cross-check
2125 for node in filenodes[f]:
2124 for node in filenodes[f]:
2126 err(_("node %s in manifests not in %s") % (hex(node), f))
2125 err(_("node %s in manifests not in %s") % (hex(node), f))
2127
2126
2128 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
2127 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
2129 (files, changesets, revisions))
2128 (files, changesets, revisions))
2130
2129
2131 if warnings[0]:
2130 if warnings[0]:
2132 self.ui.warn(_("%d warnings encountered!\n") % warnings[0])
2131 self.ui.warn(_("%d warnings encountered!\n") % warnings[0])
2133 if errors[0]:
2132 if errors[0]:
2134 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
2133 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
2135 return 1
2134 return 1
2136
2135
2137 # used to avoid circular references so destructors work
2136 # used to avoid circular references so destructors work
2138 def aftertrans(base):
2137 def aftertrans(base):
2139 p = base
2138 p = base
2140 def a():
2139 def a():
2141 util.rename(os.path.join(p, "journal"), os.path.join(p, "undo"))
2140 util.rename(os.path.join(p, "journal"), os.path.join(p, "undo"))
2142 util.rename(os.path.join(p, "journal.dirstate"),
2141 util.rename(os.path.join(p, "journal.dirstate"),
2143 os.path.join(p, "undo.dirstate"))
2142 os.path.join(p, "undo.dirstate"))
2144 return a
2143 return a
2145
2144
General Comments 0
You need to be logged in to leave comments. Login now