##// END OF EJS Templates
walk: introduce match objects
Matt Mackall -
r6576:69f3e9ac default
parent child Browse files
Show More
@@ -0,0 +1,37
1 import util
2
3 class match(object):
4 def __init__(self, root, cwd, patterns, include, exclude, default):
5 self._patterns = patterns
6 self._root = root
7 self._cwd = cwd
8 self._include = include
9 self._exclude = exclude
10 f, mf, ap = util.matcher(self._root, self._cwd, self._patterns,
11 self._include, self._exclude, self.src(),
12 default)
13 self._files = f
14 self._fmap = dict.fromkeys(f)
15 self._matchfn = mf
16 self._anypats = ap
17 def src(self):
18 return None
19 def __call__(self, fn):
20 return self._matchfn(fn)
21 def __iter__(self):
22 for f in self._files:
23 yield f
24 def bad(self, f, msg):
25 return True
26 def dir(self, f):
27 pass
28 def missing(self, f):
29 pass
30 def exact(self, f):
31 return f in self._fmap
32 def rel(self, f):
33 return util.pathto(self._root, self._cwd, f)
34 def files(self):
35 return self._files
36 def anypats(self):
37 return self._anypats
@@ -1,1182 +1,1179
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
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 from node import hex, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import os, sys, bisect, stat
10 import os, sys, bisect, stat
11 import mdiff, bdiff, util, templater, templatefilters, patch, errno
11 import mdiff, bdiff, util, templater, templatefilters, patch, errno, match
12
12
13 revrangesep = ':'
13 revrangesep = ':'
14
14
15 class UnknownCommand(Exception):
15 class UnknownCommand(Exception):
16 """Exception raised if command is not in the command table."""
16 """Exception raised if command is not in the command table."""
17 class AmbiguousCommand(Exception):
17 class AmbiguousCommand(Exception):
18 """Exception raised if command shortcut matches more than one command."""
18 """Exception raised if command shortcut matches more than one command."""
19
19
20 def findpossible(ui, cmd, table):
20 def findpossible(ui, cmd, table):
21 """
21 """
22 Return cmd -> (aliases, command table entry)
22 Return cmd -> (aliases, command table entry)
23 for each matching command.
23 for each matching command.
24 Return debug commands (or their aliases) only if no normal command matches.
24 Return debug commands (or their aliases) only if no normal command matches.
25 """
25 """
26 choice = {}
26 choice = {}
27 debugchoice = {}
27 debugchoice = {}
28 for e in table.keys():
28 for e in table.keys():
29 aliases = e.lstrip("^").split("|")
29 aliases = e.lstrip("^").split("|")
30 found = None
30 found = None
31 if cmd in aliases:
31 if cmd in aliases:
32 found = cmd
32 found = cmd
33 elif not ui.config("ui", "strict"):
33 elif not ui.config("ui", "strict"):
34 for a in aliases:
34 for a in aliases:
35 if a.startswith(cmd):
35 if a.startswith(cmd):
36 found = a
36 found = a
37 break
37 break
38 if found is not None:
38 if found is not None:
39 if aliases[0].startswith("debug") or found.startswith("debug"):
39 if aliases[0].startswith("debug") or found.startswith("debug"):
40 debugchoice[found] = (aliases, table[e])
40 debugchoice[found] = (aliases, table[e])
41 else:
41 else:
42 choice[found] = (aliases, table[e])
42 choice[found] = (aliases, table[e])
43
43
44 if not choice and debugchoice:
44 if not choice and debugchoice:
45 choice = debugchoice
45 choice = debugchoice
46
46
47 return choice
47 return choice
48
48
49 def findcmd(ui, cmd, table):
49 def findcmd(ui, cmd, table):
50 """Return (aliases, command table entry) for command string."""
50 """Return (aliases, command table entry) for command string."""
51 choice = findpossible(ui, cmd, table)
51 choice = findpossible(ui, cmd, table)
52
52
53 if cmd in choice:
53 if cmd in choice:
54 return choice[cmd]
54 return choice[cmd]
55
55
56 if len(choice) > 1:
56 if len(choice) > 1:
57 clist = choice.keys()
57 clist = choice.keys()
58 clist.sort()
58 clist.sort()
59 raise AmbiguousCommand(cmd, clist)
59 raise AmbiguousCommand(cmd, clist)
60
60
61 if choice:
61 if choice:
62 return choice.values()[0]
62 return choice.values()[0]
63
63
64 raise UnknownCommand(cmd)
64 raise UnknownCommand(cmd)
65
65
66 def bail_if_changed(repo):
66 def bail_if_changed(repo):
67 if repo.dirstate.parents()[1] != nullid:
67 if repo.dirstate.parents()[1] != nullid:
68 raise util.Abort(_('outstanding uncommitted merge'))
68 raise util.Abort(_('outstanding uncommitted merge'))
69 modified, added, removed, deleted = repo.status()[:4]
69 modified, added, removed, deleted = repo.status()[:4]
70 if modified or added or removed or deleted:
70 if modified or added or removed or deleted:
71 raise util.Abort(_("outstanding uncommitted changes"))
71 raise util.Abort(_("outstanding uncommitted changes"))
72
72
73 def logmessage(opts):
73 def logmessage(opts):
74 """ get the log message according to -m and -l option """
74 """ get the log message according to -m and -l option """
75 message = opts['message']
75 message = opts['message']
76 logfile = opts['logfile']
76 logfile = opts['logfile']
77
77
78 if message and logfile:
78 if message and logfile:
79 raise util.Abort(_('options --message and --logfile are mutually '
79 raise util.Abort(_('options --message and --logfile are mutually '
80 'exclusive'))
80 'exclusive'))
81 if not message and logfile:
81 if not message and logfile:
82 try:
82 try:
83 if logfile == '-':
83 if logfile == '-':
84 message = sys.stdin.read()
84 message = sys.stdin.read()
85 else:
85 else:
86 message = open(logfile).read()
86 message = open(logfile).read()
87 except IOError, inst:
87 except IOError, inst:
88 raise util.Abort(_("can't read commit message '%s': %s") %
88 raise util.Abort(_("can't read commit message '%s': %s") %
89 (logfile, inst.strerror))
89 (logfile, inst.strerror))
90 return message
90 return message
91
91
92 def loglimit(opts):
92 def loglimit(opts):
93 """get the log limit according to option -l/--limit"""
93 """get the log limit according to option -l/--limit"""
94 limit = opts.get('limit')
94 limit = opts.get('limit')
95 if limit:
95 if limit:
96 try:
96 try:
97 limit = int(limit)
97 limit = int(limit)
98 except ValueError:
98 except ValueError:
99 raise util.Abort(_('limit must be a positive integer'))
99 raise util.Abort(_('limit must be a positive integer'))
100 if limit <= 0: raise util.Abort(_('limit must be positive'))
100 if limit <= 0: raise util.Abort(_('limit must be positive'))
101 else:
101 else:
102 limit = sys.maxint
102 limit = sys.maxint
103 return limit
103 return limit
104
104
105 def setremoteconfig(ui, opts):
105 def setremoteconfig(ui, opts):
106 "copy remote options to ui tree"
106 "copy remote options to ui tree"
107 if opts.get('ssh'):
107 if opts.get('ssh'):
108 ui.setconfig("ui", "ssh", opts['ssh'])
108 ui.setconfig("ui", "ssh", opts['ssh'])
109 if opts.get('remotecmd'):
109 if opts.get('remotecmd'):
110 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
110 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
111
111
112 def revpair(repo, revs):
112 def revpair(repo, revs):
113 '''return pair of nodes, given list of revisions. second item can
113 '''return pair of nodes, given list of revisions. second item can
114 be None, meaning use working dir.'''
114 be None, meaning use working dir.'''
115
115
116 def revfix(repo, val, defval):
116 def revfix(repo, val, defval):
117 if not val and val != 0 and defval is not None:
117 if not val and val != 0 and defval is not None:
118 val = defval
118 val = defval
119 return repo.lookup(val)
119 return repo.lookup(val)
120
120
121 if not revs:
121 if not revs:
122 return repo.dirstate.parents()[0], None
122 return repo.dirstate.parents()[0], None
123 end = None
123 end = None
124 if len(revs) == 1:
124 if len(revs) == 1:
125 if revrangesep in revs[0]:
125 if revrangesep in revs[0]:
126 start, end = revs[0].split(revrangesep, 1)
126 start, end = revs[0].split(revrangesep, 1)
127 start = revfix(repo, start, 0)
127 start = revfix(repo, start, 0)
128 end = revfix(repo, end, repo.changelog.count() - 1)
128 end = revfix(repo, end, repo.changelog.count() - 1)
129 else:
129 else:
130 start = revfix(repo, revs[0], None)
130 start = revfix(repo, revs[0], None)
131 elif len(revs) == 2:
131 elif len(revs) == 2:
132 if revrangesep in revs[0] or revrangesep in revs[1]:
132 if revrangesep in revs[0] or revrangesep in revs[1]:
133 raise util.Abort(_('too many revisions specified'))
133 raise util.Abort(_('too many revisions specified'))
134 start = revfix(repo, revs[0], None)
134 start = revfix(repo, revs[0], None)
135 end = revfix(repo, revs[1], None)
135 end = revfix(repo, revs[1], None)
136 else:
136 else:
137 raise util.Abort(_('too many revisions specified'))
137 raise util.Abort(_('too many revisions specified'))
138 return start, end
138 return start, end
139
139
140 def revrange(repo, revs):
140 def revrange(repo, revs):
141 """Yield revision as strings from a list of revision specifications."""
141 """Yield revision as strings from a list of revision specifications."""
142
142
143 def revfix(repo, val, defval):
143 def revfix(repo, val, defval):
144 if not val and val != 0 and defval is not None:
144 if not val and val != 0 and defval is not None:
145 return defval
145 return defval
146 return repo.changelog.rev(repo.lookup(val))
146 return repo.changelog.rev(repo.lookup(val))
147
147
148 seen, l = {}, []
148 seen, l = {}, []
149 for spec in revs:
149 for spec in revs:
150 if revrangesep in spec:
150 if revrangesep in spec:
151 start, end = spec.split(revrangesep, 1)
151 start, end = spec.split(revrangesep, 1)
152 start = revfix(repo, start, 0)
152 start = revfix(repo, start, 0)
153 end = revfix(repo, end, repo.changelog.count() - 1)
153 end = revfix(repo, end, repo.changelog.count() - 1)
154 step = start > end and -1 or 1
154 step = start > end and -1 or 1
155 for rev in xrange(start, end+step, step):
155 for rev in xrange(start, end+step, step):
156 if rev in seen:
156 if rev in seen:
157 continue
157 continue
158 seen[rev] = 1
158 seen[rev] = 1
159 l.append(rev)
159 l.append(rev)
160 else:
160 else:
161 rev = revfix(repo, spec, None)
161 rev = revfix(repo, spec, None)
162 if rev in seen:
162 if rev in seen:
163 continue
163 continue
164 seen[rev] = 1
164 seen[rev] = 1
165 l.append(rev)
165 l.append(rev)
166
166
167 return l
167 return l
168
168
169 def make_filename(repo, pat, node,
169 def make_filename(repo, pat, node,
170 total=None, seqno=None, revwidth=None, pathname=None):
170 total=None, seqno=None, revwidth=None, pathname=None):
171 node_expander = {
171 node_expander = {
172 'H': lambda: hex(node),
172 'H': lambda: hex(node),
173 'R': lambda: str(repo.changelog.rev(node)),
173 'R': lambda: str(repo.changelog.rev(node)),
174 'h': lambda: short(node),
174 'h': lambda: short(node),
175 }
175 }
176 expander = {
176 expander = {
177 '%': lambda: '%',
177 '%': lambda: '%',
178 'b': lambda: os.path.basename(repo.root),
178 'b': lambda: os.path.basename(repo.root),
179 }
179 }
180
180
181 try:
181 try:
182 if node:
182 if node:
183 expander.update(node_expander)
183 expander.update(node_expander)
184 if node:
184 if node:
185 expander['r'] = (lambda:
185 expander['r'] = (lambda:
186 str(repo.changelog.rev(node)).zfill(revwidth or 0))
186 str(repo.changelog.rev(node)).zfill(revwidth or 0))
187 if total is not None:
187 if total is not None:
188 expander['N'] = lambda: str(total)
188 expander['N'] = lambda: str(total)
189 if seqno is not None:
189 if seqno is not None:
190 expander['n'] = lambda: str(seqno)
190 expander['n'] = lambda: str(seqno)
191 if total is not None and seqno is not None:
191 if total is not None and seqno is not None:
192 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
192 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
193 if pathname is not None:
193 if pathname is not None:
194 expander['s'] = lambda: os.path.basename(pathname)
194 expander['s'] = lambda: os.path.basename(pathname)
195 expander['d'] = lambda: os.path.dirname(pathname) or '.'
195 expander['d'] = lambda: os.path.dirname(pathname) or '.'
196 expander['p'] = lambda: pathname
196 expander['p'] = lambda: pathname
197
197
198 newname = []
198 newname = []
199 patlen = len(pat)
199 patlen = len(pat)
200 i = 0
200 i = 0
201 while i < patlen:
201 while i < patlen:
202 c = pat[i]
202 c = pat[i]
203 if c == '%':
203 if c == '%':
204 i += 1
204 i += 1
205 c = pat[i]
205 c = pat[i]
206 c = expander[c]()
206 c = expander[c]()
207 newname.append(c)
207 newname.append(c)
208 i += 1
208 i += 1
209 return ''.join(newname)
209 return ''.join(newname)
210 except KeyError, inst:
210 except KeyError, inst:
211 raise util.Abort(_("invalid format spec '%%%s' in output file name") %
211 raise util.Abort(_("invalid format spec '%%%s' in output file name") %
212 inst.args[0])
212 inst.args[0])
213
213
214 def make_file(repo, pat, node=None,
214 def make_file(repo, pat, node=None,
215 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
215 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
216 if not pat or pat == '-':
216 if not pat or pat == '-':
217 return 'w' in mode and sys.stdout or sys.stdin
217 return 'w' in mode and sys.stdout or sys.stdin
218 if hasattr(pat, 'write') and 'w' in mode:
218 if hasattr(pat, 'write') and 'w' in mode:
219 return pat
219 return pat
220 if hasattr(pat, 'read') and 'r' in mode:
220 if hasattr(pat, 'read') and 'r' in mode:
221 return pat
221 return pat
222 return open(make_filename(repo, pat, node, total, seqno, revwidth,
222 return open(make_filename(repo, pat, node, total, seqno, revwidth,
223 pathname),
223 pathname),
224 mode)
224 mode)
225
225
226 def matchpats(repo, pats=[], opts={}, globbed=False, default='relpath'):
226 def matchpats(repo, pats=[], opts={}, globbed=False, default='relpath'):
227 pats = pats or []
228 if not globbed and default == 'relpath':
227 if not globbed and default == 'relpath':
229 pats = util.expand_glob(pats or [])
228 pats = util.expand_glob(pats or [])
230 return util.matcher(repo.root, repo.getcwd(), pats, opts.get('include'),
229 m = match.match(repo.root, repo.getcwd(), pats, opts.get('include'),
231 opts.get('exclude'), None, default)
230 opts.get('exclude'), default)
231 return m.files(), m, m.anypats()
232
232
233 def walk(repo, pats=[], opts={}, node=None, badmatch=None, globbed=False,
233 def walk(repo, pats=[], opts={}, node=None, badmatch=None, globbed=False,
234 default='relpath'):
234 default='relpath'):
235 files, matchfn, anypats = matchpats(repo, pats, opts, globbed=globbed,
235 dummy, m, dummy = matchpats(repo, pats, opts, globbed, default)
236 default=default)
236 for src, fn in repo.walk(node=node, files=m.files(), match=m,
237 exact = dict.fromkeys(files)
238 cwd = repo.getcwd()
239 for src, fn in repo.walk(node=node, files=files, match=matchfn,
240 badmatch=badmatch):
237 badmatch=badmatch):
241 yield src, fn, repo.pathto(fn, cwd), fn in exact
238 yield src, fn, m.rel(fn), m.exact(fn)
242
239
243 def findrenames(repo, added=None, removed=None, threshold=0.5):
240 def findrenames(repo, added=None, removed=None, threshold=0.5):
244 '''find renamed files -- yields (before, after, score) tuples'''
241 '''find renamed files -- yields (before, after, score) tuples'''
245 if added is None or removed is None:
242 if added is None or removed is None:
246 added, removed = repo.status()[1:3]
243 added, removed = repo.status()[1:3]
247 ctx = repo.changectx()
244 ctx = repo.changectx()
248 for a in added:
245 for a in added:
249 aa = repo.wread(a)
246 aa = repo.wread(a)
250 bestname, bestscore = None, threshold
247 bestname, bestscore = None, threshold
251 for r in removed:
248 for r in removed:
252 rr = ctx.filectx(r).data()
249 rr = ctx.filectx(r).data()
253
250
254 # bdiff.blocks() returns blocks of matching lines
251 # bdiff.blocks() returns blocks of matching lines
255 # count the number of bytes in each
252 # count the number of bytes in each
256 equal = 0
253 equal = 0
257 alines = mdiff.splitnewlines(aa)
254 alines = mdiff.splitnewlines(aa)
258 matches = bdiff.blocks(aa, rr)
255 matches = bdiff.blocks(aa, rr)
259 for x1,x2,y1,y2 in matches:
256 for x1,x2,y1,y2 in matches:
260 for line in alines[x1:x2]:
257 for line in alines[x1:x2]:
261 equal += len(line)
258 equal += len(line)
262
259
263 lengths = len(aa) + len(rr)
260 lengths = len(aa) + len(rr)
264 if lengths:
261 if lengths:
265 myscore = equal*2.0 / lengths
262 myscore = equal*2.0 / lengths
266 if myscore >= bestscore:
263 if myscore >= bestscore:
267 bestname, bestscore = r, myscore
264 bestname, bestscore = r, myscore
268 if bestname:
265 if bestname:
269 yield bestname, a, bestscore
266 yield bestname, a, bestscore
270
267
271 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
268 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
272 if dry_run is None:
269 if dry_run is None:
273 dry_run = opts.get('dry_run')
270 dry_run = opts.get('dry_run')
274 if similarity is None:
271 if similarity is None:
275 similarity = float(opts.get('similarity') or 0)
272 similarity = float(opts.get('similarity') or 0)
276 add, remove = [], []
273 add, remove = [], []
277 mapping = {}
274 mapping = {}
278 for src, abs, rel, exact in walk(repo, pats, opts):
275 for src, abs, rel, exact in walk(repo, pats, opts):
279 target = repo.wjoin(abs)
276 target = repo.wjoin(abs)
280 if src == 'f' and abs not in repo.dirstate:
277 if src == 'f' and abs not in repo.dirstate:
281 add.append(abs)
278 add.append(abs)
282 mapping[abs] = rel, exact
279 mapping[abs] = rel, exact
283 if repo.ui.verbose or not exact:
280 if repo.ui.verbose or not exact:
284 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
281 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
285 if repo.dirstate[abs] != 'r' and (not util.lexists(target)
282 if repo.dirstate[abs] != 'r' and (not util.lexists(target)
286 or (os.path.isdir(target) and not os.path.islink(target))):
283 or (os.path.isdir(target) and not os.path.islink(target))):
287 remove.append(abs)
284 remove.append(abs)
288 mapping[abs] = rel, exact
285 mapping[abs] = rel, exact
289 if repo.ui.verbose or not exact:
286 if repo.ui.verbose or not exact:
290 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
287 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
291 if not dry_run:
288 if not dry_run:
292 repo.remove(remove)
289 repo.remove(remove)
293 repo.add(add)
290 repo.add(add)
294 if similarity > 0:
291 if similarity > 0:
295 for old, new, score in findrenames(repo, add, remove, similarity):
292 for old, new, score in findrenames(repo, add, remove, similarity):
296 oldrel, oldexact = mapping[old]
293 oldrel, oldexact = mapping[old]
297 newrel, newexact = mapping[new]
294 newrel, newexact = mapping[new]
298 if repo.ui.verbose or not oldexact or not newexact:
295 if repo.ui.verbose or not oldexact or not newexact:
299 repo.ui.status(_('recording removal of %s as rename to %s '
296 repo.ui.status(_('recording removal of %s as rename to %s '
300 '(%d%% similar)\n') %
297 '(%d%% similar)\n') %
301 (oldrel, newrel, score * 100))
298 (oldrel, newrel, score * 100))
302 if not dry_run:
299 if not dry_run:
303 repo.copy(old, new)
300 repo.copy(old, new)
304
301
305 def copy(ui, repo, pats, opts, rename=False):
302 def copy(ui, repo, pats, opts, rename=False):
306 # called with the repo lock held
303 # called with the repo lock held
307 #
304 #
308 # hgsep => pathname that uses "/" to separate directories
305 # hgsep => pathname that uses "/" to separate directories
309 # ossep => pathname that uses os.sep to separate directories
306 # ossep => pathname that uses os.sep to separate directories
310 cwd = repo.getcwd()
307 cwd = repo.getcwd()
311 targets = {}
308 targets = {}
312 after = opts.get("after")
309 after = opts.get("after")
313 dryrun = opts.get("dry_run")
310 dryrun = opts.get("dry_run")
314
311
315 def walkpat(pat):
312 def walkpat(pat):
316 srcs = []
313 srcs = []
317 for tag, abs, rel, exact in walk(repo, [pat], opts, globbed=True):
314 for tag, abs, rel, exact in walk(repo, [pat], opts, globbed=True):
318 state = repo.dirstate[abs]
315 state = repo.dirstate[abs]
319 if state in '?r':
316 if state in '?r':
320 if exact and state == '?':
317 if exact and state == '?':
321 ui.warn(_('%s: not copying - file is not managed\n') % rel)
318 ui.warn(_('%s: not copying - file is not managed\n') % rel)
322 if exact and state == 'r':
319 if exact and state == 'r':
323 ui.warn(_('%s: not copying - file has been marked for'
320 ui.warn(_('%s: not copying - file has been marked for'
324 ' remove\n') % rel)
321 ' remove\n') % rel)
325 continue
322 continue
326 # abs: hgsep
323 # abs: hgsep
327 # rel: ossep
324 # rel: ossep
328 srcs.append((abs, rel, exact))
325 srcs.append((abs, rel, exact))
329 return srcs
326 return srcs
330
327
331 # abssrc: hgsep
328 # abssrc: hgsep
332 # relsrc: ossep
329 # relsrc: ossep
333 # otarget: ossep
330 # otarget: ossep
334 def copyfile(abssrc, relsrc, otarget, exact):
331 def copyfile(abssrc, relsrc, otarget, exact):
335 abstarget = util.canonpath(repo.root, cwd, otarget)
332 abstarget = util.canonpath(repo.root, cwd, otarget)
336 reltarget = repo.pathto(abstarget, cwd)
333 reltarget = repo.pathto(abstarget, cwd)
337 target = repo.wjoin(abstarget)
334 target = repo.wjoin(abstarget)
338 src = repo.wjoin(abssrc)
335 src = repo.wjoin(abssrc)
339 state = repo.dirstate[abstarget]
336 state = repo.dirstate[abstarget]
340
337
341 # check for collisions
338 # check for collisions
342 prevsrc = targets.get(abstarget)
339 prevsrc = targets.get(abstarget)
343 if prevsrc is not None:
340 if prevsrc is not None:
344 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
341 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
345 (reltarget, repo.pathto(abssrc, cwd),
342 (reltarget, repo.pathto(abssrc, cwd),
346 repo.pathto(prevsrc, cwd)))
343 repo.pathto(prevsrc, cwd)))
347 return
344 return
348
345
349 # check for overwrites
346 # check for overwrites
350 exists = os.path.exists(target)
347 exists = os.path.exists(target)
351 if (not after and exists or after and state in 'mn'):
348 if (not after and exists or after and state in 'mn'):
352 if not opts['force']:
349 if not opts['force']:
353 ui.warn(_('%s: not overwriting - file exists\n') %
350 ui.warn(_('%s: not overwriting - file exists\n') %
354 reltarget)
351 reltarget)
355 return
352 return
356
353
357 if after:
354 if after:
358 if not exists:
355 if not exists:
359 return
356 return
360 elif not dryrun:
357 elif not dryrun:
361 try:
358 try:
362 if exists:
359 if exists:
363 os.unlink(target)
360 os.unlink(target)
364 targetdir = os.path.dirname(target) or '.'
361 targetdir = os.path.dirname(target) or '.'
365 if not os.path.isdir(targetdir):
362 if not os.path.isdir(targetdir):
366 os.makedirs(targetdir)
363 os.makedirs(targetdir)
367 util.copyfile(src, target)
364 util.copyfile(src, target)
368 except IOError, inst:
365 except IOError, inst:
369 if inst.errno == errno.ENOENT:
366 if inst.errno == errno.ENOENT:
370 ui.warn(_('%s: deleted in working copy\n') % relsrc)
367 ui.warn(_('%s: deleted in working copy\n') % relsrc)
371 else:
368 else:
372 ui.warn(_('%s: cannot copy - %s\n') %
369 ui.warn(_('%s: cannot copy - %s\n') %
373 (relsrc, inst.strerror))
370 (relsrc, inst.strerror))
374 return True # report a failure
371 return True # report a failure
375
372
376 if ui.verbose or not exact:
373 if ui.verbose or not exact:
377 action = rename and "moving" or "copying"
374 action = rename and "moving" or "copying"
378 ui.status(_('%s %s to %s\n') % (action, relsrc, reltarget))
375 ui.status(_('%s %s to %s\n') % (action, relsrc, reltarget))
379
376
380 targets[abstarget] = abssrc
377 targets[abstarget] = abssrc
381
378
382 # fix up dirstate
379 # fix up dirstate
383 origsrc = repo.dirstate.copied(abssrc) or abssrc
380 origsrc = repo.dirstate.copied(abssrc) or abssrc
384 if abstarget == origsrc: # copying back a copy?
381 if abstarget == origsrc: # copying back a copy?
385 if state not in 'mn' and not dryrun:
382 if state not in 'mn' and not dryrun:
386 repo.dirstate.normallookup(abstarget)
383 repo.dirstate.normallookup(abstarget)
387 else:
384 else:
388 if repo.dirstate[origsrc] == 'a':
385 if repo.dirstate[origsrc] == 'a':
389 if not ui.quiet:
386 if not ui.quiet:
390 ui.warn(_("%s has not been committed yet, so no copy "
387 ui.warn(_("%s has not been committed yet, so no copy "
391 "data will be stored for %s.\n")
388 "data will be stored for %s.\n")
392 % (repo.pathto(origsrc, cwd), reltarget))
389 % (repo.pathto(origsrc, cwd), reltarget))
393 if abstarget not in repo.dirstate and not dryrun:
390 if abstarget not in repo.dirstate and not dryrun:
394 repo.add([abstarget])
391 repo.add([abstarget])
395 elif not dryrun:
392 elif not dryrun:
396 repo.copy(origsrc, abstarget)
393 repo.copy(origsrc, abstarget)
397
394
398 if rename and not dryrun:
395 if rename and not dryrun:
399 repo.remove([abssrc], not after)
396 repo.remove([abssrc], not after)
400
397
401 # pat: ossep
398 # pat: ossep
402 # dest ossep
399 # dest ossep
403 # srcs: list of (hgsep, hgsep, ossep, bool)
400 # srcs: list of (hgsep, hgsep, ossep, bool)
404 # return: function that takes hgsep and returns ossep
401 # return: function that takes hgsep and returns ossep
405 def targetpathfn(pat, dest, srcs):
402 def targetpathfn(pat, dest, srcs):
406 if os.path.isdir(pat):
403 if os.path.isdir(pat):
407 abspfx = util.canonpath(repo.root, cwd, pat)
404 abspfx = util.canonpath(repo.root, cwd, pat)
408 abspfx = util.localpath(abspfx)
405 abspfx = util.localpath(abspfx)
409 if destdirexists:
406 if destdirexists:
410 striplen = len(os.path.split(abspfx)[0])
407 striplen = len(os.path.split(abspfx)[0])
411 else:
408 else:
412 striplen = len(abspfx)
409 striplen = len(abspfx)
413 if striplen:
410 if striplen:
414 striplen += len(os.sep)
411 striplen += len(os.sep)
415 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
412 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
416 elif destdirexists:
413 elif destdirexists:
417 res = lambda p: os.path.join(dest,
414 res = lambda p: os.path.join(dest,
418 os.path.basename(util.localpath(p)))
415 os.path.basename(util.localpath(p)))
419 else:
416 else:
420 res = lambda p: dest
417 res = lambda p: dest
421 return res
418 return res
422
419
423 # pat: ossep
420 # pat: ossep
424 # dest ossep
421 # dest ossep
425 # srcs: list of (hgsep, hgsep, ossep, bool)
422 # srcs: list of (hgsep, hgsep, ossep, bool)
426 # return: function that takes hgsep and returns ossep
423 # return: function that takes hgsep and returns ossep
427 def targetpathafterfn(pat, dest, srcs):
424 def targetpathafterfn(pat, dest, srcs):
428 if util.patkind(pat, None)[0]:
425 if util.patkind(pat, None)[0]:
429 # a mercurial pattern
426 # a mercurial pattern
430 res = lambda p: os.path.join(dest,
427 res = lambda p: os.path.join(dest,
431 os.path.basename(util.localpath(p)))
428 os.path.basename(util.localpath(p)))
432 else:
429 else:
433 abspfx = util.canonpath(repo.root, cwd, pat)
430 abspfx = util.canonpath(repo.root, cwd, pat)
434 if len(abspfx) < len(srcs[0][0]):
431 if len(abspfx) < len(srcs[0][0]):
435 # A directory. Either the target path contains the last
432 # A directory. Either the target path contains the last
436 # component of the source path or it does not.
433 # component of the source path or it does not.
437 def evalpath(striplen):
434 def evalpath(striplen):
438 score = 0
435 score = 0
439 for s in srcs:
436 for s in srcs:
440 t = os.path.join(dest, util.localpath(s[0])[striplen:])
437 t = os.path.join(dest, util.localpath(s[0])[striplen:])
441 if os.path.exists(t):
438 if os.path.exists(t):
442 score += 1
439 score += 1
443 return score
440 return score
444
441
445 abspfx = util.localpath(abspfx)
442 abspfx = util.localpath(abspfx)
446 striplen = len(abspfx)
443 striplen = len(abspfx)
447 if striplen:
444 if striplen:
448 striplen += len(os.sep)
445 striplen += len(os.sep)
449 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
446 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
450 score = evalpath(striplen)
447 score = evalpath(striplen)
451 striplen1 = len(os.path.split(abspfx)[0])
448 striplen1 = len(os.path.split(abspfx)[0])
452 if striplen1:
449 if striplen1:
453 striplen1 += len(os.sep)
450 striplen1 += len(os.sep)
454 if evalpath(striplen1) > score:
451 if evalpath(striplen1) > score:
455 striplen = striplen1
452 striplen = striplen1
456 res = lambda p: os.path.join(dest,
453 res = lambda p: os.path.join(dest,
457 util.localpath(p)[striplen:])
454 util.localpath(p)[striplen:])
458 else:
455 else:
459 # a file
456 # a file
460 if destdirexists:
457 if destdirexists:
461 res = lambda p: os.path.join(dest,
458 res = lambda p: os.path.join(dest,
462 os.path.basename(util.localpath(p)))
459 os.path.basename(util.localpath(p)))
463 else:
460 else:
464 res = lambda p: dest
461 res = lambda p: dest
465 return res
462 return res
466
463
467
464
468 pats = util.expand_glob(pats)
465 pats = util.expand_glob(pats)
469 if not pats:
466 if not pats:
470 raise util.Abort(_('no source or destination specified'))
467 raise util.Abort(_('no source or destination specified'))
471 if len(pats) == 1:
468 if len(pats) == 1:
472 raise util.Abort(_('no destination specified'))
469 raise util.Abort(_('no destination specified'))
473 dest = pats.pop()
470 dest = pats.pop()
474 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
471 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
475 if not destdirexists:
472 if not destdirexists:
476 if len(pats) > 1 or util.patkind(pats[0], None)[0]:
473 if len(pats) > 1 or util.patkind(pats[0], None)[0]:
477 raise util.Abort(_('with multiple sources, destination must be an '
474 raise util.Abort(_('with multiple sources, destination must be an '
478 'existing directory'))
475 'existing directory'))
479 if util.endswithsep(dest):
476 if util.endswithsep(dest):
480 raise util.Abort(_('destination %s is not a directory') % dest)
477 raise util.Abort(_('destination %s is not a directory') % dest)
481
478
482 tfn = targetpathfn
479 tfn = targetpathfn
483 if after:
480 if after:
484 tfn = targetpathafterfn
481 tfn = targetpathafterfn
485 copylist = []
482 copylist = []
486 for pat in pats:
483 for pat in pats:
487 srcs = walkpat(pat)
484 srcs = walkpat(pat)
488 if not srcs:
485 if not srcs:
489 continue
486 continue
490 copylist.append((tfn(pat, dest, srcs), srcs))
487 copylist.append((tfn(pat, dest, srcs), srcs))
491 if not copylist:
488 if not copylist:
492 raise util.Abort(_('no files to copy'))
489 raise util.Abort(_('no files to copy'))
493
490
494 errors = 0
491 errors = 0
495 for targetpath, srcs in copylist:
492 for targetpath, srcs in copylist:
496 for abssrc, relsrc, exact in srcs:
493 for abssrc, relsrc, exact in srcs:
497 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
494 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
498 errors += 1
495 errors += 1
499
496
500 if errors:
497 if errors:
501 ui.warn(_('(consider using --after)\n'))
498 ui.warn(_('(consider using --after)\n'))
502
499
503 return errors
500 return errors
504
501
505 def service(opts, parentfn=None, initfn=None, runfn=None):
502 def service(opts, parentfn=None, initfn=None, runfn=None):
506 '''Run a command as a service.'''
503 '''Run a command as a service.'''
507
504
508 if opts['daemon'] and not opts['daemon_pipefds']:
505 if opts['daemon'] and not opts['daemon_pipefds']:
509 rfd, wfd = os.pipe()
506 rfd, wfd = os.pipe()
510 args = sys.argv[:]
507 args = sys.argv[:]
511 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
508 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
512 # Don't pass --cwd to the child process, because we've already
509 # Don't pass --cwd to the child process, because we've already
513 # changed directory.
510 # changed directory.
514 for i in xrange(1,len(args)):
511 for i in xrange(1,len(args)):
515 if args[i].startswith('--cwd='):
512 if args[i].startswith('--cwd='):
516 del args[i]
513 del args[i]
517 break
514 break
518 elif args[i].startswith('--cwd'):
515 elif args[i].startswith('--cwd'):
519 del args[i:i+2]
516 del args[i:i+2]
520 break
517 break
521 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
518 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
522 args[0], args)
519 args[0], args)
523 os.close(wfd)
520 os.close(wfd)
524 os.read(rfd, 1)
521 os.read(rfd, 1)
525 if parentfn:
522 if parentfn:
526 return parentfn(pid)
523 return parentfn(pid)
527 else:
524 else:
528 os._exit(0)
525 os._exit(0)
529
526
530 if initfn:
527 if initfn:
531 initfn()
528 initfn()
532
529
533 if opts['pid_file']:
530 if opts['pid_file']:
534 fp = open(opts['pid_file'], 'w')
531 fp = open(opts['pid_file'], 'w')
535 fp.write(str(os.getpid()) + '\n')
532 fp.write(str(os.getpid()) + '\n')
536 fp.close()
533 fp.close()
537
534
538 if opts['daemon_pipefds']:
535 if opts['daemon_pipefds']:
539 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
536 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
540 os.close(rfd)
537 os.close(rfd)
541 try:
538 try:
542 os.setsid()
539 os.setsid()
543 except AttributeError:
540 except AttributeError:
544 pass
541 pass
545 os.write(wfd, 'y')
542 os.write(wfd, 'y')
546 os.close(wfd)
543 os.close(wfd)
547 sys.stdout.flush()
544 sys.stdout.flush()
548 sys.stderr.flush()
545 sys.stderr.flush()
549 fd = os.open(util.nulldev, os.O_RDWR)
546 fd = os.open(util.nulldev, os.O_RDWR)
550 if fd != 0: os.dup2(fd, 0)
547 if fd != 0: os.dup2(fd, 0)
551 if fd != 1: os.dup2(fd, 1)
548 if fd != 1: os.dup2(fd, 1)
552 if fd != 2: os.dup2(fd, 2)
549 if fd != 2: os.dup2(fd, 2)
553 if fd not in (0, 1, 2): os.close(fd)
550 if fd not in (0, 1, 2): os.close(fd)
554
551
555 if runfn:
552 if runfn:
556 return runfn()
553 return runfn()
557
554
558 class changeset_printer(object):
555 class changeset_printer(object):
559 '''show changeset information when templating not requested.'''
556 '''show changeset information when templating not requested.'''
560
557
561 def __init__(self, ui, repo, patch, buffered):
558 def __init__(self, ui, repo, patch, buffered):
562 self.ui = ui
559 self.ui = ui
563 self.repo = repo
560 self.repo = repo
564 self.buffered = buffered
561 self.buffered = buffered
565 self.patch = patch
562 self.patch = patch
566 self.header = {}
563 self.header = {}
567 self.hunk = {}
564 self.hunk = {}
568 self.lastheader = None
565 self.lastheader = None
569
566
570 def flush(self, rev):
567 def flush(self, rev):
571 if rev in self.header:
568 if rev in self.header:
572 h = self.header[rev]
569 h = self.header[rev]
573 if h != self.lastheader:
570 if h != self.lastheader:
574 self.lastheader = h
571 self.lastheader = h
575 self.ui.write(h)
572 self.ui.write(h)
576 del self.header[rev]
573 del self.header[rev]
577 if rev in self.hunk:
574 if rev in self.hunk:
578 self.ui.write(self.hunk[rev])
575 self.ui.write(self.hunk[rev])
579 del self.hunk[rev]
576 del self.hunk[rev]
580 return 1
577 return 1
581 return 0
578 return 0
582
579
583 def show(self, rev=0, changenode=None, copies=(), **props):
580 def show(self, rev=0, changenode=None, copies=(), **props):
584 if self.buffered:
581 if self.buffered:
585 self.ui.pushbuffer()
582 self.ui.pushbuffer()
586 self._show(rev, changenode, copies, props)
583 self._show(rev, changenode, copies, props)
587 self.hunk[rev] = self.ui.popbuffer()
584 self.hunk[rev] = self.ui.popbuffer()
588 else:
585 else:
589 self._show(rev, changenode, copies, props)
586 self._show(rev, changenode, copies, props)
590
587
591 def _show(self, rev, changenode, copies, props):
588 def _show(self, rev, changenode, copies, props):
592 '''show a single changeset or file revision'''
589 '''show a single changeset or file revision'''
593 log = self.repo.changelog
590 log = self.repo.changelog
594 if changenode is None:
591 if changenode is None:
595 changenode = log.node(rev)
592 changenode = log.node(rev)
596 elif not rev:
593 elif not rev:
597 rev = log.rev(changenode)
594 rev = log.rev(changenode)
598
595
599 if self.ui.quiet:
596 if self.ui.quiet:
600 self.ui.write("%d:%s\n" % (rev, short(changenode)))
597 self.ui.write("%d:%s\n" % (rev, short(changenode)))
601 return
598 return
602
599
603 changes = log.read(changenode)
600 changes = log.read(changenode)
604 date = util.datestr(changes[2])
601 date = util.datestr(changes[2])
605 extra = changes[5]
602 extra = changes[5]
606 branch = extra.get("branch")
603 branch = extra.get("branch")
607
604
608 hexfunc = self.ui.debugflag and hex or short
605 hexfunc = self.ui.debugflag and hex or short
609
606
610 parents = [(p, hexfunc(log.node(p)))
607 parents = [(p, hexfunc(log.node(p)))
611 for p in self._meaningful_parentrevs(log, rev)]
608 for p in self._meaningful_parentrevs(log, rev)]
612
609
613 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
610 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)))
614
611
615 # don't show the default branch name
612 # don't show the default branch name
616 if branch != 'default':
613 if branch != 'default':
617 branch = util.tolocal(branch)
614 branch = util.tolocal(branch)
618 self.ui.write(_("branch: %s\n") % branch)
615 self.ui.write(_("branch: %s\n") % branch)
619 for tag in self.repo.nodetags(changenode):
616 for tag in self.repo.nodetags(changenode):
620 self.ui.write(_("tag: %s\n") % tag)
617 self.ui.write(_("tag: %s\n") % tag)
621 for parent in parents:
618 for parent in parents:
622 self.ui.write(_("parent: %d:%s\n") % parent)
619 self.ui.write(_("parent: %d:%s\n") % parent)
623
620
624 if self.ui.debugflag:
621 if self.ui.debugflag:
625 self.ui.write(_("manifest: %d:%s\n") %
622 self.ui.write(_("manifest: %d:%s\n") %
626 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
623 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
627 self.ui.write(_("user: %s\n") % changes[1])
624 self.ui.write(_("user: %s\n") % changes[1])
628 self.ui.write(_("date: %s\n") % date)
625 self.ui.write(_("date: %s\n") % date)
629
626
630 if self.ui.debugflag:
627 if self.ui.debugflag:
631 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
628 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
632 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
629 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
633 files):
630 files):
634 if value:
631 if value:
635 self.ui.write("%-12s %s\n" % (key, " ".join(value)))
632 self.ui.write("%-12s %s\n" % (key, " ".join(value)))
636 elif changes[3] and self.ui.verbose:
633 elif changes[3] and self.ui.verbose:
637 self.ui.write(_("files: %s\n") % " ".join(changes[3]))
634 self.ui.write(_("files: %s\n") % " ".join(changes[3]))
638 if copies and self.ui.verbose:
635 if copies and self.ui.verbose:
639 copies = ['%s (%s)' % c for c in copies]
636 copies = ['%s (%s)' % c for c in copies]
640 self.ui.write(_("copies: %s\n") % ' '.join(copies))
637 self.ui.write(_("copies: %s\n") % ' '.join(copies))
641
638
642 if extra and self.ui.debugflag:
639 if extra and self.ui.debugflag:
643 extraitems = extra.items()
640 extraitems = extra.items()
644 extraitems.sort()
641 extraitems.sort()
645 for key, value in extraitems:
642 for key, value in extraitems:
646 self.ui.write(_("extra: %s=%s\n")
643 self.ui.write(_("extra: %s=%s\n")
647 % (key, value.encode('string_escape')))
644 % (key, value.encode('string_escape')))
648
645
649 description = changes[4].strip()
646 description = changes[4].strip()
650 if description:
647 if description:
651 if self.ui.verbose:
648 if self.ui.verbose:
652 self.ui.write(_("description:\n"))
649 self.ui.write(_("description:\n"))
653 self.ui.write(description)
650 self.ui.write(description)
654 self.ui.write("\n\n")
651 self.ui.write("\n\n")
655 else:
652 else:
656 self.ui.write(_("summary: %s\n") %
653 self.ui.write(_("summary: %s\n") %
657 description.splitlines()[0])
654 description.splitlines()[0])
658 self.ui.write("\n")
655 self.ui.write("\n")
659
656
660 self.showpatch(changenode)
657 self.showpatch(changenode)
661
658
662 def showpatch(self, node):
659 def showpatch(self, node):
663 if self.patch:
660 if self.patch:
664 prev = self.repo.changelog.parents(node)[0]
661 prev = self.repo.changelog.parents(node)[0]
665 patch.diff(self.repo, prev, node, match=self.patch, fp=self.ui,
662 patch.diff(self.repo, prev, node, match=self.patch, fp=self.ui,
666 opts=patch.diffopts(self.ui))
663 opts=patch.diffopts(self.ui))
667 self.ui.write("\n")
664 self.ui.write("\n")
668
665
669 def _meaningful_parentrevs(self, log, rev):
666 def _meaningful_parentrevs(self, log, rev):
670 """Return list of meaningful (or all if debug) parentrevs for rev.
667 """Return list of meaningful (or all if debug) parentrevs for rev.
671
668
672 For merges (two non-nullrev revisions) both parents are meaningful.
669 For merges (two non-nullrev revisions) both parents are meaningful.
673 Otherwise the first parent revision is considered meaningful if it
670 Otherwise the first parent revision is considered meaningful if it
674 is not the preceding revision.
671 is not the preceding revision.
675 """
672 """
676 parents = log.parentrevs(rev)
673 parents = log.parentrevs(rev)
677 if not self.ui.debugflag and parents[1] == nullrev:
674 if not self.ui.debugflag and parents[1] == nullrev:
678 if parents[0] >= rev - 1:
675 if parents[0] >= rev - 1:
679 parents = []
676 parents = []
680 else:
677 else:
681 parents = [parents[0]]
678 parents = [parents[0]]
682 return parents
679 return parents
683
680
684
681
685 class changeset_templater(changeset_printer):
682 class changeset_templater(changeset_printer):
686 '''format changeset information.'''
683 '''format changeset information.'''
687
684
688 def __init__(self, ui, repo, patch, mapfile, buffered):
685 def __init__(self, ui, repo, patch, mapfile, buffered):
689 changeset_printer.__init__(self, ui, repo, patch, buffered)
686 changeset_printer.__init__(self, ui, repo, patch, buffered)
690 filters = templatefilters.filters.copy()
687 filters = templatefilters.filters.copy()
691 filters['formatnode'] = (ui.debugflag and (lambda x: x)
688 filters['formatnode'] = (ui.debugflag and (lambda x: x)
692 or (lambda x: x[:12]))
689 or (lambda x: x[:12]))
693 self.t = templater.templater(mapfile, filters,
690 self.t = templater.templater(mapfile, filters,
694 cache={
691 cache={
695 'parent': '{rev}:{node|formatnode} ',
692 'parent': '{rev}:{node|formatnode} ',
696 'manifest': '{rev}:{node|formatnode}',
693 'manifest': '{rev}:{node|formatnode}',
697 'filecopy': '{name} ({source})'})
694 'filecopy': '{name} ({source})'})
698
695
699 def use_template(self, t):
696 def use_template(self, t):
700 '''set template string to use'''
697 '''set template string to use'''
701 self.t.cache['changeset'] = t
698 self.t.cache['changeset'] = t
702
699
703 def _show(self, rev, changenode, copies, props):
700 def _show(self, rev, changenode, copies, props):
704 '''show a single changeset or file revision'''
701 '''show a single changeset or file revision'''
705 log = self.repo.changelog
702 log = self.repo.changelog
706 if changenode is None:
703 if changenode is None:
707 changenode = log.node(rev)
704 changenode = log.node(rev)
708 elif not rev:
705 elif not rev:
709 rev = log.rev(changenode)
706 rev = log.rev(changenode)
710
707
711 changes = log.read(changenode)
708 changes = log.read(changenode)
712
709
713 def showlist(name, values, plural=None, **args):
710 def showlist(name, values, plural=None, **args):
714 '''expand set of values.
711 '''expand set of values.
715 name is name of key in template map.
712 name is name of key in template map.
716 values is list of strings or dicts.
713 values is list of strings or dicts.
717 plural is plural of name, if not simply name + 's'.
714 plural is plural of name, if not simply name + 's'.
718
715
719 expansion works like this, given name 'foo'.
716 expansion works like this, given name 'foo'.
720
717
721 if values is empty, expand 'no_foos'.
718 if values is empty, expand 'no_foos'.
722
719
723 if 'foo' not in template map, return values as a string,
720 if 'foo' not in template map, return values as a string,
724 joined by space.
721 joined by space.
725
722
726 expand 'start_foos'.
723 expand 'start_foos'.
727
724
728 for each value, expand 'foo'. if 'last_foo' in template
725 for each value, expand 'foo'. if 'last_foo' in template
729 map, expand it instead of 'foo' for last key.
726 map, expand it instead of 'foo' for last key.
730
727
731 expand 'end_foos'.
728 expand 'end_foos'.
732 '''
729 '''
733 if plural: names = plural
730 if plural: names = plural
734 else: names = name + 's'
731 else: names = name + 's'
735 if not values:
732 if not values:
736 noname = 'no_' + names
733 noname = 'no_' + names
737 if noname in self.t:
734 if noname in self.t:
738 yield self.t(noname, **args)
735 yield self.t(noname, **args)
739 return
736 return
740 if name not in self.t:
737 if name not in self.t:
741 if isinstance(values[0], str):
738 if isinstance(values[0], str):
742 yield ' '.join(values)
739 yield ' '.join(values)
743 else:
740 else:
744 for v in values:
741 for v in values:
745 yield dict(v, **args)
742 yield dict(v, **args)
746 return
743 return
747 startname = 'start_' + names
744 startname = 'start_' + names
748 if startname in self.t:
745 if startname in self.t:
749 yield self.t(startname, **args)
746 yield self.t(startname, **args)
750 vargs = args.copy()
747 vargs = args.copy()
751 def one(v, tag=name):
748 def one(v, tag=name):
752 try:
749 try:
753 vargs.update(v)
750 vargs.update(v)
754 except (AttributeError, ValueError):
751 except (AttributeError, ValueError):
755 try:
752 try:
756 for a, b in v:
753 for a, b in v:
757 vargs[a] = b
754 vargs[a] = b
758 except ValueError:
755 except ValueError:
759 vargs[name] = v
756 vargs[name] = v
760 return self.t(tag, **vargs)
757 return self.t(tag, **vargs)
761 lastname = 'last_' + name
758 lastname = 'last_' + name
762 if lastname in self.t:
759 if lastname in self.t:
763 last = values.pop()
760 last = values.pop()
764 else:
761 else:
765 last = None
762 last = None
766 for v in values:
763 for v in values:
767 yield one(v)
764 yield one(v)
768 if last is not None:
765 if last is not None:
769 yield one(last, tag=lastname)
766 yield one(last, tag=lastname)
770 endname = 'end_' + names
767 endname = 'end_' + names
771 if endname in self.t:
768 if endname in self.t:
772 yield self.t(endname, **args)
769 yield self.t(endname, **args)
773
770
774 def showbranches(**args):
771 def showbranches(**args):
775 branch = changes[5].get("branch")
772 branch = changes[5].get("branch")
776 if branch != 'default':
773 if branch != 'default':
777 branch = util.tolocal(branch)
774 branch = util.tolocal(branch)
778 return showlist('branch', [branch], plural='branches', **args)
775 return showlist('branch', [branch], plural='branches', **args)
779
776
780 def showparents(**args):
777 def showparents(**args):
781 parents = [[('rev', p), ('node', hex(log.node(p)))]
778 parents = [[('rev', p), ('node', hex(log.node(p)))]
782 for p in self._meaningful_parentrevs(log, rev)]
779 for p in self._meaningful_parentrevs(log, rev)]
783 return showlist('parent', parents, **args)
780 return showlist('parent', parents, **args)
784
781
785 def showtags(**args):
782 def showtags(**args):
786 return showlist('tag', self.repo.nodetags(changenode), **args)
783 return showlist('tag', self.repo.nodetags(changenode), **args)
787
784
788 def showextras(**args):
785 def showextras(**args):
789 extras = changes[5].items()
786 extras = changes[5].items()
790 extras.sort()
787 extras.sort()
791 for key, value in extras:
788 for key, value in extras:
792 args = args.copy()
789 args = args.copy()
793 args.update(dict(key=key, value=value))
790 args.update(dict(key=key, value=value))
794 yield self.t('extra', **args)
791 yield self.t('extra', **args)
795
792
796 def showcopies(**args):
793 def showcopies(**args):
797 c = [{'name': x[0], 'source': x[1]} for x in copies]
794 c = [{'name': x[0], 'source': x[1]} for x in copies]
798 return showlist('file_copy', c, plural='file_copies', **args)
795 return showlist('file_copy', c, plural='file_copies', **args)
799
796
800 files = []
797 files = []
801 def getfiles():
798 def getfiles():
802 if not files:
799 if not files:
803 files[:] = self.repo.status(
800 files[:] = self.repo.status(
804 log.parents(changenode)[0], changenode)[:3]
801 log.parents(changenode)[0], changenode)[:3]
805 return files
802 return files
806 def showfiles(**args):
803 def showfiles(**args):
807 return showlist('file', changes[3], **args)
804 return showlist('file', changes[3], **args)
808 def showmods(**args):
805 def showmods(**args):
809 return showlist('file_mod', getfiles()[0], **args)
806 return showlist('file_mod', getfiles()[0], **args)
810 def showadds(**args):
807 def showadds(**args):
811 return showlist('file_add', getfiles()[1], **args)
808 return showlist('file_add', getfiles()[1], **args)
812 def showdels(**args):
809 def showdels(**args):
813 return showlist('file_del', getfiles()[2], **args)
810 return showlist('file_del', getfiles()[2], **args)
814 def showmanifest(**args):
811 def showmanifest(**args):
815 args = args.copy()
812 args = args.copy()
816 args.update(dict(rev=self.repo.manifest.rev(changes[0]),
813 args.update(dict(rev=self.repo.manifest.rev(changes[0]),
817 node=hex(changes[0])))
814 node=hex(changes[0])))
818 return self.t('manifest', **args)
815 return self.t('manifest', **args)
819
816
820 defprops = {
817 defprops = {
821 'author': changes[1],
818 'author': changes[1],
822 'branches': showbranches,
819 'branches': showbranches,
823 'date': changes[2],
820 'date': changes[2],
824 'desc': changes[4].strip(),
821 'desc': changes[4].strip(),
825 'file_adds': showadds,
822 'file_adds': showadds,
826 'file_dels': showdels,
823 'file_dels': showdels,
827 'file_mods': showmods,
824 'file_mods': showmods,
828 'files': showfiles,
825 'files': showfiles,
829 'file_copies': showcopies,
826 'file_copies': showcopies,
830 'manifest': showmanifest,
827 'manifest': showmanifest,
831 'node': hex(changenode),
828 'node': hex(changenode),
832 'parents': showparents,
829 'parents': showparents,
833 'rev': rev,
830 'rev': rev,
834 'tags': showtags,
831 'tags': showtags,
835 'extras': showextras,
832 'extras': showextras,
836 }
833 }
837 props = props.copy()
834 props = props.copy()
838 props.update(defprops)
835 props.update(defprops)
839
836
840 try:
837 try:
841 if self.ui.debugflag and 'header_debug' in self.t:
838 if self.ui.debugflag and 'header_debug' in self.t:
842 key = 'header_debug'
839 key = 'header_debug'
843 elif self.ui.quiet and 'header_quiet' in self.t:
840 elif self.ui.quiet and 'header_quiet' in self.t:
844 key = 'header_quiet'
841 key = 'header_quiet'
845 elif self.ui.verbose and 'header_verbose' in self.t:
842 elif self.ui.verbose and 'header_verbose' in self.t:
846 key = 'header_verbose'
843 key = 'header_verbose'
847 elif 'header' in self.t:
844 elif 'header' in self.t:
848 key = 'header'
845 key = 'header'
849 else:
846 else:
850 key = ''
847 key = ''
851 if key:
848 if key:
852 h = templater.stringify(self.t(key, **props))
849 h = templater.stringify(self.t(key, **props))
853 if self.buffered:
850 if self.buffered:
854 self.header[rev] = h
851 self.header[rev] = h
855 else:
852 else:
856 self.ui.write(h)
853 self.ui.write(h)
857 if self.ui.debugflag and 'changeset_debug' in self.t:
854 if self.ui.debugflag and 'changeset_debug' in self.t:
858 key = 'changeset_debug'
855 key = 'changeset_debug'
859 elif self.ui.quiet and 'changeset_quiet' in self.t:
856 elif self.ui.quiet and 'changeset_quiet' in self.t:
860 key = 'changeset_quiet'
857 key = 'changeset_quiet'
861 elif self.ui.verbose and 'changeset_verbose' in self.t:
858 elif self.ui.verbose and 'changeset_verbose' in self.t:
862 key = 'changeset_verbose'
859 key = 'changeset_verbose'
863 else:
860 else:
864 key = 'changeset'
861 key = 'changeset'
865 self.ui.write(templater.stringify(self.t(key, **props)))
862 self.ui.write(templater.stringify(self.t(key, **props)))
866 self.showpatch(changenode)
863 self.showpatch(changenode)
867 except KeyError, inst:
864 except KeyError, inst:
868 raise util.Abort(_("%s: no key named '%s'") % (self.t.mapfile,
865 raise util.Abort(_("%s: no key named '%s'") % (self.t.mapfile,
869 inst.args[0]))
866 inst.args[0]))
870 except SyntaxError, inst:
867 except SyntaxError, inst:
871 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
868 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
872
869
873 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
870 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
874 """show one changeset using template or regular display.
871 """show one changeset using template or regular display.
875
872
876 Display format will be the first non-empty hit of:
873 Display format will be the first non-empty hit of:
877 1. option 'template'
874 1. option 'template'
878 2. option 'style'
875 2. option 'style'
879 3. [ui] setting 'logtemplate'
876 3. [ui] setting 'logtemplate'
880 4. [ui] setting 'style'
877 4. [ui] setting 'style'
881 If all of these values are either the unset or the empty string,
878 If all of these values are either the unset or the empty string,
882 regular display via changeset_printer() is done.
879 regular display via changeset_printer() is done.
883 """
880 """
884 # options
881 # options
885 patch = False
882 patch = False
886 if opts.get('patch'):
883 if opts.get('patch'):
887 patch = matchfn or util.always
884 patch = matchfn or util.always
888
885
889 tmpl = opts.get('template')
886 tmpl = opts.get('template')
890 mapfile = None
887 mapfile = None
891 if tmpl:
888 if tmpl:
892 tmpl = templater.parsestring(tmpl, quoted=False)
889 tmpl = templater.parsestring(tmpl, quoted=False)
893 else:
890 else:
894 mapfile = opts.get('style')
891 mapfile = opts.get('style')
895 # ui settings
892 # ui settings
896 if not mapfile:
893 if not mapfile:
897 tmpl = ui.config('ui', 'logtemplate')
894 tmpl = ui.config('ui', 'logtemplate')
898 if tmpl:
895 if tmpl:
899 tmpl = templater.parsestring(tmpl)
896 tmpl = templater.parsestring(tmpl)
900 else:
897 else:
901 mapfile = ui.config('ui', 'style')
898 mapfile = ui.config('ui', 'style')
902
899
903 if tmpl or mapfile:
900 if tmpl or mapfile:
904 if mapfile:
901 if mapfile:
905 if not os.path.split(mapfile)[0]:
902 if not os.path.split(mapfile)[0]:
906 mapname = (templater.templatepath('map-cmdline.' + mapfile)
903 mapname = (templater.templatepath('map-cmdline.' + mapfile)
907 or templater.templatepath(mapfile))
904 or templater.templatepath(mapfile))
908 if mapname: mapfile = mapname
905 if mapname: mapfile = mapname
909 try:
906 try:
910 t = changeset_templater(ui, repo, patch, mapfile, buffered)
907 t = changeset_templater(ui, repo, patch, mapfile, buffered)
911 except SyntaxError, inst:
908 except SyntaxError, inst:
912 raise util.Abort(inst.args[0])
909 raise util.Abort(inst.args[0])
913 if tmpl: t.use_template(tmpl)
910 if tmpl: t.use_template(tmpl)
914 return t
911 return t
915 return changeset_printer(ui, repo, patch, buffered)
912 return changeset_printer(ui, repo, patch, buffered)
916
913
917 def finddate(ui, repo, date):
914 def finddate(ui, repo, date):
918 """Find the tipmost changeset that matches the given date spec"""
915 """Find the tipmost changeset that matches the given date spec"""
919 df = util.matchdate(date)
916 df = util.matchdate(date)
920 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
917 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
921 changeiter, matchfn = walkchangerevs(ui, repo, [], get, {'rev':None})
918 changeiter, matchfn = walkchangerevs(ui, repo, [], get, {'rev':None})
922 results = {}
919 results = {}
923 for st, rev, fns in changeiter:
920 for st, rev, fns in changeiter:
924 if st == 'add':
921 if st == 'add':
925 d = get(rev)[2]
922 d = get(rev)[2]
926 if df(d[0]):
923 if df(d[0]):
927 results[rev] = d
924 results[rev] = d
928 elif st == 'iter':
925 elif st == 'iter':
929 if rev in results:
926 if rev in results:
930 ui.status("Found revision %s from %s\n" %
927 ui.status("Found revision %s from %s\n" %
931 (rev, util.datestr(results[rev])))
928 (rev, util.datestr(results[rev])))
932 return str(rev)
929 return str(rev)
933
930
934 raise util.Abort(_("revision matching date not found"))
931 raise util.Abort(_("revision matching date not found"))
935
932
936 def walkchangerevs(ui, repo, pats, change, opts):
933 def walkchangerevs(ui, repo, pats, change, opts):
937 '''Iterate over files and the revs they changed in.
934 '''Iterate over files and the revs they changed in.
938
935
939 Callers most commonly need to iterate backwards over the history
936 Callers most commonly need to iterate backwards over the history
940 it is interested in. Doing so has awful (quadratic-looking)
937 it is interested in. Doing so has awful (quadratic-looking)
941 performance, so we use iterators in a "windowed" way.
938 performance, so we use iterators in a "windowed" way.
942
939
943 We walk a window of revisions in the desired order. Within the
940 We walk a window of revisions in the desired order. Within the
944 window, we first walk forwards to gather data, then in the desired
941 window, we first walk forwards to gather data, then in the desired
945 order (usually backwards) to display it.
942 order (usually backwards) to display it.
946
943
947 This function returns an (iterator, matchfn) tuple. The iterator
944 This function returns an (iterator, matchfn) tuple. The iterator
948 yields 3-tuples. They will be of one of the following forms:
945 yields 3-tuples. They will be of one of the following forms:
949
946
950 "window", incrementing, lastrev: stepping through a window,
947 "window", incrementing, lastrev: stepping through a window,
951 positive if walking forwards through revs, last rev in the
948 positive if walking forwards through revs, last rev in the
952 sequence iterated over - use to reset state for the current window
949 sequence iterated over - use to reset state for the current window
953
950
954 "add", rev, fns: out-of-order traversal of the given file names
951 "add", rev, fns: out-of-order traversal of the given file names
955 fns, which changed during revision rev - use to gather data for
952 fns, which changed during revision rev - use to gather data for
956 possible display
953 possible display
957
954
958 "iter", rev, None: in-order traversal of the revs earlier iterated
955 "iter", rev, None: in-order traversal of the revs earlier iterated
959 over with "add" - use to display data'''
956 over with "add" - use to display data'''
960
957
961 def increasing_windows(start, end, windowsize=8, sizelimit=512):
958 def increasing_windows(start, end, windowsize=8, sizelimit=512):
962 if start < end:
959 if start < end:
963 while start < end:
960 while start < end:
964 yield start, min(windowsize, end-start)
961 yield start, min(windowsize, end-start)
965 start += windowsize
962 start += windowsize
966 if windowsize < sizelimit:
963 if windowsize < sizelimit:
967 windowsize *= 2
964 windowsize *= 2
968 else:
965 else:
969 while start > end:
966 while start > end:
970 yield start, min(windowsize, start-end-1)
967 yield start, min(windowsize, start-end-1)
971 start -= windowsize
968 start -= windowsize
972 if windowsize < sizelimit:
969 if windowsize < sizelimit:
973 windowsize *= 2
970 windowsize *= 2
974
971
975 files, matchfn, anypats = matchpats(repo, pats, opts)
972 files, matchfn, anypats = matchpats(repo, pats, opts)
976 follow = opts.get('follow') or opts.get('follow_first')
973 follow = opts.get('follow') or opts.get('follow_first')
977
974
978 if repo.changelog.count() == 0:
975 if repo.changelog.count() == 0:
979 return [], matchfn
976 return [], matchfn
980
977
981 if follow:
978 if follow:
982 defrange = '%s:0' % repo.changectx().rev()
979 defrange = '%s:0' % repo.changectx().rev()
983 else:
980 else:
984 defrange = '-1:0'
981 defrange = '-1:0'
985 revs = revrange(repo, opts['rev'] or [defrange])
982 revs = revrange(repo, opts['rev'] or [defrange])
986 wanted = {}
983 wanted = {}
987 slowpath = anypats or opts.get('removed')
984 slowpath = anypats or opts.get('removed')
988 fncache = {}
985 fncache = {}
989
986
990 if not slowpath and not files:
987 if not slowpath and not files:
991 # No files, no patterns. Display all revs.
988 # No files, no patterns. Display all revs.
992 wanted = dict.fromkeys(revs)
989 wanted = dict.fromkeys(revs)
993 copies = []
990 copies = []
994 if not slowpath:
991 if not slowpath:
995 # Only files, no patterns. Check the history of each file.
992 # Only files, no patterns. Check the history of each file.
996 def filerevgen(filelog, node):
993 def filerevgen(filelog, node):
997 cl_count = repo.changelog.count()
994 cl_count = repo.changelog.count()
998 if node is None:
995 if node is None:
999 last = filelog.count() - 1
996 last = filelog.count() - 1
1000 else:
997 else:
1001 last = filelog.rev(node)
998 last = filelog.rev(node)
1002 for i, window in increasing_windows(last, nullrev):
999 for i, window in increasing_windows(last, nullrev):
1003 revs = []
1000 revs = []
1004 for j in xrange(i - window, i + 1):
1001 for j in xrange(i - window, i + 1):
1005 n = filelog.node(j)
1002 n = filelog.node(j)
1006 revs.append((filelog.linkrev(n),
1003 revs.append((filelog.linkrev(n),
1007 follow and filelog.renamed(n)))
1004 follow and filelog.renamed(n)))
1008 revs.reverse()
1005 revs.reverse()
1009 for rev in revs:
1006 for rev in revs:
1010 # only yield rev for which we have the changelog, it can
1007 # only yield rev for which we have the changelog, it can
1011 # happen while doing "hg log" during a pull or commit
1008 # happen while doing "hg log" during a pull or commit
1012 if rev[0] < cl_count:
1009 if rev[0] < cl_count:
1013 yield rev
1010 yield rev
1014 def iterfiles():
1011 def iterfiles():
1015 for filename in files:
1012 for filename in files:
1016 yield filename, None
1013 yield filename, None
1017 for filename_node in copies:
1014 for filename_node in copies:
1018 yield filename_node
1015 yield filename_node
1019 minrev, maxrev = min(revs), max(revs)
1016 minrev, maxrev = min(revs), max(revs)
1020 for file_, node in iterfiles():
1017 for file_, node in iterfiles():
1021 filelog = repo.file(file_)
1018 filelog = repo.file(file_)
1022 if filelog.count() == 0:
1019 if filelog.count() == 0:
1023 if node is None:
1020 if node is None:
1024 # A zero count may be a directory or deleted file, so
1021 # A zero count may be a directory or deleted file, so
1025 # try to find matching entries on the slow path.
1022 # try to find matching entries on the slow path.
1026 slowpath = True
1023 slowpath = True
1027 break
1024 break
1028 else:
1025 else:
1029 ui.warn(_('%s:%s copy source revision cannot be found!\n')
1026 ui.warn(_('%s:%s copy source revision cannot be found!\n')
1030 % (file_, short(node)))
1027 % (file_, short(node)))
1031 continue
1028 continue
1032 for rev, copied in filerevgen(filelog, node):
1029 for rev, copied in filerevgen(filelog, node):
1033 if rev <= maxrev:
1030 if rev <= maxrev:
1034 if rev < minrev:
1031 if rev < minrev:
1035 break
1032 break
1036 fncache.setdefault(rev, [])
1033 fncache.setdefault(rev, [])
1037 fncache[rev].append(file_)
1034 fncache[rev].append(file_)
1038 wanted[rev] = 1
1035 wanted[rev] = 1
1039 if follow and copied:
1036 if follow and copied:
1040 copies.append(copied)
1037 copies.append(copied)
1041 if slowpath:
1038 if slowpath:
1042 if follow:
1039 if follow:
1043 raise util.Abort(_('can only follow copies/renames for explicit '
1040 raise util.Abort(_('can only follow copies/renames for explicit '
1044 'file names'))
1041 'file names'))
1045
1042
1046 # The slow path checks files modified in every changeset.
1043 # The slow path checks files modified in every changeset.
1047 def changerevgen():
1044 def changerevgen():
1048 for i, window in increasing_windows(repo.changelog.count()-1,
1045 for i, window in increasing_windows(repo.changelog.count()-1,
1049 nullrev):
1046 nullrev):
1050 for j in xrange(i - window, i + 1):
1047 for j in xrange(i - window, i + 1):
1051 yield j, change(j)[3]
1048 yield j, change(j)[3]
1052
1049
1053 for rev, changefiles in changerevgen():
1050 for rev, changefiles in changerevgen():
1054 matches = filter(matchfn, changefiles)
1051 matches = filter(matchfn, changefiles)
1055 if matches:
1052 if matches:
1056 fncache[rev] = matches
1053 fncache[rev] = matches
1057 wanted[rev] = 1
1054 wanted[rev] = 1
1058
1055
1059 class followfilter:
1056 class followfilter:
1060 def __init__(self, onlyfirst=False):
1057 def __init__(self, onlyfirst=False):
1061 self.startrev = nullrev
1058 self.startrev = nullrev
1062 self.roots = []
1059 self.roots = []
1063 self.onlyfirst = onlyfirst
1060 self.onlyfirst = onlyfirst
1064
1061
1065 def match(self, rev):
1062 def match(self, rev):
1066 def realparents(rev):
1063 def realparents(rev):
1067 if self.onlyfirst:
1064 if self.onlyfirst:
1068 return repo.changelog.parentrevs(rev)[0:1]
1065 return repo.changelog.parentrevs(rev)[0:1]
1069 else:
1066 else:
1070 return filter(lambda x: x != nullrev,
1067 return filter(lambda x: x != nullrev,
1071 repo.changelog.parentrevs(rev))
1068 repo.changelog.parentrevs(rev))
1072
1069
1073 if self.startrev == nullrev:
1070 if self.startrev == nullrev:
1074 self.startrev = rev
1071 self.startrev = rev
1075 return True
1072 return True
1076
1073
1077 if rev > self.startrev:
1074 if rev > self.startrev:
1078 # forward: all descendants
1075 # forward: all descendants
1079 if not self.roots:
1076 if not self.roots:
1080 self.roots.append(self.startrev)
1077 self.roots.append(self.startrev)
1081 for parent in realparents(rev):
1078 for parent in realparents(rev):
1082 if parent in self.roots:
1079 if parent in self.roots:
1083 self.roots.append(rev)
1080 self.roots.append(rev)
1084 return True
1081 return True
1085 else:
1082 else:
1086 # backwards: all parents
1083 # backwards: all parents
1087 if not self.roots:
1084 if not self.roots:
1088 self.roots.extend(realparents(self.startrev))
1085 self.roots.extend(realparents(self.startrev))
1089 if rev in self.roots:
1086 if rev in self.roots:
1090 self.roots.remove(rev)
1087 self.roots.remove(rev)
1091 self.roots.extend(realparents(rev))
1088 self.roots.extend(realparents(rev))
1092 return True
1089 return True
1093
1090
1094 return False
1091 return False
1095
1092
1096 # it might be worthwhile to do this in the iterator if the rev range
1093 # it might be worthwhile to do this in the iterator if the rev range
1097 # is descending and the prune args are all within that range
1094 # is descending and the prune args are all within that range
1098 for rev in opts.get('prune', ()):
1095 for rev in opts.get('prune', ()):
1099 rev = repo.changelog.rev(repo.lookup(rev))
1096 rev = repo.changelog.rev(repo.lookup(rev))
1100 ff = followfilter()
1097 ff = followfilter()
1101 stop = min(revs[0], revs[-1])
1098 stop = min(revs[0], revs[-1])
1102 for x in xrange(rev, stop-1, -1):
1099 for x in xrange(rev, stop-1, -1):
1103 if ff.match(x) and x in wanted:
1100 if ff.match(x) and x in wanted:
1104 del wanted[x]
1101 del wanted[x]
1105
1102
1106 def iterate():
1103 def iterate():
1107 if follow and not files:
1104 if follow and not files:
1108 ff = followfilter(onlyfirst=opts.get('follow_first'))
1105 ff = followfilter(onlyfirst=opts.get('follow_first'))
1109 def want(rev):
1106 def want(rev):
1110 if ff.match(rev) and rev in wanted:
1107 if ff.match(rev) and rev in wanted:
1111 return True
1108 return True
1112 return False
1109 return False
1113 else:
1110 else:
1114 def want(rev):
1111 def want(rev):
1115 return rev in wanted
1112 return rev in wanted
1116
1113
1117 for i, window in increasing_windows(0, len(revs)):
1114 for i, window in increasing_windows(0, len(revs)):
1118 yield 'window', revs[0] < revs[-1], revs[-1]
1115 yield 'window', revs[0] < revs[-1], revs[-1]
1119 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
1116 nrevs = [rev for rev in revs[i:i+window] if want(rev)]
1120 srevs = list(nrevs)
1117 srevs = list(nrevs)
1121 srevs.sort()
1118 srevs.sort()
1122 for rev in srevs:
1119 for rev in srevs:
1123 fns = fncache.get(rev)
1120 fns = fncache.get(rev)
1124 if not fns:
1121 if not fns:
1125 def fns_generator():
1122 def fns_generator():
1126 for f in change(rev)[3]:
1123 for f in change(rev)[3]:
1127 if matchfn(f):
1124 if matchfn(f):
1128 yield f
1125 yield f
1129 fns = fns_generator()
1126 fns = fns_generator()
1130 yield 'add', rev, fns
1127 yield 'add', rev, fns
1131 for rev in nrevs:
1128 for rev in nrevs:
1132 yield 'iter', rev, None
1129 yield 'iter', rev, None
1133 return iterate(), matchfn
1130 return iterate(), matchfn
1134
1131
1135 def commit(ui, repo, commitfunc, pats, opts):
1132 def commit(ui, repo, commitfunc, pats, opts):
1136 '''commit the specified files or all outstanding changes'''
1133 '''commit the specified files or all outstanding changes'''
1137 date = opts.get('date')
1134 date = opts.get('date')
1138 if date:
1135 if date:
1139 opts['date'] = util.parsedate(date)
1136 opts['date'] = util.parsedate(date)
1140 message = logmessage(opts)
1137 message = logmessage(opts)
1141
1138
1142 # extract addremove carefully -- this function can be called from a command
1139 # extract addremove carefully -- this function can be called from a command
1143 # that doesn't support addremove
1140 # that doesn't support addremove
1144 if opts.get('addremove'):
1141 if opts.get('addremove'):
1145 addremove(repo, pats, opts)
1142 addremove(repo, pats, opts)
1146
1143
1147 fns, match, anypats = matchpats(repo, pats, opts)
1144 fns, match, anypats = matchpats(repo, pats, opts)
1148 if pats:
1145 if pats:
1149 status = repo.status(files=fns, match=match)
1146 status = repo.status(files=fns, match=match)
1150 modified, added, removed, deleted, unknown = status[:5]
1147 modified, added, removed, deleted, unknown = status[:5]
1151 files = modified + added + removed
1148 files = modified + added + removed
1152 slist = None
1149 slist = None
1153 for f in fns:
1150 for f in fns:
1154 if f == '.':
1151 if f == '.':
1155 continue
1152 continue
1156 if f not in files:
1153 if f not in files:
1157 rf = repo.wjoin(f)
1154 rf = repo.wjoin(f)
1158 rel = repo.pathto(f)
1155 rel = repo.pathto(f)
1159 try:
1156 try:
1160 mode = os.lstat(rf)[stat.ST_MODE]
1157 mode = os.lstat(rf)[stat.ST_MODE]
1161 except OSError:
1158 except OSError:
1162 raise util.Abort(_("file %s not found!") % rel)
1159 raise util.Abort(_("file %s not found!") % rel)
1163 if stat.S_ISDIR(mode):
1160 if stat.S_ISDIR(mode):
1164 name = f + '/'
1161 name = f + '/'
1165 if slist is None:
1162 if slist is None:
1166 slist = list(files)
1163 slist = list(files)
1167 slist.sort()
1164 slist.sort()
1168 i = bisect.bisect(slist, name)
1165 i = bisect.bisect(slist, name)
1169 if i >= len(slist) or not slist[i].startswith(name):
1166 if i >= len(slist) or not slist[i].startswith(name):
1170 raise util.Abort(_("no match under directory %s!")
1167 raise util.Abort(_("no match under directory %s!")
1171 % rel)
1168 % rel)
1172 elif not (stat.S_ISREG(mode) or stat.S_ISLNK(mode)):
1169 elif not (stat.S_ISREG(mode) or stat.S_ISLNK(mode)):
1173 raise util.Abort(_("can't commit %s: "
1170 raise util.Abort(_("can't commit %s: "
1174 "unsupported file type!") % rel)
1171 "unsupported file type!") % rel)
1175 elif f not in repo.dirstate:
1172 elif f not in repo.dirstate:
1176 raise util.Abort(_("file %s not tracked!") % rel)
1173 raise util.Abort(_("file %s not tracked!") % rel)
1177 else:
1174 else:
1178 files = []
1175 files = []
1179 try:
1176 try:
1180 return commitfunc(ui, repo, files, message, match, opts)
1177 return commitfunc(ui, repo, files, message, match, opts)
1181 except ValueError, inst:
1178 except ValueError, inst:
1182 raise util.Abort(str(inst))
1179 raise util.Abort(str(inst))
@@ -1,2141 +1,2141
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
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 from node import bin, hex, nullid, nullrev, short
8 from node import bin, hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import repo, changegroup
10 import repo, changegroup
11 import changelog, dirstate, filelog, manifest, context, weakref
11 import changelog, dirstate, filelog, manifest, context, weakref
12 import lock, transaction, stat, errno, ui
12 import lock, transaction, stat, errno, ui
13 import os, revlog, time, util, extensions, hook, inspect
13 import os, revlog, time, util, extensions, hook, inspect
14
14
15 class localrepository(repo.repository):
15 class localrepository(repo.repository):
16 capabilities = util.set(('lookup', 'changegroupsubset'))
16 capabilities = util.set(('lookup', 'changegroupsubset'))
17 supported = ('revlogv1', 'store')
17 supported = ('revlogv1', 'store')
18
18
19 def __init__(self, parentui, path=None, create=0):
19 def __init__(self, parentui, path=None, create=0):
20 repo.repository.__init__(self)
20 repo.repository.__init__(self)
21 self.root = os.path.realpath(path)
21 self.root = os.path.realpath(path)
22 self.path = os.path.join(self.root, ".hg")
22 self.path = os.path.join(self.root, ".hg")
23 self.origroot = path
23 self.origroot = path
24 self.opener = util.opener(self.path)
24 self.opener = util.opener(self.path)
25 self.wopener = util.opener(self.root)
25 self.wopener = util.opener(self.root)
26
26
27 if not os.path.isdir(self.path):
27 if not os.path.isdir(self.path):
28 if create:
28 if create:
29 if not os.path.exists(path):
29 if not os.path.exists(path):
30 os.mkdir(path)
30 os.mkdir(path)
31 os.mkdir(self.path)
31 os.mkdir(self.path)
32 requirements = ["revlogv1"]
32 requirements = ["revlogv1"]
33 if parentui.configbool('format', 'usestore', True):
33 if parentui.configbool('format', 'usestore', True):
34 os.mkdir(os.path.join(self.path, "store"))
34 os.mkdir(os.path.join(self.path, "store"))
35 requirements.append("store")
35 requirements.append("store")
36 # create an invalid changelog
36 # create an invalid changelog
37 self.opener("00changelog.i", "a").write(
37 self.opener("00changelog.i", "a").write(
38 '\0\0\0\2' # represents revlogv2
38 '\0\0\0\2' # represents revlogv2
39 ' dummy changelog to prevent using the old repo layout'
39 ' dummy changelog to prevent using the old repo layout'
40 )
40 )
41 reqfile = self.opener("requires", "w")
41 reqfile = self.opener("requires", "w")
42 for r in requirements:
42 for r in requirements:
43 reqfile.write("%s\n" % r)
43 reqfile.write("%s\n" % r)
44 reqfile.close()
44 reqfile.close()
45 else:
45 else:
46 raise repo.RepoError(_("repository %s not found") % path)
46 raise repo.RepoError(_("repository %s not found") % path)
47 elif create:
47 elif create:
48 raise repo.RepoError(_("repository %s already exists") % path)
48 raise repo.RepoError(_("repository %s already exists") % path)
49 else:
49 else:
50 # find requirements
50 # find requirements
51 try:
51 try:
52 requirements = self.opener("requires").read().splitlines()
52 requirements = self.opener("requires").read().splitlines()
53 except IOError, inst:
53 except IOError, inst:
54 if inst.errno != errno.ENOENT:
54 if inst.errno != errno.ENOENT:
55 raise
55 raise
56 requirements = []
56 requirements = []
57 # check them
57 # check them
58 for r in requirements:
58 for r in requirements:
59 if r not in self.supported:
59 if r not in self.supported:
60 raise repo.RepoError(_("requirement '%s' not supported") % r)
60 raise repo.RepoError(_("requirement '%s' not supported") % r)
61
61
62 # setup store
62 # setup store
63 if "store" in requirements:
63 if "store" in requirements:
64 self.encodefn = util.encodefilename
64 self.encodefn = util.encodefilename
65 self.decodefn = util.decodefilename
65 self.decodefn = util.decodefilename
66 self.spath = os.path.join(self.path, "store")
66 self.spath = os.path.join(self.path, "store")
67 else:
67 else:
68 self.encodefn = lambda x: x
68 self.encodefn = lambda x: x
69 self.decodefn = lambda x: x
69 self.decodefn = lambda x: x
70 self.spath = self.path
70 self.spath = self.path
71
71
72 try:
72 try:
73 # files in .hg/ will be created using this mode
73 # files in .hg/ will be created using this mode
74 mode = os.stat(self.spath).st_mode
74 mode = os.stat(self.spath).st_mode
75 # avoid some useless chmods
75 # avoid some useless chmods
76 if (0777 & ~util._umask) == (0777 & mode):
76 if (0777 & ~util._umask) == (0777 & mode):
77 mode = None
77 mode = None
78 except OSError:
78 except OSError:
79 mode = None
79 mode = None
80
80
81 self._createmode = mode
81 self._createmode = mode
82 self.opener.createmode = mode
82 self.opener.createmode = mode
83 sopener = util.opener(self.spath)
83 sopener = util.opener(self.spath)
84 sopener.createmode = mode
84 sopener.createmode = mode
85 self.sopener = util.encodedopener(sopener, self.encodefn)
85 self.sopener = util.encodedopener(sopener, self.encodefn)
86
86
87 self.ui = ui.ui(parentui=parentui)
87 self.ui = ui.ui(parentui=parentui)
88 try:
88 try:
89 self.ui.readconfig(self.join("hgrc"), self.root)
89 self.ui.readconfig(self.join("hgrc"), self.root)
90 extensions.loadall(self.ui)
90 extensions.loadall(self.ui)
91 except IOError:
91 except IOError:
92 pass
92 pass
93
93
94 self.tagscache = None
94 self.tagscache = None
95 self._tagstypecache = None
95 self._tagstypecache = None
96 self.branchcache = None
96 self.branchcache = None
97 self._ubranchcache = None # UTF-8 version of branchcache
97 self._ubranchcache = None # UTF-8 version of branchcache
98 self._branchcachetip = None
98 self._branchcachetip = None
99 self.nodetagscache = None
99 self.nodetagscache = None
100 self.filterpats = {}
100 self.filterpats = {}
101 self._datafilters = {}
101 self._datafilters = {}
102 self._transref = self._lockref = self._wlockref = None
102 self._transref = self._lockref = self._wlockref = None
103
103
104 def __getattr__(self, name):
104 def __getattr__(self, name):
105 if name == 'changelog':
105 if name == 'changelog':
106 self.changelog = changelog.changelog(self.sopener)
106 self.changelog = changelog.changelog(self.sopener)
107 self.sopener.defversion = self.changelog.version
107 self.sopener.defversion = self.changelog.version
108 return self.changelog
108 return self.changelog
109 if name == 'manifest':
109 if name == 'manifest':
110 self.changelog
110 self.changelog
111 self.manifest = manifest.manifest(self.sopener)
111 self.manifest = manifest.manifest(self.sopener)
112 return self.manifest
112 return self.manifest
113 if name == 'dirstate':
113 if name == 'dirstate':
114 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
114 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
115 return self.dirstate
115 return self.dirstate
116 else:
116 else:
117 raise AttributeError, name
117 raise AttributeError, name
118
118
119 def url(self):
119 def url(self):
120 return 'file:' + self.root
120 return 'file:' + self.root
121
121
122 def hook(self, name, throw=False, **args):
122 def hook(self, name, throw=False, **args):
123 return hook.hook(self.ui, self, name, throw, **args)
123 return hook.hook(self.ui, self, name, throw, **args)
124
124
125 tag_disallowed = ':\r\n'
125 tag_disallowed = ':\r\n'
126
126
127 def _tag(self, names, node, message, local, user, date, parent=None,
127 def _tag(self, names, node, message, local, user, date, parent=None,
128 extra={}):
128 extra={}):
129 use_dirstate = parent is None
129 use_dirstate = parent is None
130
130
131 if isinstance(names, str):
131 if isinstance(names, str):
132 allchars = names
132 allchars = names
133 names = (names,)
133 names = (names,)
134 else:
134 else:
135 allchars = ''.join(names)
135 allchars = ''.join(names)
136 for c in self.tag_disallowed:
136 for c in self.tag_disallowed:
137 if c in allchars:
137 if c in allchars:
138 raise util.Abort(_('%r cannot be used in a tag name') % c)
138 raise util.Abort(_('%r cannot be used in a tag name') % c)
139
139
140 for name in names:
140 for name in names:
141 self.hook('pretag', throw=True, node=hex(node), tag=name,
141 self.hook('pretag', throw=True, node=hex(node), tag=name,
142 local=local)
142 local=local)
143
143
144 def writetags(fp, names, munge, prevtags):
144 def writetags(fp, names, munge, prevtags):
145 fp.seek(0, 2)
145 fp.seek(0, 2)
146 if prevtags and prevtags[-1] != '\n':
146 if prevtags and prevtags[-1] != '\n':
147 fp.write('\n')
147 fp.write('\n')
148 for name in names:
148 for name in names:
149 fp.write('%s %s\n' % (hex(node), munge and munge(name) or name))
149 fp.write('%s %s\n' % (hex(node), munge and munge(name) or name))
150 fp.close()
150 fp.close()
151
151
152 prevtags = ''
152 prevtags = ''
153 if local:
153 if local:
154 try:
154 try:
155 fp = self.opener('localtags', 'r+')
155 fp = self.opener('localtags', 'r+')
156 except IOError, err:
156 except IOError, err:
157 fp = self.opener('localtags', 'a')
157 fp = self.opener('localtags', 'a')
158 else:
158 else:
159 prevtags = fp.read()
159 prevtags = fp.read()
160
160
161 # local tags are stored in the current charset
161 # local tags are stored in the current charset
162 writetags(fp, names, None, prevtags)
162 writetags(fp, names, None, prevtags)
163 for name in names:
163 for name in names:
164 self.hook('tag', node=hex(node), tag=name, local=local)
164 self.hook('tag', node=hex(node), tag=name, local=local)
165 return
165 return
166
166
167 if use_dirstate:
167 if use_dirstate:
168 try:
168 try:
169 fp = self.wfile('.hgtags', 'rb+')
169 fp = self.wfile('.hgtags', 'rb+')
170 except IOError, err:
170 except IOError, err:
171 fp = self.wfile('.hgtags', 'ab')
171 fp = self.wfile('.hgtags', 'ab')
172 else:
172 else:
173 prevtags = fp.read()
173 prevtags = fp.read()
174 else:
174 else:
175 try:
175 try:
176 prevtags = self.filectx('.hgtags', parent).data()
176 prevtags = self.filectx('.hgtags', parent).data()
177 except revlog.LookupError:
177 except revlog.LookupError:
178 pass
178 pass
179 fp = self.wfile('.hgtags', 'wb')
179 fp = self.wfile('.hgtags', 'wb')
180 if prevtags:
180 if prevtags:
181 fp.write(prevtags)
181 fp.write(prevtags)
182
182
183 # committed tags are stored in UTF-8
183 # committed tags are stored in UTF-8
184 writetags(fp, names, util.fromlocal, prevtags)
184 writetags(fp, names, util.fromlocal, prevtags)
185
185
186 if use_dirstate and '.hgtags' not in self.dirstate:
186 if use_dirstate and '.hgtags' not in self.dirstate:
187 self.add(['.hgtags'])
187 self.add(['.hgtags'])
188
188
189 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
189 tagnode = self.commit(['.hgtags'], message, user, date, p1=parent,
190 extra=extra)
190 extra=extra)
191
191
192 for name in names:
192 for name in names:
193 self.hook('tag', node=hex(node), tag=name, local=local)
193 self.hook('tag', node=hex(node), tag=name, local=local)
194
194
195 return tagnode
195 return tagnode
196
196
197 def tag(self, names, node, message, local, user, date):
197 def tag(self, names, node, message, local, user, date):
198 '''tag a revision with one or more symbolic names.
198 '''tag a revision with one or more symbolic names.
199
199
200 names is a list of strings or, when adding a single tag, names may be a
200 names is a list of strings or, when adding a single tag, names may be a
201 string.
201 string.
202
202
203 if local is True, the tags are stored in a per-repository file.
203 if local is True, the tags are stored in a per-repository file.
204 otherwise, they are stored in the .hgtags file, and a new
204 otherwise, they are stored in the .hgtags file, and a new
205 changeset is committed with the change.
205 changeset is committed with the change.
206
206
207 keyword arguments:
207 keyword arguments:
208
208
209 local: whether to store tags in non-version-controlled file
209 local: whether to store tags in non-version-controlled file
210 (default False)
210 (default False)
211
211
212 message: commit message to use if committing
212 message: commit message to use if committing
213
213
214 user: name of user to use if committing
214 user: name of user to use if committing
215
215
216 date: date tuple to use if committing'''
216 date: date tuple to use if committing'''
217
217
218 for x in self.status()[:5]:
218 for x in self.status()[:5]:
219 if '.hgtags' in x:
219 if '.hgtags' in x:
220 raise util.Abort(_('working copy of .hgtags is changed '
220 raise util.Abort(_('working copy of .hgtags is changed '
221 '(please commit .hgtags manually)'))
221 '(please commit .hgtags manually)'))
222
222
223 self._tag(names, node, message, local, user, date)
223 self._tag(names, node, message, local, user, date)
224
224
225 def tags(self):
225 def tags(self):
226 '''return a mapping of tag to node'''
226 '''return a mapping of tag to node'''
227 if self.tagscache:
227 if self.tagscache:
228 return self.tagscache
228 return self.tagscache
229
229
230 globaltags = {}
230 globaltags = {}
231 tagtypes = {}
231 tagtypes = {}
232
232
233 def readtags(lines, fn, tagtype):
233 def readtags(lines, fn, tagtype):
234 filetags = {}
234 filetags = {}
235 count = 0
235 count = 0
236
236
237 def warn(msg):
237 def warn(msg):
238 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
238 self.ui.warn(_("%s, line %s: %s\n") % (fn, count, msg))
239
239
240 for l in lines:
240 for l in lines:
241 count += 1
241 count += 1
242 if not l:
242 if not l:
243 continue
243 continue
244 s = l.split(" ", 1)
244 s = l.split(" ", 1)
245 if len(s) != 2:
245 if len(s) != 2:
246 warn(_("cannot parse entry"))
246 warn(_("cannot parse entry"))
247 continue
247 continue
248 node, key = s
248 node, key = s
249 key = util.tolocal(key.strip()) # stored in UTF-8
249 key = util.tolocal(key.strip()) # stored in UTF-8
250 try:
250 try:
251 bin_n = bin(node)
251 bin_n = bin(node)
252 except TypeError:
252 except TypeError:
253 warn(_("node '%s' is not well formed") % node)
253 warn(_("node '%s' is not well formed") % node)
254 continue
254 continue
255 if bin_n not in self.changelog.nodemap:
255 if bin_n not in self.changelog.nodemap:
256 warn(_("tag '%s' refers to unknown node") % key)
256 warn(_("tag '%s' refers to unknown node") % key)
257 continue
257 continue
258
258
259 h = []
259 h = []
260 if key in filetags:
260 if key in filetags:
261 n, h = filetags[key]
261 n, h = filetags[key]
262 h.append(n)
262 h.append(n)
263 filetags[key] = (bin_n, h)
263 filetags[key] = (bin_n, h)
264
264
265 for k, nh in filetags.items():
265 for k, nh in filetags.items():
266 if k not in globaltags:
266 if k not in globaltags:
267 globaltags[k] = nh
267 globaltags[k] = nh
268 tagtypes[k] = tagtype
268 tagtypes[k] = tagtype
269 continue
269 continue
270
270
271 # we prefer the global tag if:
271 # we prefer the global tag if:
272 # it supercedes us OR
272 # it supercedes us OR
273 # mutual supercedes and it has a higher rank
273 # mutual supercedes and it has a higher rank
274 # otherwise we win because we're tip-most
274 # otherwise we win because we're tip-most
275 an, ah = nh
275 an, ah = nh
276 bn, bh = globaltags[k]
276 bn, bh = globaltags[k]
277 if (bn != an and an in bh and
277 if (bn != an and an in bh and
278 (bn not in ah or len(bh) > len(ah))):
278 (bn not in ah or len(bh) > len(ah))):
279 an = bn
279 an = bn
280 ah.extend([n for n in bh if n not in ah])
280 ah.extend([n for n in bh if n not in ah])
281 globaltags[k] = an, ah
281 globaltags[k] = an, ah
282 tagtypes[k] = tagtype
282 tagtypes[k] = tagtype
283
283
284 # read the tags file from each head, ending with the tip
284 # read the tags file from each head, ending with the tip
285 f = None
285 f = None
286 for rev, node, fnode in self._hgtagsnodes():
286 for rev, node, fnode in self._hgtagsnodes():
287 f = (f and f.filectx(fnode) or
287 f = (f and f.filectx(fnode) or
288 self.filectx('.hgtags', fileid=fnode))
288 self.filectx('.hgtags', fileid=fnode))
289 readtags(f.data().splitlines(), f, "global")
289 readtags(f.data().splitlines(), f, "global")
290
290
291 try:
291 try:
292 data = util.fromlocal(self.opener("localtags").read())
292 data = util.fromlocal(self.opener("localtags").read())
293 # localtags are stored in the local character set
293 # localtags are stored in the local character set
294 # while the internal tag table is stored in UTF-8
294 # while the internal tag table is stored in UTF-8
295 readtags(data.splitlines(), "localtags", "local")
295 readtags(data.splitlines(), "localtags", "local")
296 except IOError:
296 except IOError:
297 pass
297 pass
298
298
299 self.tagscache = {}
299 self.tagscache = {}
300 self._tagstypecache = {}
300 self._tagstypecache = {}
301 for k,nh in globaltags.items():
301 for k,nh in globaltags.items():
302 n = nh[0]
302 n = nh[0]
303 if n != nullid:
303 if n != nullid:
304 self.tagscache[k] = n
304 self.tagscache[k] = n
305 self._tagstypecache[k] = tagtypes[k]
305 self._tagstypecache[k] = tagtypes[k]
306 self.tagscache['tip'] = self.changelog.tip()
306 self.tagscache['tip'] = self.changelog.tip()
307
307
308 return self.tagscache
308 return self.tagscache
309
309
310 def tagtype(self, tagname):
310 def tagtype(self, tagname):
311 '''
311 '''
312 return the type of the given tag. result can be:
312 return the type of the given tag. result can be:
313
313
314 'local' : a local tag
314 'local' : a local tag
315 'global' : a global tag
315 'global' : a global tag
316 None : tag does not exist
316 None : tag does not exist
317 '''
317 '''
318
318
319 self.tags()
319 self.tags()
320
320
321 return self._tagstypecache.get(tagname)
321 return self._tagstypecache.get(tagname)
322
322
323 def _hgtagsnodes(self):
323 def _hgtagsnodes(self):
324 heads = self.heads()
324 heads = self.heads()
325 heads.reverse()
325 heads.reverse()
326 last = {}
326 last = {}
327 ret = []
327 ret = []
328 for node in heads:
328 for node in heads:
329 c = self.changectx(node)
329 c = self.changectx(node)
330 rev = c.rev()
330 rev = c.rev()
331 try:
331 try:
332 fnode = c.filenode('.hgtags')
332 fnode = c.filenode('.hgtags')
333 except revlog.LookupError:
333 except revlog.LookupError:
334 continue
334 continue
335 ret.append((rev, node, fnode))
335 ret.append((rev, node, fnode))
336 if fnode in last:
336 if fnode in last:
337 ret[last[fnode]] = None
337 ret[last[fnode]] = None
338 last[fnode] = len(ret) - 1
338 last[fnode] = len(ret) - 1
339 return [item for item in ret if item]
339 return [item for item in ret if item]
340
340
341 def tagslist(self):
341 def tagslist(self):
342 '''return a list of tags ordered by revision'''
342 '''return a list of tags ordered by revision'''
343 l = []
343 l = []
344 for t, n in self.tags().items():
344 for t, n in self.tags().items():
345 try:
345 try:
346 r = self.changelog.rev(n)
346 r = self.changelog.rev(n)
347 except:
347 except:
348 r = -2 # sort to the beginning of the list if unknown
348 r = -2 # sort to the beginning of the list if unknown
349 l.append((r, t, n))
349 l.append((r, t, n))
350 l.sort()
350 l.sort()
351 return [(t, n) for r, t, n in l]
351 return [(t, n) for r, t, n in l]
352
352
353 def nodetags(self, node):
353 def nodetags(self, node):
354 '''return the tags associated with a node'''
354 '''return the tags associated with a node'''
355 if not self.nodetagscache:
355 if not self.nodetagscache:
356 self.nodetagscache = {}
356 self.nodetagscache = {}
357 for t, n in self.tags().items():
357 for t, n in self.tags().items():
358 self.nodetagscache.setdefault(n, []).append(t)
358 self.nodetagscache.setdefault(n, []).append(t)
359 return self.nodetagscache.get(node, [])
359 return self.nodetagscache.get(node, [])
360
360
361 def _branchtags(self, partial, lrev):
361 def _branchtags(self, partial, lrev):
362 tiprev = self.changelog.count() - 1
362 tiprev = self.changelog.count() - 1
363 if lrev != tiprev:
363 if lrev != tiprev:
364 self._updatebranchcache(partial, lrev+1, tiprev+1)
364 self._updatebranchcache(partial, lrev+1, tiprev+1)
365 self._writebranchcache(partial, self.changelog.tip(), tiprev)
365 self._writebranchcache(partial, self.changelog.tip(), tiprev)
366
366
367 return partial
367 return partial
368
368
369 def branchtags(self):
369 def branchtags(self):
370 tip = self.changelog.tip()
370 tip = self.changelog.tip()
371 if self.branchcache is not None and self._branchcachetip == tip:
371 if self.branchcache is not None and self._branchcachetip == tip:
372 return self.branchcache
372 return self.branchcache
373
373
374 oldtip = self._branchcachetip
374 oldtip = self._branchcachetip
375 self._branchcachetip = tip
375 self._branchcachetip = tip
376 if self.branchcache is None:
376 if self.branchcache is None:
377 self.branchcache = {} # avoid recursion in changectx
377 self.branchcache = {} # avoid recursion in changectx
378 else:
378 else:
379 self.branchcache.clear() # keep using the same dict
379 self.branchcache.clear() # keep using the same dict
380 if oldtip is None or oldtip not in self.changelog.nodemap:
380 if oldtip is None or oldtip not in self.changelog.nodemap:
381 partial, last, lrev = self._readbranchcache()
381 partial, last, lrev = self._readbranchcache()
382 else:
382 else:
383 lrev = self.changelog.rev(oldtip)
383 lrev = self.changelog.rev(oldtip)
384 partial = self._ubranchcache
384 partial = self._ubranchcache
385
385
386 self._branchtags(partial, lrev)
386 self._branchtags(partial, lrev)
387
387
388 # the branch cache is stored on disk as UTF-8, but in the local
388 # the branch cache is stored on disk as UTF-8, but in the local
389 # charset internally
389 # charset internally
390 for k, v in partial.items():
390 for k, v in partial.items():
391 self.branchcache[util.tolocal(k)] = v
391 self.branchcache[util.tolocal(k)] = v
392 self._ubranchcache = partial
392 self._ubranchcache = partial
393 return self.branchcache
393 return self.branchcache
394
394
395 def _readbranchcache(self):
395 def _readbranchcache(self):
396 partial = {}
396 partial = {}
397 try:
397 try:
398 f = self.opener("branch.cache")
398 f = self.opener("branch.cache")
399 lines = f.read().split('\n')
399 lines = f.read().split('\n')
400 f.close()
400 f.close()
401 except (IOError, OSError):
401 except (IOError, OSError):
402 return {}, nullid, nullrev
402 return {}, nullid, nullrev
403
403
404 try:
404 try:
405 last, lrev = lines.pop(0).split(" ", 1)
405 last, lrev = lines.pop(0).split(" ", 1)
406 last, lrev = bin(last), int(lrev)
406 last, lrev = bin(last), int(lrev)
407 if not (lrev < self.changelog.count() and
407 if not (lrev < self.changelog.count() and
408 self.changelog.node(lrev) == last): # sanity check
408 self.changelog.node(lrev) == last): # sanity check
409 # invalidate the cache
409 # invalidate the cache
410 raise ValueError('invalidating branch cache (tip differs)')
410 raise ValueError('invalidating branch cache (tip differs)')
411 for l in lines:
411 for l in lines:
412 if not l: continue
412 if not l: continue
413 node, label = l.split(" ", 1)
413 node, label = l.split(" ", 1)
414 partial[label.strip()] = bin(node)
414 partial[label.strip()] = bin(node)
415 except (KeyboardInterrupt, util.SignalInterrupt):
415 except (KeyboardInterrupt, util.SignalInterrupt):
416 raise
416 raise
417 except Exception, inst:
417 except Exception, inst:
418 if self.ui.debugflag:
418 if self.ui.debugflag:
419 self.ui.warn(str(inst), '\n')
419 self.ui.warn(str(inst), '\n')
420 partial, last, lrev = {}, nullid, nullrev
420 partial, last, lrev = {}, nullid, nullrev
421 return partial, last, lrev
421 return partial, last, lrev
422
422
423 def _writebranchcache(self, branches, tip, tiprev):
423 def _writebranchcache(self, branches, tip, tiprev):
424 try:
424 try:
425 f = self.opener("branch.cache", "w", atomictemp=True)
425 f = self.opener("branch.cache", "w", atomictemp=True)
426 f.write("%s %s\n" % (hex(tip), tiprev))
426 f.write("%s %s\n" % (hex(tip), tiprev))
427 for label, node in branches.iteritems():
427 for label, node in branches.iteritems():
428 f.write("%s %s\n" % (hex(node), label))
428 f.write("%s %s\n" % (hex(node), label))
429 f.rename()
429 f.rename()
430 except (IOError, OSError):
430 except (IOError, OSError):
431 pass
431 pass
432
432
433 def _updatebranchcache(self, partial, start, end):
433 def _updatebranchcache(self, partial, start, end):
434 for r in xrange(start, end):
434 for r in xrange(start, end):
435 c = self.changectx(r)
435 c = self.changectx(r)
436 b = c.branch()
436 b = c.branch()
437 partial[b] = c.node()
437 partial[b] = c.node()
438
438
439 def lookup(self, key):
439 def lookup(self, key):
440 if key == '.':
440 if key == '.':
441 key, second = self.dirstate.parents()
441 key, second = self.dirstate.parents()
442 if key == nullid:
442 if key == nullid:
443 raise repo.RepoError(_("no revision checked out"))
443 raise repo.RepoError(_("no revision checked out"))
444 if second != nullid:
444 if second != nullid:
445 self.ui.warn(_("warning: working directory has two parents, "
445 self.ui.warn(_("warning: working directory has two parents, "
446 "tag '.' uses the first\n"))
446 "tag '.' uses the first\n"))
447 elif key == 'null':
447 elif key == 'null':
448 return nullid
448 return nullid
449 n = self.changelog._match(key)
449 n = self.changelog._match(key)
450 if n:
450 if n:
451 return n
451 return n
452 if key in self.tags():
452 if key in self.tags():
453 return self.tags()[key]
453 return self.tags()[key]
454 if key in self.branchtags():
454 if key in self.branchtags():
455 return self.branchtags()[key]
455 return self.branchtags()[key]
456 n = self.changelog._partialmatch(key)
456 n = self.changelog._partialmatch(key)
457 if n:
457 if n:
458 return n
458 return n
459 try:
459 try:
460 if len(key) == 20:
460 if len(key) == 20:
461 key = hex(key)
461 key = hex(key)
462 except:
462 except:
463 pass
463 pass
464 raise repo.RepoError(_("unknown revision '%s'") % key)
464 raise repo.RepoError(_("unknown revision '%s'") % key)
465
465
466 def local(self):
466 def local(self):
467 return True
467 return True
468
468
469 def join(self, f):
469 def join(self, f):
470 return os.path.join(self.path, f)
470 return os.path.join(self.path, f)
471
471
472 def sjoin(self, f):
472 def sjoin(self, f):
473 f = self.encodefn(f)
473 f = self.encodefn(f)
474 return os.path.join(self.spath, f)
474 return os.path.join(self.spath, f)
475
475
476 def wjoin(self, f):
476 def wjoin(self, f):
477 return os.path.join(self.root, f)
477 return os.path.join(self.root, f)
478
478
479 def rjoin(self, f):
479 def rjoin(self, f):
480 return os.path.join(self.root, util.pconvert(f))
480 return os.path.join(self.root, util.pconvert(f))
481
481
482 def file(self, f):
482 def file(self, f):
483 if f[0] == '/':
483 if f[0] == '/':
484 f = f[1:]
484 f = f[1:]
485 return filelog.filelog(self.sopener, f)
485 return filelog.filelog(self.sopener, f)
486
486
487 def changectx(self, changeid=None):
487 def changectx(self, changeid=None):
488 return context.changectx(self, changeid)
488 return context.changectx(self, changeid)
489
489
490 def workingctx(self):
490 def workingctx(self):
491 return context.workingctx(self)
491 return context.workingctx(self)
492
492
493 def parents(self, changeid=None):
493 def parents(self, changeid=None):
494 '''
494 '''
495 get list of changectxs for parents of changeid or working directory
495 get list of changectxs for parents of changeid or working directory
496 '''
496 '''
497 if changeid is None:
497 if changeid is None:
498 pl = self.dirstate.parents()
498 pl = self.dirstate.parents()
499 else:
499 else:
500 n = self.changelog.lookup(changeid)
500 n = self.changelog.lookup(changeid)
501 pl = self.changelog.parents(n)
501 pl = self.changelog.parents(n)
502 if pl[1] == nullid:
502 if pl[1] == nullid:
503 return [self.changectx(pl[0])]
503 return [self.changectx(pl[0])]
504 return [self.changectx(pl[0]), self.changectx(pl[1])]
504 return [self.changectx(pl[0]), self.changectx(pl[1])]
505
505
506 def filectx(self, path, changeid=None, fileid=None):
506 def filectx(self, path, changeid=None, fileid=None):
507 """changeid can be a changeset revision, node, or tag.
507 """changeid can be a changeset revision, node, or tag.
508 fileid can be a file revision or node."""
508 fileid can be a file revision or node."""
509 return context.filectx(self, path, changeid, fileid)
509 return context.filectx(self, path, changeid, fileid)
510
510
511 def getcwd(self):
511 def getcwd(self):
512 return self.dirstate.getcwd()
512 return self.dirstate.getcwd()
513
513
514 def pathto(self, f, cwd=None):
514 def pathto(self, f, cwd=None):
515 return self.dirstate.pathto(f, cwd)
515 return self.dirstate.pathto(f, cwd)
516
516
517 def wfile(self, f, mode='r'):
517 def wfile(self, f, mode='r'):
518 return self.wopener(f, mode)
518 return self.wopener(f, mode)
519
519
520 def _link(self, f):
520 def _link(self, f):
521 return os.path.islink(self.wjoin(f))
521 return os.path.islink(self.wjoin(f))
522
522
523 def _filter(self, filter, filename, data):
523 def _filter(self, filter, filename, data):
524 if filter not in self.filterpats:
524 if filter not in self.filterpats:
525 l = []
525 l = []
526 for pat, cmd in self.ui.configitems(filter):
526 for pat, cmd in self.ui.configitems(filter):
527 mf = util.matcher(self.root, "", [pat], [], [])[1]
527 mf = util.matcher(self.root, "", [pat], [], [])[1]
528 fn = None
528 fn = None
529 params = cmd
529 params = cmd
530 for name, filterfn in self._datafilters.iteritems():
530 for name, filterfn in self._datafilters.iteritems():
531 if cmd.startswith(name):
531 if cmd.startswith(name):
532 fn = filterfn
532 fn = filterfn
533 params = cmd[len(name):].lstrip()
533 params = cmd[len(name):].lstrip()
534 break
534 break
535 if not fn:
535 if not fn:
536 fn = lambda s, c, **kwargs: util.filter(s, c)
536 fn = lambda s, c, **kwargs: util.filter(s, c)
537 # Wrap old filters not supporting keyword arguments
537 # Wrap old filters not supporting keyword arguments
538 if not inspect.getargspec(fn)[2]:
538 if not inspect.getargspec(fn)[2]:
539 oldfn = fn
539 oldfn = fn
540 fn = lambda s, c, **kwargs: oldfn(s, c)
540 fn = lambda s, c, **kwargs: oldfn(s, c)
541 l.append((mf, fn, params))
541 l.append((mf, fn, params))
542 self.filterpats[filter] = l
542 self.filterpats[filter] = l
543
543
544 for mf, fn, cmd in self.filterpats[filter]:
544 for mf, fn, cmd in self.filterpats[filter]:
545 if mf(filename):
545 if mf(filename):
546 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
546 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
547 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
547 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
548 break
548 break
549
549
550 return data
550 return data
551
551
552 def adddatafilter(self, name, filter):
552 def adddatafilter(self, name, filter):
553 self._datafilters[name] = filter
553 self._datafilters[name] = filter
554
554
555 def wread(self, filename):
555 def wread(self, filename):
556 if self._link(filename):
556 if self._link(filename):
557 data = os.readlink(self.wjoin(filename))
557 data = os.readlink(self.wjoin(filename))
558 else:
558 else:
559 data = self.wopener(filename, 'r').read()
559 data = self.wopener(filename, 'r').read()
560 return self._filter("encode", filename, data)
560 return self._filter("encode", filename, data)
561
561
562 def wwrite(self, filename, data, flags):
562 def wwrite(self, filename, data, flags):
563 data = self._filter("decode", filename, data)
563 data = self._filter("decode", filename, data)
564 try:
564 try:
565 os.unlink(self.wjoin(filename))
565 os.unlink(self.wjoin(filename))
566 except OSError:
566 except OSError:
567 pass
567 pass
568 self.wopener(filename, 'w').write(data)
568 self.wopener(filename, 'w').write(data)
569 util.set_flags(self.wjoin(filename), flags)
569 util.set_flags(self.wjoin(filename), flags)
570
570
571 def wwritedata(self, filename, data):
571 def wwritedata(self, filename, data):
572 return self._filter("decode", filename, data)
572 return self._filter("decode", filename, data)
573
573
574 def transaction(self):
574 def transaction(self):
575 if self._transref and self._transref():
575 if self._transref and self._transref():
576 return self._transref().nest()
576 return self._transref().nest()
577
577
578 # abort here if the journal already exists
578 # abort here if the journal already exists
579 if os.path.exists(self.sjoin("journal")):
579 if os.path.exists(self.sjoin("journal")):
580 raise repo.RepoError(_("journal already exists - run hg recover"))
580 raise repo.RepoError(_("journal already exists - run hg recover"))
581
581
582 # save dirstate for rollback
582 # save dirstate for rollback
583 try:
583 try:
584 ds = self.opener("dirstate").read()
584 ds = self.opener("dirstate").read()
585 except IOError:
585 except IOError:
586 ds = ""
586 ds = ""
587 self.opener("journal.dirstate", "w").write(ds)
587 self.opener("journal.dirstate", "w").write(ds)
588 self.opener("journal.branch", "w").write(self.dirstate.branch())
588 self.opener("journal.branch", "w").write(self.dirstate.branch())
589
589
590 renames = [(self.sjoin("journal"), self.sjoin("undo")),
590 renames = [(self.sjoin("journal"), self.sjoin("undo")),
591 (self.join("journal.dirstate"), self.join("undo.dirstate")),
591 (self.join("journal.dirstate"), self.join("undo.dirstate")),
592 (self.join("journal.branch"), self.join("undo.branch"))]
592 (self.join("journal.branch"), self.join("undo.branch"))]
593 tr = transaction.transaction(self.ui.warn, self.sopener,
593 tr = transaction.transaction(self.ui.warn, self.sopener,
594 self.sjoin("journal"),
594 self.sjoin("journal"),
595 aftertrans(renames),
595 aftertrans(renames),
596 self._createmode)
596 self._createmode)
597 self._transref = weakref.ref(tr)
597 self._transref = weakref.ref(tr)
598 return tr
598 return tr
599
599
600 def recover(self):
600 def recover(self):
601 l = self.lock()
601 l = self.lock()
602 try:
602 try:
603 if os.path.exists(self.sjoin("journal")):
603 if os.path.exists(self.sjoin("journal")):
604 self.ui.status(_("rolling back interrupted transaction\n"))
604 self.ui.status(_("rolling back interrupted transaction\n"))
605 transaction.rollback(self.sopener, self.sjoin("journal"))
605 transaction.rollback(self.sopener, self.sjoin("journal"))
606 self.invalidate()
606 self.invalidate()
607 return True
607 return True
608 else:
608 else:
609 self.ui.warn(_("no interrupted transaction available\n"))
609 self.ui.warn(_("no interrupted transaction available\n"))
610 return False
610 return False
611 finally:
611 finally:
612 del l
612 del l
613
613
614 def rollback(self):
614 def rollback(self):
615 wlock = lock = None
615 wlock = lock = None
616 try:
616 try:
617 wlock = self.wlock()
617 wlock = self.wlock()
618 lock = self.lock()
618 lock = self.lock()
619 if os.path.exists(self.sjoin("undo")):
619 if os.path.exists(self.sjoin("undo")):
620 self.ui.status(_("rolling back last transaction\n"))
620 self.ui.status(_("rolling back last transaction\n"))
621 transaction.rollback(self.sopener, self.sjoin("undo"))
621 transaction.rollback(self.sopener, self.sjoin("undo"))
622 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
622 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
623 try:
623 try:
624 branch = self.opener("undo.branch").read()
624 branch = self.opener("undo.branch").read()
625 self.dirstate.setbranch(branch)
625 self.dirstate.setbranch(branch)
626 except IOError:
626 except IOError:
627 self.ui.warn(_("Named branch could not be reset, "
627 self.ui.warn(_("Named branch could not be reset, "
628 "current branch still is: %s\n")
628 "current branch still is: %s\n")
629 % util.tolocal(self.dirstate.branch()))
629 % util.tolocal(self.dirstate.branch()))
630 self.invalidate()
630 self.invalidate()
631 self.dirstate.invalidate()
631 self.dirstate.invalidate()
632 else:
632 else:
633 self.ui.warn(_("no rollback information available\n"))
633 self.ui.warn(_("no rollback information available\n"))
634 finally:
634 finally:
635 del lock, wlock
635 del lock, wlock
636
636
637 def invalidate(self):
637 def invalidate(self):
638 for a in "changelog manifest".split():
638 for a in "changelog manifest".split():
639 if a in self.__dict__:
639 if a in self.__dict__:
640 delattr(self, a)
640 delattr(self, a)
641 self.tagscache = None
641 self.tagscache = None
642 self._tagstypecache = None
642 self._tagstypecache = None
643 self.nodetagscache = None
643 self.nodetagscache = None
644 self.branchcache = None
644 self.branchcache = None
645 self._ubranchcache = None
645 self._ubranchcache = None
646 self._branchcachetip = None
646 self._branchcachetip = None
647
647
648 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
648 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
649 try:
649 try:
650 l = lock.lock(lockname, 0, releasefn, desc=desc)
650 l = lock.lock(lockname, 0, releasefn, desc=desc)
651 except lock.LockHeld, inst:
651 except lock.LockHeld, inst:
652 if not wait:
652 if not wait:
653 raise
653 raise
654 self.ui.warn(_("waiting for lock on %s held by %r\n") %
654 self.ui.warn(_("waiting for lock on %s held by %r\n") %
655 (desc, inst.locker))
655 (desc, inst.locker))
656 # default to 600 seconds timeout
656 # default to 600 seconds timeout
657 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
657 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
658 releasefn, desc=desc)
658 releasefn, desc=desc)
659 if acquirefn:
659 if acquirefn:
660 acquirefn()
660 acquirefn()
661 return l
661 return l
662
662
663 def lock(self, wait=True):
663 def lock(self, wait=True):
664 if self._lockref and self._lockref():
664 if self._lockref and self._lockref():
665 return self._lockref()
665 return self._lockref()
666
666
667 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
667 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
668 _('repository %s') % self.origroot)
668 _('repository %s') % self.origroot)
669 self._lockref = weakref.ref(l)
669 self._lockref = weakref.ref(l)
670 return l
670 return l
671
671
672 def wlock(self, wait=True):
672 def wlock(self, wait=True):
673 if self._wlockref and self._wlockref():
673 if self._wlockref and self._wlockref():
674 return self._wlockref()
674 return self._wlockref()
675
675
676 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
676 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
677 self.dirstate.invalidate, _('working directory of %s') %
677 self.dirstate.invalidate, _('working directory of %s') %
678 self.origroot)
678 self.origroot)
679 self._wlockref = weakref.ref(l)
679 self._wlockref = weakref.ref(l)
680 return l
680 return l
681
681
682 def filecommit(self, fn, manifest1, manifest2, linkrev, tr, changelist):
682 def filecommit(self, fn, manifest1, manifest2, linkrev, tr, changelist):
683 """
683 """
684 commit an individual file as part of a larger transaction
684 commit an individual file as part of a larger transaction
685 """
685 """
686
686
687 t = self.wread(fn)
687 t = self.wread(fn)
688 fl = self.file(fn)
688 fl = self.file(fn)
689 fp1 = manifest1.get(fn, nullid)
689 fp1 = manifest1.get(fn, nullid)
690 fp2 = manifest2.get(fn, nullid)
690 fp2 = manifest2.get(fn, nullid)
691
691
692 meta = {}
692 meta = {}
693 cp = self.dirstate.copied(fn)
693 cp = self.dirstate.copied(fn)
694 if cp:
694 if cp:
695 # Mark the new revision of this file as a copy of another
695 # Mark the new revision of this file as a copy of another
696 # file. This copy data will effectively act as a parent
696 # file. This copy data will effectively act as a parent
697 # of this new revision. If this is a merge, the first
697 # of this new revision. If this is a merge, the first
698 # parent will be the nullid (meaning "look up the copy data")
698 # parent will be the nullid (meaning "look up the copy data")
699 # and the second one will be the other parent. For example:
699 # and the second one will be the other parent. For example:
700 #
700 #
701 # 0 --- 1 --- 3 rev1 changes file foo
701 # 0 --- 1 --- 3 rev1 changes file foo
702 # \ / rev2 renames foo to bar and changes it
702 # \ / rev2 renames foo to bar and changes it
703 # \- 2 -/ rev3 should have bar with all changes and
703 # \- 2 -/ rev3 should have bar with all changes and
704 # should record that bar descends from
704 # should record that bar descends from
705 # bar in rev2 and foo in rev1
705 # bar in rev2 and foo in rev1
706 #
706 #
707 # this allows this merge to succeed:
707 # this allows this merge to succeed:
708 #
708 #
709 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
709 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
710 # \ / merging rev3 and rev4 should use bar@rev2
710 # \ / merging rev3 and rev4 should use bar@rev2
711 # \- 2 --- 4 as the merge base
711 # \- 2 --- 4 as the merge base
712 #
712 #
713 meta["copy"] = cp
713 meta["copy"] = cp
714 if not manifest2: # not a branch merge
714 if not manifest2: # not a branch merge
715 meta["copyrev"] = hex(manifest1[cp])
715 meta["copyrev"] = hex(manifest1[cp])
716 fp2 = nullid
716 fp2 = nullid
717 elif fp2 != nullid: # copied on remote side
717 elif fp2 != nullid: # copied on remote side
718 meta["copyrev"] = hex(manifest1[cp])
718 meta["copyrev"] = hex(manifest1[cp])
719 elif fp1 != nullid: # copied on local side, reversed
719 elif fp1 != nullid: # copied on local side, reversed
720 meta["copyrev"] = hex(manifest2[cp])
720 meta["copyrev"] = hex(manifest2[cp])
721 fp2 = fp1
721 fp2 = fp1
722 elif cp in manifest2: # directory rename on local side
722 elif cp in manifest2: # directory rename on local side
723 meta["copyrev"] = hex(manifest2[cp])
723 meta["copyrev"] = hex(manifest2[cp])
724 else: # directory rename on remote side
724 else: # directory rename on remote side
725 meta["copyrev"] = hex(manifest1[cp])
725 meta["copyrev"] = hex(manifest1[cp])
726 self.ui.debug(_(" %s: copy %s:%s\n") %
726 self.ui.debug(_(" %s: copy %s:%s\n") %
727 (fn, cp, meta["copyrev"]))
727 (fn, cp, meta["copyrev"]))
728 fp1 = nullid
728 fp1 = nullid
729 elif fp2 != nullid:
729 elif fp2 != nullid:
730 # is one parent an ancestor of the other?
730 # is one parent an ancestor of the other?
731 fpa = fl.ancestor(fp1, fp2)
731 fpa = fl.ancestor(fp1, fp2)
732 if fpa == fp1:
732 if fpa == fp1:
733 fp1, fp2 = fp2, nullid
733 fp1, fp2 = fp2, nullid
734 elif fpa == fp2:
734 elif fpa == fp2:
735 fp2 = nullid
735 fp2 = nullid
736
736
737 # is the file unmodified from the parent? report existing entry
737 # is the file unmodified from the parent? report existing entry
738 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
738 if fp2 == nullid and not fl.cmp(fp1, t) and not meta:
739 return fp1
739 return fp1
740
740
741 changelist.append(fn)
741 changelist.append(fn)
742 return fl.add(t, meta, tr, linkrev, fp1, fp2)
742 return fl.add(t, meta, tr, linkrev, fp1, fp2)
743
743
744 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
744 def rawcommit(self, files, text, user, date, p1=None, p2=None, extra={}):
745 if p1 is None:
745 if p1 is None:
746 p1, p2 = self.dirstate.parents()
746 p1, p2 = self.dirstate.parents()
747 return self.commit(files=files, text=text, user=user, date=date,
747 return self.commit(files=files, text=text, user=user, date=date,
748 p1=p1, p2=p2, extra=extra, empty_ok=True)
748 p1=p1, p2=p2, extra=extra, empty_ok=True)
749
749
750 def commit(self, files=None, text="", user=None, date=None,
750 def commit(self, files=None, text="", user=None, date=None,
751 match=util.always, force=False, force_editor=False,
751 match=util.always, force=False, force_editor=False,
752 p1=None, p2=None, extra={}, empty_ok=False):
752 p1=None, p2=None, extra={}, empty_ok=False):
753 wlock = lock = tr = None
753 wlock = lock = tr = None
754 valid = 0 # don't save the dirstate if this isn't set
754 valid = 0 # don't save the dirstate if this isn't set
755 if files:
755 if files:
756 files = util.unique(files)
756 files = util.unique(files)
757 try:
757 try:
758 wlock = self.wlock()
758 wlock = self.wlock()
759 lock = self.lock()
759 lock = self.lock()
760 commit = []
760 commit = []
761 remove = []
761 remove = []
762 changed = []
762 changed = []
763 use_dirstate = (p1 is None) # not rawcommit
763 use_dirstate = (p1 is None) # not rawcommit
764 extra = extra.copy()
764 extra = extra.copy()
765
765
766 if use_dirstate:
766 if use_dirstate:
767 if files:
767 if files:
768 for f in files:
768 for f in files:
769 s = self.dirstate[f]
769 s = self.dirstate[f]
770 if s in 'nma':
770 if s in 'nma':
771 commit.append(f)
771 commit.append(f)
772 elif s == 'r':
772 elif s == 'r':
773 remove.append(f)
773 remove.append(f)
774 else:
774 else:
775 self.ui.warn(_("%s not tracked!\n") % f)
775 self.ui.warn(_("%s not tracked!\n") % f)
776 else:
776 else:
777 changes = self.status(match=match)[:5]
777 changes = self.status(match=match)[:5]
778 modified, added, removed, deleted, unknown = changes
778 modified, added, removed, deleted, unknown = changes
779 commit = modified + added
779 commit = modified + added
780 remove = removed
780 remove = removed
781 else:
781 else:
782 commit = files
782 commit = files
783
783
784 if use_dirstate:
784 if use_dirstate:
785 p1, p2 = self.dirstate.parents()
785 p1, p2 = self.dirstate.parents()
786 update_dirstate = True
786 update_dirstate = True
787
787
788 if (not force and p2 != nullid and
788 if (not force and p2 != nullid and
789 (files or match != util.always)):
789 (match.files() or match.anypats())):
790 raise util.Abort(_('cannot partially commit a merge '
790 raise util.Abort(_('cannot partially commit a merge '
791 '(do not specify files or patterns)'))
791 '(do not specify files or patterns)'))
792 else:
792 else:
793 p1, p2 = p1, p2 or nullid
793 p1, p2 = p1, p2 or nullid
794 update_dirstate = (self.dirstate.parents()[0] == p1)
794 update_dirstate = (self.dirstate.parents()[0] == p1)
795
795
796 c1 = self.changelog.read(p1)
796 c1 = self.changelog.read(p1)
797 c2 = self.changelog.read(p2)
797 c2 = self.changelog.read(p2)
798 m1 = self.manifest.read(c1[0]).copy()
798 m1 = self.manifest.read(c1[0]).copy()
799 m2 = self.manifest.read(c2[0])
799 m2 = self.manifest.read(c2[0])
800
800
801 if use_dirstate:
801 if use_dirstate:
802 branchname = self.workingctx().branch()
802 branchname = self.workingctx().branch()
803 try:
803 try:
804 branchname = branchname.decode('UTF-8').encode('UTF-8')
804 branchname = branchname.decode('UTF-8').encode('UTF-8')
805 except UnicodeDecodeError:
805 except UnicodeDecodeError:
806 raise util.Abort(_('branch name not in UTF-8!'))
806 raise util.Abort(_('branch name not in UTF-8!'))
807 else:
807 else:
808 branchname = ""
808 branchname = ""
809
809
810 if use_dirstate:
810 if use_dirstate:
811 oldname = c1[5].get("branch") # stored in UTF-8
811 oldname = c1[5].get("branch") # stored in UTF-8
812 if (not commit and not remove and not force and p2 == nullid
812 if (not commit and not remove and not force and p2 == nullid
813 and branchname == oldname):
813 and branchname == oldname):
814 self.ui.status(_("nothing changed\n"))
814 self.ui.status(_("nothing changed\n"))
815 return None
815 return None
816
816
817 xp1 = hex(p1)
817 xp1 = hex(p1)
818 if p2 == nullid: xp2 = ''
818 if p2 == nullid: xp2 = ''
819 else: xp2 = hex(p2)
819 else: xp2 = hex(p2)
820
820
821 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
821 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
822
822
823 tr = self.transaction()
823 tr = self.transaction()
824 trp = weakref.proxy(tr)
824 trp = weakref.proxy(tr)
825
825
826 # check in files
826 # check in files
827 new = {}
827 new = {}
828 linkrev = self.changelog.count()
828 linkrev = self.changelog.count()
829 commit.sort()
829 commit.sort()
830 is_exec = util.execfunc(self.root, m1.execf)
830 is_exec = util.execfunc(self.root, m1.execf)
831 is_link = util.linkfunc(self.root, m1.linkf)
831 is_link = util.linkfunc(self.root, m1.linkf)
832 for f in commit:
832 for f in commit:
833 self.ui.note(f + "\n")
833 self.ui.note(f + "\n")
834 try:
834 try:
835 new[f] = self.filecommit(f, m1, m2, linkrev, trp, changed)
835 new[f] = self.filecommit(f, m1, m2, linkrev, trp, changed)
836 new_exec = is_exec(f)
836 new_exec = is_exec(f)
837 new_link = is_link(f)
837 new_link = is_link(f)
838 if ((not changed or changed[-1] != f) and
838 if ((not changed or changed[-1] != f) and
839 m2.get(f) != new[f]):
839 m2.get(f) != new[f]):
840 # mention the file in the changelog if some
840 # mention the file in the changelog if some
841 # flag changed, even if there was no content
841 # flag changed, even if there was no content
842 # change.
842 # change.
843 old_exec = m1.execf(f)
843 old_exec = m1.execf(f)
844 old_link = m1.linkf(f)
844 old_link = m1.linkf(f)
845 if old_exec != new_exec or old_link != new_link:
845 if old_exec != new_exec or old_link != new_link:
846 changed.append(f)
846 changed.append(f)
847 m1.set(f, new_exec, new_link)
847 m1.set(f, new_exec, new_link)
848 if use_dirstate:
848 if use_dirstate:
849 self.dirstate.normal(f)
849 self.dirstate.normal(f)
850
850
851 except (OSError, IOError):
851 except (OSError, IOError):
852 if use_dirstate:
852 if use_dirstate:
853 self.ui.warn(_("trouble committing %s!\n") % f)
853 self.ui.warn(_("trouble committing %s!\n") % f)
854 raise
854 raise
855 else:
855 else:
856 remove.append(f)
856 remove.append(f)
857
857
858 # update manifest
858 # update manifest
859 m1.update(new)
859 m1.update(new)
860 remove.sort()
860 remove.sort()
861 removed = []
861 removed = []
862
862
863 for f in remove:
863 for f in remove:
864 if f in m1:
864 if f in m1:
865 del m1[f]
865 del m1[f]
866 removed.append(f)
866 removed.append(f)
867 elif f in m2:
867 elif f in m2:
868 removed.append(f)
868 removed.append(f)
869 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
869 mn = self.manifest.add(m1, trp, linkrev, c1[0], c2[0],
870 (new, removed))
870 (new, removed))
871
871
872 # add changeset
872 # add changeset
873 new = new.keys()
873 new = new.keys()
874 new.sort()
874 new.sort()
875
875
876 user = user or self.ui.username()
876 user = user or self.ui.username()
877 if (not empty_ok and not text) or force_editor:
877 if (not empty_ok and not text) or force_editor:
878 edittext = []
878 edittext = []
879 if text:
879 if text:
880 edittext.append(text)
880 edittext.append(text)
881 edittext.append("")
881 edittext.append("")
882 edittext.append(_("HG: Enter commit message."
882 edittext.append(_("HG: Enter commit message."
883 " Lines beginning with 'HG:' are removed."))
883 " Lines beginning with 'HG:' are removed."))
884 edittext.append("HG: --")
884 edittext.append("HG: --")
885 edittext.append("HG: user: %s" % user)
885 edittext.append("HG: user: %s" % user)
886 if p2 != nullid:
886 if p2 != nullid:
887 edittext.append("HG: branch merge")
887 edittext.append("HG: branch merge")
888 if branchname:
888 if branchname:
889 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
889 edittext.append("HG: branch '%s'" % util.tolocal(branchname))
890 edittext.extend(["HG: changed %s" % f for f in changed])
890 edittext.extend(["HG: changed %s" % f for f in changed])
891 edittext.extend(["HG: removed %s" % f for f in removed])
891 edittext.extend(["HG: removed %s" % f for f in removed])
892 if not changed and not remove:
892 if not changed and not remove:
893 edittext.append("HG: no files changed")
893 edittext.append("HG: no files changed")
894 edittext.append("")
894 edittext.append("")
895 # run editor in the repository root
895 # run editor in the repository root
896 olddir = os.getcwd()
896 olddir = os.getcwd()
897 os.chdir(self.root)
897 os.chdir(self.root)
898 text = self.ui.edit("\n".join(edittext), user)
898 text = self.ui.edit("\n".join(edittext), user)
899 os.chdir(olddir)
899 os.chdir(olddir)
900
900
901 if branchname:
901 if branchname:
902 extra["branch"] = branchname
902 extra["branch"] = branchname
903
903
904 lines = [line.rstrip() for line in text.rstrip().splitlines()]
904 lines = [line.rstrip() for line in text.rstrip().splitlines()]
905 while lines and not lines[0]:
905 while lines and not lines[0]:
906 del lines[0]
906 del lines[0]
907 if not lines and use_dirstate:
907 if not lines and use_dirstate:
908 raise util.Abort(_("empty commit message"))
908 raise util.Abort(_("empty commit message"))
909 text = '\n'.join(lines)
909 text = '\n'.join(lines)
910
910
911 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
911 n = self.changelog.add(mn, changed + removed, text, trp, p1, p2,
912 user, date, extra)
912 user, date, extra)
913 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
913 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
914 parent2=xp2)
914 parent2=xp2)
915 tr.close()
915 tr.close()
916
916
917 if self.branchcache:
917 if self.branchcache:
918 self.branchtags()
918 self.branchtags()
919
919
920 if use_dirstate or update_dirstate:
920 if use_dirstate or update_dirstate:
921 self.dirstate.setparents(n)
921 self.dirstate.setparents(n)
922 if use_dirstate:
922 if use_dirstate:
923 for f in removed:
923 for f in removed:
924 self.dirstate.forget(f)
924 self.dirstate.forget(f)
925 valid = 1 # our dirstate updates are complete
925 valid = 1 # our dirstate updates are complete
926
926
927 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
927 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
928 return n
928 return n
929 finally:
929 finally:
930 if not valid: # don't save our updated dirstate
930 if not valid: # don't save our updated dirstate
931 self.dirstate.invalidate()
931 self.dirstate.invalidate()
932 del tr, lock, wlock
932 del tr, lock, wlock
933
933
934 def walk(self, node, files, match, badmatch):
934 def walk(self, node, files, match, badmatch):
935 '''
935 '''
936 walk recursively through the directory tree or a given
936 walk recursively through the directory tree or a given
937 changeset, finding all files matched by the match
937 changeset, finding all files matched by the match
938 function
938 function
939
939
940 results are yielded in a tuple (src, filename), where src
940 results are yielded in a tuple (src, filename), where src
941 is one of:
941 is one of:
942 'f' the file was found in the directory tree
942 'f' the file was found in the directory tree
943 'm' the file was only in the dirstate and not in the tree
943 'm' the file was only in the dirstate and not in the tree
944 'b' file was not found and matched badmatch
944 'b' file was not found and matched badmatch
945 '''
945 '''
946
946
947 if node:
947 if node:
948 fdict = dict.fromkeys(files)
948 fdict = dict.fromkeys(files)
949 # for dirstate.walk, files=['.'] means "walk the whole tree".
949 # for dirstate.walk, files=['.'] means "walk the whole tree".
950 # follow that here, too
950 # follow that here, too
951 fdict.pop('.', None)
951 fdict.pop('.', None)
952 mdict = self.manifest.read(self.changelog.read(node)[0])
952 mdict = self.manifest.read(self.changelog.read(node)[0])
953 mfiles = mdict.keys()
953 mfiles = mdict.keys()
954 mfiles.sort()
954 mfiles.sort()
955 for fn in mfiles:
955 for fn in mfiles:
956 for ffn in fdict:
956 for ffn in fdict:
957 # match if the file is the exact name or a directory
957 # match if the file is the exact name or a directory
958 if ffn == fn or fn.startswith("%s/" % ffn):
958 if ffn == fn or fn.startswith("%s/" % ffn):
959 del fdict[ffn]
959 del fdict[ffn]
960 break
960 break
961 if match(fn):
961 if match(fn):
962 yield 'm', fn
962 yield 'm', fn
963 ffiles = fdict.keys()
963 ffiles = fdict.keys()
964 ffiles.sort()
964 ffiles.sort()
965 for fn in ffiles:
965 for fn in ffiles:
966 if badmatch and badmatch(fn):
966 if badmatch and badmatch(fn):
967 if match(fn):
967 if match(fn):
968 yield 'b', fn
968 yield 'b', fn
969 else:
969 else:
970 self.ui.warn(_('%s: No such file in rev %s\n')
970 self.ui.warn(_('%s: No such file in rev %s\n')
971 % (self.pathto(fn), short(node)))
971 % (self.pathto(fn), short(node)))
972 else:
972 else:
973 for src, fn in self.dirstate.walk(files, match, badmatch):
973 for src, fn in self.dirstate.walk(files, match, badmatch):
974 yield src, fn
974 yield src, fn
975
975
976 def status(self, node1=None, node2=None, files=[], match=util.always,
976 def status(self, node1=None, node2=None, files=[], match=util.always,
977 list_ignored=False, list_clean=False, list_unknown=True):
977 list_ignored=False, list_clean=False, list_unknown=True):
978 """return status of files between two nodes or node and working directory
978 """return status of files between two nodes or node and working directory
979
979
980 If node1 is None, use the first dirstate parent instead.
980 If node1 is None, use the first dirstate parent instead.
981 If node2 is None, compare node1 with working directory.
981 If node2 is None, compare node1 with working directory.
982 """
982 """
983
983
984 def fcmp(fn, getnode):
984 def fcmp(fn, getnode):
985 t1 = self.wread(fn)
985 t1 = self.wread(fn)
986 return self.file(fn).cmp(getnode(fn), t1)
986 return self.file(fn).cmp(getnode(fn), t1)
987
987
988 def mfmatches(node):
988 def mfmatches(node):
989 change = self.changelog.read(node)
989 change = self.changelog.read(node)
990 mf = self.manifest.read(change[0]).copy()
990 mf = self.manifest.read(change[0]).copy()
991 for fn in mf.keys():
991 for fn in mf.keys():
992 if not match(fn):
992 if not match(fn):
993 del mf[fn]
993 del mf[fn]
994 return mf
994 return mf
995
995
996 modified, added, removed, deleted, unknown = [], [], [], [], []
996 modified, added, removed, deleted, unknown = [], [], [], [], []
997 ignored, clean = [], []
997 ignored, clean = [], []
998
998
999 compareworking = False
999 compareworking = False
1000 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
1000 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
1001 compareworking = True
1001 compareworking = True
1002
1002
1003 if not compareworking:
1003 if not compareworking:
1004 # read the manifest from node1 before the manifest from node2,
1004 # read the manifest from node1 before the manifest from node2,
1005 # so that we'll hit the manifest cache if we're going through
1005 # so that we'll hit the manifest cache if we're going through
1006 # all the revisions in parent->child order.
1006 # all the revisions in parent->child order.
1007 mf1 = mfmatches(node1)
1007 mf1 = mfmatches(node1)
1008
1008
1009 # are we comparing the working directory?
1009 # are we comparing the working directory?
1010 if not node2:
1010 if not node2:
1011 (lookup, modified, added, removed, deleted, unknown,
1011 (lookup, modified, added, removed, deleted, unknown,
1012 ignored, clean) = self.dirstate.status(files, match,
1012 ignored, clean) = self.dirstate.status(files, match,
1013 list_ignored, list_clean,
1013 list_ignored, list_clean,
1014 list_unknown)
1014 list_unknown)
1015
1015
1016 # are we comparing working dir against its parent?
1016 # are we comparing working dir against its parent?
1017 if compareworking:
1017 if compareworking:
1018 if lookup:
1018 if lookup:
1019 fixup = []
1019 fixup = []
1020 # do a full compare of any files that might have changed
1020 # do a full compare of any files that might have changed
1021 ctx = self.changectx()
1021 ctx = self.changectx()
1022 mexec = lambda f: 'x' in ctx.fileflags(f)
1022 mexec = lambda f: 'x' in ctx.fileflags(f)
1023 mlink = lambda f: 'l' in ctx.fileflags(f)
1023 mlink = lambda f: 'l' in ctx.fileflags(f)
1024 is_exec = util.execfunc(self.root, mexec)
1024 is_exec = util.execfunc(self.root, mexec)
1025 is_link = util.linkfunc(self.root, mlink)
1025 is_link = util.linkfunc(self.root, mlink)
1026 def flags(f):
1026 def flags(f):
1027 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1027 return is_link(f) and 'l' or is_exec(f) and 'x' or ''
1028 for f in lookup:
1028 for f in lookup:
1029 if (f not in ctx or flags(f) != ctx.fileflags(f)
1029 if (f not in ctx or flags(f) != ctx.fileflags(f)
1030 or ctx[f].cmp(self.wread(f))):
1030 or ctx[f].cmp(self.wread(f))):
1031 modified.append(f)
1031 modified.append(f)
1032 else:
1032 else:
1033 fixup.append(f)
1033 fixup.append(f)
1034 if list_clean:
1034 if list_clean:
1035 clean.append(f)
1035 clean.append(f)
1036
1036
1037 # update dirstate for files that are actually clean
1037 # update dirstate for files that are actually clean
1038 if fixup:
1038 if fixup:
1039 wlock = None
1039 wlock = None
1040 try:
1040 try:
1041 try:
1041 try:
1042 wlock = self.wlock(False)
1042 wlock = self.wlock(False)
1043 except lock.LockException:
1043 except lock.LockException:
1044 pass
1044 pass
1045 if wlock:
1045 if wlock:
1046 for f in fixup:
1046 for f in fixup:
1047 self.dirstate.normal(f)
1047 self.dirstate.normal(f)
1048 finally:
1048 finally:
1049 del wlock
1049 del wlock
1050 else:
1050 else:
1051 # we are comparing working dir against non-parent
1051 # we are comparing working dir against non-parent
1052 # generate a pseudo-manifest for the working dir
1052 # generate a pseudo-manifest for the working dir
1053 # XXX: create it in dirstate.py ?
1053 # XXX: create it in dirstate.py ?
1054 mf2 = mfmatches(self.dirstate.parents()[0])
1054 mf2 = mfmatches(self.dirstate.parents()[0])
1055 is_exec = util.execfunc(self.root, mf2.execf)
1055 is_exec = util.execfunc(self.root, mf2.execf)
1056 is_link = util.linkfunc(self.root, mf2.linkf)
1056 is_link = util.linkfunc(self.root, mf2.linkf)
1057 for f in lookup + modified + added:
1057 for f in lookup + modified + added:
1058 mf2[f] = ""
1058 mf2[f] = ""
1059 mf2.set(f, is_exec(f), is_link(f))
1059 mf2.set(f, is_exec(f), is_link(f))
1060 for f in removed:
1060 for f in removed:
1061 if f in mf2:
1061 if f in mf2:
1062 del mf2[f]
1062 del mf2[f]
1063
1063
1064 else:
1064 else:
1065 # we are comparing two revisions
1065 # we are comparing two revisions
1066 mf2 = mfmatches(node2)
1066 mf2 = mfmatches(node2)
1067
1067
1068 if not compareworking:
1068 if not compareworking:
1069 # flush lists from dirstate before comparing manifests
1069 # flush lists from dirstate before comparing manifests
1070 modified, added, clean = [], [], []
1070 modified, added, clean = [], [], []
1071
1071
1072 # make sure to sort the files so we talk to the disk in a
1072 # make sure to sort the files so we talk to the disk in a
1073 # reasonable order
1073 # reasonable order
1074 mf2keys = mf2.keys()
1074 mf2keys = mf2.keys()
1075 mf2keys.sort()
1075 mf2keys.sort()
1076 getnode = lambda fn: mf1.get(fn, nullid)
1076 getnode = lambda fn: mf1.get(fn, nullid)
1077 for fn in mf2keys:
1077 for fn in mf2keys:
1078 if fn in mf1:
1078 if fn in mf1:
1079 if (mf1.flags(fn) != mf2.flags(fn) or
1079 if (mf1.flags(fn) != mf2.flags(fn) or
1080 (mf1[fn] != mf2[fn] and
1080 (mf1[fn] != mf2[fn] and
1081 (mf2[fn] != "" or fcmp(fn, getnode)))):
1081 (mf2[fn] != "" or fcmp(fn, getnode)))):
1082 modified.append(fn)
1082 modified.append(fn)
1083 elif list_clean:
1083 elif list_clean:
1084 clean.append(fn)
1084 clean.append(fn)
1085 del mf1[fn]
1085 del mf1[fn]
1086 else:
1086 else:
1087 added.append(fn)
1087 added.append(fn)
1088
1088
1089 removed = mf1.keys()
1089 removed = mf1.keys()
1090
1090
1091 # sort and return results:
1091 # sort and return results:
1092 for l in modified, added, removed, deleted, unknown, ignored, clean:
1092 for l in modified, added, removed, deleted, unknown, ignored, clean:
1093 l.sort()
1093 l.sort()
1094 return (modified, added, removed, deleted, unknown, ignored, clean)
1094 return (modified, added, removed, deleted, unknown, ignored, clean)
1095
1095
1096 def add(self, list):
1096 def add(self, list):
1097 wlock = self.wlock()
1097 wlock = self.wlock()
1098 try:
1098 try:
1099 rejected = []
1099 rejected = []
1100 for f in list:
1100 for f in list:
1101 p = self.wjoin(f)
1101 p = self.wjoin(f)
1102 try:
1102 try:
1103 st = os.lstat(p)
1103 st = os.lstat(p)
1104 except:
1104 except:
1105 self.ui.warn(_("%s does not exist!\n") % f)
1105 self.ui.warn(_("%s does not exist!\n") % f)
1106 rejected.append(f)
1106 rejected.append(f)
1107 continue
1107 continue
1108 if st.st_size > 10000000:
1108 if st.st_size > 10000000:
1109 self.ui.warn(_("%s: files over 10MB may cause memory and"
1109 self.ui.warn(_("%s: files over 10MB may cause memory and"
1110 " performance problems\n"
1110 " performance problems\n"
1111 "(use 'hg revert %s' to unadd the file)\n")
1111 "(use 'hg revert %s' to unadd the file)\n")
1112 % (f, f))
1112 % (f, f))
1113 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1113 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1114 self.ui.warn(_("%s not added: only files and symlinks "
1114 self.ui.warn(_("%s not added: only files and symlinks "
1115 "supported currently\n") % f)
1115 "supported currently\n") % f)
1116 rejected.append(p)
1116 rejected.append(p)
1117 elif self.dirstate[f] in 'amn':
1117 elif self.dirstate[f] in 'amn':
1118 self.ui.warn(_("%s already tracked!\n") % f)
1118 self.ui.warn(_("%s already tracked!\n") % f)
1119 elif self.dirstate[f] == 'r':
1119 elif self.dirstate[f] == 'r':
1120 self.dirstate.normallookup(f)
1120 self.dirstate.normallookup(f)
1121 else:
1121 else:
1122 self.dirstate.add(f)
1122 self.dirstate.add(f)
1123 return rejected
1123 return rejected
1124 finally:
1124 finally:
1125 del wlock
1125 del wlock
1126
1126
1127 def forget(self, list):
1127 def forget(self, list):
1128 wlock = self.wlock()
1128 wlock = self.wlock()
1129 try:
1129 try:
1130 for f in list:
1130 for f in list:
1131 if self.dirstate[f] != 'a':
1131 if self.dirstate[f] != 'a':
1132 self.ui.warn(_("%s not added!\n") % f)
1132 self.ui.warn(_("%s not added!\n") % f)
1133 else:
1133 else:
1134 self.dirstate.forget(f)
1134 self.dirstate.forget(f)
1135 finally:
1135 finally:
1136 del wlock
1136 del wlock
1137
1137
1138 def remove(self, list, unlink=False):
1138 def remove(self, list, unlink=False):
1139 wlock = None
1139 wlock = None
1140 try:
1140 try:
1141 if unlink:
1141 if unlink:
1142 for f in list:
1142 for f in list:
1143 try:
1143 try:
1144 util.unlink(self.wjoin(f))
1144 util.unlink(self.wjoin(f))
1145 except OSError, inst:
1145 except OSError, inst:
1146 if inst.errno != errno.ENOENT:
1146 if inst.errno != errno.ENOENT:
1147 raise
1147 raise
1148 wlock = self.wlock()
1148 wlock = self.wlock()
1149 for f in list:
1149 for f in list:
1150 if unlink and os.path.exists(self.wjoin(f)):
1150 if unlink and os.path.exists(self.wjoin(f)):
1151 self.ui.warn(_("%s still exists!\n") % f)
1151 self.ui.warn(_("%s still exists!\n") % f)
1152 elif self.dirstate[f] == 'a':
1152 elif self.dirstate[f] == 'a':
1153 self.dirstate.forget(f)
1153 self.dirstate.forget(f)
1154 elif f not in self.dirstate:
1154 elif f not in self.dirstate:
1155 self.ui.warn(_("%s not tracked!\n") % f)
1155 self.ui.warn(_("%s not tracked!\n") % f)
1156 else:
1156 else:
1157 self.dirstate.remove(f)
1157 self.dirstate.remove(f)
1158 finally:
1158 finally:
1159 del wlock
1159 del wlock
1160
1160
1161 def undelete(self, list):
1161 def undelete(self, list):
1162 wlock = None
1162 wlock = None
1163 try:
1163 try:
1164 manifests = [self.manifest.read(self.changelog.read(p)[0])
1164 manifests = [self.manifest.read(self.changelog.read(p)[0])
1165 for p in self.dirstate.parents() if p != nullid]
1165 for p in self.dirstate.parents() if p != nullid]
1166 wlock = self.wlock()
1166 wlock = self.wlock()
1167 for f in list:
1167 for f in list:
1168 if self.dirstate[f] != 'r':
1168 if self.dirstate[f] != 'r':
1169 self.ui.warn("%s not removed!\n" % f)
1169 self.ui.warn("%s not removed!\n" % f)
1170 else:
1170 else:
1171 m = f in manifests[0] and manifests[0] or manifests[1]
1171 m = f in manifests[0] and manifests[0] or manifests[1]
1172 t = self.file(f).read(m[f])
1172 t = self.file(f).read(m[f])
1173 self.wwrite(f, t, m.flags(f))
1173 self.wwrite(f, t, m.flags(f))
1174 self.dirstate.normal(f)
1174 self.dirstate.normal(f)
1175 finally:
1175 finally:
1176 del wlock
1176 del wlock
1177
1177
1178 def copy(self, source, dest):
1178 def copy(self, source, dest):
1179 wlock = None
1179 wlock = None
1180 try:
1180 try:
1181 p = self.wjoin(dest)
1181 p = self.wjoin(dest)
1182 if not (os.path.exists(p) or os.path.islink(p)):
1182 if not (os.path.exists(p) or os.path.islink(p)):
1183 self.ui.warn(_("%s does not exist!\n") % dest)
1183 self.ui.warn(_("%s does not exist!\n") % dest)
1184 elif not (os.path.isfile(p) or os.path.islink(p)):
1184 elif not (os.path.isfile(p) or os.path.islink(p)):
1185 self.ui.warn(_("copy failed: %s is not a file or a "
1185 self.ui.warn(_("copy failed: %s is not a file or a "
1186 "symbolic link\n") % dest)
1186 "symbolic link\n") % dest)
1187 else:
1187 else:
1188 wlock = self.wlock()
1188 wlock = self.wlock()
1189 if dest not in self.dirstate:
1189 if dest not in self.dirstate:
1190 self.dirstate.add(dest)
1190 self.dirstate.add(dest)
1191 self.dirstate.copy(source, dest)
1191 self.dirstate.copy(source, dest)
1192 finally:
1192 finally:
1193 del wlock
1193 del wlock
1194
1194
1195 def heads(self, start=None):
1195 def heads(self, start=None):
1196 heads = self.changelog.heads(start)
1196 heads = self.changelog.heads(start)
1197 # sort the output in rev descending order
1197 # sort the output in rev descending order
1198 heads = [(-self.changelog.rev(h), h) for h in heads]
1198 heads = [(-self.changelog.rev(h), h) for h in heads]
1199 heads.sort()
1199 heads.sort()
1200 return [n for (r, n) in heads]
1200 return [n for (r, n) in heads]
1201
1201
1202 def branchheads(self, branch, start=None):
1202 def branchheads(self, branch, start=None):
1203 branches = self.branchtags()
1203 branches = self.branchtags()
1204 if branch not in branches:
1204 if branch not in branches:
1205 return []
1205 return []
1206 # The basic algorithm is this:
1206 # The basic algorithm is this:
1207 #
1207 #
1208 # Start from the branch tip since there are no later revisions that can
1208 # Start from the branch tip since there are no later revisions that can
1209 # possibly be in this branch, and the tip is a guaranteed head.
1209 # possibly be in this branch, and the tip is a guaranteed head.
1210 #
1210 #
1211 # Remember the tip's parents as the first ancestors, since these by
1211 # Remember the tip's parents as the first ancestors, since these by
1212 # definition are not heads.
1212 # definition are not heads.
1213 #
1213 #
1214 # Step backwards from the brach tip through all the revisions. We are
1214 # Step backwards from the brach tip through all the revisions. We are
1215 # guaranteed by the rules of Mercurial that we will now be visiting the
1215 # guaranteed by the rules of Mercurial that we will now be visiting the
1216 # nodes in reverse topological order (children before parents).
1216 # nodes in reverse topological order (children before parents).
1217 #
1217 #
1218 # If a revision is one of the ancestors of a head then we can toss it
1218 # If a revision is one of the ancestors of a head then we can toss it
1219 # out of the ancestors set (we've already found it and won't be
1219 # out of the ancestors set (we've already found it and won't be
1220 # visiting it again) and put its parents in the ancestors set.
1220 # visiting it again) and put its parents in the ancestors set.
1221 #
1221 #
1222 # Otherwise, if a revision is in the branch it's another head, since it
1222 # Otherwise, if a revision is in the branch it's another head, since it
1223 # wasn't in the ancestor list of an existing head. So add it to the
1223 # wasn't in the ancestor list of an existing head. So add it to the
1224 # head list, and add its parents to the ancestor list.
1224 # head list, and add its parents to the ancestor list.
1225 #
1225 #
1226 # If it is not in the branch ignore it.
1226 # If it is not in the branch ignore it.
1227 #
1227 #
1228 # Once we have a list of heads, use nodesbetween to filter out all the
1228 # Once we have a list of heads, use nodesbetween to filter out all the
1229 # heads that cannot be reached from startrev. There may be a more
1229 # heads that cannot be reached from startrev. There may be a more
1230 # efficient way to do this as part of the previous algorithm.
1230 # efficient way to do this as part of the previous algorithm.
1231
1231
1232 set = util.set
1232 set = util.set
1233 heads = [self.changelog.rev(branches[branch])]
1233 heads = [self.changelog.rev(branches[branch])]
1234 # Don't care if ancestors contains nullrev or not.
1234 # Don't care if ancestors contains nullrev or not.
1235 ancestors = set(self.changelog.parentrevs(heads[0]))
1235 ancestors = set(self.changelog.parentrevs(heads[0]))
1236 for rev in xrange(heads[0] - 1, nullrev, -1):
1236 for rev in xrange(heads[0] - 1, nullrev, -1):
1237 if rev in ancestors:
1237 if rev in ancestors:
1238 ancestors.update(self.changelog.parentrevs(rev))
1238 ancestors.update(self.changelog.parentrevs(rev))
1239 ancestors.remove(rev)
1239 ancestors.remove(rev)
1240 elif self.changectx(rev).branch() == branch:
1240 elif self.changectx(rev).branch() == branch:
1241 heads.append(rev)
1241 heads.append(rev)
1242 ancestors.update(self.changelog.parentrevs(rev))
1242 ancestors.update(self.changelog.parentrevs(rev))
1243 heads = [self.changelog.node(rev) for rev in heads]
1243 heads = [self.changelog.node(rev) for rev in heads]
1244 if start is not None:
1244 if start is not None:
1245 heads = self.changelog.nodesbetween([start], heads)[2]
1245 heads = self.changelog.nodesbetween([start], heads)[2]
1246 return heads
1246 return heads
1247
1247
1248 def branches(self, nodes):
1248 def branches(self, nodes):
1249 if not nodes:
1249 if not nodes:
1250 nodes = [self.changelog.tip()]
1250 nodes = [self.changelog.tip()]
1251 b = []
1251 b = []
1252 for n in nodes:
1252 for n in nodes:
1253 t = n
1253 t = n
1254 while 1:
1254 while 1:
1255 p = self.changelog.parents(n)
1255 p = self.changelog.parents(n)
1256 if p[1] != nullid or p[0] == nullid:
1256 if p[1] != nullid or p[0] == nullid:
1257 b.append((t, n, p[0], p[1]))
1257 b.append((t, n, p[0], p[1]))
1258 break
1258 break
1259 n = p[0]
1259 n = p[0]
1260 return b
1260 return b
1261
1261
1262 def between(self, pairs):
1262 def between(self, pairs):
1263 r = []
1263 r = []
1264
1264
1265 for top, bottom in pairs:
1265 for top, bottom in pairs:
1266 n, l, i = top, [], 0
1266 n, l, i = top, [], 0
1267 f = 1
1267 f = 1
1268
1268
1269 while n != bottom:
1269 while n != bottom:
1270 p = self.changelog.parents(n)[0]
1270 p = self.changelog.parents(n)[0]
1271 if i == f:
1271 if i == f:
1272 l.append(n)
1272 l.append(n)
1273 f = f * 2
1273 f = f * 2
1274 n = p
1274 n = p
1275 i += 1
1275 i += 1
1276
1276
1277 r.append(l)
1277 r.append(l)
1278
1278
1279 return r
1279 return r
1280
1280
1281 def findincoming(self, remote, base=None, heads=None, force=False):
1281 def findincoming(self, remote, base=None, heads=None, force=False):
1282 """Return list of roots of the subsets of missing nodes from remote
1282 """Return list of roots of the subsets of missing nodes from remote
1283
1283
1284 If base dict is specified, assume that these nodes and their parents
1284 If base dict is specified, assume that these nodes and their parents
1285 exist on the remote side and that no child of a node of base exists
1285 exist on the remote side and that no child of a node of base exists
1286 in both remote and self.
1286 in both remote and self.
1287 Furthermore base will be updated to include the nodes that exists
1287 Furthermore base will be updated to include the nodes that exists
1288 in self and remote but no children exists in self and remote.
1288 in self and remote but no children exists in self and remote.
1289 If a list of heads is specified, return only nodes which are heads
1289 If a list of heads is specified, return only nodes which are heads
1290 or ancestors of these heads.
1290 or ancestors of these heads.
1291
1291
1292 All the ancestors of base are in self and in remote.
1292 All the ancestors of base are in self and in remote.
1293 All the descendants of the list returned are missing in self.
1293 All the descendants of the list returned are missing in self.
1294 (and so we know that the rest of the nodes are missing in remote, see
1294 (and so we know that the rest of the nodes are missing in remote, see
1295 outgoing)
1295 outgoing)
1296 """
1296 """
1297 m = self.changelog.nodemap
1297 m = self.changelog.nodemap
1298 search = []
1298 search = []
1299 fetch = {}
1299 fetch = {}
1300 seen = {}
1300 seen = {}
1301 seenbranch = {}
1301 seenbranch = {}
1302 if base == None:
1302 if base == None:
1303 base = {}
1303 base = {}
1304
1304
1305 if not heads:
1305 if not heads:
1306 heads = remote.heads()
1306 heads = remote.heads()
1307
1307
1308 if self.changelog.tip() == nullid:
1308 if self.changelog.tip() == nullid:
1309 base[nullid] = 1
1309 base[nullid] = 1
1310 if heads != [nullid]:
1310 if heads != [nullid]:
1311 return [nullid]
1311 return [nullid]
1312 return []
1312 return []
1313
1313
1314 # assume we're closer to the tip than the root
1314 # assume we're closer to the tip than the root
1315 # and start by examining the heads
1315 # and start by examining the heads
1316 self.ui.status(_("searching for changes\n"))
1316 self.ui.status(_("searching for changes\n"))
1317
1317
1318 unknown = []
1318 unknown = []
1319 for h in heads:
1319 for h in heads:
1320 if h not in m:
1320 if h not in m:
1321 unknown.append(h)
1321 unknown.append(h)
1322 else:
1322 else:
1323 base[h] = 1
1323 base[h] = 1
1324
1324
1325 if not unknown:
1325 if not unknown:
1326 return []
1326 return []
1327
1327
1328 req = dict.fromkeys(unknown)
1328 req = dict.fromkeys(unknown)
1329 reqcnt = 0
1329 reqcnt = 0
1330
1330
1331 # search through remote branches
1331 # search through remote branches
1332 # a 'branch' here is a linear segment of history, with four parts:
1332 # a 'branch' here is a linear segment of history, with four parts:
1333 # head, root, first parent, second parent
1333 # head, root, first parent, second parent
1334 # (a branch always has two parents (or none) by definition)
1334 # (a branch always has two parents (or none) by definition)
1335 unknown = remote.branches(unknown)
1335 unknown = remote.branches(unknown)
1336 while unknown:
1336 while unknown:
1337 r = []
1337 r = []
1338 while unknown:
1338 while unknown:
1339 n = unknown.pop(0)
1339 n = unknown.pop(0)
1340 if n[0] in seen:
1340 if n[0] in seen:
1341 continue
1341 continue
1342
1342
1343 self.ui.debug(_("examining %s:%s\n")
1343 self.ui.debug(_("examining %s:%s\n")
1344 % (short(n[0]), short(n[1])))
1344 % (short(n[0]), short(n[1])))
1345 if n[0] == nullid: # found the end of the branch
1345 if n[0] == nullid: # found the end of the branch
1346 pass
1346 pass
1347 elif n in seenbranch:
1347 elif n in seenbranch:
1348 self.ui.debug(_("branch already found\n"))
1348 self.ui.debug(_("branch already found\n"))
1349 continue
1349 continue
1350 elif n[1] and n[1] in m: # do we know the base?
1350 elif n[1] and n[1] in m: # do we know the base?
1351 self.ui.debug(_("found incomplete branch %s:%s\n")
1351 self.ui.debug(_("found incomplete branch %s:%s\n")
1352 % (short(n[0]), short(n[1])))
1352 % (short(n[0]), short(n[1])))
1353 search.append(n) # schedule branch range for scanning
1353 search.append(n) # schedule branch range for scanning
1354 seenbranch[n] = 1
1354 seenbranch[n] = 1
1355 else:
1355 else:
1356 if n[1] not in seen and n[1] not in fetch:
1356 if n[1] not in seen and n[1] not in fetch:
1357 if n[2] in m and n[3] in m:
1357 if n[2] in m and n[3] in m:
1358 self.ui.debug(_("found new changeset %s\n") %
1358 self.ui.debug(_("found new changeset %s\n") %
1359 short(n[1]))
1359 short(n[1]))
1360 fetch[n[1]] = 1 # earliest unknown
1360 fetch[n[1]] = 1 # earliest unknown
1361 for p in n[2:4]:
1361 for p in n[2:4]:
1362 if p in m:
1362 if p in m:
1363 base[p] = 1 # latest known
1363 base[p] = 1 # latest known
1364
1364
1365 for p in n[2:4]:
1365 for p in n[2:4]:
1366 if p not in req and p not in m:
1366 if p not in req and p not in m:
1367 r.append(p)
1367 r.append(p)
1368 req[p] = 1
1368 req[p] = 1
1369 seen[n[0]] = 1
1369 seen[n[0]] = 1
1370
1370
1371 if r:
1371 if r:
1372 reqcnt += 1
1372 reqcnt += 1
1373 self.ui.debug(_("request %d: %s\n") %
1373 self.ui.debug(_("request %d: %s\n") %
1374 (reqcnt, " ".join(map(short, r))))
1374 (reqcnt, " ".join(map(short, r))))
1375 for p in xrange(0, len(r), 10):
1375 for p in xrange(0, len(r), 10):
1376 for b in remote.branches(r[p:p+10]):
1376 for b in remote.branches(r[p:p+10]):
1377 self.ui.debug(_("received %s:%s\n") %
1377 self.ui.debug(_("received %s:%s\n") %
1378 (short(b[0]), short(b[1])))
1378 (short(b[0]), short(b[1])))
1379 unknown.append(b)
1379 unknown.append(b)
1380
1380
1381 # do binary search on the branches we found
1381 # do binary search on the branches we found
1382 while search:
1382 while search:
1383 n = search.pop(0)
1383 n = search.pop(0)
1384 reqcnt += 1
1384 reqcnt += 1
1385 l = remote.between([(n[0], n[1])])[0]
1385 l = remote.between([(n[0], n[1])])[0]
1386 l.append(n[1])
1386 l.append(n[1])
1387 p = n[0]
1387 p = n[0]
1388 f = 1
1388 f = 1
1389 for i in l:
1389 for i in l:
1390 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1390 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1391 if i in m:
1391 if i in m:
1392 if f <= 2:
1392 if f <= 2:
1393 self.ui.debug(_("found new branch changeset %s\n") %
1393 self.ui.debug(_("found new branch changeset %s\n") %
1394 short(p))
1394 short(p))
1395 fetch[p] = 1
1395 fetch[p] = 1
1396 base[i] = 1
1396 base[i] = 1
1397 else:
1397 else:
1398 self.ui.debug(_("narrowed branch search to %s:%s\n")
1398 self.ui.debug(_("narrowed branch search to %s:%s\n")
1399 % (short(p), short(i)))
1399 % (short(p), short(i)))
1400 search.append((p, i))
1400 search.append((p, i))
1401 break
1401 break
1402 p, f = i, f * 2
1402 p, f = i, f * 2
1403
1403
1404 # sanity check our fetch list
1404 # sanity check our fetch list
1405 for f in fetch.keys():
1405 for f in fetch.keys():
1406 if f in m:
1406 if f in m:
1407 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1407 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1408
1408
1409 if base.keys() == [nullid]:
1409 if base.keys() == [nullid]:
1410 if force:
1410 if force:
1411 self.ui.warn(_("warning: repository is unrelated\n"))
1411 self.ui.warn(_("warning: repository is unrelated\n"))
1412 else:
1412 else:
1413 raise util.Abort(_("repository is unrelated"))
1413 raise util.Abort(_("repository is unrelated"))
1414
1414
1415 self.ui.debug(_("found new changesets starting at ") +
1415 self.ui.debug(_("found new changesets starting at ") +
1416 " ".join([short(f) for f in fetch]) + "\n")
1416 " ".join([short(f) for f in fetch]) + "\n")
1417
1417
1418 self.ui.debug(_("%d total queries\n") % reqcnt)
1418 self.ui.debug(_("%d total queries\n") % reqcnt)
1419
1419
1420 return fetch.keys()
1420 return fetch.keys()
1421
1421
1422 def findoutgoing(self, remote, base=None, heads=None, force=False):
1422 def findoutgoing(self, remote, base=None, heads=None, force=False):
1423 """Return list of nodes that are roots of subsets not in remote
1423 """Return list of nodes that are roots of subsets not in remote
1424
1424
1425 If base dict is specified, assume that these nodes and their parents
1425 If base dict is specified, assume that these nodes and their parents
1426 exist on the remote side.
1426 exist on the remote side.
1427 If a list of heads is specified, return only nodes which are heads
1427 If a list of heads is specified, return only nodes which are heads
1428 or ancestors of these heads, and return a second element which
1428 or ancestors of these heads, and return a second element which
1429 contains all remote heads which get new children.
1429 contains all remote heads which get new children.
1430 """
1430 """
1431 if base == None:
1431 if base == None:
1432 base = {}
1432 base = {}
1433 self.findincoming(remote, base, heads, force=force)
1433 self.findincoming(remote, base, heads, force=force)
1434
1434
1435 self.ui.debug(_("common changesets up to ")
1435 self.ui.debug(_("common changesets up to ")
1436 + " ".join(map(short, base.keys())) + "\n")
1436 + " ".join(map(short, base.keys())) + "\n")
1437
1437
1438 remain = dict.fromkeys(self.changelog.nodemap)
1438 remain = dict.fromkeys(self.changelog.nodemap)
1439
1439
1440 # prune everything remote has from the tree
1440 # prune everything remote has from the tree
1441 del remain[nullid]
1441 del remain[nullid]
1442 remove = base.keys()
1442 remove = base.keys()
1443 while remove:
1443 while remove:
1444 n = remove.pop(0)
1444 n = remove.pop(0)
1445 if n in remain:
1445 if n in remain:
1446 del remain[n]
1446 del remain[n]
1447 for p in self.changelog.parents(n):
1447 for p in self.changelog.parents(n):
1448 remove.append(p)
1448 remove.append(p)
1449
1449
1450 # find every node whose parents have been pruned
1450 # find every node whose parents have been pruned
1451 subset = []
1451 subset = []
1452 # find every remote head that will get new children
1452 # find every remote head that will get new children
1453 updated_heads = {}
1453 updated_heads = {}
1454 for n in remain:
1454 for n in remain:
1455 p1, p2 = self.changelog.parents(n)
1455 p1, p2 = self.changelog.parents(n)
1456 if p1 not in remain and p2 not in remain:
1456 if p1 not in remain and p2 not in remain:
1457 subset.append(n)
1457 subset.append(n)
1458 if heads:
1458 if heads:
1459 if p1 in heads:
1459 if p1 in heads:
1460 updated_heads[p1] = True
1460 updated_heads[p1] = True
1461 if p2 in heads:
1461 if p2 in heads:
1462 updated_heads[p2] = True
1462 updated_heads[p2] = True
1463
1463
1464 # this is the set of all roots we have to push
1464 # this is the set of all roots we have to push
1465 if heads:
1465 if heads:
1466 return subset, updated_heads.keys()
1466 return subset, updated_heads.keys()
1467 else:
1467 else:
1468 return subset
1468 return subset
1469
1469
1470 def pull(self, remote, heads=None, force=False):
1470 def pull(self, remote, heads=None, force=False):
1471 lock = self.lock()
1471 lock = self.lock()
1472 try:
1472 try:
1473 fetch = self.findincoming(remote, heads=heads, force=force)
1473 fetch = self.findincoming(remote, heads=heads, force=force)
1474 if fetch == [nullid]:
1474 if fetch == [nullid]:
1475 self.ui.status(_("requesting all changes\n"))
1475 self.ui.status(_("requesting all changes\n"))
1476
1476
1477 if not fetch:
1477 if not fetch:
1478 self.ui.status(_("no changes found\n"))
1478 self.ui.status(_("no changes found\n"))
1479 return 0
1479 return 0
1480
1480
1481 if heads is None:
1481 if heads is None:
1482 cg = remote.changegroup(fetch, 'pull')
1482 cg = remote.changegroup(fetch, 'pull')
1483 else:
1483 else:
1484 if 'changegroupsubset' not in remote.capabilities:
1484 if 'changegroupsubset' not in remote.capabilities:
1485 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1485 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1486 cg = remote.changegroupsubset(fetch, heads, 'pull')
1486 cg = remote.changegroupsubset(fetch, heads, 'pull')
1487 return self.addchangegroup(cg, 'pull', remote.url())
1487 return self.addchangegroup(cg, 'pull', remote.url())
1488 finally:
1488 finally:
1489 del lock
1489 del lock
1490
1490
1491 def push(self, remote, force=False, revs=None):
1491 def push(self, remote, force=False, revs=None):
1492 # there are two ways to push to remote repo:
1492 # there are two ways to push to remote repo:
1493 #
1493 #
1494 # addchangegroup assumes local user can lock remote
1494 # addchangegroup assumes local user can lock remote
1495 # repo (local filesystem, old ssh servers).
1495 # repo (local filesystem, old ssh servers).
1496 #
1496 #
1497 # unbundle assumes local user cannot lock remote repo (new ssh
1497 # unbundle assumes local user cannot lock remote repo (new ssh
1498 # servers, http servers).
1498 # servers, http servers).
1499
1499
1500 if remote.capable('unbundle'):
1500 if remote.capable('unbundle'):
1501 return self.push_unbundle(remote, force, revs)
1501 return self.push_unbundle(remote, force, revs)
1502 return self.push_addchangegroup(remote, force, revs)
1502 return self.push_addchangegroup(remote, force, revs)
1503
1503
1504 def prepush(self, remote, force, revs):
1504 def prepush(self, remote, force, revs):
1505 base = {}
1505 base = {}
1506 remote_heads = remote.heads()
1506 remote_heads = remote.heads()
1507 inc = self.findincoming(remote, base, remote_heads, force=force)
1507 inc = self.findincoming(remote, base, remote_heads, force=force)
1508
1508
1509 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1509 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1510 if revs is not None:
1510 if revs is not None:
1511 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1511 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1512 else:
1512 else:
1513 bases, heads = update, self.changelog.heads()
1513 bases, heads = update, self.changelog.heads()
1514
1514
1515 if not bases:
1515 if not bases:
1516 self.ui.status(_("no changes found\n"))
1516 self.ui.status(_("no changes found\n"))
1517 return None, 1
1517 return None, 1
1518 elif not force:
1518 elif not force:
1519 # check if we're creating new remote heads
1519 # check if we're creating new remote heads
1520 # to be a remote head after push, node must be either
1520 # to be a remote head after push, node must be either
1521 # - unknown locally
1521 # - unknown locally
1522 # - a local outgoing head descended from update
1522 # - a local outgoing head descended from update
1523 # - a remote head that's known locally and not
1523 # - a remote head that's known locally and not
1524 # ancestral to an outgoing head
1524 # ancestral to an outgoing head
1525
1525
1526 warn = 0
1526 warn = 0
1527
1527
1528 if remote_heads == [nullid]:
1528 if remote_heads == [nullid]:
1529 warn = 0
1529 warn = 0
1530 elif not revs and len(heads) > len(remote_heads):
1530 elif not revs and len(heads) > len(remote_heads):
1531 warn = 1
1531 warn = 1
1532 else:
1532 else:
1533 newheads = list(heads)
1533 newheads = list(heads)
1534 for r in remote_heads:
1534 for r in remote_heads:
1535 if r in self.changelog.nodemap:
1535 if r in self.changelog.nodemap:
1536 desc = self.changelog.heads(r, heads)
1536 desc = self.changelog.heads(r, heads)
1537 l = [h for h in heads if h in desc]
1537 l = [h for h in heads if h in desc]
1538 if not l:
1538 if not l:
1539 newheads.append(r)
1539 newheads.append(r)
1540 else:
1540 else:
1541 newheads.append(r)
1541 newheads.append(r)
1542 if len(newheads) > len(remote_heads):
1542 if len(newheads) > len(remote_heads):
1543 warn = 1
1543 warn = 1
1544
1544
1545 if warn:
1545 if warn:
1546 self.ui.warn(_("abort: push creates new remote heads!\n"))
1546 self.ui.warn(_("abort: push creates new remote heads!\n"))
1547 self.ui.status(_("(did you forget to merge?"
1547 self.ui.status(_("(did you forget to merge?"
1548 " use push -f to force)\n"))
1548 " use push -f to force)\n"))
1549 return None, 0
1549 return None, 0
1550 elif inc:
1550 elif inc:
1551 self.ui.warn(_("note: unsynced remote changes!\n"))
1551 self.ui.warn(_("note: unsynced remote changes!\n"))
1552
1552
1553
1553
1554 if revs is None:
1554 if revs is None:
1555 cg = self.changegroup(update, 'push')
1555 cg = self.changegroup(update, 'push')
1556 else:
1556 else:
1557 cg = self.changegroupsubset(update, revs, 'push')
1557 cg = self.changegroupsubset(update, revs, 'push')
1558 return cg, remote_heads
1558 return cg, remote_heads
1559
1559
1560 def push_addchangegroup(self, remote, force, revs):
1560 def push_addchangegroup(self, remote, force, revs):
1561 lock = remote.lock()
1561 lock = remote.lock()
1562 try:
1562 try:
1563 ret = self.prepush(remote, force, revs)
1563 ret = self.prepush(remote, force, revs)
1564 if ret[0] is not None:
1564 if ret[0] is not None:
1565 cg, remote_heads = ret
1565 cg, remote_heads = ret
1566 return remote.addchangegroup(cg, 'push', self.url())
1566 return remote.addchangegroup(cg, 'push', self.url())
1567 return ret[1]
1567 return ret[1]
1568 finally:
1568 finally:
1569 del lock
1569 del lock
1570
1570
1571 def push_unbundle(self, remote, force, revs):
1571 def push_unbundle(self, remote, force, revs):
1572 # local repo finds heads on server, finds out what revs it
1572 # local repo finds heads on server, finds out what revs it
1573 # must push. once revs transferred, if server finds it has
1573 # must push. once revs transferred, if server finds it has
1574 # different heads (someone else won commit/push race), server
1574 # different heads (someone else won commit/push race), server
1575 # aborts.
1575 # aborts.
1576
1576
1577 ret = self.prepush(remote, force, revs)
1577 ret = self.prepush(remote, force, revs)
1578 if ret[0] is not None:
1578 if ret[0] is not None:
1579 cg, remote_heads = ret
1579 cg, remote_heads = ret
1580 if force: remote_heads = ['force']
1580 if force: remote_heads = ['force']
1581 return remote.unbundle(cg, remote_heads, 'push')
1581 return remote.unbundle(cg, remote_heads, 'push')
1582 return ret[1]
1582 return ret[1]
1583
1583
1584 def changegroupinfo(self, nodes, source):
1584 def changegroupinfo(self, nodes, source):
1585 if self.ui.verbose or source == 'bundle':
1585 if self.ui.verbose or source == 'bundle':
1586 self.ui.status(_("%d changesets found\n") % len(nodes))
1586 self.ui.status(_("%d changesets found\n") % len(nodes))
1587 if self.ui.debugflag:
1587 if self.ui.debugflag:
1588 self.ui.debug(_("List of changesets:\n"))
1588 self.ui.debug(_("List of changesets:\n"))
1589 for node in nodes:
1589 for node in nodes:
1590 self.ui.debug("%s\n" % hex(node))
1590 self.ui.debug("%s\n" % hex(node))
1591
1591
1592 def changegroupsubset(self, bases, heads, source, extranodes=None):
1592 def changegroupsubset(self, bases, heads, source, extranodes=None):
1593 """This function generates a changegroup consisting of all the nodes
1593 """This function generates a changegroup consisting of all the nodes
1594 that are descendents of any of the bases, and ancestors of any of
1594 that are descendents of any of the bases, and ancestors of any of
1595 the heads.
1595 the heads.
1596
1596
1597 It is fairly complex as determining which filenodes and which
1597 It is fairly complex as determining which filenodes and which
1598 manifest nodes need to be included for the changeset to be complete
1598 manifest nodes need to be included for the changeset to be complete
1599 is non-trivial.
1599 is non-trivial.
1600
1600
1601 Another wrinkle is doing the reverse, figuring out which changeset in
1601 Another wrinkle is doing the reverse, figuring out which changeset in
1602 the changegroup a particular filenode or manifestnode belongs to.
1602 the changegroup a particular filenode or manifestnode belongs to.
1603
1603
1604 The caller can specify some nodes that must be included in the
1604 The caller can specify some nodes that must be included in the
1605 changegroup using the extranodes argument. It should be a dict
1605 changegroup using the extranodes argument. It should be a dict
1606 where the keys are the filenames (or 1 for the manifest), and the
1606 where the keys are the filenames (or 1 for the manifest), and the
1607 values are lists of (node, linknode) tuples, where node is a wanted
1607 values are lists of (node, linknode) tuples, where node is a wanted
1608 node and linknode is the changelog node that should be transmitted as
1608 node and linknode is the changelog node that should be transmitted as
1609 the linkrev.
1609 the linkrev.
1610 """
1610 """
1611
1611
1612 self.hook('preoutgoing', throw=True, source=source)
1612 self.hook('preoutgoing', throw=True, source=source)
1613
1613
1614 # Set up some initial variables
1614 # Set up some initial variables
1615 # Make it easy to refer to self.changelog
1615 # Make it easy to refer to self.changelog
1616 cl = self.changelog
1616 cl = self.changelog
1617 # msng is short for missing - compute the list of changesets in this
1617 # msng is short for missing - compute the list of changesets in this
1618 # changegroup.
1618 # changegroup.
1619 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1619 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1620 self.changegroupinfo(msng_cl_lst, source)
1620 self.changegroupinfo(msng_cl_lst, source)
1621 # Some bases may turn out to be superfluous, and some heads may be
1621 # Some bases may turn out to be superfluous, and some heads may be
1622 # too. nodesbetween will return the minimal set of bases and heads
1622 # too. nodesbetween will return the minimal set of bases and heads
1623 # necessary to re-create the changegroup.
1623 # necessary to re-create the changegroup.
1624
1624
1625 # Known heads are the list of heads that it is assumed the recipient
1625 # Known heads are the list of heads that it is assumed the recipient
1626 # of this changegroup will know about.
1626 # of this changegroup will know about.
1627 knownheads = {}
1627 knownheads = {}
1628 # We assume that all parents of bases are known heads.
1628 # We assume that all parents of bases are known heads.
1629 for n in bases:
1629 for n in bases:
1630 for p in cl.parents(n):
1630 for p in cl.parents(n):
1631 if p != nullid:
1631 if p != nullid:
1632 knownheads[p] = 1
1632 knownheads[p] = 1
1633 knownheads = knownheads.keys()
1633 knownheads = knownheads.keys()
1634 if knownheads:
1634 if knownheads:
1635 # Now that we know what heads are known, we can compute which
1635 # Now that we know what heads are known, we can compute which
1636 # changesets are known. The recipient must know about all
1636 # changesets are known. The recipient must know about all
1637 # changesets required to reach the known heads from the null
1637 # changesets required to reach the known heads from the null
1638 # changeset.
1638 # changeset.
1639 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1639 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1640 junk = None
1640 junk = None
1641 # Transform the list into an ersatz set.
1641 # Transform the list into an ersatz set.
1642 has_cl_set = dict.fromkeys(has_cl_set)
1642 has_cl_set = dict.fromkeys(has_cl_set)
1643 else:
1643 else:
1644 # If there were no known heads, the recipient cannot be assumed to
1644 # If there were no known heads, the recipient cannot be assumed to
1645 # know about any changesets.
1645 # know about any changesets.
1646 has_cl_set = {}
1646 has_cl_set = {}
1647
1647
1648 # Make it easy to refer to self.manifest
1648 # Make it easy to refer to self.manifest
1649 mnfst = self.manifest
1649 mnfst = self.manifest
1650 # We don't know which manifests are missing yet
1650 # We don't know which manifests are missing yet
1651 msng_mnfst_set = {}
1651 msng_mnfst_set = {}
1652 # Nor do we know which filenodes are missing.
1652 # Nor do we know which filenodes are missing.
1653 msng_filenode_set = {}
1653 msng_filenode_set = {}
1654
1654
1655 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1655 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1656 junk = None
1656 junk = None
1657
1657
1658 # A changeset always belongs to itself, so the changenode lookup
1658 # A changeset always belongs to itself, so the changenode lookup
1659 # function for a changenode is identity.
1659 # function for a changenode is identity.
1660 def identity(x):
1660 def identity(x):
1661 return x
1661 return x
1662
1662
1663 # A function generating function. Sets up an environment for the
1663 # A function generating function. Sets up an environment for the
1664 # inner function.
1664 # inner function.
1665 def cmp_by_rev_func(revlog):
1665 def cmp_by_rev_func(revlog):
1666 # Compare two nodes by their revision number in the environment's
1666 # Compare two nodes by their revision number in the environment's
1667 # revision history. Since the revision number both represents the
1667 # revision history. Since the revision number both represents the
1668 # most efficient order to read the nodes in, and represents a
1668 # most efficient order to read the nodes in, and represents a
1669 # topological sorting of the nodes, this function is often useful.
1669 # topological sorting of the nodes, this function is often useful.
1670 def cmp_by_rev(a, b):
1670 def cmp_by_rev(a, b):
1671 return cmp(revlog.rev(a), revlog.rev(b))
1671 return cmp(revlog.rev(a), revlog.rev(b))
1672 return cmp_by_rev
1672 return cmp_by_rev
1673
1673
1674 # If we determine that a particular file or manifest node must be a
1674 # If we determine that a particular file or manifest node must be a
1675 # node that the recipient of the changegroup will already have, we can
1675 # node that the recipient of the changegroup will already have, we can
1676 # also assume the recipient will have all the parents. This function
1676 # also assume the recipient will have all the parents. This function
1677 # prunes them from the set of missing nodes.
1677 # prunes them from the set of missing nodes.
1678 def prune_parents(revlog, hasset, msngset):
1678 def prune_parents(revlog, hasset, msngset):
1679 haslst = hasset.keys()
1679 haslst = hasset.keys()
1680 haslst.sort(cmp_by_rev_func(revlog))
1680 haslst.sort(cmp_by_rev_func(revlog))
1681 for node in haslst:
1681 for node in haslst:
1682 parentlst = [p for p in revlog.parents(node) if p != nullid]
1682 parentlst = [p for p in revlog.parents(node) if p != nullid]
1683 while parentlst:
1683 while parentlst:
1684 n = parentlst.pop()
1684 n = parentlst.pop()
1685 if n not in hasset:
1685 if n not in hasset:
1686 hasset[n] = 1
1686 hasset[n] = 1
1687 p = [p for p in revlog.parents(n) if p != nullid]
1687 p = [p for p in revlog.parents(n) if p != nullid]
1688 parentlst.extend(p)
1688 parentlst.extend(p)
1689 for n in hasset:
1689 for n in hasset:
1690 msngset.pop(n, None)
1690 msngset.pop(n, None)
1691
1691
1692 # This is a function generating function used to set up an environment
1692 # This is a function generating function used to set up an environment
1693 # for the inner function to execute in.
1693 # for the inner function to execute in.
1694 def manifest_and_file_collector(changedfileset):
1694 def manifest_and_file_collector(changedfileset):
1695 # This is an information gathering function that gathers
1695 # This is an information gathering function that gathers
1696 # information from each changeset node that goes out as part of
1696 # information from each changeset node that goes out as part of
1697 # the changegroup. The information gathered is a list of which
1697 # the changegroup. The information gathered is a list of which
1698 # manifest nodes are potentially required (the recipient may
1698 # manifest nodes are potentially required (the recipient may
1699 # already have them) and total list of all files which were
1699 # already have them) and total list of all files which were
1700 # changed in any changeset in the changegroup.
1700 # changed in any changeset in the changegroup.
1701 #
1701 #
1702 # We also remember the first changenode we saw any manifest
1702 # We also remember the first changenode we saw any manifest
1703 # referenced by so we can later determine which changenode 'owns'
1703 # referenced by so we can later determine which changenode 'owns'
1704 # the manifest.
1704 # the manifest.
1705 def collect_manifests_and_files(clnode):
1705 def collect_manifests_and_files(clnode):
1706 c = cl.read(clnode)
1706 c = cl.read(clnode)
1707 for f in c[3]:
1707 for f in c[3]:
1708 # This is to make sure we only have one instance of each
1708 # This is to make sure we only have one instance of each
1709 # filename string for each filename.
1709 # filename string for each filename.
1710 changedfileset.setdefault(f, f)
1710 changedfileset.setdefault(f, f)
1711 msng_mnfst_set.setdefault(c[0], clnode)
1711 msng_mnfst_set.setdefault(c[0], clnode)
1712 return collect_manifests_and_files
1712 return collect_manifests_and_files
1713
1713
1714 # Figure out which manifest nodes (of the ones we think might be part
1714 # Figure out which manifest nodes (of the ones we think might be part
1715 # of the changegroup) the recipient must know about and remove them
1715 # of the changegroup) the recipient must know about and remove them
1716 # from the changegroup.
1716 # from the changegroup.
1717 def prune_manifests():
1717 def prune_manifests():
1718 has_mnfst_set = {}
1718 has_mnfst_set = {}
1719 for n in msng_mnfst_set:
1719 for n in msng_mnfst_set:
1720 # If a 'missing' manifest thinks it belongs to a changenode
1720 # If a 'missing' manifest thinks it belongs to a changenode
1721 # the recipient is assumed to have, obviously the recipient
1721 # the recipient is assumed to have, obviously the recipient
1722 # must have that manifest.
1722 # must have that manifest.
1723 linknode = cl.node(mnfst.linkrev(n))
1723 linknode = cl.node(mnfst.linkrev(n))
1724 if linknode in has_cl_set:
1724 if linknode in has_cl_set:
1725 has_mnfst_set[n] = 1
1725 has_mnfst_set[n] = 1
1726 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1726 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1727
1727
1728 # Use the information collected in collect_manifests_and_files to say
1728 # Use the information collected in collect_manifests_and_files to say
1729 # which changenode any manifestnode belongs to.
1729 # which changenode any manifestnode belongs to.
1730 def lookup_manifest_link(mnfstnode):
1730 def lookup_manifest_link(mnfstnode):
1731 return msng_mnfst_set[mnfstnode]
1731 return msng_mnfst_set[mnfstnode]
1732
1732
1733 # A function generating function that sets up the initial environment
1733 # A function generating function that sets up the initial environment
1734 # the inner function.
1734 # the inner function.
1735 def filenode_collector(changedfiles):
1735 def filenode_collector(changedfiles):
1736 next_rev = [0]
1736 next_rev = [0]
1737 # This gathers information from each manifestnode included in the
1737 # This gathers information from each manifestnode included in the
1738 # changegroup about which filenodes the manifest node references
1738 # changegroup about which filenodes the manifest node references
1739 # so we can include those in the changegroup too.
1739 # so we can include those in the changegroup too.
1740 #
1740 #
1741 # It also remembers which changenode each filenode belongs to. It
1741 # It also remembers which changenode each filenode belongs to. It
1742 # does this by assuming the a filenode belongs to the changenode
1742 # does this by assuming the a filenode belongs to the changenode
1743 # the first manifest that references it belongs to.
1743 # the first manifest that references it belongs to.
1744 def collect_msng_filenodes(mnfstnode):
1744 def collect_msng_filenodes(mnfstnode):
1745 r = mnfst.rev(mnfstnode)
1745 r = mnfst.rev(mnfstnode)
1746 if r == next_rev[0]:
1746 if r == next_rev[0]:
1747 # If the last rev we looked at was the one just previous,
1747 # If the last rev we looked at was the one just previous,
1748 # we only need to see a diff.
1748 # we only need to see a diff.
1749 deltamf = mnfst.readdelta(mnfstnode)
1749 deltamf = mnfst.readdelta(mnfstnode)
1750 # For each line in the delta
1750 # For each line in the delta
1751 for f, fnode in deltamf.items():
1751 for f, fnode in deltamf.items():
1752 f = changedfiles.get(f, None)
1752 f = changedfiles.get(f, None)
1753 # And if the file is in the list of files we care
1753 # And if the file is in the list of files we care
1754 # about.
1754 # about.
1755 if f is not None:
1755 if f is not None:
1756 # Get the changenode this manifest belongs to
1756 # Get the changenode this manifest belongs to
1757 clnode = msng_mnfst_set[mnfstnode]
1757 clnode = msng_mnfst_set[mnfstnode]
1758 # Create the set of filenodes for the file if
1758 # Create the set of filenodes for the file if
1759 # there isn't one already.
1759 # there isn't one already.
1760 ndset = msng_filenode_set.setdefault(f, {})
1760 ndset = msng_filenode_set.setdefault(f, {})
1761 # And set the filenode's changelog node to the
1761 # And set the filenode's changelog node to the
1762 # manifest's if it hasn't been set already.
1762 # manifest's if it hasn't been set already.
1763 ndset.setdefault(fnode, clnode)
1763 ndset.setdefault(fnode, clnode)
1764 else:
1764 else:
1765 # Otherwise we need a full manifest.
1765 # Otherwise we need a full manifest.
1766 m = mnfst.read(mnfstnode)
1766 m = mnfst.read(mnfstnode)
1767 # For every file in we care about.
1767 # For every file in we care about.
1768 for f in changedfiles:
1768 for f in changedfiles:
1769 fnode = m.get(f, None)
1769 fnode = m.get(f, None)
1770 # If it's in the manifest
1770 # If it's in the manifest
1771 if fnode is not None:
1771 if fnode is not None:
1772 # See comments above.
1772 # See comments above.
1773 clnode = msng_mnfst_set[mnfstnode]
1773 clnode = msng_mnfst_set[mnfstnode]
1774 ndset = msng_filenode_set.setdefault(f, {})
1774 ndset = msng_filenode_set.setdefault(f, {})
1775 ndset.setdefault(fnode, clnode)
1775 ndset.setdefault(fnode, clnode)
1776 # Remember the revision we hope to see next.
1776 # Remember the revision we hope to see next.
1777 next_rev[0] = r + 1
1777 next_rev[0] = r + 1
1778 return collect_msng_filenodes
1778 return collect_msng_filenodes
1779
1779
1780 # We have a list of filenodes we think we need for a file, lets remove
1780 # We have a list of filenodes we think we need for a file, lets remove
1781 # all those we now the recipient must have.
1781 # all those we now the recipient must have.
1782 def prune_filenodes(f, filerevlog):
1782 def prune_filenodes(f, filerevlog):
1783 msngset = msng_filenode_set[f]
1783 msngset = msng_filenode_set[f]
1784 hasset = {}
1784 hasset = {}
1785 # If a 'missing' filenode thinks it belongs to a changenode we
1785 # If a 'missing' filenode thinks it belongs to a changenode we
1786 # assume the recipient must have, then the recipient must have
1786 # assume the recipient must have, then the recipient must have
1787 # that filenode.
1787 # that filenode.
1788 for n in msngset:
1788 for n in msngset:
1789 clnode = cl.node(filerevlog.linkrev(n))
1789 clnode = cl.node(filerevlog.linkrev(n))
1790 if clnode in has_cl_set:
1790 if clnode in has_cl_set:
1791 hasset[n] = 1
1791 hasset[n] = 1
1792 prune_parents(filerevlog, hasset, msngset)
1792 prune_parents(filerevlog, hasset, msngset)
1793
1793
1794 # A function generator function that sets up the a context for the
1794 # A function generator function that sets up the a context for the
1795 # inner function.
1795 # inner function.
1796 def lookup_filenode_link_func(fname):
1796 def lookup_filenode_link_func(fname):
1797 msngset = msng_filenode_set[fname]
1797 msngset = msng_filenode_set[fname]
1798 # Lookup the changenode the filenode belongs to.
1798 # Lookup the changenode the filenode belongs to.
1799 def lookup_filenode_link(fnode):
1799 def lookup_filenode_link(fnode):
1800 return msngset[fnode]
1800 return msngset[fnode]
1801 return lookup_filenode_link
1801 return lookup_filenode_link
1802
1802
1803 # Add the nodes that were explicitly requested.
1803 # Add the nodes that were explicitly requested.
1804 def add_extra_nodes(name, nodes):
1804 def add_extra_nodes(name, nodes):
1805 if not extranodes or name not in extranodes:
1805 if not extranodes or name not in extranodes:
1806 return
1806 return
1807
1807
1808 for node, linknode in extranodes[name]:
1808 for node, linknode in extranodes[name]:
1809 if node not in nodes:
1809 if node not in nodes:
1810 nodes[node] = linknode
1810 nodes[node] = linknode
1811
1811
1812 # Now that we have all theses utility functions to help out and
1812 # Now that we have all theses utility functions to help out and
1813 # logically divide up the task, generate the group.
1813 # logically divide up the task, generate the group.
1814 def gengroup():
1814 def gengroup():
1815 # The set of changed files starts empty.
1815 # The set of changed files starts empty.
1816 changedfiles = {}
1816 changedfiles = {}
1817 # Create a changenode group generator that will call our functions
1817 # Create a changenode group generator that will call our functions
1818 # back to lookup the owning changenode and collect information.
1818 # back to lookup the owning changenode and collect information.
1819 group = cl.group(msng_cl_lst, identity,
1819 group = cl.group(msng_cl_lst, identity,
1820 manifest_and_file_collector(changedfiles))
1820 manifest_and_file_collector(changedfiles))
1821 for chnk in group:
1821 for chnk in group:
1822 yield chnk
1822 yield chnk
1823
1823
1824 # The list of manifests has been collected by the generator
1824 # The list of manifests has been collected by the generator
1825 # calling our functions back.
1825 # calling our functions back.
1826 prune_manifests()
1826 prune_manifests()
1827 add_extra_nodes(1, msng_mnfst_set)
1827 add_extra_nodes(1, msng_mnfst_set)
1828 msng_mnfst_lst = msng_mnfst_set.keys()
1828 msng_mnfst_lst = msng_mnfst_set.keys()
1829 # Sort the manifestnodes by revision number.
1829 # Sort the manifestnodes by revision number.
1830 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1830 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1831 # Create a generator for the manifestnodes that calls our lookup
1831 # Create a generator for the manifestnodes that calls our lookup
1832 # and data collection functions back.
1832 # and data collection functions back.
1833 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1833 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1834 filenode_collector(changedfiles))
1834 filenode_collector(changedfiles))
1835 for chnk in group:
1835 for chnk in group:
1836 yield chnk
1836 yield chnk
1837
1837
1838 # These are no longer needed, dereference and toss the memory for
1838 # These are no longer needed, dereference and toss the memory for
1839 # them.
1839 # them.
1840 msng_mnfst_lst = None
1840 msng_mnfst_lst = None
1841 msng_mnfst_set.clear()
1841 msng_mnfst_set.clear()
1842
1842
1843 if extranodes:
1843 if extranodes:
1844 for fname in extranodes:
1844 for fname in extranodes:
1845 if isinstance(fname, int):
1845 if isinstance(fname, int):
1846 continue
1846 continue
1847 add_extra_nodes(fname,
1847 add_extra_nodes(fname,
1848 msng_filenode_set.setdefault(fname, {}))
1848 msng_filenode_set.setdefault(fname, {}))
1849 changedfiles[fname] = 1
1849 changedfiles[fname] = 1
1850 changedfiles = changedfiles.keys()
1850 changedfiles = changedfiles.keys()
1851 changedfiles.sort()
1851 changedfiles.sort()
1852 # Go through all our files in order sorted by name.
1852 # Go through all our files in order sorted by name.
1853 for fname in changedfiles:
1853 for fname in changedfiles:
1854 filerevlog = self.file(fname)
1854 filerevlog = self.file(fname)
1855 if filerevlog.count() == 0:
1855 if filerevlog.count() == 0:
1856 raise util.Abort(_("empty or missing revlog for %s") % fname)
1856 raise util.Abort(_("empty or missing revlog for %s") % fname)
1857 # Toss out the filenodes that the recipient isn't really
1857 # Toss out the filenodes that the recipient isn't really
1858 # missing.
1858 # missing.
1859 if fname in msng_filenode_set:
1859 if fname in msng_filenode_set:
1860 prune_filenodes(fname, filerevlog)
1860 prune_filenodes(fname, filerevlog)
1861 msng_filenode_lst = msng_filenode_set[fname].keys()
1861 msng_filenode_lst = msng_filenode_set[fname].keys()
1862 else:
1862 else:
1863 msng_filenode_lst = []
1863 msng_filenode_lst = []
1864 # If any filenodes are left, generate the group for them,
1864 # If any filenodes are left, generate the group for them,
1865 # otherwise don't bother.
1865 # otherwise don't bother.
1866 if len(msng_filenode_lst) > 0:
1866 if len(msng_filenode_lst) > 0:
1867 yield changegroup.chunkheader(len(fname))
1867 yield changegroup.chunkheader(len(fname))
1868 yield fname
1868 yield fname
1869 # Sort the filenodes by their revision #
1869 # Sort the filenodes by their revision #
1870 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1870 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1871 # Create a group generator and only pass in a changenode
1871 # Create a group generator and only pass in a changenode
1872 # lookup function as we need to collect no information
1872 # lookup function as we need to collect no information
1873 # from filenodes.
1873 # from filenodes.
1874 group = filerevlog.group(msng_filenode_lst,
1874 group = filerevlog.group(msng_filenode_lst,
1875 lookup_filenode_link_func(fname))
1875 lookup_filenode_link_func(fname))
1876 for chnk in group:
1876 for chnk in group:
1877 yield chnk
1877 yield chnk
1878 if fname in msng_filenode_set:
1878 if fname in msng_filenode_set:
1879 # Don't need this anymore, toss it to free memory.
1879 # Don't need this anymore, toss it to free memory.
1880 del msng_filenode_set[fname]
1880 del msng_filenode_set[fname]
1881 # Signal that no more groups are left.
1881 # Signal that no more groups are left.
1882 yield changegroup.closechunk()
1882 yield changegroup.closechunk()
1883
1883
1884 if msng_cl_lst:
1884 if msng_cl_lst:
1885 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1885 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1886
1886
1887 return util.chunkbuffer(gengroup())
1887 return util.chunkbuffer(gengroup())
1888
1888
1889 def changegroup(self, basenodes, source):
1889 def changegroup(self, basenodes, source):
1890 """Generate a changegroup of all nodes that we have that a recipient
1890 """Generate a changegroup of all nodes that we have that a recipient
1891 doesn't.
1891 doesn't.
1892
1892
1893 This is much easier than the previous function as we can assume that
1893 This is much easier than the previous function as we can assume that
1894 the recipient has any changenode we aren't sending them."""
1894 the recipient has any changenode we aren't sending them."""
1895
1895
1896 self.hook('preoutgoing', throw=True, source=source)
1896 self.hook('preoutgoing', throw=True, source=source)
1897
1897
1898 cl = self.changelog
1898 cl = self.changelog
1899 nodes = cl.nodesbetween(basenodes, None)[0]
1899 nodes = cl.nodesbetween(basenodes, None)[0]
1900 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1900 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1901 self.changegroupinfo(nodes, source)
1901 self.changegroupinfo(nodes, source)
1902
1902
1903 def identity(x):
1903 def identity(x):
1904 return x
1904 return x
1905
1905
1906 def gennodelst(revlog):
1906 def gennodelst(revlog):
1907 for r in xrange(0, revlog.count()):
1907 for r in xrange(0, revlog.count()):
1908 n = revlog.node(r)
1908 n = revlog.node(r)
1909 if revlog.linkrev(n) in revset:
1909 if revlog.linkrev(n) in revset:
1910 yield n
1910 yield n
1911
1911
1912 def changed_file_collector(changedfileset):
1912 def changed_file_collector(changedfileset):
1913 def collect_changed_files(clnode):
1913 def collect_changed_files(clnode):
1914 c = cl.read(clnode)
1914 c = cl.read(clnode)
1915 for fname in c[3]:
1915 for fname in c[3]:
1916 changedfileset[fname] = 1
1916 changedfileset[fname] = 1
1917 return collect_changed_files
1917 return collect_changed_files
1918
1918
1919 def lookuprevlink_func(revlog):
1919 def lookuprevlink_func(revlog):
1920 def lookuprevlink(n):
1920 def lookuprevlink(n):
1921 return cl.node(revlog.linkrev(n))
1921 return cl.node(revlog.linkrev(n))
1922 return lookuprevlink
1922 return lookuprevlink
1923
1923
1924 def gengroup():
1924 def gengroup():
1925 # construct a list of all changed files
1925 # construct a list of all changed files
1926 changedfiles = {}
1926 changedfiles = {}
1927
1927
1928 for chnk in cl.group(nodes, identity,
1928 for chnk in cl.group(nodes, identity,
1929 changed_file_collector(changedfiles)):
1929 changed_file_collector(changedfiles)):
1930 yield chnk
1930 yield chnk
1931 changedfiles = changedfiles.keys()
1931 changedfiles = changedfiles.keys()
1932 changedfiles.sort()
1932 changedfiles.sort()
1933
1933
1934 mnfst = self.manifest
1934 mnfst = self.manifest
1935 nodeiter = gennodelst(mnfst)
1935 nodeiter = gennodelst(mnfst)
1936 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1936 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1937 yield chnk
1937 yield chnk
1938
1938
1939 for fname in changedfiles:
1939 for fname in changedfiles:
1940 filerevlog = self.file(fname)
1940 filerevlog = self.file(fname)
1941 if filerevlog.count() == 0:
1941 if filerevlog.count() == 0:
1942 raise util.Abort(_("empty or missing revlog for %s") % fname)
1942 raise util.Abort(_("empty or missing revlog for %s") % fname)
1943 nodeiter = gennodelst(filerevlog)
1943 nodeiter = gennodelst(filerevlog)
1944 nodeiter = list(nodeiter)
1944 nodeiter = list(nodeiter)
1945 if nodeiter:
1945 if nodeiter:
1946 yield changegroup.chunkheader(len(fname))
1946 yield changegroup.chunkheader(len(fname))
1947 yield fname
1947 yield fname
1948 lookup = lookuprevlink_func(filerevlog)
1948 lookup = lookuprevlink_func(filerevlog)
1949 for chnk in filerevlog.group(nodeiter, lookup):
1949 for chnk in filerevlog.group(nodeiter, lookup):
1950 yield chnk
1950 yield chnk
1951
1951
1952 yield changegroup.closechunk()
1952 yield changegroup.closechunk()
1953
1953
1954 if nodes:
1954 if nodes:
1955 self.hook('outgoing', node=hex(nodes[0]), source=source)
1955 self.hook('outgoing', node=hex(nodes[0]), source=source)
1956
1956
1957 return util.chunkbuffer(gengroup())
1957 return util.chunkbuffer(gengroup())
1958
1958
1959 def addchangegroup(self, source, srctype, url, emptyok=False):
1959 def addchangegroup(self, source, srctype, url, emptyok=False):
1960 """add changegroup to repo.
1960 """add changegroup to repo.
1961
1961
1962 return values:
1962 return values:
1963 - nothing changed or no source: 0
1963 - nothing changed or no source: 0
1964 - more heads than before: 1+added heads (2..n)
1964 - more heads than before: 1+added heads (2..n)
1965 - less heads than before: -1-removed heads (-2..-n)
1965 - less heads than before: -1-removed heads (-2..-n)
1966 - number of heads stays the same: 1
1966 - number of heads stays the same: 1
1967 """
1967 """
1968 def csmap(x):
1968 def csmap(x):
1969 self.ui.debug(_("add changeset %s\n") % short(x))
1969 self.ui.debug(_("add changeset %s\n") % short(x))
1970 return cl.count()
1970 return cl.count()
1971
1971
1972 def revmap(x):
1972 def revmap(x):
1973 return cl.rev(x)
1973 return cl.rev(x)
1974
1974
1975 if not source:
1975 if not source:
1976 return 0
1976 return 0
1977
1977
1978 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1978 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1979
1979
1980 changesets = files = revisions = 0
1980 changesets = files = revisions = 0
1981
1981
1982 # write changelog data to temp files so concurrent readers will not see
1982 # write changelog data to temp files so concurrent readers will not see
1983 # inconsistent view
1983 # inconsistent view
1984 cl = self.changelog
1984 cl = self.changelog
1985 cl.delayupdate()
1985 cl.delayupdate()
1986 oldheads = len(cl.heads())
1986 oldheads = len(cl.heads())
1987
1987
1988 tr = self.transaction()
1988 tr = self.transaction()
1989 try:
1989 try:
1990 trp = weakref.proxy(tr)
1990 trp = weakref.proxy(tr)
1991 # pull off the changeset group
1991 # pull off the changeset group
1992 self.ui.status(_("adding changesets\n"))
1992 self.ui.status(_("adding changesets\n"))
1993 cor = cl.count() - 1
1993 cor = cl.count() - 1
1994 chunkiter = changegroup.chunkiter(source)
1994 chunkiter = changegroup.chunkiter(source)
1995 if cl.addgroup(chunkiter, csmap, trp, 1) is None and not emptyok:
1995 if cl.addgroup(chunkiter, csmap, trp, 1) is None and not emptyok:
1996 raise util.Abort(_("received changelog group is empty"))
1996 raise util.Abort(_("received changelog group is empty"))
1997 cnr = cl.count() - 1
1997 cnr = cl.count() - 1
1998 changesets = cnr - cor
1998 changesets = cnr - cor
1999
1999
2000 # pull off the manifest group
2000 # pull off the manifest group
2001 self.ui.status(_("adding manifests\n"))
2001 self.ui.status(_("adding manifests\n"))
2002 chunkiter = changegroup.chunkiter(source)
2002 chunkiter = changegroup.chunkiter(source)
2003 # no need to check for empty manifest group here:
2003 # no need to check for empty manifest group here:
2004 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2004 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2005 # no new manifest will be created and the manifest group will
2005 # no new manifest will be created and the manifest group will
2006 # be empty during the pull
2006 # be empty during the pull
2007 self.manifest.addgroup(chunkiter, revmap, trp)
2007 self.manifest.addgroup(chunkiter, revmap, trp)
2008
2008
2009 # process the files
2009 # process the files
2010 self.ui.status(_("adding file changes\n"))
2010 self.ui.status(_("adding file changes\n"))
2011 while 1:
2011 while 1:
2012 f = changegroup.getchunk(source)
2012 f = changegroup.getchunk(source)
2013 if not f:
2013 if not f:
2014 break
2014 break
2015 self.ui.debug(_("adding %s revisions\n") % f)
2015 self.ui.debug(_("adding %s revisions\n") % f)
2016 fl = self.file(f)
2016 fl = self.file(f)
2017 o = fl.count()
2017 o = fl.count()
2018 chunkiter = changegroup.chunkiter(source)
2018 chunkiter = changegroup.chunkiter(source)
2019 if fl.addgroup(chunkiter, revmap, trp) is None:
2019 if fl.addgroup(chunkiter, revmap, trp) is None:
2020 raise util.Abort(_("received file revlog group is empty"))
2020 raise util.Abort(_("received file revlog group is empty"))
2021 revisions += fl.count() - o
2021 revisions += fl.count() - o
2022 files += 1
2022 files += 1
2023
2023
2024 # make changelog see real files again
2024 # make changelog see real files again
2025 cl.finalize(trp)
2025 cl.finalize(trp)
2026
2026
2027 newheads = len(self.changelog.heads())
2027 newheads = len(self.changelog.heads())
2028 heads = ""
2028 heads = ""
2029 if oldheads and newheads != oldheads:
2029 if oldheads and newheads != oldheads:
2030 heads = _(" (%+d heads)") % (newheads - oldheads)
2030 heads = _(" (%+d heads)") % (newheads - oldheads)
2031
2031
2032 self.ui.status(_("added %d changesets"
2032 self.ui.status(_("added %d changesets"
2033 " with %d changes to %d files%s\n")
2033 " with %d changes to %d files%s\n")
2034 % (changesets, revisions, files, heads))
2034 % (changesets, revisions, files, heads))
2035
2035
2036 if changesets > 0:
2036 if changesets > 0:
2037 self.hook('pretxnchangegroup', throw=True,
2037 self.hook('pretxnchangegroup', throw=True,
2038 node=hex(self.changelog.node(cor+1)), source=srctype,
2038 node=hex(self.changelog.node(cor+1)), source=srctype,
2039 url=url)
2039 url=url)
2040
2040
2041 tr.close()
2041 tr.close()
2042 finally:
2042 finally:
2043 del tr
2043 del tr
2044
2044
2045 if changesets > 0:
2045 if changesets > 0:
2046 # forcefully update the on-disk branch cache
2046 # forcefully update the on-disk branch cache
2047 self.ui.debug(_("updating the branch cache\n"))
2047 self.ui.debug(_("updating the branch cache\n"))
2048 self.branchtags()
2048 self.branchtags()
2049 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2049 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
2050 source=srctype, url=url)
2050 source=srctype, url=url)
2051
2051
2052 for i in xrange(cor + 1, cnr + 1):
2052 for i in xrange(cor + 1, cnr + 1):
2053 self.hook("incoming", node=hex(self.changelog.node(i)),
2053 self.hook("incoming", node=hex(self.changelog.node(i)),
2054 source=srctype, url=url)
2054 source=srctype, url=url)
2055
2055
2056 # never return 0 here:
2056 # never return 0 here:
2057 if newheads < oldheads:
2057 if newheads < oldheads:
2058 return newheads - oldheads - 1
2058 return newheads - oldheads - 1
2059 else:
2059 else:
2060 return newheads - oldheads + 1
2060 return newheads - oldheads + 1
2061
2061
2062
2062
2063 def stream_in(self, remote):
2063 def stream_in(self, remote):
2064 fp = remote.stream_out()
2064 fp = remote.stream_out()
2065 l = fp.readline()
2065 l = fp.readline()
2066 try:
2066 try:
2067 resp = int(l)
2067 resp = int(l)
2068 except ValueError:
2068 except ValueError:
2069 raise util.UnexpectedOutput(
2069 raise util.UnexpectedOutput(
2070 _('Unexpected response from remote server:'), l)
2070 _('Unexpected response from remote server:'), l)
2071 if resp == 1:
2071 if resp == 1:
2072 raise util.Abort(_('operation forbidden by server'))
2072 raise util.Abort(_('operation forbidden by server'))
2073 elif resp == 2:
2073 elif resp == 2:
2074 raise util.Abort(_('locking the remote repository failed'))
2074 raise util.Abort(_('locking the remote repository failed'))
2075 elif resp != 0:
2075 elif resp != 0:
2076 raise util.Abort(_('the server sent an unknown error code'))
2076 raise util.Abort(_('the server sent an unknown error code'))
2077 self.ui.status(_('streaming all changes\n'))
2077 self.ui.status(_('streaming all changes\n'))
2078 l = fp.readline()
2078 l = fp.readline()
2079 try:
2079 try:
2080 total_files, total_bytes = map(int, l.split(' ', 1))
2080 total_files, total_bytes = map(int, l.split(' ', 1))
2081 except (ValueError, TypeError):
2081 except (ValueError, TypeError):
2082 raise util.UnexpectedOutput(
2082 raise util.UnexpectedOutput(
2083 _('Unexpected response from remote server:'), l)
2083 _('Unexpected response from remote server:'), l)
2084 self.ui.status(_('%d files to transfer, %s of data\n') %
2084 self.ui.status(_('%d files to transfer, %s of data\n') %
2085 (total_files, util.bytecount(total_bytes)))
2085 (total_files, util.bytecount(total_bytes)))
2086 start = time.time()
2086 start = time.time()
2087 for i in xrange(total_files):
2087 for i in xrange(total_files):
2088 # XXX doesn't support '\n' or '\r' in filenames
2088 # XXX doesn't support '\n' or '\r' in filenames
2089 l = fp.readline()
2089 l = fp.readline()
2090 try:
2090 try:
2091 name, size = l.split('\0', 1)
2091 name, size = l.split('\0', 1)
2092 size = int(size)
2092 size = int(size)
2093 except ValueError, TypeError:
2093 except ValueError, TypeError:
2094 raise util.UnexpectedOutput(
2094 raise util.UnexpectedOutput(
2095 _('Unexpected response from remote server:'), l)
2095 _('Unexpected response from remote server:'), l)
2096 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2096 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2097 ofp = self.sopener(name, 'w')
2097 ofp = self.sopener(name, 'w')
2098 for chunk in util.filechunkiter(fp, limit=size):
2098 for chunk in util.filechunkiter(fp, limit=size):
2099 ofp.write(chunk)
2099 ofp.write(chunk)
2100 ofp.close()
2100 ofp.close()
2101 elapsed = time.time() - start
2101 elapsed = time.time() - start
2102 if elapsed <= 0:
2102 if elapsed <= 0:
2103 elapsed = 0.001
2103 elapsed = 0.001
2104 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2104 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2105 (util.bytecount(total_bytes), elapsed,
2105 (util.bytecount(total_bytes), elapsed,
2106 util.bytecount(total_bytes / elapsed)))
2106 util.bytecount(total_bytes / elapsed)))
2107 self.invalidate()
2107 self.invalidate()
2108 return len(self.heads()) + 1
2108 return len(self.heads()) + 1
2109
2109
2110 def clone(self, remote, heads=[], stream=False):
2110 def clone(self, remote, heads=[], stream=False):
2111 '''clone remote repository.
2111 '''clone remote repository.
2112
2112
2113 keyword arguments:
2113 keyword arguments:
2114 heads: list of revs to clone (forces use of pull)
2114 heads: list of revs to clone (forces use of pull)
2115 stream: use streaming clone if possible'''
2115 stream: use streaming clone if possible'''
2116
2116
2117 # now, all clients that can request uncompressed clones can
2117 # now, all clients that can request uncompressed clones can
2118 # read repo formats supported by all servers that can serve
2118 # read repo formats supported by all servers that can serve
2119 # them.
2119 # them.
2120
2120
2121 # if revlog format changes, client will have to check version
2121 # if revlog format changes, client will have to check version
2122 # and format flags on "stream" capability, and use
2122 # and format flags on "stream" capability, and use
2123 # uncompressed only if compatible.
2123 # uncompressed only if compatible.
2124
2124
2125 if stream and not heads and remote.capable('stream'):
2125 if stream and not heads and remote.capable('stream'):
2126 return self.stream_in(remote)
2126 return self.stream_in(remote)
2127 return self.pull(remote, heads)
2127 return self.pull(remote, heads)
2128
2128
2129 # used to avoid circular references so destructors work
2129 # used to avoid circular references so destructors work
2130 def aftertrans(files):
2130 def aftertrans(files):
2131 renamefiles = [tuple(t) for t in files]
2131 renamefiles = [tuple(t) for t in files]
2132 def a():
2132 def a():
2133 for src, dest in renamefiles:
2133 for src, dest in renamefiles:
2134 util.rename(src, dest)
2134 util.rename(src, dest)
2135 return a
2135 return a
2136
2136
2137 def instance(ui, path, create):
2137 def instance(ui, path, create):
2138 return localrepository(ui, util.drop_scheme('file', path), create)
2138 return localrepository(ui, util.drop_scheme('file', path), create)
2139
2139
2140 def islocal(path):
2140 def islocal(path):
2141 return True
2141 return True
General Comments 0
You need to be logged in to leave comments. Login now