##// END OF EJS Templates
use demandload more.
Vadim Gelfer -
r2470:fe168927 default
parent child Browse files
Show More
@@ -1,44 +1,43 b''
1 """
1 """
2 changegroup.py - Mercurial changegroup manipulation functions
2 changegroup.py - Mercurial changegroup manipulation functions
3
3
4 Copyright 2006 Matt Mackall <mpm@selenic.com>
4 Copyright 2006 Matt Mackall <mpm@selenic.com>
5
5
6 This software may be used and distributed according to the terms
6 This software may be used and distributed according to the terms
7 of the GNU General Public License, incorporated herein by reference.
7 of the GNU General Public License, incorporated herein by reference.
8 """
8 """
9 import struct
10 from i18n import gettext as _
9 from i18n import gettext as _
11 from demandload import *
10 from demandload import *
12 demandload(globals(), "util")
11 demandload(globals(), "struct util")
13
12
14 def getchunk(source):
13 def getchunk(source):
15 """get a chunk from a changegroup"""
14 """get a chunk from a changegroup"""
16 d = source.read(4)
15 d = source.read(4)
17 if not d:
16 if not d:
18 return ""
17 return ""
19 l = struct.unpack(">l", d)[0]
18 l = struct.unpack(">l", d)[0]
20 if l <= 4:
19 if l <= 4:
21 return ""
20 return ""
22 d = source.read(l - 4)
21 d = source.read(l - 4)
23 if len(d) < l - 4:
22 if len(d) < l - 4:
24 raise util.Abort(_("premature EOF reading chunk"
23 raise util.Abort(_("premature EOF reading chunk"
25 " (got %d bytes, expected %d)")
24 " (got %d bytes, expected %d)")
26 % (len(d), l - 4))
25 % (len(d), l - 4))
27 return d
26 return d
28
27
29 def chunkiter(source):
28 def chunkiter(source):
30 """iterate through the chunks in source"""
29 """iterate through the chunks in source"""
31 while 1:
30 while 1:
32 c = getchunk(source)
31 c = getchunk(source)
33 if not c:
32 if not c:
34 break
33 break
35 yield c
34 yield c
36
35
37 def genchunk(data):
36 def genchunk(data):
38 """build a changegroup chunk"""
37 """build a changegroup chunk"""
39 header = struct.pack(">l", len(data)+ 4)
38 header = struct.pack(">l", len(data)+ 4)
40 return "%s%s" % (header, data)
39 return "%s%s" % (header, data)
41
40
42 def closechunk():
41 def closechunk():
43 return struct.pack(">l", 0)
42 return struct.pack(">l", 0)
44
43
@@ -1,487 +1,486 b''
1 """
1 """
2 dirstate.py - working directory tracking for mercurial
2 dirstate.py - working directory tracking for mercurial
3
3
4 Copyright 2005 Matt Mackall <mpm@selenic.com>
4 Copyright 2005 Matt Mackall <mpm@selenic.com>
5
5
6 This software may be used and distributed according to the terms
6 This software may be used and distributed according to the terms
7 of the GNU General Public License, incorporated herein by reference.
7 of the GNU General Public License, incorporated herein by reference.
8 """
8 """
9
9
10 import struct, os
11 from node import *
10 from node import *
12 from i18n import gettext as _
11 from i18n import gettext as _
13 from demandload import *
12 from demandload import *
14 demandload(globals(), "time bisect stat util re errno")
13 demandload(globals(), "struct os time bisect stat util re errno")
15
14
16 class dirstate(object):
15 class dirstate(object):
17 format = ">cllll"
16 format = ">cllll"
18
17
19 def __init__(self, opener, ui, root):
18 def __init__(self, opener, ui, root):
20 self.opener = opener
19 self.opener = opener
21 self.root = root
20 self.root = root
22 self.dirty = 0
21 self.dirty = 0
23 self.ui = ui
22 self.ui = ui
24 self.map = None
23 self.map = None
25 self.pl = None
24 self.pl = None
26 self.copies = {}
25 self.copies = {}
27 self.ignorefunc = None
26 self.ignorefunc = None
28 self.blockignore = False
27 self.blockignore = False
29
28
30 def wjoin(self, f):
29 def wjoin(self, f):
31 return os.path.join(self.root, f)
30 return os.path.join(self.root, f)
32
31
33 def getcwd(self):
32 def getcwd(self):
34 cwd = os.getcwd()
33 cwd = os.getcwd()
35 if cwd == self.root: return ''
34 if cwd == self.root: return ''
36 return cwd[len(self.root) + 1:]
35 return cwd[len(self.root) + 1:]
37
36
38 def hgignore(self):
37 def hgignore(self):
39 '''return the contents of .hgignore files as a list of patterns.
38 '''return the contents of .hgignore files as a list of patterns.
40
39
41 the files parsed for patterns include:
40 the files parsed for patterns include:
42 .hgignore in the repository root
41 .hgignore in the repository root
43 any additional files specified in the [ui] section of ~/.hgrc
42 any additional files specified in the [ui] section of ~/.hgrc
44
43
45 trailing white space is dropped.
44 trailing white space is dropped.
46 the escape character is backslash.
45 the escape character is backslash.
47 comments start with #.
46 comments start with #.
48 empty lines are skipped.
47 empty lines are skipped.
49
48
50 lines can be of the following formats:
49 lines can be of the following formats:
51
50
52 syntax: regexp # defaults following lines to non-rooted regexps
51 syntax: regexp # defaults following lines to non-rooted regexps
53 syntax: glob # defaults following lines to non-rooted globs
52 syntax: glob # defaults following lines to non-rooted globs
54 re:pattern # non-rooted regular expression
53 re:pattern # non-rooted regular expression
55 glob:pattern # non-rooted glob
54 glob:pattern # non-rooted glob
56 pattern # pattern of the current default type'''
55 pattern # pattern of the current default type'''
57 syntaxes = {'re': 'relre:', 'regexp': 'relre:', 'glob': 'relglob:'}
56 syntaxes = {'re': 'relre:', 'regexp': 'relre:', 'glob': 'relglob:'}
58 def parselines(fp):
57 def parselines(fp):
59 for line in fp:
58 for line in fp:
60 escape = False
59 escape = False
61 for i in xrange(len(line)):
60 for i in xrange(len(line)):
62 if escape: escape = False
61 if escape: escape = False
63 elif line[i] == '\\': escape = True
62 elif line[i] == '\\': escape = True
64 elif line[i] == '#': break
63 elif line[i] == '#': break
65 line = line[:i].rstrip()
64 line = line[:i].rstrip()
66 if line: yield line
65 if line: yield line
67 repoignore = self.wjoin('.hgignore')
66 repoignore = self.wjoin('.hgignore')
68 files = [repoignore]
67 files = [repoignore]
69 files.extend(self.ui.hgignorefiles())
68 files.extend(self.ui.hgignorefiles())
70 pats = {}
69 pats = {}
71 for f in files:
70 for f in files:
72 try:
71 try:
73 pats[f] = []
72 pats[f] = []
74 fp = open(f)
73 fp = open(f)
75 syntax = 'relre:'
74 syntax = 'relre:'
76 for line in parselines(fp):
75 for line in parselines(fp):
77 if line.startswith('syntax:'):
76 if line.startswith('syntax:'):
78 s = line[7:].strip()
77 s = line[7:].strip()
79 try:
78 try:
80 syntax = syntaxes[s]
79 syntax = syntaxes[s]
81 except KeyError:
80 except KeyError:
82 self.ui.warn(_("%s: ignoring invalid "
81 self.ui.warn(_("%s: ignoring invalid "
83 "syntax '%s'\n") % (f, s))
82 "syntax '%s'\n") % (f, s))
84 continue
83 continue
85 pat = syntax + line
84 pat = syntax + line
86 for s in syntaxes.values():
85 for s in syntaxes.values():
87 if line.startswith(s):
86 if line.startswith(s):
88 pat = line
87 pat = line
89 break
88 break
90 pats[f].append(pat)
89 pats[f].append(pat)
91 except IOError, inst:
90 except IOError, inst:
92 if f != repoignore:
91 if f != repoignore:
93 self.ui.warn(_("skipping unreadable ignore file"
92 self.ui.warn(_("skipping unreadable ignore file"
94 " '%s': %s\n") % (f, inst.strerror))
93 " '%s': %s\n") % (f, inst.strerror))
95 return pats
94 return pats
96
95
97 def ignore(self, fn):
96 def ignore(self, fn):
98 '''default match function used by dirstate and
97 '''default match function used by dirstate and
99 localrepository. this honours the repository .hgignore file
98 localrepository. this honours the repository .hgignore file
100 and any other files specified in the [ui] section of .hgrc.'''
99 and any other files specified in the [ui] section of .hgrc.'''
101 if self.blockignore:
100 if self.blockignore:
102 return False
101 return False
103 if not self.ignorefunc:
102 if not self.ignorefunc:
104 ignore = self.hgignore()
103 ignore = self.hgignore()
105 allpats = []
104 allpats = []
106 [allpats.extend(patlist) for patlist in ignore.values()]
105 [allpats.extend(patlist) for patlist in ignore.values()]
107 if allpats:
106 if allpats:
108 try:
107 try:
109 files, self.ignorefunc, anypats = (
108 files, self.ignorefunc, anypats = (
110 util.matcher(self.root, inc=allpats, src='.hgignore'))
109 util.matcher(self.root, inc=allpats, src='.hgignore'))
111 except util.Abort:
110 except util.Abort:
112 # Re-raise an exception where the src is the right file
111 # Re-raise an exception where the src is the right file
113 for f, patlist in ignore.items():
112 for f, patlist in ignore.items():
114 files, self.ignorefunc, anypats = (
113 files, self.ignorefunc, anypats = (
115 util.matcher(self.root, inc=patlist, src=f))
114 util.matcher(self.root, inc=patlist, src=f))
116 else:
115 else:
117 self.ignorefunc = util.never
116 self.ignorefunc = util.never
118 return self.ignorefunc(fn)
117 return self.ignorefunc(fn)
119
118
120 def __del__(self):
119 def __del__(self):
121 if self.dirty:
120 if self.dirty:
122 self.write()
121 self.write()
123
122
124 def __getitem__(self, key):
123 def __getitem__(self, key):
125 try:
124 try:
126 return self.map[key]
125 return self.map[key]
127 except TypeError:
126 except TypeError:
128 self.lazyread()
127 self.lazyread()
129 return self[key]
128 return self[key]
130
129
131 def __contains__(self, key):
130 def __contains__(self, key):
132 self.lazyread()
131 self.lazyread()
133 return key in self.map
132 return key in self.map
134
133
135 def parents(self):
134 def parents(self):
136 self.lazyread()
135 self.lazyread()
137 return self.pl
136 return self.pl
138
137
139 def markdirty(self):
138 def markdirty(self):
140 if not self.dirty:
139 if not self.dirty:
141 self.dirty = 1
140 self.dirty = 1
142
141
143 def setparents(self, p1, p2=nullid):
142 def setparents(self, p1, p2=nullid):
144 self.lazyread()
143 self.lazyread()
145 self.markdirty()
144 self.markdirty()
146 self.pl = p1, p2
145 self.pl = p1, p2
147
146
148 def state(self, key):
147 def state(self, key):
149 try:
148 try:
150 return self[key][0]
149 return self[key][0]
151 except KeyError:
150 except KeyError:
152 return "?"
151 return "?"
153
152
154 def lazyread(self):
153 def lazyread(self):
155 if self.map is None:
154 if self.map is None:
156 self.read()
155 self.read()
157
156
158 def parse(self, st):
157 def parse(self, st):
159 self.pl = [st[:20], st[20: 40]]
158 self.pl = [st[:20], st[20: 40]]
160
159
161 # deref fields so they will be local in loop
160 # deref fields so they will be local in loop
162 map = self.map
161 map = self.map
163 copies = self.copies
162 copies = self.copies
164 format = self.format
163 format = self.format
165 unpack = struct.unpack
164 unpack = struct.unpack
166
165
167 pos = 40
166 pos = 40
168 e_size = struct.calcsize(format)
167 e_size = struct.calcsize(format)
169
168
170 while pos < len(st):
169 while pos < len(st):
171 newpos = pos + e_size
170 newpos = pos + e_size
172 e = unpack(format, st[pos:newpos])
171 e = unpack(format, st[pos:newpos])
173 l = e[4]
172 l = e[4]
174 pos = newpos
173 pos = newpos
175 newpos = pos + l
174 newpos = pos + l
176 f = st[pos:newpos]
175 f = st[pos:newpos]
177 if '\0' in f:
176 if '\0' in f:
178 f, c = f.split('\0')
177 f, c = f.split('\0')
179 copies[f] = c
178 copies[f] = c
180 map[f] = e[:4]
179 map[f] = e[:4]
181 pos = newpos
180 pos = newpos
182
181
183 def read(self):
182 def read(self):
184 self.map = {}
183 self.map = {}
185 self.pl = [nullid, nullid]
184 self.pl = [nullid, nullid]
186 try:
185 try:
187 st = self.opener("dirstate").read()
186 st = self.opener("dirstate").read()
188 if st:
187 if st:
189 self.parse(st)
188 self.parse(st)
190 except IOError, err:
189 except IOError, err:
191 if err.errno != errno.ENOENT: raise
190 if err.errno != errno.ENOENT: raise
192
191
193 def copy(self, source, dest):
192 def copy(self, source, dest):
194 self.lazyread()
193 self.lazyread()
195 self.markdirty()
194 self.markdirty()
196 self.copies[dest] = source
195 self.copies[dest] = source
197
196
198 def copied(self, file):
197 def copied(self, file):
199 return self.copies.get(file, None)
198 return self.copies.get(file, None)
200
199
201 def update(self, files, state, **kw):
200 def update(self, files, state, **kw):
202 ''' current states:
201 ''' current states:
203 n normal
202 n normal
204 m needs merging
203 m needs merging
205 r marked for removal
204 r marked for removal
206 a marked for addition'''
205 a marked for addition'''
207
206
208 if not files: return
207 if not files: return
209 self.lazyread()
208 self.lazyread()
210 self.markdirty()
209 self.markdirty()
211 for f in files:
210 for f in files:
212 if state == "r":
211 if state == "r":
213 self.map[f] = ('r', 0, 0, 0)
212 self.map[f] = ('r', 0, 0, 0)
214 else:
213 else:
215 s = os.lstat(self.wjoin(f))
214 s = os.lstat(self.wjoin(f))
216 st_size = kw.get('st_size', s.st_size)
215 st_size = kw.get('st_size', s.st_size)
217 st_mtime = kw.get('st_mtime', s.st_mtime)
216 st_mtime = kw.get('st_mtime', s.st_mtime)
218 self.map[f] = (state, s.st_mode, st_size, st_mtime)
217 self.map[f] = (state, s.st_mode, st_size, st_mtime)
219 if self.copies.has_key(f):
218 if self.copies.has_key(f):
220 del self.copies[f]
219 del self.copies[f]
221
220
222 def forget(self, files):
221 def forget(self, files):
223 if not files: return
222 if not files: return
224 self.lazyread()
223 self.lazyread()
225 self.markdirty()
224 self.markdirty()
226 for f in files:
225 for f in files:
227 try:
226 try:
228 del self.map[f]
227 del self.map[f]
229 except KeyError:
228 except KeyError:
230 self.ui.warn(_("not in dirstate: %s!\n") % f)
229 self.ui.warn(_("not in dirstate: %s!\n") % f)
231 pass
230 pass
232
231
233 def clear(self):
232 def clear(self):
234 self.map = {}
233 self.map = {}
235 self.copies = {}
234 self.copies = {}
236 self.markdirty()
235 self.markdirty()
237
236
238 def rebuild(self, parent, files):
237 def rebuild(self, parent, files):
239 self.clear()
238 self.clear()
240 umask = os.umask(0)
239 umask = os.umask(0)
241 os.umask(umask)
240 os.umask(umask)
242 for f, mode in files:
241 for f, mode in files:
243 if mode:
242 if mode:
244 self.map[f] = ('n', ~umask, -1, 0)
243 self.map[f] = ('n', ~umask, -1, 0)
245 else:
244 else:
246 self.map[f] = ('n', ~umask & 0666, -1, 0)
245 self.map[f] = ('n', ~umask & 0666, -1, 0)
247 self.pl = (parent, nullid)
246 self.pl = (parent, nullid)
248 self.markdirty()
247 self.markdirty()
249
248
250 def write(self):
249 def write(self):
251 if not self.dirty:
250 if not self.dirty:
252 return
251 return
253 st = self.opener("dirstate", "w", atomic=True)
252 st = self.opener("dirstate", "w", atomic=True)
254 st.write("".join(self.pl))
253 st.write("".join(self.pl))
255 for f, e in self.map.items():
254 for f, e in self.map.items():
256 c = self.copied(f)
255 c = self.copied(f)
257 if c:
256 if c:
258 f = f + "\0" + c
257 f = f + "\0" + c
259 e = struct.pack(self.format, e[0], e[1], e[2], e[3], len(f))
258 e = struct.pack(self.format, e[0], e[1], e[2], e[3], len(f))
260 st.write(e + f)
259 st.write(e + f)
261 self.dirty = 0
260 self.dirty = 0
262
261
263 def filterfiles(self, files):
262 def filterfiles(self, files):
264 ret = {}
263 ret = {}
265 unknown = []
264 unknown = []
266
265
267 for x in files:
266 for x in files:
268 if x == '.':
267 if x == '.':
269 return self.map.copy()
268 return self.map.copy()
270 if x not in self.map:
269 if x not in self.map:
271 unknown.append(x)
270 unknown.append(x)
272 else:
271 else:
273 ret[x] = self.map[x]
272 ret[x] = self.map[x]
274
273
275 if not unknown:
274 if not unknown:
276 return ret
275 return ret
277
276
278 b = self.map.keys()
277 b = self.map.keys()
279 b.sort()
278 b.sort()
280 blen = len(b)
279 blen = len(b)
281
280
282 for x in unknown:
281 for x in unknown:
283 bs = bisect.bisect(b, x)
282 bs = bisect.bisect(b, x)
284 if bs != 0 and b[bs-1] == x:
283 if bs != 0 and b[bs-1] == x:
285 ret[x] = self.map[x]
284 ret[x] = self.map[x]
286 continue
285 continue
287 while bs < blen:
286 while bs < blen:
288 s = b[bs]
287 s = b[bs]
289 if len(s) > len(x) and s.startswith(x) and s[len(x)] == '/':
288 if len(s) > len(x) and s.startswith(x) and s[len(x)] == '/':
290 ret[s] = self.map[s]
289 ret[s] = self.map[s]
291 else:
290 else:
292 break
291 break
293 bs += 1
292 bs += 1
294 return ret
293 return ret
295
294
296 def supported_type(self, f, st, verbose=False):
295 def supported_type(self, f, st, verbose=False):
297 if stat.S_ISREG(st.st_mode):
296 if stat.S_ISREG(st.st_mode):
298 return True
297 return True
299 if verbose:
298 if verbose:
300 kind = 'unknown'
299 kind = 'unknown'
301 if stat.S_ISCHR(st.st_mode): kind = _('character device')
300 if stat.S_ISCHR(st.st_mode): kind = _('character device')
302 elif stat.S_ISBLK(st.st_mode): kind = _('block device')
301 elif stat.S_ISBLK(st.st_mode): kind = _('block device')
303 elif stat.S_ISFIFO(st.st_mode): kind = _('fifo')
302 elif stat.S_ISFIFO(st.st_mode): kind = _('fifo')
304 elif stat.S_ISLNK(st.st_mode): kind = _('symbolic link')
303 elif stat.S_ISLNK(st.st_mode): kind = _('symbolic link')
305 elif stat.S_ISSOCK(st.st_mode): kind = _('socket')
304 elif stat.S_ISSOCK(st.st_mode): kind = _('socket')
306 elif stat.S_ISDIR(st.st_mode): kind = _('directory')
305 elif stat.S_ISDIR(st.st_mode): kind = _('directory')
307 self.ui.warn(_('%s: unsupported file type (type is %s)\n') % (
306 self.ui.warn(_('%s: unsupported file type (type is %s)\n') % (
308 util.pathto(self.getcwd(), f),
307 util.pathto(self.getcwd(), f),
309 kind))
308 kind))
310 return False
309 return False
311
310
312 def statwalk(self, files=None, match=util.always, dc=None, ignored=False,
311 def statwalk(self, files=None, match=util.always, dc=None, ignored=False,
313 badmatch=None):
312 badmatch=None):
314 self.lazyread()
313 self.lazyread()
315
314
316 # walk all files by default
315 # walk all files by default
317 if not files:
316 if not files:
318 files = [self.root]
317 files = [self.root]
319 if not dc:
318 if not dc:
320 dc = self.map.copy()
319 dc = self.map.copy()
321 elif not dc:
320 elif not dc:
322 dc = self.filterfiles(files)
321 dc = self.filterfiles(files)
323
322
324 def statmatch(file_, stat):
323 def statmatch(file_, stat):
325 file_ = util.pconvert(file_)
324 file_ = util.pconvert(file_)
326 if not ignored and file_ not in dc and self.ignore(file_):
325 if not ignored and file_ not in dc and self.ignore(file_):
327 return False
326 return False
328 return match(file_)
327 return match(file_)
329
328
330 return self.walkhelper(files=files, statmatch=statmatch, dc=dc,
329 return self.walkhelper(files=files, statmatch=statmatch, dc=dc,
331 badmatch=badmatch)
330 badmatch=badmatch)
332
331
333 def walk(self, files=None, match=util.always, dc=None, badmatch=None):
332 def walk(self, files=None, match=util.always, dc=None, badmatch=None):
334 # filter out the stat
333 # filter out the stat
335 for src, f, st in self.statwalk(files, match, dc, badmatch=badmatch):
334 for src, f, st in self.statwalk(files, match, dc, badmatch=badmatch):
336 yield src, f
335 yield src, f
337
336
338 # walk recursively through the directory tree, finding all files
337 # walk recursively through the directory tree, finding all files
339 # matched by the statmatch function
338 # matched by the statmatch function
340 #
339 #
341 # results are yielded in a tuple (src, filename, st), where src
340 # results are yielded in a tuple (src, filename, st), where src
342 # is one of:
341 # is one of:
343 # 'f' the file was found in the directory tree
342 # 'f' the file was found in the directory tree
344 # 'm' the file was only in the dirstate and not in the tree
343 # 'm' the file was only in the dirstate and not in the tree
345 # and st is the stat result if the file was found in the directory.
344 # and st is the stat result if the file was found in the directory.
346 #
345 #
347 # dc is an optional arg for the current dirstate. dc is not modified
346 # dc is an optional arg for the current dirstate. dc is not modified
348 # directly by this function, but might be modified by your statmatch call.
347 # directly by this function, but might be modified by your statmatch call.
349 #
348 #
350 def walkhelper(self, files, statmatch, dc, badmatch=None):
349 def walkhelper(self, files, statmatch, dc, badmatch=None):
351 # recursion free walker, faster than os.walk.
350 # recursion free walker, faster than os.walk.
352 def findfiles(s):
351 def findfiles(s):
353 work = [s]
352 work = [s]
354 while work:
353 while work:
355 top = work.pop()
354 top = work.pop()
356 names = os.listdir(top)
355 names = os.listdir(top)
357 names.sort()
356 names.sort()
358 # nd is the top of the repository dir tree
357 # nd is the top of the repository dir tree
359 nd = util.normpath(top[len(self.root) + 1:])
358 nd = util.normpath(top[len(self.root) + 1:])
360 if nd == '.':
359 if nd == '.':
361 nd = ''
360 nd = ''
362 else:
361 else:
363 # do not recurse into a repo contained in this
362 # do not recurse into a repo contained in this
364 # one. use bisect to find .hg directory so speed
363 # one. use bisect to find .hg directory so speed
365 # is good on big directory.
364 # is good on big directory.
366 hg = bisect.bisect_left(names, '.hg')
365 hg = bisect.bisect_left(names, '.hg')
367 if hg < len(names) and names[hg] == '.hg':
366 if hg < len(names) and names[hg] == '.hg':
368 if os.path.isdir(os.path.join(top, '.hg')):
367 if os.path.isdir(os.path.join(top, '.hg')):
369 continue
368 continue
370 for f in names:
369 for f in names:
371 np = util.pconvert(os.path.join(nd, f))
370 np = util.pconvert(os.path.join(nd, f))
372 if seen(np):
371 if seen(np):
373 continue
372 continue
374 p = os.path.join(top, f)
373 p = os.path.join(top, f)
375 # don't trip over symlinks
374 # don't trip over symlinks
376 st = os.lstat(p)
375 st = os.lstat(p)
377 if stat.S_ISDIR(st.st_mode):
376 if stat.S_ISDIR(st.st_mode):
378 ds = os.path.join(nd, f +'/')
377 ds = os.path.join(nd, f +'/')
379 if statmatch(ds, st):
378 if statmatch(ds, st):
380 work.append(p)
379 work.append(p)
381 if statmatch(np, st) and np in dc:
380 if statmatch(np, st) and np in dc:
382 yield 'm', np, st
381 yield 'm', np, st
383 elif statmatch(np, st):
382 elif statmatch(np, st):
384 if self.supported_type(np, st):
383 if self.supported_type(np, st):
385 yield 'f', np, st
384 yield 'f', np, st
386 elif np in dc:
385 elif np in dc:
387 yield 'm', np, st
386 yield 'm', np, st
388
387
389 known = {'.hg': 1}
388 known = {'.hg': 1}
390 def seen(fn):
389 def seen(fn):
391 if fn in known: return True
390 if fn in known: return True
392 known[fn] = 1
391 known[fn] = 1
393
392
394 # step one, find all files that match our criteria
393 # step one, find all files that match our criteria
395 files.sort()
394 files.sort()
396 for ff in util.unique(files):
395 for ff in util.unique(files):
397 f = self.wjoin(ff)
396 f = self.wjoin(ff)
398 try:
397 try:
399 st = os.lstat(f)
398 st = os.lstat(f)
400 except OSError, inst:
399 except OSError, inst:
401 nf = util.normpath(ff)
400 nf = util.normpath(ff)
402 found = False
401 found = False
403 for fn in dc:
402 for fn in dc:
404 if nf == fn or (fn.startswith(nf) and fn[len(nf)] == '/'):
403 if nf == fn or (fn.startswith(nf) and fn[len(nf)] == '/'):
405 found = True
404 found = True
406 break
405 break
407 if not found:
406 if not found:
408 if inst.errno != errno.ENOENT or not badmatch:
407 if inst.errno != errno.ENOENT or not badmatch:
409 self.ui.warn('%s: %s\n' % (
408 self.ui.warn('%s: %s\n' % (
410 util.pathto(self.getcwd(), ff),
409 util.pathto(self.getcwd(), ff),
411 inst.strerror))
410 inst.strerror))
412 elif badmatch and badmatch(ff) and statmatch(ff, None):
411 elif badmatch and badmatch(ff) and statmatch(ff, None):
413 yield 'b', ff, None
412 yield 'b', ff, None
414 continue
413 continue
415 if stat.S_ISDIR(st.st_mode):
414 if stat.S_ISDIR(st.st_mode):
416 cmp1 = (lambda x, y: cmp(x[1], y[1]))
415 cmp1 = (lambda x, y: cmp(x[1], y[1]))
417 sorted_ = [ x for x in findfiles(f) ]
416 sorted_ = [ x for x in findfiles(f) ]
418 sorted_.sort(cmp1)
417 sorted_.sort(cmp1)
419 for e in sorted_:
418 for e in sorted_:
420 yield e
419 yield e
421 else:
420 else:
422 ff = util.normpath(ff)
421 ff = util.normpath(ff)
423 if seen(ff):
422 if seen(ff):
424 continue
423 continue
425 self.blockignore = True
424 self.blockignore = True
426 if statmatch(ff, st):
425 if statmatch(ff, st):
427 if self.supported_type(ff, st, verbose=True):
426 if self.supported_type(ff, st, verbose=True):
428 yield 'f', ff, st
427 yield 'f', ff, st
429 elif ff in dc:
428 elif ff in dc:
430 yield 'm', ff, st
429 yield 'm', ff, st
431 self.blockignore = False
430 self.blockignore = False
432
431
433 # step two run through anything left in the dc hash and yield
432 # step two run through anything left in the dc hash and yield
434 # if we haven't already seen it
433 # if we haven't already seen it
435 ks = dc.keys()
434 ks = dc.keys()
436 ks.sort()
435 ks.sort()
437 for k in ks:
436 for k in ks:
438 if not seen(k) and (statmatch(k, None)):
437 if not seen(k) and (statmatch(k, None)):
439 yield 'm', k, None
438 yield 'm', k, None
440
439
441 def changes(self, files=None, match=util.always, show_ignored=None):
440 def changes(self, files=None, match=util.always, show_ignored=None):
442 lookup, modified, added, unknown, ignored = [], [], [], [], []
441 lookup, modified, added, unknown, ignored = [], [], [], [], []
443 removed, deleted = [], []
442 removed, deleted = [], []
444
443
445 for src, fn, st in self.statwalk(files, match, ignored=show_ignored):
444 for src, fn, st in self.statwalk(files, match, ignored=show_ignored):
446 try:
445 try:
447 type_, mode, size, time = self[fn]
446 type_, mode, size, time = self[fn]
448 except KeyError:
447 except KeyError:
449 if show_ignored and self.ignore(fn):
448 if show_ignored and self.ignore(fn):
450 ignored.append(fn)
449 ignored.append(fn)
451 else:
450 else:
452 unknown.append(fn)
451 unknown.append(fn)
453 continue
452 continue
454 if src == 'm':
453 if src == 'm':
455 nonexistent = True
454 nonexistent = True
456 if not st:
455 if not st:
457 try:
456 try:
458 st = os.lstat(self.wjoin(fn))
457 st = os.lstat(self.wjoin(fn))
459 except OSError, inst:
458 except OSError, inst:
460 if inst.errno != errno.ENOENT:
459 if inst.errno != errno.ENOENT:
461 raise
460 raise
462 st = None
461 st = None
463 # We need to re-check that it is a valid file
462 # We need to re-check that it is a valid file
464 if st and self.supported_type(fn, st):
463 if st and self.supported_type(fn, st):
465 nonexistent = False
464 nonexistent = False
466 # XXX: what to do with file no longer present in the fs
465 # XXX: what to do with file no longer present in the fs
467 # who are not removed in the dirstate ?
466 # who are not removed in the dirstate ?
468 if nonexistent and type_ in "nm":
467 if nonexistent and type_ in "nm":
469 deleted.append(fn)
468 deleted.append(fn)
470 continue
469 continue
471 # check the common case first
470 # check the common case first
472 if type_ == 'n':
471 if type_ == 'n':
473 if not st:
472 if not st:
474 st = os.lstat(self.wjoin(fn))
473 st = os.lstat(self.wjoin(fn))
475 if size >= 0 and (size != st.st_size
474 if size >= 0 and (size != st.st_size
476 or (mode ^ st.st_mode) & 0100):
475 or (mode ^ st.st_mode) & 0100):
477 modified.append(fn)
476 modified.append(fn)
478 elif time != st.st_mtime:
477 elif time != st.st_mtime:
479 lookup.append(fn)
478 lookup.append(fn)
480 elif type_ == 'm':
479 elif type_ == 'm':
481 modified.append(fn)
480 modified.append(fn)
482 elif type_ == 'a':
481 elif type_ == 'a':
483 added.append(fn)
482 added.append(fn)
484 elif type_ == 'r':
483 elif type_ == 'r':
485 removed.append(fn)
484 removed.append(fn)
486
485
487 return (lookup, modified, added, removed, deleted, unknown, ignored)
486 return (lookup, modified, added, removed, deleted, unknown, ignored)
@@ -1,108 +1,107 b''
1 # filelog.py - file history class for mercurial
1 # filelog.py - file history class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import os
9 from revlog import *
8 from revlog import *
10 from demandload import *
9 from demandload import *
11 demandload(globals(), "bdiff")
10 demandload(globals(), "bdiff os")
12
11
13 class filelog(revlog):
12 class filelog(revlog):
14 def __init__(self, opener, path, defversion=REVLOG_DEFAULT_VERSION):
13 def __init__(self, opener, path, defversion=REVLOG_DEFAULT_VERSION):
15 revlog.__init__(self, opener,
14 revlog.__init__(self, opener,
16 os.path.join("data", self.encodedir(path + ".i")),
15 os.path.join("data", self.encodedir(path + ".i")),
17 os.path.join("data", self.encodedir(path + ".d")),
16 os.path.join("data", self.encodedir(path + ".d")),
18 defversion)
17 defversion)
19
18
20 # This avoids a collision between a file named foo and a dir named
19 # This avoids a collision between a file named foo and a dir named
21 # foo.i or foo.d
20 # foo.i or foo.d
22 def encodedir(self, path):
21 def encodedir(self, path):
23 return (path
22 return (path
24 .replace(".hg/", ".hg.hg/")
23 .replace(".hg/", ".hg.hg/")
25 .replace(".i/", ".i.hg/")
24 .replace(".i/", ".i.hg/")
26 .replace(".d/", ".d.hg/"))
25 .replace(".d/", ".d.hg/"))
27
26
28 def decodedir(self, path):
27 def decodedir(self, path):
29 return (path
28 return (path
30 .replace(".d.hg/", ".d/")
29 .replace(".d.hg/", ".d/")
31 .replace(".i.hg/", ".i/")
30 .replace(".i.hg/", ".i/")
32 .replace(".hg.hg/", ".hg/"))
31 .replace(".hg.hg/", ".hg/"))
33
32
34 def read(self, node):
33 def read(self, node):
35 t = self.revision(node)
34 t = self.revision(node)
36 if not t.startswith('\1\n'):
35 if not t.startswith('\1\n'):
37 return t
36 return t
38 s = t.find('\1\n', 2)
37 s = t.find('\1\n', 2)
39 return t[s+2:]
38 return t[s+2:]
40
39
41 def readmeta(self, node):
40 def readmeta(self, node):
42 t = self.revision(node)
41 t = self.revision(node)
43 if not t.startswith('\1\n'):
42 if not t.startswith('\1\n'):
44 return {}
43 return {}
45 s = t.find('\1\n', 2)
44 s = t.find('\1\n', 2)
46 mt = t[2:s]
45 mt = t[2:s]
47 m = {}
46 m = {}
48 for l in mt.splitlines():
47 for l in mt.splitlines():
49 k, v = l.split(": ", 1)
48 k, v = l.split(": ", 1)
50 m[k] = v
49 m[k] = v
51 return m
50 return m
52
51
53 def add(self, text, meta, transaction, link, p1=None, p2=None):
52 def add(self, text, meta, transaction, link, p1=None, p2=None):
54 if meta or text.startswith('\1\n'):
53 if meta or text.startswith('\1\n'):
55 mt = ""
54 mt = ""
56 if meta:
55 if meta:
57 mt = [ "%s: %s\n" % (k, v) for k,v in meta.items() ]
56 mt = [ "%s: %s\n" % (k, v) for k,v in meta.items() ]
58 text = "\1\n%s\1\n%s" % ("".join(mt), text)
57 text = "\1\n%s\1\n%s" % ("".join(mt), text)
59 return self.addrevision(text, transaction, link, p1, p2)
58 return self.addrevision(text, transaction, link, p1, p2)
60
59
61 def renamed(self, node):
60 def renamed(self, node):
62 if self.parents(node)[0] != nullid:
61 if self.parents(node)[0] != nullid:
63 return False
62 return False
64 m = self.readmeta(node)
63 m = self.readmeta(node)
65 if m and m.has_key("copy"):
64 if m and m.has_key("copy"):
66 return (m["copy"], bin(m["copyrev"]))
65 return (m["copy"], bin(m["copyrev"]))
67 return False
66 return False
68
67
69 def annotate(self, node):
68 def annotate(self, node):
70
69
71 def decorate(text, rev):
70 def decorate(text, rev):
72 return ([rev] * len(text.splitlines()), text)
71 return ([rev] * len(text.splitlines()), text)
73
72
74 def pair(parent, child):
73 def pair(parent, child):
75 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
74 for a1, a2, b1, b2 in bdiff.blocks(parent[1], child[1]):
76 child[0][b1:b2] = parent[0][a1:a2]
75 child[0][b1:b2] = parent[0][a1:a2]
77 return child
76 return child
78
77
79 # find all ancestors
78 # find all ancestors
80 needed = {node:1}
79 needed = {node:1}
81 visit = [node]
80 visit = [node]
82 while visit:
81 while visit:
83 n = visit.pop(0)
82 n = visit.pop(0)
84 for p in self.parents(n):
83 for p in self.parents(n):
85 if p not in needed:
84 if p not in needed:
86 needed[p] = 1
85 needed[p] = 1
87 visit.append(p)
86 visit.append(p)
88 else:
87 else:
89 # count how many times we'll use this
88 # count how many times we'll use this
90 needed[p] += 1
89 needed[p] += 1
91
90
92 # sort by revision which is a topological order
91 # sort by revision which is a topological order
93 visit = [ (self.rev(n), n) for n in needed.keys() ]
92 visit = [ (self.rev(n), n) for n in needed.keys() ]
94 visit.sort()
93 visit.sort()
95 hist = {}
94 hist = {}
96
95
97 for r,n in visit:
96 for r,n in visit:
98 curr = decorate(self.read(n), self.linkrev(n))
97 curr = decorate(self.read(n), self.linkrev(n))
99 for p in self.parents(n):
98 for p in self.parents(n):
100 if p != nullid:
99 if p != nullid:
101 curr = pair(hist[p], curr)
100 curr = pair(hist[p], curr)
102 # trim the history of unneeded revs
101 # trim the history of unneeded revs
103 needed[p] -= 1
102 needed[p] -= 1
104 if not needed[p]:
103 if not needed[p]:
105 del hist[p]
104 del hist[p]
106 hist[n] = curr
105 hist[n] = curr
107
106
108 return zip(hist[n][0], hist[n][1].splitlines(1))
107 return zip(hist[n][0], hist[n][1].splitlines(1))
@@ -1,2145 +1,2144 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import os, util
9 import filelog, manifest, changelog, dirstate, repo
10 from node import *
8 from node import *
11 from i18n import gettext as _
9 from i18n import gettext as _
12 from demandload import *
10 from demandload import *
13 demandload(globals(), "appendfile changegroup")
11 demandload(globals(), "appendfile changegroup")
12 demandload(globals(), "changelog dirstate filelog manifest repo")
14 demandload(globals(), "re lock transaction tempfile stat mdiff errno ui")
13 demandload(globals(), "re lock transaction tempfile stat mdiff errno ui")
15 demandload(globals(), "revlog")
14 demandload(globals(), "os revlog util")
16
15
17 class localrepository(object):
16 class localrepository(object):
18 capabilities = ()
17 capabilities = ()
19
18
20 def __del__(self):
19 def __del__(self):
21 self.transhandle = None
20 self.transhandle = None
22 def __init__(self, parentui, path=None, create=0):
21 def __init__(self, parentui, path=None, create=0):
23 if not path:
22 if not path:
24 p = os.getcwd()
23 p = os.getcwd()
25 while not os.path.isdir(os.path.join(p, ".hg")):
24 while not os.path.isdir(os.path.join(p, ".hg")):
26 oldp = p
25 oldp = p
27 p = os.path.dirname(p)
26 p = os.path.dirname(p)
28 if p == oldp:
27 if p == oldp:
29 raise repo.RepoError(_("no repo found"))
28 raise repo.RepoError(_("no repo found"))
30 path = p
29 path = p
31 self.path = os.path.join(path, ".hg")
30 self.path = os.path.join(path, ".hg")
32
31
33 if not create and not os.path.isdir(self.path):
32 if not create and not os.path.isdir(self.path):
34 raise repo.RepoError(_("repository %s not found") % path)
33 raise repo.RepoError(_("repository %s not found") % path)
35
34
36 self.root = os.path.abspath(path)
35 self.root = os.path.abspath(path)
37 self.origroot = path
36 self.origroot = path
38 self.ui = ui.ui(parentui=parentui)
37 self.ui = ui.ui(parentui=parentui)
39 self.opener = util.opener(self.path)
38 self.opener = util.opener(self.path)
40 self.wopener = util.opener(self.root)
39 self.wopener = util.opener(self.root)
41
40
42 try:
41 try:
43 self.ui.readconfig(self.join("hgrc"), self.root)
42 self.ui.readconfig(self.join("hgrc"), self.root)
44 except IOError:
43 except IOError:
45 pass
44 pass
46
45
47 v = self.ui.revlogopts
46 v = self.ui.revlogopts
48 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
47 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
49 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
48 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
50 fl = v.get('flags', None)
49 fl = v.get('flags', None)
51 flags = 0
50 flags = 0
52 if fl != None:
51 if fl != None:
53 for x in fl.split():
52 for x in fl.split():
54 flags |= revlog.flagstr(x)
53 flags |= revlog.flagstr(x)
55 elif self.revlogv1:
54 elif self.revlogv1:
56 flags = revlog.REVLOG_DEFAULT_FLAGS
55 flags = revlog.REVLOG_DEFAULT_FLAGS
57
56
58 v = self.revlogversion | flags
57 v = self.revlogversion | flags
59 self.manifest = manifest.manifest(self.opener, v)
58 self.manifest = manifest.manifest(self.opener, v)
60 self.changelog = changelog.changelog(self.opener, v)
59 self.changelog = changelog.changelog(self.opener, v)
61
60
62 # the changelog might not have the inline index flag
61 # the changelog might not have the inline index flag
63 # on. If the format of the changelog is the same as found in
62 # on. If the format of the changelog is the same as found in
64 # .hgrc, apply any flags found in the .hgrc as well.
63 # .hgrc, apply any flags found in the .hgrc as well.
65 # Otherwise, just version from the changelog
64 # Otherwise, just version from the changelog
66 v = self.changelog.version
65 v = self.changelog.version
67 if v == self.revlogversion:
66 if v == self.revlogversion:
68 v |= flags
67 v |= flags
69 self.revlogversion = v
68 self.revlogversion = v
70
69
71 self.tagscache = None
70 self.tagscache = None
72 self.nodetagscache = None
71 self.nodetagscache = None
73 self.encodepats = None
72 self.encodepats = None
74 self.decodepats = None
73 self.decodepats = None
75 self.transhandle = None
74 self.transhandle = None
76
75
77 if create:
76 if create:
78 os.mkdir(self.path)
77 os.mkdir(self.path)
79 os.mkdir(self.join("data"))
78 os.mkdir(self.join("data"))
80
79
81 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
80 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
82
81
83 def hook(self, name, throw=False, **args):
82 def hook(self, name, throw=False, **args):
84 def callhook(hname, funcname):
83 def callhook(hname, funcname):
85 '''call python hook. hook is callable object, looked up as
84 '''call python hook. hook is callable object, looked up as
86 name in python module. if callable returns "true", hook
85 name in python module. if callable returns "true", hook
87 fails, else passes. if hook raises exception, treated as
86 fails, else passes. if hook raises exception, treated as
88 hook failure. exception propagates if throw is "true".
87 hook failure. exception propagates if throw is "true".
89
88
90 reason for "true" meaning "hook failed" is so that
89 reason for "true" meaning "hook failed" is so that
91 unmodified commands (e.g. mercurial.commands.update) can
90 unmodified commands (e.g. mercurial.commands.update) can
92 be run as hooks without wrappers to convert return values.'''
91 be run as hooks without wrappers to convert return values.'''
93
92
94 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
93 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
95 d = funcname.rfind('.')
94 d = funcname.rfind('.')
96 if d == -1:
95 if d == -1:
97 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
96 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
98 % (hname, funcname))
97 % (hname, funcname))
99 modname = funcname[:d]
98 modname = funcname[:d]
100 try:
99 try:
101 obj = __import__(modname)
100 obj = __import__(modname)
102 except ImportError:
101 except ImportError:
103 raise util.Abort(_('%s hook is invalid '
102 raise util.Abort(_('%s hook is invalid '
104 '(import of "%s" failed)') %
103 '(import of "%s" failed)') %
105 (hname, modname))
104 (hname, modname))
106 try:
105 try:
107 for p in funcname.split('.')[1:]:
106 for p in funcname.split('.')[1:]:
108 obj = getattr(obj, p)
107 obj = getattr(obj, p)
109 except AttributeError, err:
108 except AttributeError, err:
110 raise util.Abort(_('%s hook is invalid '
109 raise util.Abort(_('%s hook is invalid '
111 '("%s" is not defined)') %
110 '("%s" is not defined)') %
112 (hname, funcname))
111 (hname, funcname))
113 if not callable(obj):
112 if not callable(obj):
114 raise util.Abort(_('%s hook is invalid '
113 raise util.Abort(_('%s hook is invalid '
115 '("%s" is not callable)') %
114 '("%s" is not callable)') %
116 (hname, funcname))
115 (hname, funcname))
117 try:
116 try:
118 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
117 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
119 except (KeyboardInterrupt, util.SignalInterrupt):
118 except (KeyboardInterrupt, util.SignalInterrupt):
120 raise
119 raise
121 except Exception, exc:
120 except Exception, exc:
122 if isinstance(exc, util.Abort):
121 if isinstance(exc, util.Abort):
123 self.ui.warn(_('error: %s hook failed: %s\n') %
122 self.ui.warn(_('error: %s hook failed: %s\n') %
124 (hname, exc.args[0] % exc.args[1:]))
123 (hname, exc.args[0] % exc.args[1:]))
125 else:
124 else:
126 self.ui.warn(_('error: %s hook raised an exception: '
125 self.ui.warn(_('error: %s hook raised an exception: '
127 '%s\n') % (hname, exc))
126 '%s\n') % (hname, exc))
128 if throw:
127 if throw:
129 raise
128 raise
130 self.ui.print_exc()
129 self.ui.print_exc()
131 return True
130 return True
132 if r:
131 if r:
133 if throw:
132 if throw:
134 raise util.Abort(_('%s hook failed') % hname)
133 raise util.Abort(_('%s hook failed') % hname)
135 self.ui.warn(_('warning: %s hook failed\n') % hname)
134 self.ui.warn(_('warning: %s hook failed\n') % hname)
136 return r
135 return r
137
136
138 def runhook(name, cmd):
137 def runhook(name, cmd):
139 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
138 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
140 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
139 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
141 r = util.system(cmd, environ=env, cwd=self.root)
140 r = util.system(cmd, environ=env, cwd=self.root)
142 if r:
141 if r:
143 desc, r = util.explain_exit(r)
142 desc, r = util.explain_exit(r)
144 if throw:
143 if throw:
145 raise util.Abort(_('%s hook %s') % (name, desc))
144 raise util.Abort(_('%s hook %s') % (name, desc))
146 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
145 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
147 return r
146 return r
148
147
149 r = False
148 r = False
150 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
149 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
151 if hname.split(".", 1)[0] == name and cmd]
150 if hname.split(".", 1)[0] == name and cmd]
152 hooks.sort()
151 hooks.sort()
153 for hname, cmd in hooks:
152 for hname, cmd in hooks:
154 if cmd.startswith('python:'):
153 if cmd.startswith('python:'):
155 r = callhook(hname, cmd[7:].strip()) or r
154 r = callhook(hname, cmd[7:].strip()) or r
156 else:
155 else:
157 r = runhook(hname, cmd) or r
156 r = runhook(hname, cmd) or r
158 return r
157 return r
159
158
160 def tags(self):
159 def tags(self):
161 '''return a mapping of tag to node'''
160 '''return a mapping of tag to node'''
162 if not self.tagscache:
161 if not self.tagscache:
163 self.tagscache = {}
162 self.tagscache = {}
164
163
165 def parsetag(line, context):
164 def parsetag(line, context):
166 if not line:
165 if not line:
167 return
166 return
168 s = l.split(" ", 1)
167 s = l.split(" ", 1)
169 if len(s) != 2:
168 if len(s) != 2:
170 self.ui.warn(_("%s: cannot parse entry\n") % context)
169 self.ui.warn(_("%s: cannot parse entry\n") % context)
171 return
170 return
172 node, key = s
171 node, key = s
173 key = key.strip()
172 key = key.strip()
174 try:
173 try:
175 bin_n = bin(node)
174 bin_n = bin(node)
176 except TypeError:
175 except TypeError:
177 self.ui.warn(_("%s: node '%s' is not well formed\n") %
176 self.ui.warn(_("%s: node '%s' is not well formed\n") %
178 (context, node))
177 (context, node))
179 return
178 return
180 if bin_n not in self.changelog.nodemap:
179 if bin_n not in self.changelog.nodemap:
181 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
180 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
182 (context, key))
181 (context, key))
183 return
182 return
184 self.tagscache[key] = bin_n
183 self.tagscache[key] = bin_n
185
184
186 # read the tags file from each head, ending with the tip,
185 # read the tags file from each head, ending with the tip,
187 # and add each tag found to the map, with "newer" ones
186 # and add each tag found to the map, with "newer" ones
188 # taking precedence
187 # taking precedence
189 heads = self.heads()
188 heads = self.heads()
190 heads.reverse()
189 heads.reverse()
191 fl = self.file(".hgtags")
190 fl = self.file(".hgtags")
192 for node in heads:
191 for node in heads:
193 change = self.changelog.read(node)
192 change = self.changelog.read(node)
194 rev = self.changelog.rev(node)
193 rev = self.changelog.rev(node)
195 fn, ff = self.manifest.find(change[0], '.hgtags')
194 fn, ff = self.manifest.find(change[0], '.hgtags')
196 if fn is None: continue
195 if fn is None: continue
197 count = 0
196 count = 0
198 for l in fl.read(fn).splitlines():
197 for l in fl.read(fn).splitlines():
199 count += 1
198 count += 1
200 parsetag(l, _(".hgtags (rev %d:%s), line %d") %
199 parsetag(l, _(".hgtags (rev %d:%s), line %d") %
201 (rev, short(node), count))
200 (rev, short(node), count))
202 try:
201 try:
203 f = self.opener("localtags")
202 f = self.opener("localtags")
204 count = 0
203 count = 0
205 for l in f:
204 for l in f:
206 count += 1
205 count += 1
207 parsetag(l, _("localtags, line %d") % count)
206 parsetag(l, _("localtags, line %d") % count)
208 except IOError:
207 except IOError:
209 pass
208 pass
210
209
211 self.tagscache['tip'] = self.changelog.tip()
210 self.tagscache['tip'] = self.changelog.tip()
212
211
213 return self.tagscache
212 return self.tagscache
214
213
215 def tagslist(self):
214 def tagslist(self):
216 '''return a list of tags ordered by revision'''
215 '''return a list of tags ordered by revision'''
217 l = []
216 l = []
218 for t, n in self.tags().items():
217 for t, n in self.tags().items():
219 try:
218 try:
220 r = self.changelog.rev(n)
219 r = self.changelog.rev(n)
221 except:
220 except:
222 r = -2 # sort to the beginning of the list if unknown
221 r = -2 # sort to the beginning of the list if unknown
223 l.append((r, t, n))
222 l.append((r, t, n))
224 l.sort()
223 l.sort()
225 return [(t, n) for r, t, n in l]
224 return [(t, n) for r, t, n in l]
226
225
227 def nodetags(self, node):
226 def nodetags(self, node):
228 '''return the tags associated with a node'''
227 '''return the tags associated with a node'''
229 if not self.nodetagscache:
228 if not self.nodetagscache:
230 self.nodetagscache = {}
229 self.nodetagscache = {}
231 for t, n in self.tags().items():
230 for t, n in self.tags().items():
232 self.nodetagscache.setdefault(n, []).append(t)
231 self.nodetagscache.setdefault(n, []).append(t)
233 return self.nodetagscache.get(node, [])
232 return self.nodetagscache.get(node, [])
234
233
235 def lookup(self, key):
234 def lookup(self, key):
236 try:
235 try:
237 return self.tags()[key]
236 return self.tags()[key]
238 except KeyError:
237 except KeyError:
239 try:
238 try:
240 return self.changelog.lookup(key)
239 return self.changelog.lookup(key)
241 except:
240 except:
242 raise repo.RepoError(_("unknown revision '%s'") % key)
241 raise repo.RepoError(_("unknown revision '%s'") % key)
243
242
244 def dev(self):
243 def dev(self):
245 return os.lstat(self.path).st_dev
244 return os.lstat(self.path).st_dev
246
245
247 def local(self):
246 def local(self):
248 return True
247 return True
249
248
250 def join(self, f):
249 def join(self, f):
251 return os.path.join(self.path, f)
250 return os.path.join(self.path, f)
252
251
253 def wjoin(self, f):
252 def wjoin(self, f):
254 return os.path.join(self.root, f)
253 return os.path.join(self.root, f)
255
254
256 def file(self, f):
255 def file(self, f):
257 if f[0] == '/':
256 if f[0] == '/':
258 f = f[1:]
257 f = f[1:]
259 return filelog.filelog(self.opener, f, self.revlogversion)
258 return filelog.filelog(self.opener, f, self.revlogversion)
260
259
261 def getcwd(self):
260 def getcwd(self):
262 return self.dirstate.getcwd()
261 return self.dirstate.getcwd()
263
262
264 def wfile(self, f, mode='r'):
263 def wfile(self, f, mode='r'):
265 return self.wopener(f, mode)
264 return self.wopener(f, mode)
266
265
267 def wread(self, filename):
266 def wread(self, filename):
268 if self.encodepats == None:
267 if self.encodepats == None:
269 l = []
268 l = []
270 for pat, cmd in self.ui.configitems("encode"):
269 for pat, cmd in self.ui.configitems("encode"):
271 mf = util.matcher(self.root, "", [pat], [], [])[1]
270 mf = util.matcher(self.root, "", [pat], [], [])[1]
272 l.append((mf, cmd))
271 l.append((mf, cmd))
273 self.encodepats = l
272 self.encodepats = l
274
273
275 data = self.wopener(filename, 'r').read()
274 data = self.wopener(filename, 'r').read()
276
275
277 for mf, cmd in self.encodepats:
276 for mf, cmd in self.encodepats:
278 if mf(filename):
277 if mf(filename):
279 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
278 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
280 data = util.filter(data, cmd)
279 data = util.filter(data, cmd)
281 break
280 break
282
281
283 return data
282 return data
284
283
285 def wwrite(self, filename, data, fd=None):
284 def wwrite(self, filename, data, fd=None):
286 if self.decodepats == None:
285 if self.decodepats == None:
287 l = []
286 l = []
288 for pat, cmd in self.ui.configitems("decode"):
287 for pat, cmd in self.ui.configitems("decode"):
289 mf = util.matcher(self.root, "", [pat], [], [])[1]
288 mf = util.matcher(self.root, "", [pat], [], [])[1]
290 l.append((mf, cmd))
289 l.append((mf, cmd))
291 self.decodepats = l
290 self.decodepats = l
292
291
293 for mf, cmd in self.decodepats:
292 for mf, cmd in self.decodepats:
294 if mf(filename):
293 if mf(filename):
295 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
294 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
296 data = util.filter(data, cmd)
295 data = util.filter(data, cmd)
297 break
296 break
298
297
299 if fd:
298 if fd:
300 return fd.write(data)
299 return fd.write(data)
301 return self.wopener(filename, 'w').write(data)
300 return self.wopener(filename, 'w').write(data)
302
301
303 def transaction(self):
302 def transaction(self):
304 tr = self.transhandle
303 tr = self.transhandle
305 if tr != None and tr.running():
304 if tr != None and tr.running():
306 return tr.nest()
305 return tr.nest()
307
306
308 # save dirstate for rollback
307 # save dirstate for rollback
309 try:
308 try:
310 ds = self.opener("dirstate").read()
309 ds = self.opener("dirstate").read()
311 except IOError:
310 except IOError:
312 ds = ""
311 ds = ""
313 self.opener("journal.dirstate", "w").write(ds)
312 self.opener("journal.dirstate", "w").write(ds)
314
313
315 tr = transaction.transaction(self.ui.warn, self.opener,
314 tr = transaction.transaction(self.ui.warn, self.opener,
316 self.join("journal"),
315 self.join("journal"),
317 aftertrans(self.path))
316 aftertrans(self.path))
318 self.transhandle = tr
317 self.transhandle = tr
319 return tr
318 return tr
320
319
321 def recover(self):
320 def recover(self):
322 l = self.lock()
321 l = self.lock()
323 if os.path.exists(self.join("journal")):
322 if os.path.exists(self.join("journal")):
324 self.ui.status(_("rolling back interrupted transaction\n"))
323 self.ui.status(_("rolling back interrupted transaction\n"))
325 transaction.rollback(self.opener, self.join("journal"))
324 transaction.rollback(self.opener, self.join("journal"))
326 self.reload()
325 self.reload()
327 return True
326 return True
328 else:
327 else:
329 self.ui.warn(_("no interrupted transaction available\n"))
328 self.ui.warn(_("no interrupted transaction available\n"))
330 return False
329 return False
331
330
332 def rollback(self, wlock=None):
331 def rollback(self, wlock=None):
333 if not wlock:
332 if not wlock:
334 wlock = self.wlock()
333 wlock = self.wlock()
335 l = self.lock()
334 l = self.lock()
336 if os.path.exists(self.join("undo")):
335 if os.path.exists(self.join("undo")):
337 self.ui.status(_("rolling back last transaction\n"))
336 self.ui.status(_("rolling back last transaction\n"))
338 transaction.rollback(self.opener, self.join("undo"))
337 transaction.rollback(self.opener, self.join("undo"))
339 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
338 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
340 self.reload()
339 self.reload()
341 self.wreload()
340 self.wreload()
342 else:
341 else:
343 self.ui.warn(_("no rollback information available\n"))
342 self.ui.warn(_("no rollback information available\n"))
344
343
345 def wreload(self):
344 def wreload(self):
346 self.dirstate.read()
345 self.dirstate.read()
347
346
348 def reload(self):
347 def reload(self):
349 self.changelog.load()
348 self.changelog.load()
350 self.manifest.load()
349 self.manifest.load()
351 self.tagscache = None
350 self.tagscache = None
352 self.nodetagscache = None
351 self.nodetagscache = None
353
352
354 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
353 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
355 desc=None):
354 desc=None):
356 try:
355 try:
357 l = lock.lock(self.join(lockname), 0, releasefn, desc=desc)
356 l = lock.lock(self.join(lockname), 0, releasefn, desc=desc)
358 except lock.LockHeld, inst:
357 except lock.LockHeld, inst:
359 if not wait:
358 if not wait:
360 raise
359 raise
361 self.ui.warn(_("waiting for lock on %s held by %s\n") %
360 self.ui.warn(_("waiting for lock on %s held by %s\n") %
362 (desc, inst.args[0]))
361 (desc, inst.args[0]))
363 # default to 600 seconds timeout
362 # default to 600 seconds timeout
364 l = lock.lock(self.join(lockname),
363 l = lock.lock(self.join(lockname),
365 int(self.ui.config("ui", "timeout") or 600),
364 int(self.ui.config("ui", "timeout") or 600),
366 releasefn, desc=desc)
365 releasefn, desc=desc)
367 if acquirefn:
366 if acquirefn:
368 acquirefn()
367 acquirefn()
369 return l
368 return l
370
369
371 def lock(self, wait=1):
370 def lock(self, wait=1):
372 return self.do_lock("lock", wait, acquirefn=self.reload,
371 return self.do_lock("lock", wait, acquirefn=self.reload,
373 desc=_('repository %s') % self.origroot)
372 desc=_('repository %s') % self.origroot)
374
373
375 def wlock(self, wait=1):
374 def wlock(self, wait=1):
376 return self.do_lock("wlock", wait, self.dirstate.write,
375 return self.do_lock("wlock", wait, self.dirstate.write,
377 self.wreload,
376 self.wreload,
378 desc=_('working directory of %s') % self.origroot)
377 desc=_('working directory of %s') % self.origroot)
379
378
380 def checkfilemerge(self, filename, text, filelog, manifest1, manifest2):
379 def checkfilemerge(self, filename, text, filelog, manifest1, manifest2):
381 "determine whether a new filenode is needed"
380 "determine whether a new filenode is needed"
382 fp1 = manifest1.get(filename, nullid)
381 fp1 = manifest1.get(filename, nullid)
383 fp2 = manifest2.get(filename, nullid)
382 fp2 = manifest2.get(filename, nullid)
384
383
385 if fp2 != nullid:
384 if fp2 != nullid:
386 # is one parent an ancestor of the other?
385 # is one parent an ancestor of the other?
387 fpa = filelog.ancestor(fp1, fp2)
386 fpa = filelog.ancestor(fp1, fp2)
388 if fpa == fp1:
387 if fpa == fp1:
389 fp1, fp2 = fp2, nullid
388 fp1, fp2 = fp2, nullid
390 elif fpa == fp2:
389 elif fpa == fp2:
391 fp2 = nullid
390 fp2 = nullid
392
391
393 # is the file unmodified from the parent? report existing entry
392 # is the file unmodified from the parent? report existing entry
394 if fp2 == nullid and text == filelog.read(fp1):
393 if fp2 == nullid and text == filelog.read(fp1):
395 return (fp1, None, None)
394 return (fp1, None, None)
396
395
397 return (None, fp1, fp2)
396 return (None, fp1, fp2)
398
397
399 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
398 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
400 orig_parent = self.dirstate.parents()[0] or nullid
399 orig_parent = self.dirstate.parents()[0] or nullid
401 p1 = p1 or self.dirstate.parents()[0] or nullid
400 p1 = p1 or self.dirstate.parents()[0] or nullid
402 p2 = p2 or self.dirstate.parents()[1] or nullid
401 p2 = p2 or self.dirstate.parents()[1] or nullid
403 c1 = self.changelog.read(p1)
402 c1 = self.changelog.read(p1)
404 c2 = self.changelog.read(p2)
403 c2 = self.changelog.read(p2)
405 m1 = self.manifest.read(c1[0])
404 m1 = self.manifest.read(c1[0])
406 mf1 = self.manifest.readflags(c1[0])
405 mf1 = self.manifest.readflags(c1[0])
407 m2 = self.manifest.read(c2[0])
406 m2 = self.manifest.read(c2[0])
408 changed = []
407 changed = []
409
408
410 if orig_parent == p1:
409 if orig_parent == p1:
411 update_dirstate = 1
410 update_dirstate = 1
412 else:
411 else:
413 update_dirstate = 0
412 update_dirstate = 0
414
413
415 if not wlock:
414 if not wlock:
416 wlock = self.wlock()
415 wlock = self.wlock()
417 l = self.lock()
416 l = self.lock()
418 tr = self.transaction()
417 tr = self.transaction()
419 mm = m1.copy()
418 mm = m1.copy()
420 mfm = mf1.copy()
419 mfm = mf1.copy()
421 linkrev = self.changelog.count()
420 linkrev = self.changelog.count()
422 for f in files:
421 for f in files:
423 try:
422 try:
424 t = self.wread(f)
423 t = self.wread(f)
425 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
424 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
426 r = self.file(f)
425 r = self.file(f)
427 mfm[f] = tm
426 mfm[f] = tm
428
427
429 (entry, fp1, fp2) = self.checkfilemerge(f, t, r, m1, m2)
428 (entry, fp1, fp2) = self.checkfilemerge(f, t, r, m1, m2)
430 if entry:
429 if entry:
431 mm[f] = entry
430 mm[f] = entry
432 continue
431 continue
433
432
434 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
433 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
435 changed.append(f)
434 changed.append(f)
436 if update_dirstate:
435 if update_dirstate:
437 self.dirstate.update([f], "n")
436 self.dirstate.update([f], "n")
438 except IOError:
437 except IOError:
439 try:
438 try:
440 del mm[f]
439 del mm[f]
441 del mfm[f]
440 del mfm[f]
442 if update_dirstate:
441 if update_dirstate:
443 self.dirstate.forget([f])
442 self.dirstate.forget([f])
444 except:
443 except:
445 # deleted from p2?
444 # deleted from p2?
446 pass
445 pass
447
446
448 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
447 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
449 user = user or self.ui.username()
448 user = user or self.ui.username()
450 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
449 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
451 tr.close()
450 tr.close()
452 if update_dirstate:
451 if update_dirstate:
453 self.dirstate.setparents(n, nullid)
452 self.dirstate.setparents(n, nullid)
454
453
455 def commit(self, files=None, text="", user=None, date=None,
454 def commit(self, files=None, text="", user=None, date=None,
456 match=util.always, force=False, lock=None, wlock=None,
455 match=util.always, force=False, lock=None, wlock=None,
457 force_editor=False):
456 force_editor=False):
458 commit = []
457 commit = []
459 remove = []
458 remove = []
460 changed = []
459 changed = []
461
460
462 if files:
461 if files:
463 for f in files:
462 for f in files:
464 s = self.dirstate.state(f)
463 s = self.dirstate.state(f)
465 if s in 'nmai':
464 if s in 'nmai':
466 commit.append(f)
465 commit.append(f)
467 elif s == 'r':
466 elif s == 'r':
468 remove.append(f)
467 remove.append(f)
469 else:
468 else:
470 self.ui.warn(_("%s not tracked!\n") % f)
469 self.ui.warn(_("%s not tracked!\n") % f)
471 else:
470 else:
472 modified, added, removed, deleted, unknown = self.changes(match=match)
471 modified, added, removed, deleted, unknown = self.changes(match=match)
473 commit = modified + added
472 commit = modified + added
474 remove = removed
473 remove = removed
475
474
476 p1, p2 = self.dirstate.parents()
475 p1, p2 = self.dirstate.parents()
477 c1 = self.changelog.read(p1)
476 c1 = self.changelog.read(p1)
478 c2 = self.changelog.read(p2)
477 c2 = self.changelog.read(p2)
479 m1 = self.manifest.read(c1[0])
478 m1 = self.manifest.read(c1[0])
480 mf1 = self.manifest.readflags(c1[0])
479 mf1 = self.manifest.readflags(c1[0])
481 m2 = self.manifest.read(c2[0])
480 m2 = self.manifest.read(c2[0])
482
481
483 if not commit and not remove and not force and p2 == nullid:
482 if not commit and not remove and not force and p2 == nullid:
484 self.ui.status(_("nothing changed\n"))
483 self.ui.status(_("nothing changed\n"))
485 return None
484 return None
486
485
487 xp1 = hex(p1)
486 xp1 = hex(p1)
488 if p2 == nullid: xp2 = ''
487 if p2 == nullid: xp2 = ''
489 else: xp2 = hex(p2)
488 else: xp2 = hex(p2)
490
489
491 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
490 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
492
491
493 if not wlock:
492 if not wlock:
494 wlock = self.wlock()
493 wlock = self.wlock()
495 if not lock:
494 if not lock:
496 lock = self.lock()
495 lock = self.lock()
497 tr = self.transaction()
496 tr = self.transaction()
498
497
499 # check in files
498 # check in files
500 new = {}
499 new = {}
501 linkrev = self.changelog.count()
500 linkrev = self.changelog.count()
502 commit.sort()
501 commit.sort()
503 for f in commit:
502 for f in commit:
504 self.ui.note(f + "\n")
503 self.ui.note(f + "\n")
505 try:
504 try:
506 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
505 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
507 t = self.wread(f)
506 t = self.wread(f)
508 except IOError:
507 except IOError:
509 self.ui.warn(_("trouble committing %s!\n") % f)
508 self.ui.warn(_("trouble committing %s!\n") % f)
510 raise
509 raise
511
510
512 r = self.file(f)
511 r = self.file(f)
513
512
514 meta = {}
513 meta = {}
515 cp = self.dirstate.copied(f)
514 cp = self.dirstate.copied(f)
516 if cp:
515 if cp:
517 meta["copy"] = cp
516 meta["copy"] = cp
518 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
517 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
519 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
518 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
520 fp1, fp2 = nullid, nullid
519 fp1, fp2 = nullid, nullid
521 else:
520 else:
522 entry, fp1, fp2 = self.checkfilemerge(f, t, r, m1, m2)
521 entry, fp1, fp2 = self.checkfilemerge(f, t, r, m1, m2)
523 if entry:
522 if entry:
524 new[f] = entry
523 new[f] = entry
525 continue
524 continue
526
525
527 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
526 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
528 # remember what we've added so that we can later calculate
527 # remember what we've added so that we can later calculate
529 # the files to pull from a set of changesets
528 # the files to pull from a set of changesets
530 changed.append(f)
529 changed.append(f)
531
530
532 # update manifest
531 # update manifest
533 m1 = m1.copy()
532 m1 = m1.copy()
534 m1.update(new)
533 m1.update(new)
535 for f in remove:
534 for f in remove:
536 if f in m1:
535 if f in m1:
537 del m1[f]
536 del m1[f]
538 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
537 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
539 (new, remove))
538 (new, remove))
540
539
541 # add changeset
540 # add changeset
542 new = new.keys()
541 new = new.keys()
543 new.sort()
542 new.sort()
544
543
545 user = user or self.ui.username()
544 user = user or self.ui.username()
546 if not text or force_editor:
545 if not text or force_editor:
547 edittext = []
546 edittext = []
548 if text:
547 if text:
549 edittext.append(text)
548 edittext.append(text)
550 edittext.append("")
549 edittext.append("")
551 if p2 != nullid:
550 if p2 != nullid:
552 edittext.append("HG: branch merge")
551 edittext.append("HG: branch merge")
553 edittext.extend(["HG: changed %s" % f for f in changed])
552 edittext.extend(["HG: changed %s" % f for f in changed])
554 edittext.extend(["HG: removed %s" % f for f in remove])
553 edittext.extend(["HG: removed %s" % f for f in remove])
555 if not changed and not remove:
554 if not changed and not remove:
556 edittext.append("HG: no files changed")
555 edittext.append("HG: no files changed")
557 edittext.append("")
556 edittext.append("")
558 # run editor in the repository root
557 # run editor in the repository root
559 olddir = os.getcwd()
558 olddir = os.getcwd()
560 os.chdir(self.root)
559 os.chdir(self.root)
561 text = self.ui.edit("\n".join(edittext), user)
560 text = self.ui.edit("\n".join(edittext), user)
562 os.chdir(olddir)
561 os.chdir(olddir)
563
562
564 lines = [line.rstrip() for line in text.rstrip().splitlines()]
563 lines = [line.rstrip() for line in text.rstrip().splitlines()]
565 while lines and not lines[0]:
564 while lines and not lines[0]:
566 del lines[0]
565 del lines[0]
567 if not lines:
566 if not lines:
568 return None
567 return None
569 text = '\n'.join(lines)
568 text = '\n'.join(lines)
570 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
569 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
571 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
570 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
572 parent2=xp2)
571 parent2=xp2)
573 tr.close()
572 tr.close()
574
573
575 self.dirstate.setparents(n)
574 self.dirstate.setparents(n)
576 self.dirstate.update(new, "n")
575 self.dirstate.update(new, "n")
577 self.dirstate.forget(remove)
576 self.dirstate.forget(remove)
578
577
579 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
578 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
580 return n
579 return n
581
580
582 def walk(self, node=None, files=[], match=util.always, badmatch=None):
581 def walk(self, node=None, files=[], match=util.always, badmatch=None):
583 if node:
582 if node:
584 fdict = dict.fromkeys(files)
583 fdict = dict.fromkeys(files)
585 for fn in self.manifest.read(self.changelog.read(node)[0]):
584 for fn in self.manifest.read(self.changelog.read(node)[0]):
586 fdict.pop(fn, None)
585 fdict.pop(fn, None)
587 if match(fn):
586 if match(fn):
588 yield 'm', fn
587 yield 'm', fn
589 for fn in fdict:
588 for fn in fdict:
590 if badmatch and badmatch(fn):
589 if badmatch and badmatch(fn):
591 if match(fn):
590 if match(fn):
592 yield 'b', fn
591 yield 'b', fn
593 else:
592 else:
594 self.ui.warn(_('%s: No such file in rev %s\n') % (
593 self.ui.warn(_('%s: No such file in rev %s\n') % (
595 util.pathto(self.getcwd(), fn), short(node)))
594 util.pathto(self.getcwd(), fn), short(node)))
596 else:
595 else:
597 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
596 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
598 yield src, fn
597 yield src, fn
599
598
600 def changes(self, node1=None, node2=None, files=[], match=util.always,
599 def changes(self, node1=None, node2=None, files=[], match=util.always,
601 wlock=None, show_ignored=None):
600 wlock=None, show_ignored=None):
602 """return changes between two nodes or node and working directory
601 """return changes between two nodes or node and working directory
603
602
604 If node1 is None, use the first dirstate parent instead.
603 If node1 is None, use the first dirstate parent instead.
605 If node2 is None, compare node1 with working directory.
604 If node2 is None, compare node1 with working directory.
606 """
605 """
607
606
608 def fcmp(fn, mf):
607 def fcmp(fn, mf):
609 t1 = self.wread(fn)
608 t1 = self.wread(fn)
610 t2 = self.file(fn).read(mf.get(fn, nullid))
609 t2 = self.file(fn).read(mf.get(fn, nullid))
611 return cmp(t1, t2)
610 return cmp(t1, t2)
612
611
613 def mfmatches(node):
612 def mfmatches(node):
614 change = self.changelog.read(node)
613 change = self.changelog.read(node)
615 mf = dict(self.manifest.read(change[0]))
614 mf = dict(self.manifest.read(change[0]))
616 for fn in mf.keys():
615 for fn in mf.keys():
617 if not match(fn):
616 if not match(fn):
618 del mf[fn]
617 del mf[fn]
619 return mf
618 return mf
620
619
621 if node1:
620 if node1:
622 # read the manifest from node1 before the manifest from node2,
621 # read the manifest from node1 before the manifest from node2,
623 # so that we'll hit the manifest cache if we're going through
622 # so that we'll hit the manifest cache if we're going through
624 # all the revisions in parent->child order.
623 # all the revisions in parent->child order.
625 mf1 = mfmatches(node1)
624 mf1 = mfmatches(node1)
626
625
627 # are we comparing the working directory?
626 # are we comparing the working directory?
628 if not node2:
627 if not node2:
629 if not wlock:
628 if not wlock:
630 try:
629 try:
631 wlock = self.wlock(wait=0)
630 wlock = self.wlock(wait=0)
632 except lock.LockException:
631 except lock.LockException:
633 wlock = None
632 wlock = None
634 lookup, modified, added, removed, deleted, unknown, ignored = (
633 lookup, modified, added, removed, deleted, unknown, ignored = (
635 self.dirstate.changes(files, match, show_ignored))
634 self.dirstate.changes(files, match, show_ignored))
636
635
637 # are we comparing working dir against its parent?
636 # are we comparing working dir against its parent?
638 if not node1:
637 if not node1:
639 if lookup:
638 if lookup:
640 # do a full compare of any files that might have changed
639 # do a full compare of any files that might have changed
641 mf2 = mfmatches(self.dirstate.parents()[0])
640 mf2 = mfmatches(self.dirstate.parents()[0])
642 for f in lookup:
641 for f in lookup:
643 if fcmp(f, mf2):
642 if fcmp(f, mf2):
644 modified.append(f)
643 modified.append(f)
645 elif wlock is not None:
644 elif wlock is not None:
646 self.dirstate.update([f], "n")
645 self.dirstate.update([f], "n")
647 else:
646 else:
648 # we are comparing working dir against non-parent
647 # we are comparing working dir against non-parent
649 # generate a pseudo-manifest for the working dir
648 # generate a pseudo-manifest for the working dir
650 mf2 = mfmatches(self.dirstate.parents()[0])
649 mf2 = mfmatches(self.dirstate.parents()[0])
651 for f in lookup + modified + added:
650 for f in lookup + modified + added:
652 mf2[f] = ""
651 mf2[f] = ""
653 for f in removed:
652 for f in removed:
654 if f in mf2:
653 if f in mf2:
655 del mf2[f]
654 del mf2[f]
656 else:
655 else:
657 # we are comparing two revisions
656 # we are comparing two revisions
658 deleted, unknown, ignored = [], [], []
657 deleted, unknown, ignored = [], [], []
659 mf2 = mfmatches(node2)
658 mf2 = mfmatches(node2)
660
659
661 if node1:
660 if node1:
662 # flush lists from dirstate before comparing manifests
661 # flush lists from dirstate before comparing manifests
663 modified, added = [], []
662 modified, added = [], []
664
663
665 for fn in mf2:
664 for fn in mf2:
666 if mf1.has_key(fn):
665 if mf1.has_key(fn):
667 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
666 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
668 modified.append(fn)
667 modified.append(fn)
669 del mf1[fn]
668 del mf1[fn]
670 else:
669 else:
671 added.append(fn)
670 added.append(fn)
672
671
673 removed = mf1.keys()
672 removed = mf1.keys()
674
673
675 # sort and return results:
674 # sort and return results:
676 for l in modified, added, removed, deleted, unknown, ignored:
675 for l in modified, added, removed, deleted, unknown, ignored:
677 l.sort()
676 l.sort()
678 if show_ignored is None:
677 if show_ignored is None:
679 return (modified, added, removed, deleted, unknown)
678 return (modified, added, removed, deleted, unknown)
680 else:
679 else:
681 return (modified, added, removed, deleted, unknown, ignored)
680 return (modified, added, removed, deleted, unknown, ignored)
682
681
683 def add(self, list, wlock=None):
682 def add(self, list, wlock=None):
684 if not wlock:
683 if not wlock:
685 wlock = self.wlock()
684 wlock = self.wlock()
686 for f in list:
685 for f in list:
687 p = self.wjoin(f)
686 p = self.wjoin(f)
688 if not os.path.exists(p):
687 if not os.path.exists(p):
689 self.ui.warn(_("%s does not exist!\n") % f)
688 self.ui.warn(_("%s does not exist!\n") % f)
690 elif not os.path.isfile(p):
689 elif not os.path.isfile(p):
691 self.ui.warn(_("%s not added: only files supported currently\n")
690 self.ui.warn(_("%s not added: only files supported currently\n")
692 % f)
691 % f)
693 elif self.dirstate.state(f) in 'an':
692 elif self.dirstate.state(f) in 'an':
694 self.ui.warn(_("%s already tracked!\n") % f)
693 self.ui.warn(_("%s already tracked!\n") % f)
695 else:
694 else:
696 self.dirstate.update([f], "a")
695 self.dirstate.update([f], "a")
697
696
698 def forget(self, list, wlock=None):
697 def forget(self, list, wlock=None):
699 if not wlock:
698 if not wlock:
700 wlock = self.wlock()
699 wlock = self.wlock()
701 for f in list:
700 for f in list:
702 if self.dirstate.state(f) not in 'ai':
701 if self.dirstate.state(f) not in 'ai':
703 self.ui.warn(_("%s not added!\n") % f)
702 self.ui.warn(_("%s not added!\n") % f)
704 else:
703 else:
705 self.dirstate.forget([f])
704 self.dirstate.forget([f])
706
705
707 def remove(self, list, unlink=False, wlock=None):
706 def remove(self, list, unlink=False, wlock=None):
708 if unlink:
707 if unlink:
709 for f in list:
708 for f in list:
710 try:
709 try:
711 util.unlink(self.wjoin(f))
710 util.unlink(self.wjoin(f))
712 except OSError, inst:
711 except OSError, inst:
713 if inst.errno != errno.ENOENT:
712 if inst.errno != errno.ENOENT:
714 raise
713 raise
715 if not wlock:
714 if not wlock:
716 wlock = self.wlock()
715 wlock = self.wlock()
717 for f in list:
716 for f in list:
718 p = self.wjoin(f)
717 p = self.wjoin(f)
719 if os.path.exists(p):
718 if os.path.exists(p):
720 self.ui.warn(_("%s still exists!\n") % f)
719 self.ui.warn(_("%s still exists!\n") % f)
721 elif self.dirstate.state(f) == 'a':
720 elif self.dirstate.state(f) == 'a':
722 self.dirstate.forget([f])
721 self.dirstate.forget([f])
723 elif f not in self.dirstate:
722 elif f not in self.dirstate:
724 self.ui.warn(_("%s not tracked!\n") % f)
723 self.ui.warn(_("%s not tracked!\n") % f)
725 else:
724 else:
726 self.dirstate.update([f], "r")
725 self.dirstate.update([f], "r")
727
726
728 def undelete(self, list, wlock=None):
727 def undelete(self, list, wlock=None):
729 p = self.dirstate.parents()[0]
728 p = self.dirstate.parents()[0]
730 mn = self.changelog.read(p)[0]
729 mn = self.changelog.read(p)[0]
731 mf = self.manifest.readflags(mn)
730 mf = self.manifest.readflags(mn)
732 m = self.manifest.read(mn)
731 m = self.manifest.read(mn)
733 if not wlock:
732 if not wlock:
734 wlock = self.wlock()
733 wlock = self.wlock()
735 for f in list:
734 for f in list:
736 if self.dirstate.state(f) not in "r":
735 if self.dirstate.state(f) not in "r":
737 self.ui.warn("%s not removed!\n" % f)
736 self.ui.warn("%s not removed!\n" % f)
738 else:
737 else:
739 t = self.file(f).read(m[f])
738 t = self.file(f).read(m[f])
740 self.wwrite(f, t)
739 self.wwrite(f, t)
741 util.set_exec(self.wjoin(f), mf[f])
740 util.set_exec(self.wjoin(f), mf[f])
742 self.dirstate.update([f], "n")
741 self.dirstate.update([f], "n")
743
742
744 def copy(self, source, dest, wlock=None):
743 def copy(self, source, dest, wlock=None):
745 p = self.wjoin(dest)
744 p = self.wjoin(dest)
746 if not os.path.exists(p):
745 if not os.path.exists(p):
747 self.ui.warn(_("%s does not exist!\n") % dest)
746 self.ui.warn(_("%s does not exist!\n") % dest)
748 elif not os.path.isfile(p):
747 elif not os.path.isfile(p):
749 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
748 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
750 else:
749 else:
751 if not wlock:
750 if not wlock:
752 wlock = self.wlock()
751 wlock = self.wlock()
753 if self.dirstate.state(dest) == '?':
752 if self.dirstate.state(dest) == '?':
754 self.dirstate.update([dest], "a")
753 self.dirstate.update([dest], "a")
755 self.dirstate.copy(source, dest)
754 self.dirstate.copy(source, dest)
756
755
757 def heads(self, start=None):
756 def heads(self, start=None):
758 heads = self.changelog.heads(start)
757 heads = self.changelog.heads(start)
759 # sort the output in rev descending order
758 # sort the output in rev descending order
760 heads = [(-self.changelog.rev(h), h) for h in heads]
759 heads = [(-self.changelog.rev(h), h) for h in heads]
761 heads.sort()
760 heads.sort()
762 return [n for (r, n) in heads]
761 return [n for (r, n) in heads]
763
762
764 # branchlookup returns a dict giving a list of branches for
763 # branchlookup returns a dict giving a list of branches for
765 # each head. A branch is defined as the tag of a node or
764 # each head. A branch is defined as the tag of a node or
766 # the branch of the node's parents. If a node has multiple
765 # the branch of the node's parents. If a node has multiple
767 # branch tags, tags are eliminated if they are visible from other
766 # branch tags, tags are eliminated if they are visible from other
768 # branch tags.
767 # branch tags.
769 #
768 #
770 # So, for this graph: a->b->c->d->e
769 # So, for this graph: a->b->c->d->e
771 # \ /
770 # \ /
772 # aa -----/
771 # aa -----/
773 # a has tag 2.6.12
772 # a has tag 2.6.12
774 # d has tag 2.6.13
773 # d has tag 2.6.13
775 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
774 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
776 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
775 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
777 # from the list.
776 # from the list.
778 #
777 #
779 # It is possible that more than one head will have the same branch tag.
778 # It is possible that more than one head will have the same branch tag.
780 # callers need to check the result for multiple heads under the same
779 # callers need to check the result for multiple heads under the same
781 # branch tag if that is a problem for them (ie checkout of a specific
780 # branch tag if that is a problem for them (ie checkout of a specific
782 # branch).
781 # branch).
783 #
782 #
784 # passing in a specific branch will limit the depth of the search
783 # passing in a specific branch will limit the depth of the search
785 # through the parents. It won't limit the branches returned in the
784 # through the parents. It won't limit the branches returned in the
786 # result though.
785 # result though.
787 def branchlookup(self, heads=None, branch=None):
786 def branchlookup(self, heads=None, branch=None):
788 if not heads:
787 if not heads:
789 heads = self.heads()
788 heads = self.heads()
790 headt = [ h for h in heads ]
789 headt = [ h for h in heads ]
791 chlog = self.changelog
790 chlog = self.changelog
792 branches = {}
791 branches = {}
793 merges = []
792 merges = []
794 seenmerge = {}
793 seenmerge = {}
795
794
796 # traverse the tree once for each head, recording in the branches
795 # traverse the tree once for each head, recording in the branches
797 # dict which tags are visible from this head. The branches
796 # dict which tags are visible from this head. The branches
798 # dict also records which tags are visible from each tag
797 # dict also records which tags are visible from each tag
799 # while we traverse.
798 # while we traverse.
800 while headt or merges:
799 while headt or merges:
801 if merges:
800 if merges:
802 n, found = merges.pop()
801 n, found = merges.pop()
803 visit = [n]
802 visit = [n]
804 else:
803 else:
805 h = headt.pop()
804 h = headt.pop()
806 visit = [h]
805 visit = [h]
807 found = [h]
806 found = [h]
808 seen = {}
807 seen = {}
809 while visit:
808 while visit:
810 n = visit.pop()
809 n = visit.pop()
811 if n in seen:
810 if n in seen:
812 continue
811 continue
813 pp = chlog.parents(n)
812 pp = chlog.parents(n)
814 tags = self.nodetags(n)
813 tags = self.nodetags(n)
815 if tags:
814 if tags:
816 for x in tags:
815 for x in tags:
817 if x == 'tip':
816 if x == 'tip':
818 continue
817 continue
819 for f in found:
818 for f in found:
820 branches.setdefault(f, {})[n] = 1
819 branches.setdefault(f, {})[n] = 1
821 branches.setdefault(n, {})[n] = 1
820 branches.setdefault(n, {})[n] = 1
822 break
821 break
823 if n not in found:
822 if n not in found:
824 found.append(n)
823 found.append(n)
825 if branch in tags:
824 if branch in tags:
826 continue
825 continue
827 seen[n] = 1
826 seen[n] = 1
828 if pp[1] != nullid and n not in seenmerge:
827 if pp[1] != nullid and n not in seenmerge:
829 merges.append((pp[1], [x for x in found]))
828 merges.append((pp[1], [x for x in found]))
830 seenmerge[n] = 1
829 seenmerge[n] = 1
831 if pp[0] != nullid:
830 if pp[0] != nullid:
832 visit.append(pp[0])
831 visit.append(pp[0])
833 # traverse the branches dict, eliminating branch tags from each
832 # traverse the branches dict, eliminating branch tags from each
834 # head that are visible from another branch tag for that head.
833 # head that are visible from another branch tag for that head.
835 out = {}
834 out = {}
836 viscache = {}
835 viscache = {}
837 for h in heads:
836 for h in heads:
838 def visible(node):
837 def visible(node):
839 if node in viscache:
838 if node in viscache:
840 return viscache[node]
839 return viscache[node]
841 ret = {}
840 ret = {}
842 visit = [node]
841 visit = [node]
843 while visit:
842 while visit:
844 x = visit.pop()
843 x = visit.pop()
845 if x in viscache:
844 if x in viscache:
846 ret.update(viscache[x])
845 ret.update(viscache[x])
847 elif x not in ret:
846 elif x not in ret:
848 ret[x] = 1
847 ret[x] = 1
849 if x in branches:
848 if x in branches:
850 visit[len(visit):] = branches[x].keys()
849 visit[len(visit):] = branches[x].keys()
851 viscache[node] = ret
850 viscache[node] = ret
852 return ret
851 return ret
853 if h not in branches:
852 if h not in branches:
854 continue
853 continue
855 # O(n^2), but somewhat limited. This only searches the
854 # O(n^2), but somewhat limited. This only searches the
856 # tags visible from a specific head, not all the tags in the
855 # tags visible from a specific head, not all the tags in the
857 # whole repo.
856 # whole repo.
858 for b in branches[h]:
857 for b in branches[h]:
859 vis = False
858 vis = False
860 for bb in branches[h].keys():
859 for bb in branches[h].keys():
861 if b != bb:
860 if b != bb:
862 if b in visible(bb):
861 if b in visible(bb):
863 vis = True
862 vis = True
864 break
863 break
865 if not vis:
864 if not vis:
866 l = out.setdefault(h, [])
865 l = out.setdefault(h, [])
867 l[len(l):] = self.nodetags(b)
866 l[len(l):] = self.nodetags(b)
868 return out
867 return out
869
868
870 def branches(self, nodes):
869 def branches(self, nodes):
871 if not nodes:
870 if not nodes:
872 nodes = [self.changelog.tip()]
871 nodes = [self.changelog.tip()]
873 b = []
872 b = []
874 for n in nodes:
873 for n in nodes:
875 t = n
874 t = n
876 while 1:
875 while 1:
877 p = self.changelog.parents(n)
876 p = self.changelog.parents(n)
878 if p[1] != nullid or p[0] == nullid:
877 if p[1] != nullid or p[0] == nullid:
879 b.append((t, n, p[0], p[1]))
878 b.append((t, n, p[0], p[1]))
880 break
879 break
881 n = p[0]
880 n = p[0]
882 return b
881 return b
883
882
884 def between(self, pairs):
883 def between(self, pairs):
885 r = []
884 r = []
886
885
887 for top, bottom in pairs:
886 for top, bottom in pairs:
888 n, l, i = top, [], 0
887 n, l, i = top, [], 0
889 f = 1
888 f = 1
890
889
891 while n != bottom:
890 while n != bottom:
892 p = self.changelog.parents(n)[0]
891 p = self.changelog.parents(n)[0]
893 if i == f:
892 if i == f:
894 l.append(n)
893 l.append(n)
895 f = f * 2
894 f = f * 2
896 n = p
895 n = p
897 i += 1
896 i += 1
898
897
899 r.append(l)
898 r.append(l)
900
899
901 return r
900 return r
902
901
903 def findincoming(self, remote, base=None, heads=None, force=False):
902 def findincoming(self, remote, base=None, heads=None, force=False):
904 """Return list of roots of the subsets of missing nodes from remote
903 """Return list of roots of the subsets of missing nodes from remote
905
904
906 If base dict is specified, assume that these nodes and their parents
905 If base dict is specified, assume that these nodes and their parents
907 exist on the remote side and that no child of a node of base exists
906 exist on the remote side and that no child of a node of base exists
908 in both remote and self.
907 in both remote and self.
909 Furthermore base will be updated to include the nodes that exists
908 Furthermore base will be updated to include the nodes that exists
910 in self and remote but no children exists in self and remote.
909 in self and remote but no children exists in self and remote.
911 If a list of heads is specified, return only nodes which are heads
910 If a list of heads is specified, return only nodes which are heads
912 or ancestors of these heads.
911 or ancestors of these heads.
913
912
914 All the ancestors of base are in self and in remote.
913 All the ancestors of base are in self and in remote.
915 All the descendants of the list returned are missing in self.
914 All the descendants of the list returned are missing in self.
916 (and so we know that the rest of the nodes are missing in remote, see
915 (and so we know that the rest of the nodes are missing in remote, see
917 outgoing)
916 outgoing)
918 """
917 """
919 m = self.changelog.nodemap
918 m = self.changelog.nodemap
920 search = []
919 search = []
921 fetch = {}
920 fetch = {}
922 seen = {}
921 seen = {}
923 seenbranch = {}
922 seenbranch = {}
924 if base == None:
923 if base == None:
925 base = {}
924 base = {}
926
925
927 if not heads:
926 if not heads:
928 heads = remote.heads()
927 heads = remote.heads()
929
928
930 if self.changelog.tip() == nullid:
929 if self.changelog.tip() == nullid:
931 base[nullid] = 1
930 base[nullid] = 1
932 if heads != [nullid]:
931 if heads != [nullid]:
933 return [nullid]
932 return [nullid]
934 return []
933 return []
935
934
936 # assume we're closer to the tip than the root
935 # assume we're closer to the tip than the root
937 # and start by examining the heads
936 # and start by examining the heads
938 self.ui.status(_("searching for changes\n"))
937 self.ui.status(_("searching for changes\n"))
939
938
940 unknown = []
939 unknown = []
941 for h in heads:
940 for h in heads:
942 if h not in m:
941 if h not in m:
943 unknown.append(h)
942 unknown.append(h)
944 else:
943 else:
945 base[h] = 1
944 base[h] = 1
946
945
947 if not unknown:
946 if not unknown:
948 return []
947 return []
949
948
950 req = dict.fromkeys(unknown)
949 req = dict.fromkeys(unknown)
951 reqcnt = 0
950 reqcnt = 0
952
951
953 # search through remote branches
952 # search through remote branches
954 # a 'branch' here is a linear segment of history, with four parts:
953 # a 'branch' here is a linear segment of history, with four parts:
955 # head, root, first parent, second parent
954 # head, root, first parent, second parent
956 # (a branch always has two parents (or none) by definition)
955 # (a branch always has two parents (or none) by definition)
957 unknown = remote.branches(unknown)
956 unknown = remote.branches(unknown)
958 while unknown:
957 while unknown:
959 r = []
958 r = []
960 while unknown:
959 while unknown:
961 n = unknown.pop(0)
960 n = unknown.pop(0)
962 if n[0] in seen:
961 if n[0] in seen:
963 continue
962 continue
964
963
965 self.ui.debug(_("examining %s:%s\n")
964 self.ui.debug(_("examining %s:%s\n")
966 % (short(n[0]), short(n[1])))
965 % (short(n[0]), short(n[1])))
967 if n[0] == nullid: # found the end of the branch
966 if n[0] == nullid: # found the end of the branch
968 pass
967 pass
969 elif n in seenbranch:
968 elif n in seenbranch:
970 self.ui.debug(_("branch already found\n"))
969 self.ui.debug(_("branch already found\n"))
971 continue
970 continue
972 elif n[1] and n[1] in m: # do we know the base?
971 elif n[1] and n[1] in m: # do we know the base?
973 self.ui.debug(_("found incomplete branch %s:%s\n")
972 self.ui.debug(_("found incomplete branch %s:%s\n")
974 % (short(n[0]), short(n[1])))
973 % (short(n[0]), short(n[1])))
975 search.append(n) # schedule branch range for scanning
974 search.append(n) # schedule branch range for scanning
976 seenbranch[n] = 1
975 seenbranch[n] = 1
977 else:
976 else:
978 if n[1] not in seen and n[1] not in fetch:
977 if n[1] not in seen and n[1] not in fetch:
979 if n[2] in m and n[3] in m:
978 if n[2] in m and n[3] in m:
980 self.ui.debug(_("found new changeset %s\n") %
979 self.ui.debug(_("found new changeset %s\n") %
981 short(n[1]))
980 short(n[1]))
982 fetch[n[1]] = 1 # earliest unknown
981 fetch[n[1]] = 1 # earliest unknown
983 for p in n[2:4]:
982 for p in n[2:4]:
984 if p in m:
983 if p in m:
985 base[p] = 1 # latest known
984 base[p] = 1 # latest known
986
985
987 for p in n[2:4]:
986 for p in n[2:4]:
988 if p not in req and p not in m:
987 if p not in req and p not in m:
989 r.append(p)
988 r.append(p)
990 req[p] = 1
989 req[p] = 1
991 seen[n[0]] = 1
990 seen[n[0]] = 1
992
991
993 if r:
992 if r:
994 reqcnt += 1
993 reqcnt += 1
995 self.ui.debug(_("request %d: %s\n") %
994 self.ui.debug(_("request %d: %s\n") %
996 (reqcnt, " ".join(map(short, r))))
995 (reqcnt, " ".join(map(short, r))))
997 for p in range(0, len(r), 10):
996 for p in range(0, len(r), 10):
998 for b in remote.branches(r[p:p+10]):
997 for b in remote.branches(r[p:p+10]):
999 self.ui.debug(_("received %s:%s\n") %
998 self.ui.debug(_("received %s:%s\n") %
1000 (short(b[0]), short(b[1])))
999 (short(b[0]), short(b[1])))
1001 unknown.append(b)
1000 unknown.append(b)
1002
1001
1003 # do binary search on the branches we found
1002 # do binary search on the branches we found
1004 while search:
1003 while search:
1005 n = search.pop(0)
1004 n = search.pop(0)
1006 reqcnt += 1
1005 reqcnt += 1
1007 l = remote.between([(n[0], n[1])])[0]
1006 l = remote.between([(n[0], n[1])])[0]
1008 l.append(n[1])
1007 l.append(n[1])
1009 p = n[0]
1008 p = n[0]
1010 f = 1
1009 f = 1
1011 for i in l:
1010 for i in l:
1012 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1011 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1013 if i in m:
1012 if i in m:
1014 if f <= 2:
1013 if f <= 2:
1015 self.ui.debug(_("found new branch changeset %s\n") %
1014 self.ui.debug(_("found new branch changeset %s\n") %
1016 short(p))
1015 short(p))
1017 fetch[p] = 1
1016 fetch[p] = 1
1018 base[i] = 1
1017 base[i] = 1
1019 else:
1018 else:
1020 self.ui.debug(_("narrowed branch search to %s:%s\n")
1019 self.ui.debug(_("narrowed branch search to %s:%s\n")
1021 % (short(p), short(i)))
1020 % (short(p), short(i)))
1022 search.append((p, i))
1021 search.append((p, i))
1023 break
1022 break
1024 p, f = i, f * 2
1023 p, f = i, f * 2
1025
1024
1026 # sanity check our fetch list
1025 # sanity check our fetch list
1027 for f in fetch.keys():
1026 for f in fetch.keys():
1028 if f in m:
1027 if f in m:
1029 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1028 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1030
1029
1031 if base.keys() == [nullid]:
1030 if base.keys() == [nullid]:
1032 if force:
1031 if force:
1033 self.ui.warn(_("warning: repository is unrelated\n"))
1032 self.ui.warn(_("warning: repository is unrelated\n"))
1034 else:
1033 else:
1035 raise util.Abort(_("repository is unrelated"))
1034 raise util.Abort(_("repository is unrelated"))
1036
1035
1037 self.ui.note(_("found new changesets starting at ") +
1036 self.ui.note(_("found new changesets starting at ") +
1038 " ".join([short(f) for f in fetch]) + "\n")
1037 " ".join([short(f) for f in fetch]) + "\n")
1039
1038
1040 self.ui.debug(_("%d total queries\n") % reqcnt)
1039 self.ui.debug(_("%d total queries\n") % reqcnt)
1041
1040
1042 return fetch.keys()
1041 return fetch.keys()
1043
1042
1044 def findoutgoing(self, remote, base=None, heads=None, force=False):
1043 def findoutgoing(self, remote, base=None, heads=None, force=False):
1045 """Return list of nodes that are roots of subsets not in remote
1044 """Return list of nodes that are roots of subsets not in remote
1046
1045
1047 If base dict is specified, assume that these nodes and their parents
1046 If base dict is specified, assume that these nodes and their parents
1048 exist on the remote side.
1047 exist on the remote side.
1049 If a list of heads is specified, return only nodes which are heads
1048 If a list of heads is specified, return only nodes which are heads
1050 or ancestors of these heads, and return a second element which
1049 or ancestors of these heads, and return a second element which
1051 contains all remote heads which get new children.
1050 contains all remote heads which get new children.
1052 """
1051 """
1053 if base == None:
1052 if base == None:
1054 base = {}
1053 base = {}
1055 self.findincoming(remote, base, heads, force=force)
1054 self.findincoming(remote, base, heads, force=force)
1056
1055
1057 self.ui.debug(_("common changesets up to ")
1056 self.ui.debug(_("common changesets up to ")
1058 + " ".join(map(short, base.keys())) + "\n")
1057 + " ".join(map(short, base.keys())) + "\n")
1059
1058
1060 remain = dict.fromkeys(self.changelog.nodemap)
1059 remain = dict.fromkeys(self.changelog.nodemap)
1061
1060
1062 # prune everything remote has from the tree
1061 # prune everything remote has from the tree
1063 del remain[nullid]
1062 del remain[nullid]
1064 remove = base.keys()
1063 remove = base.keys()
1065 while remove:
1064 while remove:
1066 n = remove.pop(0)
1065 n = remove.pop(0)
1067 if n in remain:
1066 if n in remain:
1068 del remain[n]
1067 del remain[n]
1069 for p in self.changelog.parents(n):
1068 for p in self.changelog.parents(n):
1070 remove.append(p)
1069 remove.append(p)
1071
1070
1072 # find every node whose parents have been pruned
1071 # find every node whose parents have been pruned
1073 subset = []
1072 subset = []
1074 # find every remote head that will get new children
1073 # find every remote head that will get new children
1075 updated_heads = {}
1074 updated_heads = {}
1076 for n in remain:
1075 for n in remain:
1077 p1, p2 = self.changelog.parents(n)
1076 p1, p2 = self.changelog.parents(n)
1078 if p1 not in remain and p2 not in remain:
1077 if p1 not in remain and p2 not in remain:
1079 subset.append(n)
1078 subset.append(n)
1080 if heads:
1079 if heads:
1081 if p1 in heads:
1080 if p1 in heads:
1082 updated_heads[p1] = True
1081 updated_heads[p1] = True
1083 if p2 in heads:
1082 if p2 in heads:
1084 updated_heads[p2] = True
1083 updated_heads[p2] = True
1085
1084
1086 # this is the set of all roots we have to push
1085 # this is the set of all roots we have to push
1087 if heads:
1086 if heads:
1088 return subset, updated_heads.keys()
1087 return subset, updated_heads.keys()
1089 else:
1088 else:
1090 return subset
1089 return subset
1091
1090
1092 def pull(self, remote, heads=None, force=False):
1091 def pull(self, remote, heads=None, force=False):
1093 l = self.lock()
1092 l = self.lock()
1094
1093
1095 fetch = self.findincoming(remote, force=force)
1094 fetch = self.findincoming(remote, force=force)
1096 if fetch == [nullid]:
1095 if fetch == [nullid]:
1097 self.ui.status(_("requesting all changes\n"))
1096 self.ui.status(_("requesting all changes\n"))
1098
1097
1099 if not fetch:
1098 if not fetch:
1100 self.ui.status(_("no changes found\n"))
1099 self.ui.status(_("no changes found\n"))
1101 return 0
1100 return 0
1102
1101
1103 if heads is None:
1102 if heads is None:
1104 cg = remote.changegroup(fetch, 'pull')
1103 cg = remote.changegroup(fetch, 'pull')
1105 else:
1104 else:
1106 cg = remote.changegroupsubset(fetch, heads, 'pull')
1105 cg = remote.changegroupsubset(fetch, heads, 'pull')
1107 return self.addchangegroup(cg, 'pull')
1106 return self.addchangegroup(cg, 'pull')
1108
1107
1109 def push(self, remote, force=False, revs=None):
1108 def push(self, remote, force=False, revs=None):
1110 # there are two ways to push to remote repo:
1109 # there are two ways to push to remote repo:
1111 #
1110 #
1112 # addchangegroup assumes local user can lock remote
1111 # addchangegroup assumes local user can lock remote
1113 # repo (local filesystem, old ssh servers).
1112 # repo (local filesystem, old ssh servers).
1114 #
1113 #
1115 # unbundle assumes local user cannot lock remote repo (new ssh
1114 # unbundle assumes local user cannot lock remote repo (new ssh
1116 # servers, http servers).
1115 # servers, http servers).
1117
1116
1118 if 'unbundle' in remote.capabilities:
1117 if 'unbundle' in remote.capabilities:
1119 self.push_unbundle(remote, force, revs)
1118 self.push_unbundle(remote, force, revs)
1120 else:
1119 else:
1121 self.push_addchangegroup(remote, force, revs)
1120 self.push_addchangegroup(remote, force, revs)
1122
1121
1123 def prepush(self, remote, force, revs):
1122 def prepush(self, remote, force, revs):
1124 base = {}
1123 base = {}
1125 remote_heads = remote.heads()
1124 remote_heads = remote.heads()
1126 inc = self.findincoming(remote, base, remote_heads, force=force)
1125 inc = self.findincoming(remote, base, remote_heads, force=force)
1127 if not force and inc:
1126 if not force and inc:
1128 self.ui.warn(_("abort: unsynced remote changes!\n"))
1127 self.ui.warn(_("abort: unsynced remote changes!\n"))
1129 self.ui.status(_("(did you forget to sync?"
1128 self.ui.status(_("(did you forget to sync?"
1130 " use push -f to force)\n"))
1129 " use push -f to force)\n"))
1131 return None, 1
1130 return None, 1
1132
1131
1133 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1132 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1134 if revs is not None:
1133 if revs is not None:
1135 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1134 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1136 else:
1135 else:
1137 bases, heads = update, self.changelog.heads()
1136 bases, heads = update, self.changelog.heads()
1138
1137
1139 if not bases:
1138 if not bases:
1140 self.ui.status(_("no changes found\n"))
1139 self.ui.status(_("no changes found\n"))
1141 return None, 1
1140 return None, 1
1142 elif not force:
1141 elif not force:
1143 # FIXME we don't properly detect creation of new heads
1142 # FIXME we don't properly detect creation of new heads
1144 # in the push -r case, assume the user knows what he's doing
1143 # in the push -r case, assume the user knows what he's doing
1145 if not revs and len(remote_heads) < len(heads) \
1144 if not revs and len(remote_heads) < len(heads) \
1146 and remote_heads != [nullid]:
1145 and remote_heads != [nullid]:
1147 self.ui.warn(_("abort: push creates new remote branches!\n"))
1146 self.ui.warn(_("abort: push creates new remote branches!\n"))
1148 self.ui.status(_("(did you forget to merge?"
1147 self.ui.status(_("(did you forget to merge?"
1149 " use push -f to force)\n"))
1148 " use push -f to force)\n"))
1150 return None, 1
1149 return None, 1
1151
1150
1152 if revs is None:
1151 if revs is None:
1153 cg = self.changegroup(update, 'push')
1152 cg = self.changegroup(update, 'push')
1154 else:
1153 else:
1155 cg = self.changegroupsubset(update, revs, 'push')
1154 cg = self.changegroupsubset(update, revs, 'push')
1156 return cg, remote_heads
1155 return cg, remote_heads
1157
1156
1158 def push_addchangegroup(self, remote, force, revs):
1157 def push_addchangegroup(self, remote, force, revs):
1159 lock = remote.lock()
1158 lock = remote.lock()
1160
1159
1161 ret = self.prepush(remote, force, revs)
1160 ret = self.prepush(remote, force, revs)
1162 if ret[0] is not None:
1161 if ret[0] is not None:
1163 cg, remote_heads = ret
1162 cg, remote_heads = ret
1164 return remote.addchangegroup(cg, 'push')
1163 return remote.addchangegroup(cg, 'push')
1165 return ret[1]
1164 return ret[1]
1166
1165
1167 def push_unbundle(self, remote, force, revs):
1166 def push_unbundle(self, remote, force, revs):
1168 # local repo finds heads on server, finds out what revs it
1167 # local repo finds heads on server, finds out what revs it
1169 # must push. once revs transferred, if server finds it has
1168 # must push. once revs transferred, if server finds it has
1170 # different heads (someone else won commit/push race), server
1169 # different heads (someone else won commit/push race), server
1171 # aborts.
1170 # aborts.
1172
1171
1173 ret = self.prepush(remote, force, revs)
1172 ret = self.prepush(remote, force, revs)
1174 if ret[0] is not None:
1173 if ret[0] is not None:
1175 cg, remote_heads = ret
1174 cg, remote_heads = ret
1176 if force: remote_heads = ['force']
1175 if force: remote_heads = ['force']
1177 return remote.unbundle(cg, remote_heads, 'push')
1176 return remote.unbundle(cg, remote_heads, 'push')
1178 return ret[1]
1177 return ret[1]
1179
1178
1180 def changegroupsubset(self, bases, heads, source):
1179 def changegroupsubset(self, bases, heads, source):
1181 """This function generates a changegroup consisting of all the nodes
1180 """This function generates a changegroup consisting of all the nodes
1182 that are descendents of any of the bases, and ancestors of any of
1181 that are descendents of any of the bases, and ancestors of any of
1183 the heads.
1182 the heads.
1184
1183
1185 It is fairly complex as determining which filenodes and which
1184 It is fairly complex as determining which filenodes and which
1186 manifest nodes need to be included for the changeset to be complete
1185 manifest nodes need to be included for the changeset to be complete
1187 is non-trivial.
1186 is non-trivial.
1188
1187
1189 Another wrinkle is doing the reverse, figuring out which changeset in
1188 Another wrinkle is doing the reverse, figuring out which changeset in
1190 the changegroup a particular filenode or manifestnode belongs to."""
1189 the changegroup a particular filenode or manifestnode belongs to."""
1191
1190
1192 self.hook('preoutgoing', throw=True, source=source)
1191 self.hook('preoutgoing', throw=True, source=source)
1193
1192
1194 # Set up some initial variables
1193 # Set up some initial variables
1195 # Make it easy to refer to self.changelog
1194 # Make it easy to refer to self.changelog
1196 cl = self.changelog
1195 cl = self.changelog
1197 # msng is short for missing - compute the list of changesets in this
1196 # msng is short for missing - compute the list of changesets in this
1198 # changegroup.
1197 # changegroup.
1199 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1198 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1200 # Some bases may turn out to be superfluous, and some heads may be
1199 # Some bases may turn out to be superfluous, and some heads may be
1201 # too. nodesbetween will return the minimal set of bases and heads
1200 # too. nodesbetween will return the minimal set of bases and heads
1202 # necessary to re-create the changegroup.
1201 # necessary to re-create the changegroup.
1203
1202
1204 # Known heads are the list of heads that it is assumed the recipient
1203 # Known heads are the list of heads that it is assumed the recipient
1205 # of this changegroup will know about.
1204 # of this changegroup will know about.
1206 knownheads = {}
1205 knownheads = {}
1207 # We assume that all parents of bases are known heads.
1206 # We assume that all parents of bases are known heads.
1208 for n in bases:
1207 for n in bases:
1209 for p in cl.parents(n):
1208 for p in cl.parents(n):
1210 if p != nullid:
1209 if p != nullid:
1211 knownheads[p] = 1
1210 knownheads[p] = 1
1212 knownheads = knownheads.keys()
1211 knownheads = knownheads.keys()
1213 if knownheads:
1212 if knownheads:
1214 # Now that we know what heads are known, we can compute which
1213 # Now that we know what heads are known, we can compute which
1215 # changesets are known. The recipient must know about all
1214 # changesets are known. The recipient must know about all
1216 # changesets required to reach the known heads from the null
1215 # changesets required to reach the known heads from the null
1217 # changeset.
1216 # changeset.
1218 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1217 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1219 junk = None
1218 junk = None
1220 # Transform the list into an ersatz set.
1219 # Transform the list into an ersatz set.
1221 has_cl_set = dict.fromkeys(has_cl_set)
1220 has_cl_set = dict.fromkeys(has_cl_set)
1222 else:
1221 else:
1223 # If there were no known heads, the recipient cannot be assumed to
1222 # If there were no known heads, the recipient cannot be assumed to
1224 # know about any changesets.
1223 # know about any changesets.
1225 has_cl_set = {}
1224 has_cl_set = {}
1226
1225
1227 # Make it easy to refer to self.manifest
1226 # Make it easy to refer to self.manifest
1228 mnfst = self.manifest
1227 mnfst = self.manifest
1229 # We don't know which manifests are missing yet
1228 # We don't know which manifests are missing yet
1230 msng_mnfst_set = {}
1229 msng_mnfst_set = {}
1231 # Nor do we know which filenodes are missing.
1230 # Nor do we know which filenodes are missing.
1232 msng_filenode_set = {}
1231 msng_filenode_set = {}
1233
1232
1234 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1233 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1235 junk = None
1234 junk = None
1236
1235
1237 # A changeset always belongs to itself, so the changenode lookup
1236 # A changeset always belongs to itself, so the changenode lookup
1238 # function for a changenode is identity.
1237 # function for a changenode is identity.
1239 def identity(x):
1238 def identity(x):
1240 return x
1239 return x
1241
1240
1242 # A function generating function. Sets up an environment for the
1241 # A function generating function. Sets up an environment for the
1243 # inner function.
1242 # inner function.
1244 def cmp_by_rev_func(revlog):
1243 def cmp_by_rev_func(revlog):
1245 # Compare two nodes by their revision number in the environment's
1244 # Compare two nodes by their revision number in the environment's
1246 # revision history. Since the revision number both represents the
1245 # revision history. Since the revision number both represents the
1247 # most efficient order to read the nodes in, and represents a
1246 # most efficient order to read the nodes in, and represents a
1248 # topological sorting of the nodes, this function is often useful.
1247 # topological sorting of the nodes, this function is often useful.
1249 def cmp_by_rev(a, b):
1248 def cmp_by_rev(a, b):
1250 return cmp(revlog.rev(a), revlog.rev(b))
1249 return cmp(revlog.rev(a), revlog.rev(b))
1251 return cmp_by_rev
1250 return cmp_by_rev
1252
1251
1253 # If we determine that a particular file or manifest node must be a
1252 # If we determine that a particular file or manifest node must be a
1254 # node that the recipient of the changegroup will already have, we can
1253 # node that the recipient of the changegroup will already have, we can
1255 # also assume the recipient will have all the parents. This function
1254 # also assume the recipient will have all the parents. This function
1256 # prunes them from the set of missing nodes.
1255 # prunes them from the set of missing nodes.
1257 def prune_parents(revlog, hasset, msngset):
1256 def prune_parents(revlog, hasset, msngset):
1258 haslst = hasset.keys()
1257 haslst = hasset.keys()
1259 haslst.sort(cmp_by_rev_func(revlog))
1258 haslst.sort(cmp_by_rev_func(revlog))
1260 for node in haslst:
1259 for node in haslst:
1261 parentlst = [p for p in revlog.parents(node) if p != nullid]
1260 parentlst = [p for p in revlog.parents(node) if p != nullid]
1262 while parentlst:
1261 while parentlst:
1263 n = parentlst.pop()
1262 n = parentlst.pop()
1264 if n not in hasset:
1263 if n not in hasset:
1265 hasset[n] = 1
1264 hasset[n] = 1
1266 p = [p for p in revlog.parents(n) if p != nullid]
1265 p = [p for p in revlog.parents(n) if p != nullid]
1267 parentlst.extend(p)
1266 parentlst.extend(p)
1268 for n in hasset:
1267 for n in hasset:
1269 msngset.pop(n, None)
1268 msngset.pop(n, None)
1270
1269
1271 # This is a function generating function used to set up an environment
1270 # This is a function generating function used to set up an environment
1272 # for the inner function to execute in.
1271 # for the inner function to execute in.
1273 def manifest_and_file_collector(changedfileset):
1272 def manifest_and_file_collector(changedfileset):
1274 # This is an information gathering function that gathers
1273 # This is an information gathering function that gathers
1275 # information from each changeset node that goes out as part of
1274 # information from each changeset node that goes out as part of
1276 # the changegroup. The information gathered is a list of which
1275 # the changegroup. The information gathered is a list of which
1277 # manifest nodes are potentially required (the recipient may
1276 # manifest nodes are potentially required (the recipient may
1278 # already have them) and total list of all files which were
1277 # already have them) and total list of all files which were
1279 # changed in any changeset in the changegroup.
1278 # changed in any changeset in the changegroup.
1280 #
1279 #
1281 # We also remember the first changenode we saw any manifest
1280 # We also remember the first changenode we saw any manifest
1282 # referenced by so we can later determine which changenode 'owns'
1281 # referenced by so we can later determine which changenode 'owns'
1283 # the manifest.
1282 # the manifest.
1284 def collect_manifests_and_files(clnode):
1283 def collect_manifests_and_files(clnode):
1285 c = cl.read(clnode)
1284 c = cl.read(clnode)
1286 for f in c[3]:
1285 for f in c[3]:
1287 # This is to make sure we only have one instance of each
1286 # This is to make sure we only have one instance of each
1288 # filename string for each filename.
1287 # filename string for each filename.
1289 changedfileset.setdefault(f, f)
1288 changedfileset.setdefault(f, f)
1290 msng_mnfst_set.setdefault(c[0], clnode)
1289 msng_mnfst_set.setdefault(c[0], clnode)
1291 return collect_manifests_and_files
1290 return collect_manifests_and_files
1292
1291
1293 # Figure out which manifest nodes (of the ones we think might be part
1292 # Figure out which manifest nodes (of the ones we think might be part
1294 # of the changegroup) the recipient must know about and remove them
1293 # of the changegroup) the recipient must know about and remove them
1295 # from the changegroup.
1294 # from the changegroup.
1296 def prune_manifests():
1295 def prune_manifests():
1297 has_mnfst_set = {}
1296 has_mnfst_set = {}
1298 for n in msng_mnfst_set:
1297 for n in msng_mnfst_set:
1299 # If a 'missing' manifest thinks it belongs to a changenode
1298 # If a 'missing' manifest thinks it belongs to a changenode
1300 # the recipient is assumed to have, obviously the recipient
1299 # the recipient is assumed to have, obviously the recipient
1301 # must have that manifest.
1300 # must have that manifest.
1302 linknode = cl.node(mnfst.linkrev(n))
1301 linknode = cl.node(mnfst.linkrev(n))
1303 if linknode in has_cl_set:
1302 if linknode in has_cl_set:
1304 has_mnfst_set[n] = 1
1303 has_mnfst_set[n] = 1
1305 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1304 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1306
1305
1307 # Use the information collected in collect_manifests_and_files to say
1306 # Use the information collected in collect_manifests_and_files to say
1308 # which changenode any manifestnode belongs to.
1307 # which changenode any manifestnode belongs to.
1309 def lookup_manifest_link(mnfstnode):
1308 def lookup_manifest_link(mnfstnode):
1310 return msng_mnfst_set[mnfstnode]
1309 return msng_mnfst_set[mnfstnode]
1311
1310
1312 # A function generating function that sets up the initial environment
1311 # A function generating function that sets up the initial environment
1313 # the inner function.
1312 # the inner function.
1314 def filenode_collector(changedfiles):
1313 def filenode_collector(changedfiles):
1315 next_rev = [0]
1314 next_rev = [0]
1316 # This gathers information from each manifestnode included in the
1315 # This gathers information from each manifestnode included in the
1317 # changegroup about which filenodes the manifest node references
1316 # changegroup about which filenodes the manifest node references
1318 # so we can include those in the changegroup too.
1317 # so we can include those in the changegroup too.
1319 #
1318 #
1320 # It also remembers which changenode each filenode belongs to. It
1319 # It also remembers which changenode each filenode belongs to. It
1321 # does this by assuming the a filenode belongs to the changenode
1320 # does this by assuming the a filenode belongs to the changenode
1322 # the first manifest that references it belongs to.
1321 # the first manifest that references it belongs to.
1323 def collect_msng_filenodes(mnfstnode):
1322 def collect_msng_filenodes(mnfstnode):
1324 r = mnfst.rev(mnfstnode)
1323 r = mnfst.rev(mnfstnode)
1325 if r == next_rev[0]:
1324 if r == next_rev[0]:
1326 # If the last rev we looked at was the one just previous,
1325 # If the last rev we looked at was the one just previous,
1327 # we only need to see a diff.
1326 # we only need to see a diff.
1328 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1327 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1329 # For each line in the delta
1328 # For each line in the delta
1330 for dline in delta.splitlines():
1329 for dline in delta.splitlines():
1331 # get the filename and filenode for that line
1330 # get the filename and filenode for that line
1332 f, fnode = dline.split('\0')
1331 f, fnode = dline.split('\0')
1333 fnode = bin(fnode[:40])
1332 fnode = bin(fnode[:40])
1334 f = changedfiles.get(f, None)
1333 f = changedfiles.get(f, None)
1335 # And if the file is in the list of files we care
1334 # And if the file is in the list of files we care
1336 # about.
1335 # about.
1337 if f is not None:
1336 if f is not None:
1338 # Get the changenode this manifest belongs to
1337 # Get the changenode this manifest belongs to
1339 clnode = msng_mnfst_set[mnfstnode]
1338 clnode = msng_mnfst_set[mnfstnode]
1340 # Create the set of filenodes for the file if
1339 # Create the set of filenodes for the file if
1341 # there isn't one already.
1340 # there isn't one already.
1342 ndset = msng_filenode_set.setdefault(f, {})
1341 ndset = msng_filenode_set.setdefault(f, {})
1343 # And set the filenode's changelog node to the
1342 # And set the filenode's changelog node to the
1344 # manifest's if it hasn't been set already.
1343 # manifest's if it hasn't been set already.
1345 ndset.setdefault(fnode, clnode)
1344 ndset.setdefault(fnode, clnode)
1346 else:
1345 else:
1347 # Otherwise we need a full manifest.
1346 # Otherwise we need a full manifest.
1348 m = mnfst.read(mnfstnode)
1347 m = mnfst.read(mnfstnode)
1349 # For every file in we care about.
1348 # For every file in we care about.
1350 for f in changedfiles:
1349 for f in changedfiles:
1351 fnode = m.get(f, None)
1350 fnode = m.get(f, None)
1352 # If it's in the manifest
1351 # If it's in the manifest
1353 if fnode is not None:
1352 if fnode is not None:
1354 # See comments above.
1353 # See comments above.
1355 clnode = msng_mnfst_set[mnfstnode]
1354 clnode = msng_mnfst_set[mnfstnode]
1356 ndset = msng_filenode_set.setdefault(f, {})
1355 ndset = msng_filenode_set.setdefault(f, {})
1357 ndset.setdefault(fnode, clnode)
1356 ndset.setdefault(fnode, clnode)
1358 # Remember the revision we hope to see next.
1357 # Remember the revision we hope to see next.
1359 next_rev[0] = r + 1
1358 next_rev[0] = r + 1
1360 return collect_msng_filenodes
1359 return collect_msng_filenodes
1361
1360
1362 # We have a list of filenodes we think we need for a file, lets remove
1361 # We have a list of filenodes we think we need for a file, lets remove
1363 # all those we now the recipient must have.
1362 # all those we now the recipient must have.
1364 def prune_filenodes(f, filerevlog):
1363 def prune_filenodes(f, filerevlog):
1365 msngset = msng_filenode_set[f]
1364 msngset = msng_filenode_set[f]
1366 hasset = {}
1365 hasset = {}
1367 # If a 'missing' filenode thinks it belongs to a changenode we
1366 # If a 'missing' filenode thinks it belongs to a changenode we
1368 # assume the recipient must have, then the recipient must have
1367 # assume the recipient must have, then the recipient must have
1369 # that filenode.
1368 # that filenode.
1370 for n in msngset:
1369 for n in msngset:
1371 clnode = cl.node(filerevlog.linkrev(n))
1370 clnode = cl.node(filerevlog.linkrev(n))
1372 if clnode in has_cl_set:
1371 if clnode in has_cl_set:
1373 hasset[n] = 1
1372 hasset[n] = 1
1374 prune_parents(filerevlog, hasset, msngset)
1373 prune_parents(filerevlog, hasset, msngset)
1375
1374
1376 # A function generator function that sets up the a context for the
1375 # A function generator function that sets up the a context for the
1377 # inner function.
1376 # inner function.
1378 def lookup_filenode_link_func(fname):
1377 def lookup_filenode_link_func(fname):
1379 msngset = msng_filenode_set[fname]
1378 msngset = msng_filenode_set[fname]
1380 # Lookup the changenode the filenode belongs to.
1379 # Lookup the changenode the filenode belongs to.
1381 def lookup_filenode_link(fnode):
1380 def lookup_filenode_link(fnode):
1382 return msngset[fnode]
1381 return msngset[fnode]
1383 return lookup_filenode_link
1382 return lookup_filenode_link
1384
1383
1385 # Now that we have all theses utility functions to help out and
1384 # Now that we have all theses utility functions to help out and
1386 # logically divide up the task, generate the group.
1385 # logically divide up the task, generate the group.
1387 def gengroup():
1386 def gengroup():
1388 # The set of changed files starts empty.
1387 # The set of changed files starts empty.
1389 changedfiles = {}
1388 changedfiles = {}
1390 # Create a changenode group generator that will call our functions
1389 # Create a changenode group generator that will call our functions
1391 # back to lookup the owning changenode and collect information.
1390 # back to lookup the owning changenode and collect information.
1392 group = cl.group(msng_cl_lst, identity,
1391 group = cl.group(msng_cl_lst, identity,
1393 manifest_and_file_collector(changedfiles))
1392 manifest_and_file_collector(changedfiles))
1394 for chnk in group:
1393 for chnk in group:
1395 yield chnk
1394 yield chnk
1396
1395
1397 # The list of manifests has been collected by the generator
1396 # The list of manifests has been collected by the generator
1398 # calling our functions back.
1397 # calling our functions back.
1399 prune_manifests()
1398 prune_manifests()
1400 msng_mnfst_lst = msng_mnfst_set.keys()
1399 msng_mnfst_lst = msng_mnfst_set.keys()
1401 # Sort the manifestnodes by revision number.
1400 # Sort the manifestnodes by revision number.
1402 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1401 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1403 # Create a generator for the manifestnodes that calls our lookup
1402 # Create a generator for the manifestnodes that calls our lookup
1404 # and data collection functions back.
1403 # and data collection functions back.
1405 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1404 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1406 filenode_collector(changedfiles))
1405 filenode_collector(changedfiles))
1407 for chnk in group:
1406 for chnk in group:
1408 yield chnk
1407 yield chnk
1409
1408
1410 # These are no longer needed, dereference and toss the memory for
1409 # These are no longer needed, dereference and toss the memory for
1411 # them.
1410 # them.
1412 msng_mnfst_lst = None
1411 msng_mnfst_lst = None
1413 msng_mnfst_set.clear()
1412 msng_mnfst_set.clear()
1414
1413
1415 changedfiles = changedfiles.keys()
1414 changedfiles = changedfiles.keys()
1416 changedfiles.sort()
1415 changedfiles.sort()
1417 # Go through all our files in order sorted by name.
1416 # Go through all our files in order sorted by name.
1418 for fname in changedfiles:
1417 for fname in changedfiles:
1419 filerevlog = self.file(fname)
1418 filerevlog = self.file(fname)
1420 # Toss out the filenodes that the recipient isn't really
1419 # Toss out the filenodes that the recipient isn't really
1421 # missing.
1420 # missing.
1422 if msng_filenode_set.has_key(fname):
1421 if msng_filenode_set.has_key(fname):
1423 prune_filenodes(fname, filerevlog)
1422 prune_filenodes(fname, filerevlog)
1424 msng_filenode_lst = msng_filenode_set[fname].keys()
1423 msng_filenode_lst = msng_filenode_set[fname].keys()
1425 else:
1424 else:
1426 msng_filenode_lst = []
1425 msng_filenode_lst = []
1427 # If any filenodes are left, generate the group for them,
1426 # If any filenodes are left, generate the group for them,
1428 # otherwise don't bother.
1427 # otherwise don't bother.
1429 if len(msng_filenode_lst) > 0:
1428 if len(msng_filenode_lst) > 0:
1430 yield changegroup.genchunk(fname)
1429 yield changegroup.genchunk(fname)
1431 # Sort the filenodes by their revision #
1430 # Sort the filenodes by their revision #
1432 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1431 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1433 # Create a group generator and only pass in a changenode
1432 # Create a group generator and only pass in a changenode
1434 # lookup function as we need to collect no information
1433 # lookup function as we need to collect no information
1435 # from filenodes.
1434 # from filenodes.
1436 group = filerevlog.group(msng_filenode_lst,
1435 group = filerevlog.group(msng_filenode_lst,
1437 lookup_filenode_link_func(fname))
1436 lookup_filenode_link_func(fname))
1438 for chnk in group:
1437 for chnk in group:
1439 yield chnk
1438 yield chnk
1440 if msng_filenode_set.has_key(fname):
1439 if msng_filenode_set.has_key(fname):
1441 # Don't need this anymore, toss it to free memory.
1440 # Don't need this anymore, toss it to free memory.
1442 del msng_filenode_set[fname]
1441 del msng_filenode_set[fname]
1443 # Signal that no more groups are left.
1442 # Signal that no more groups are left.
1444 yield changegroup.closechunk()
1443 yield changegroup.closechunk()
1445
1444
1446 if msng_cl_lst:
1445 if msng_cl_lst:
1447 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1446 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1448
1447
1449 return util.chunkbuffer(gengroup())
1448 return util.chunkbuffer(gengroup())
1450
1449
1451 def changegroup(self, basenodes, source):
1450 def changegroup(self, basenodes, source):
1452 """Generate a changegroup of all nodes that we have that a recipient
1451 """Generate a changegroup of all nodes that we have that a recipient
1453 doesn't.
1452 doesn't.
1454
1453
1455 This is much easier than the previous function as we can assume that
1454 This is much easier than the previous function as we can assume that
1456 the recipient has any changenode we aren't sending them."""
1455 the recipient has any changenode we aren't sending them."""
1457
1456
1458 self.hook('preoutgoing', throw=True, source=source)
1457 self.hook('preoutgoing', throw=True, source=source)
1459
1458
1460 cl = self.changelog
1459 cl = self.changelog
1461 nodes = cl.nodesbetween(basenodes, None)[0]
1460 nodes = cl.nodesbetween(basenodes, None)[0]
1462 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1461 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1463
1462
1464 def identity(x):
1463 def identity(x):
1465 return x
1464 return x
1466
1465
1467 def gennodelst(revlog):
1466 def gennodelst(revlog):
1468 for r in xrange(0, revlog.count()):
1467 for r in xrange(0, revlog.count()):
1469 n = revlog.node(r)
1468 n = revlog.node(r)
1470 if revlog.linkrev(n) in revset:
1469 if revlog.linkrev(n) in revset:
1471 yield n
1470 yield n
1472
1471
1473 def changed_file_collector(changedfileset):
1472 def changed_file_collector(changedfileset):
1474 def collect_changed_files(clnode):
1473 def collect_changed_files(clnode):
1475 c = cl.read(clnode)
1474 c = cl.read(clnode)
1476 for fname in c[3]:
1475 for fname in c[3]:
1477 changedfileset[fname] = 1
1476 changedfileset[fname] = 1
1478 return collect_changed_files
1477 return collect_changed_files
1479
1478
1480 def lookuprevlink_func(revlog):
1479 def lookuprevlink_func(revlog):
1481 def lookuprevlink(n):
1480 def lookuprevlink(n):
1482 return cl.node(revlog.linkrev(n))
1481 return cl.node(revlog.linkrev(n))
1483 return lookuprevlink
1482 return lookuprevlink
1484
1483
1485 def gengroup():
1484 def gengroup():
1486 # construct a list of all changed files
1485 # construct a list of all changed files
1487 changedfiles = {}
1486 changedfiles = {}
1488
1487
1489 for chnk in cl.group(nodes, identity,
1488 for chnk in cl.group(nodes, identity,
1490 changed_file_collector(changedfiles)):
1489 changed_file_collector(changedfiles)):
1491 yield chnk
1490 yield chnk
1492 changedfiles = changedfiles.keys()
1491 changedfiles = changedfiles.keys()
1493 changedfiles.sort()
1492 changedfiles.sort()
1494
1493
1495 mnfst = self.manifest
1494 mnfst = self.manifest
1496 nodeiter = gennodelst(mnfst)
1495 nodeiter = gennodelst(mnfst)
1497 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1496 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1498 yield chnk
1497 yield chnk
1499
1498
1500 for fname in changedfiles:
1499 for fname in changedfiles:
1501 filerevlog = self.file(fname)
1500 filerevlog = self.file(fname)
1502 nodeiter = gennodelst(filerevlog)
1501 nodeiter = gennodelst(filerevlog)
1503 nodeiter = list(nodeiter)
1502 nodeiter = list(nodeiter)
1504 if nodeiter:
1503 if nodeiter:
1505 yield changegroup.genchunk(fname)
1504 yield changegroup.genchunk(fname)
1506 lookup = lookuprevlink_func(filerevlog)
1505 lookup = lookuprevlink_func(filerevlog)
1507 for chnk in filerevlog.group(nodeiter, lookup):
1506 for chnk in filerevlog.group(nodeiter, lookup):
1508 yield chnk
1507 yield chnk
1509
1508
1510 yield changegroup.closechunk()
1509 yield changegroup.closechunk()
1511
1510
1512 if nodes:
1511 if nodes:
1513 self.hook('outgoing', node=hex(nodes[0]), source=source)
1512 self.hook('outgoing', node=hex(nodes[0]), source=source)
1514
1513
1515 return util.chunkbuffer(gengroup())
1514 return util.chunkbuffer(gengroup())
1516
1515
1517 def addchangegroup(self, source, srctype):
1516 def addchangegroup(self, source, srctype):
1518 """add changegroup to repo.
1517 """add changegroup to repo.
1519 returns number of heads modified or added + 1."""
1518 returns number of heads modified or added + 1."""
1520
1519
1521 def csmap(x):
1520 def csmap(x):
1522 self.ui.debug(_("add changeset %s\n") % short(x))
1521 self.ui.debug(_("add changeset %s\n") % short(x))
1523 return cl.count()
1522 return cl.count()
1524
1523
1525 def revmap(x):
1524 def revmap(x):
1526 return cl.rev(x)
1525 return cl.rev(x)
1527
1526
1528 if not source:
1527 if not source:
1529 return 0
1528 return 0
1530
1529
1531 self.hook('prechangegroup', throw=True, source=srctype)
1530 self.hook('prechangegroup', throw=True, source=srctype)
1532
1531
1533 changesets = files = revisions = 0
1532 changesets = files = revisions = 0
1534
1533
1535 tr = self.transaction()
1534 tr = self.transaction()
1536
1535
1537 # write changelog data to temp files so concurrent readers will not see
1536 # write changelog data to temp files so concurrent readers will not see
1538 # inconsistent view
1537 # inconsistent view
1539 cl = None
1538 cl = None
1540 try:
1539 try:
1541 cl = appendfile.appendchangelog(self.opener, self.changelog.version)
1540 cl = appendfile.appendchangelog(self.opener, self.changelog.version)
1542
1541
1543 oldheads = len(cl.heads())
1542 oldheads = len(cl.heads())
1544
1543
1545 # pull off the changeset group
1544 # pull off the changeset group
1546 self.ui.status(_("adding changesets\n"))
1545 self.ui.status(_("adding changesets\n"))
1547 cor = cl.count() - 1
1546 cor = cl.count() - 1
1548 chunkiter = changegroup.chunkiter(source)
1547 chunkiter = changegroup.chunkiter(source)
1549 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1548 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1550 raise util.Abort(_("received changelog group is empty"))
1549 raise util.Abort(_("received changelog group is empty"))
1551 cnr = cl.count() - 1
1550 cnr = cl.count() - 1
1552 changesets = cnr - cor
1551 changesets = cnr - cor
1553
1552
1554 # pull off the manifest group
1553 # pull off the manifest group
1555 self.ui.status(_("adding manifests\n"))
1554 self.ui.status(_("adding manifests\n"))
1556 chunkiter = changegroup.chunkiter(source)
1555 chunkiter = changegroup.chunkiter(source)
1557 # no need to check for empty manifest group here:
1556 # no need to check for empty manifest group here:
1558 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1557 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1559 # no new manifest will be created and the manifest group will
1558 # no new manifest will be created and the manifest group will
1560 # be empty during the pull
1559 # be empty during the pull
1561 self.manifest.addgroup(chunkiter, revmap, tr)
1560 self.manifest.addgroup(chunkiter, revmap, tr)
1562
1561
1563 # process the files
1562 # process the files
1564 self.ui.status(_("adding file changes\n"))
1563 self.ui.status(_("adding file changes\n"))
1565 while 1:
1564 while 1:
1566 f = changegroup.getchunk(source)
1565 f = changegroup.getchunk(source)
1567 if not f:
1566 if not f:
1568 break
1567 break
1569 self.ui.debug(_("adding %s revisions\n") % f)
1568 self.ui.debug(_("adding %s revisions\n") % f)
1570 fl = self.file(f)
1569 fl = self.file(f)
1571 o = fl.count()
1570 o = fl.count()
1572 chunkiter = changegroup.chunkiter(source)
1571 chunkiter = changegroup.chunkiter(source)
1573 if fl.addgroup(chunkiter, revmap, tr) is None:
1572 if fl.addgroup(chunkiter, revmap, tr) is None:
1574 raise util.Abort(_("received file revlog group is empty"))
1573 raise util.Abort(_("received file revlog group is empty"))
1575 revisions += fl.count() - o
1574 revisions += fl.count() - o
1576 files += 1
1575 files += 1
1577
1576
1578 cl.writedata()
1577 cl.writedata()
1579 finally:
1578 finally:
1580 if cl:
1579 if cl:
1581 cl.cleanup()
1580 cl.cleanup()
1582
1581
1583 # make changelog see real files again
1582 # make changelog see real files again
1584 self.changelog = changelog.changelog(self.opener, self.changelog.version)
1583 self.changelog = changelog.changelog(self.opener, self.changelog.version)
1585 self.changelog.checkinlinesize(tr)
1584 self.changelog.checkinlinesize(tr)
1586
1585
1587 newheads = len(self.changelog.heads())
1586 newheads = len(self.changelog.heads())
1588 heads = ""
1587 heads = ""
1589 if oldheads and newheads != oldheads:
1588 if oldheads and newheads != oldheads:
1590 heads = _(" (%+d heads)") % (newheads - oldheads)
1589 heads = _(" (%+d heads)") % (newheads - oldheads)
1591
1590
1592 self.ui.status(_("added %d changesets"
1591 self.ui.status(_("added %d changesets"
1593 " with %d changes to %d files%s\n")
1592 " with %d changes to %d files%s\n")
1594 % (changesets, revisions, files, heads))
1593 % (changesets, revisions, files, heads))
1595
1594
1596 if changesets > 0:
1595 if changesets > 0:
1597 self.hook('pretxnchangegroup', throw=True,
1596 self.hook('pretxnchangegroup', throw=True,
1598 node=hex(self.changelog.node(cor+1)), source=srctype)
1597 node=hex(self.changelog.node(cor+1)), source=srctype)
1599
1598
1600 tr.close()
1599 tr.close()
1601
1600
1602 if changesets > 0:
1601 if changesets > 0:
1603 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1602 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1604 source=srctype)
1603 source=srctype)
1605
1604
1606 for i in range(cor + 1, cnr + 1):
1605 for i in range(cor + 1, cnr + 1):
1607 self.hook("incoming", node=hex(self.changelog.node(i)),
1606 self.hook("incoming", node=hex(self.changelog.node(i)),
1608 source=srctype)
1607 source=srctype)
1609
1608
1610 return newheads - oldheads + 1
1609 return newheads - oldheads + 1
1611
1610
1612 def update(self, node, allow=False, force=False, choose=None,
1611 def update(self, node, allow=False, force=False, choose=None,
1613 moddirstate=True, forcemerge=False, wlock=None, show_stats=True):
1612 moddirstate=True, forcemerge=False, wlock=None, show_stats=True):
1614 pl = self.dirstate.parents()
1613 pl = self.dirstate.parents()
1615 if not force and pl[1] != nullid:
1614 if not force and pl[1] != nullid:
1616 raise util.Abort(_("outstanding uncommitted merges"))
1615 raise util.Abort(_("outstanding uncommitted merges"))
1617
1616
1618 err = False
1617 err = False
1619
1618
1620 p1, p2 = pl[0], node
1619 p1, p2 = pl[0], node
1621 pa = self.changelog.ancestor(p1, p2)
1620 pa = self.changelog.ancestor(p1, p2)
1622 m1n = self.changelog.read(p1)[0]
1621 m1n = self.changelog.read(p1)[0]
1623 m2n = self.changelog.read(p2)[0]
1622 m2n = self.changelog.read(p2)[0]
1624 man = self.manifest.ancestor(m1n, m2n)
1623 man = self.manifest.ancestor(m1n, m2n)
1625 m1 = self.manifest.read(m1n)
1624 m1 = self.manifest.read(m1n)
1626 mf1 = self.manifest.readflags(m1n)
1625 mf1 = self.manifest.readflags(m1n)
1627 m2 = self.manifest.read(m2n).copy()
1626 m2 = self.manifest.read(m2n).copy()
1628 mf2 = self.manifest.readflags(m2n)
1627 mf2 = self.manifest.readflags(m2n)
1629 ma = self.manifest.read(man)
1628 ma = self.manifest.read(man)
1630 mfa = self.manifest.readflags(man)
1629 mfa = self.manifest.readflags(man)
1631
1630
1632 modified, added, removed, deleted, unknown = self.changes()
1631 modified, added, removed, deleted, unknown = self.changes()
1633
1632
1634 # is this a jump, or a merge? i.e. is there a linear path
1633 # is this a jump, or a merge? i.e. is there a linear path
1635 # from p1 to p2?
1634 # from p1 to p2?
1636 linear_path = (pa == p1 or pa == p2)
1635 linear_path = (pa == p1 or pa == p2)
1637
1636
1638 if allow and linear_path:
1637 if allow and linear_path:
1639 raise util.Abort(_("there is nothing to merge, "
1638 raise util.Abort(_("there is nothing to merge, "
1640 "just use 'hg update'"))
1639 "just use 'hg update'"))
1641 if allow and not forcemerge:
1640 if allow and not forcemerge:
1642 if modified or added or removed:
1641 if modified or added or removed:
1643 raise util.Abort(_("outstanding uncommitted changes"))
1642 raise util.Abort(_("outstanding uncommitted changes"))
1644
1643
1645 if not forcemerge and not force:
1644 if not forcemerge and not force:
1646 for f in unknown:
1645 for f in unknown:
1647 if f in m2:
1646 if f in m2:
1648 t1 = self.wread(f)
1647 t1 = self.wread(f)
1649 t2 = self.file(f).read(m2[f])
1648 t2 = self.file(f).read(m2[f])
1650 if cmp(t1, t2) != 0:
1649 if cmp(t1, t2) != 0:
1651 raise util.Abort(_("'%s' already exists in the working"
1650 raise util.Abort(_("'%s' already exists in the working"
1652 " dir and differs from remote") % f)
1651 " dir and differs from remote") % f)
1653
1652
1654 # resolve the manifest to determine which files
1653 # resolve the manifest to determine which files
1655 # we care about merging
1654 # we care about merging
1656 self.ui.note(_("resolving manifests\n"))
1655 self.ui.note(_("resolving manifests\n"))
1657 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1656 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1658 (force, allow, moddirstate, linear_path))
1657 (force, allow, moddirstate, linear_path))
1659 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1658 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1660 (short(man), short(m1n), short(m2n)))
1659 (short(man), short(m1n), short(m2n)))
1661
1660
1662 merge = {}
1661 merge = {}
1663 get = {}
1662 get = {}
1664 remove = []
1663 remove = []
1665
1664
1666 # construct a working dir manifest
1665 # construct a working dir manifest
1667 mw = m1.copy()
1666 mw = m1.copy()
1668 mfw = mf1.copy()
1667 mfw = mf1.copy()
1669 umap = dict.fromkeys(unknown)
1668 umap = dict.fromkeys(unknown)
1670
1669
1671 for f in added + modified + unknown:
1670 for f in added + modified + unknown:
1672 mw[f] = ""
1671 mw[f] = ""
1673 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1672 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1674
1673
1675 if moddirstate and not wlock:
1674 if moddirstate and not wlock:
1676 wlock = self.wlock()
1675 wlock = self.wlock()
1677
1676
1678 for f in deleted + removed:
1677 for f in deleted + removed:
1679 if f in mw:
1678 if f in mw:
1680 del mw[f]
1679 del mw[f]
1681
1680
1682 # If we're jumping between revisions (as opposed to merging),
1681 # If we're jumping between revisions (as opposed to merging),
1683 # and if neither the working directory nor the target rev has
1682 # and if neither the working directory nor the target rev has
1684 # the file, then we need to remove it from the dirstate, to
1683 # the file, then we need to remove it from the dirstate, to
1685 # prevent the dirstate from listing the file when it is no
1684 # prevent the dirstate from listing the file when it is no
1686 # longer in the manifest.
1685 # longer in the manifest.
1687 if moddirstate and linear_path and f not in m2:
1686 if moddirstate and linear_path and f not in m2:
1688 self.dirstate.forget((f,))
1687 self.dirstate.forget((f,))
1689
1688
1690 # Compare manifests
1689 # Compare manifests
1691 for f, n in mw.iteritems():
1690 for f, n in mw.iteritems():
1692 if choose and not choose(f):
1691 if choose and not choose(f):
1693 continue
1692 continue
1694 if f in m2:
1693 if f in m2:
1695 s = 0
1694 s = 0
1696
1695
1697 # is the wfile new since m1, and match m2?
1696 # is the wfile new since m1, and match m2?
1698 if f not in m1:
1697 if f not in m1:
1699 t1 = self.wread(f)
1698 t1 = self.wread(f)
1700 t2 = self.file(f).read(m2[f])
1699 t2 = self.file(f).read(m2[f])
1701 if cmp(t1, t2) == 0:
1700 if cmp(t1, t2) == 0:
1702 n = m2[f]
1701 n = m2[f]
1703 del t1, t2
1702 del t1, t2
1704
1703
1705 # are files different?
1704 # are files different?
1706 if n != m2[f]:
1705 if n != m2[f]:
1707 a = ma.get(f, nullid)
1706 a = ma.get(f, nullid)
1708 # are both different from the ancestor?
1707 # are both different from the ancestor?
1709 if n != a and m2[f] != a:
1708 if n != a and m2[f] != a:
1710 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1709 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1711 # merge executable bits
1710 # merge executable bits
1712 # "if we changed or they changed, change in merge"
1711 # "if we changed or they changed, change in merge"
1713 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1712 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1714 mode = ((a^b) | (a^c)) ^ a
1713 mode = ((a^b) | (a^c)) ^ a
1715 merge[f] = (m1.get(f, nullid), m2[f], mode)
1714 merge[f] = (m1.get(f, nullid), m2[f], mode)
1716 s = 1
1715 s = 1
1717 # are we clobbering?
1716 # are we clobbering?
1718 # is remote's version newer?
1717 # is remote's version newer?
1719 # or are we going back in time?
1718 # or are we going back in time?
1720 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1719 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1721 self.ui.debug(_(" remote %s is newer, get\n") % f)
1720 self.ui.debug(_(" remote %s is newer, get\n") % f)
1722 get[f] = m2[f]
1721 get[f] = m2[f]
1723 s = 1
1722 s = 1
1724 elif f in umap or f in added:
1723 elif f in umap or f in added:
1725 # this unknown file is the same as the checkout
1724 # this unknown file is the same as the checkout
1726 # we need to reset the dirstate if the file was added
1725 # we need to reset the dirstate if the file was added
1727 get[f] = m2[f]
1726 get[f] = m2[f]
1728
1727
1729 if not s and mfw[f] != mf2[f]:
1728 if not s and mfw[f] != mf2[f]:
1730 if force:
1729 if force:
1731 self.ui.debug(_(" updating permissions for %s\n") % f)
1730 self.ui.debug(_(" updating permissions for %s\n") % f)
1732 util.set_exec(self.wjoin(f), mf2[f])
1731 util.set_exec(self.wjoin(f), mf2[f])
1733 else:
1732 else:
1734 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1733 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1735 mode = ((a^b) | (a^c)) ^ a
1734 mode = ((a^b) | (a^c)) ^ a
1736 if mode != b:
1735 if mode != b:
1737 self.ui.debug(_(" updating permissions for %s\n")
1736 self.ui.debug(_(" updating permissions for %s\n")
1738 % f)
1737 % f)
1739 util.set_exec(self.wjoin(f), mode)
1738 util.set_exec(self.wjoin(f), mode)
1740 del m2[f]
1739 del m2[f]
1741 elif f in ma:
1740 elif f in ma:
1742 if n != ma[f]:
1741 if n != ma[f]:
1743 r = _("d")
1742 r = _("d")
1744 if not force and (linear_path or allow):
1743 if not force and (linear_path or allow):
1745 r = self.ui.prompt(
1744 r = self.ui.prompt(
1746 (_(" local changed %s which remote deleted\n") % f) +
1745 (_(" local changed %s which remote deleted\n") % f) +
1747 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1746 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1748 if r == _("d"):
1747 if r == _("d"):
1749 remove.append(f)
1748 remove.append(f)
1750 else:
1749 else:
1751 self.ui.debug(_("other deleted %s\n") % f)
1750 self.ui.debug(_("other deleted %s\n") % f)
1752 remove.append(f) # other deleted it
1751 remove.append(f) # other deleted it
1753 else:
1752 else:
1754 # file is created on branch or in working directory
1753 # file is created on branch or in working directory
1755 if force and f not in umap:
1754 if force and f not in umap:
1756 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1755 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1757 remove.append(f)
1756 remove.append(f)
1758 elif n == m1.get(f, nullid): # same as parent
1757 elif n == m1.get(f, nullid): # same as parent
1759 if p2 == pa: # going backwards?
1758 if p2 == pa: # going backwards?
1760 self.ui.debug(_("remote deleted %s\n") % f)
1759 self.ui.debug(_("remote deleted %s\n") % f)
1761 remove.append(f)
1760 remove.append(f)
1762 else:
1761 else:
1763 self.ui.debug(_("local modified %s, keeping\n") % f)
1762 self.ui.debug(_("local modified %s, keeping\n") % f)
1764 else:
1763 else:
1765 self.ui.debug(_("working dir created %s, keeping\n") % f)
1764 self.ui.debug(_("working dir created %s, keeping\n") % f)
1766
1765
1767 for f, n in m2.iteritems():
1766 for f, n in m2.iteritems():
1768 if choose and not choose(f):
1767 if choose and not choose(f):
1769 continue
1768 continue
1770 if f[0] == "/":
1769 if f[0] == "/":
1771 continue
1770 continue
1772 if f in ma and n != ma[f]:
1771 if f in ma and n != ma[f]:
1773 r = _("k")
1772 r = _("k")
1774 if not force and (linear_path or allow):
1773 if not force and (linear_path or allow):
1775 r = self.ui.prompt(
1774 r = self.ui.prompt(
1776 (_("remote changed %s which local deleted\n") % f) +
1775 (_("remote changed %s which local deleted\n") % f) +
1777 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1776 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1778 if r == _("k"):
1777 if r == _("k"):
1779 get[f] = n
1778 get[f] = n
1780 elif f not in ma:
1779 elif f not in ma:
1781 self.ui.debug(_("remote created %s\n") % f)
1780 self.ui.debug(_("remote created %s\n") % f)
1782 get[f] = n
1781 get[f] = n
1783 else:
1782 else:
1784 if force or p2 == pa: # going backwards?
1783 if force or p2 == pa: # going backwards?
1785 self.ui.debug(_("local deleted %s, recreating\n") % f)
1784 self.ui.debug(_("local deleted %s, recreating\n") % f)
1786 get[f] = n
1785 get[f] = n
1787 else:
1786 else:
1788 self.ui.debug(_("local deleted %s\n") % f)
1787 self.ui.debug(_("local deleted %s\n") % f)
1789
1788
1790 del mw, m1, m2, ma
1789 del mw, m1, m2, ma
1791
1790
1792 if force:
1791 if force:
1793 for f in merge:
1792 for f in merge:
1794 get[f] = merge[f][1]
1793 get[f] = merge[f][1]
1795 merge = {}
1794 merge = {}
1796
1795
1797 if linear_path or force:
1796 if linear_path or force:
1798 # we don't need to do any magic, just jump to the new rev
1797 # we don't need to do any magic, just jump to the new rev
1799 branch_merge = False
1798 branch_merge = False
1800 p1, p2 = p2, nullid
1799 p1, p2 = p2, nullid
1801 else:
1800 else:
1802 if not allow:
1801 if not allow:
1803 self.ui.status(_("this update spans a branch"
1802 self.ui.status(_("this update spans a branch"
1804 " affecting the following files:\n"))
1803 " affecting the following files:\n"))
1805 fl = merge.keys() + get.keys()
1804 fl = merge.keys() + get.keys()
1806 fl.sort()
1805 fl.sort()
1807 for f in fl:
1806 for f in fl:
1808 cf = ""
1807 cf = ""
1809 if f in merge:
1808 if f in merge:
1810 cf = _(" (resolve)")
1809 cf = _(" (resolve)")
1811 self.ui.status(" %s%s\n" % (f, cf))
1810 self.ui.status(" %s%s\n" % (f, cf))
1812 self.ui.warn(_("aborting update spanning branches!\n"))
1811 self.ui.warn(_("aborting update spanning branches!\n"))
1813 self.ui.status(_("(use 'hg merge' to merge across branches"
1812 self.ui.status(_("(use 'hg merge' to merge across branches"
1814 " or 'hg update -C' to lose changes)\n"))
1813 " or 'hg update -C' to lose changes)\n"))
1815 return 1
1814 return 1
1816 branch_merge = True
1815 branch_merge = True
1817
1816
1818 xp1 = hex(p1)
1817 xp1 = hex(p1)
1819 xp2 = hex(p2)
1818 xp2 = hex(p2)
1820 if p2 == nullid: xxp2 = ''
1819 if p2 == nullid: xxp2 = ''
1821 else: xxp2 = xp2
1820 else: xxp2 = xp2
1822
1821
1823 self.hook('preupdate', throw=True, parent1=xp1, parent2=xxp2)
1822 self.hook('preupdate', throw=True, parent1=xp1, parent2=xxp2)
1824
1823
1825 # get the files we don't need to change
1824 # get the files we don't need to change
1826 files = get.keys()
1825 files = get.keys()
1827 files.sort()
1826 files.sort()
1828 for f in files:
1827 for f in files:
1829 if f[0] == "/":
1828 if f[0] == "/":
1830 continue
1829 continue
1831 self.ui.note(_("getting %s\n") % f)
1830 self.ui.note(_("getting %s\n") % f)
1832 t = self.file(f).read(get[f])
1831 t = self.file(f).read(get[f])
1833 self.wwrite(f, t)
1832 self.wwrite(f, t)
1834 util.set_exec(self.wjoin(f), mf2[f])
1833 util.set_exec(self.wjoin(f), mf2[f])
1835 if moddirstate:
1834 if moddirstate:
1836 if branch_merge:
1835 if branch_merge:
1837 self.dirstate.update([f], 'n', st_mtime=-1)
1836 self.dirstate.update([f], 'n', st_mtime=-1)
1838 else:
1837 else:
1839 self.dirstate.update([f], 'n')
1838 self.dirstate.update([f], 'n')
1840
1839
1841 # merge the tricky bits
1840 # merge the tricky bits
1842 failedmerge = []
1841 failedmerge = []
1843 files = merge.keys()
1842 files = merge.keys()
1844 files.sort()
1843 files.sort()
1845 for f in files:
1844 for f in files:
1846 self.ui.status(_("merging %s\n") % f)
1845 self.ui.status(_("merging %s\n") % f)
1847 my, other, flag = merge[f]
1846 my, other, flag = merge[f]
1848 ret = self.merge3(f, my, other, xp1, xp2)
1847 ret = self.merge3(f, my, other, xp1, xp2)
1849 if ret:
1848 if ret:
1850 err = True
1849 err = True
1851 failedmerge.append(f)
1850 failedmerge.append(f)
1852 util.set_exec(self.wjoin(f), flag)
1851 util.set_exec(self.wjoin(f), flag)
1853 if moddirstate:
1852 if moddirstate:
1854 if branch_merge:
1853 if branch_merge:
1855 # We've done a branch merge, mark this file as merged
1854 # We've done a branch merge, mark this file as merged
1856 # so that we properly record the merger later
1855 # so that we properly record the merger later
1857 self.dirstate.update([f], 'm')
1856 self.dirstate.update([f], 'm')
1858 else:
1857 else:
1859 # We've update-merged a locally modified file, so
1858 # We've update-merged a locally modified file, so
1860 # we set the dirstate to emulate a normal checkout
1859 # we set the dirstate to emulate a normal checkout
1861 # of that file some time in the past. Thus our
1860 # of that file some time in the past. Thus our
1862 # merge will appear as a normal local file
1861 # merge will appear as a normal local file
1863 # modification.
1862 # modification.
1864 f_len = len(self.file(f).read(other))
1863 f_len = len(self.file(f).read(other))
1865 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1864 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1866
1865
1867 remove.sort()
1866 remove.sort()
1868 for f in remove:
1867 for f in remove:
1869 self.ui.note(_("removing %s\n") % f)
1868 self.ui.note(_("removing %s\n") % f)
1870 util.audit_path(f)
1869 util.audit_path(f)
1871 try:
1870 try:
1872 util.unlink(self.wjoin(f))
1871 util.unlink(self.wjoin(f))
1873 except OSError, inst:
1872 except OSError, inst:
1874 if inst.errno != errno.ENOENT:
1873 if inst.errno != errno.ENOENT:
1875 self.ui.warn(_("update failed to remove %s: %s!\n") %
1874 self.ui.warn(_("update failed to remove %s: %s!\n") %
1876 (f, inst.strerror))
1875 (f, inst.strerror))
1877 if moddirstate:
1876 if moddirstate:
1878 if branch_merge:
1877 if branch_merge:
1879 self.dirstate.update(remove, 'r')
1878 self.dirstate.update(remove, 'r')
1880 else:
1879 else:
1881 self.dirstate.forget(remove)
1880 self.dirstate.forget(remove)
1882
1881
1883 if moddirstate:
1882 if moddirstate:
1884 self.dirstate.setparents(p1, p2)
1883 self.dirstate.setparents(p1, p2)
1885
1884
1886 if show_stats:
1885 if show_stats:
1887 stats = ((len(get), _("updated")),
1886 stats = ((len(get), _("updated")),
1888 (len(merge) - len(failedmerge), _("merged")),
1887 (len(merge) - len(failedmerge), _("merged")),
1889 (len(remove), _("removed")),
1888 (len(remove), _("removed")),
1890 (len(failedmerge), _("unresolved")))
1889 (len(failedmerge), _("unresolved")))
1891 note = ", ".join([_("%d files %s") % s for s in stats])
1890 note = ", ".join([_("%d files %s") % s for s in stats])
1892 self.ui.status("%s\n" % note)
1891 self.ui.status("%s\n" % note)
1893 if moddirstate:
1892 if moddirstate:
1894 if branch_merge:
1893 if branch_merge:
1895 if failedmerge:
1894 if failedmerge:
1896 self.ui.status(_("There are unresolved merges,"
1895 self.ui.status(_("There are unresolved merges,"
1897 " you can redo the full merge using:\n"
1896 " you can redo the full merge using:\n"
1898 " hg update -C %s\n"
1897 " hg update -C %s\n"
1899 " hg merge %s\n"
1898 " hg merge %s\n"
1900 % (self.changelog.rev(p1),
1899 % (self.changelog.rev(p1),
1901 self.changelog.rev(p2))))
1900 self.changelog.rev(p2))))
1902 else:
1901 else:
1903 self.ui.status(_("(branch merge, don't forget to commit)\n"))
1902 self.ui.status(_("(branch merge, don't forget to commit)\n"))
1904 elif failedmerge:
1903 elif failedmerge:
1905 self.ui.status(_("There are unresolved merges with"
1904 self.ui.status(_("There are unresolved merges with"
1906 " locally modified files.\n"))
1905 " locally modified files.\n"))
1907
1906
1908 self.hook('update', parent1=xp1, parent2=xxp2, error=int(err))
1907 self.hook('update', parent1=xp1, parent2=xxp2, error=int(err))
1909 return err
1908 return err
1910
1909
1911 def merge3(self, fn, my, other, p1, p2):
1910 def merge3(self, fn, my, other, p1, p2):
1912 """perform a 3-way merge in the working directory"""
1911 """perform a 3-way merge in the working directory"""
1913
1912
1914 def temp(prefix, node):
1913 def temp(prefix, node):
1915 pre = "%s~%s." % (os.path.basename(fn), prefix)
1914 pre = "%s~%s." % (os.path.basename(fn), prefix)
1916 (fd, name) = tempfile.mkstemp(prefix=pre)
1915 (fd, name) = tempfile.mkstemp(prefix=pre)
1917 f = os.fdopen(fd, "wb")
1916 f = os.fdopen(fd, "wb")
1918 self.wwrite(fn, fl.read(node), f)
1917 self.wwrite(fn, fl.read(node), f)
1919 f.close()
1918 f.close()
1920 return name
1919 return name
1921
1920
1922 fl = self.file(fn)
1921 fl = self.file(fn)
1923 base = fl.ancestor(my, other)
1922 base = fl.ancestor(my, other)
1924 a = self.wjoin(fn)
1923 a = self.wjoin(fn)
1925 b = temp("base", base)
1924 b = temp("base", base)
1926 c = temp("other", other)
1925 c = temp("other", other)
1927
1926
1928 self.ui.note(_("resolving %s\n") % fn)
1927 self.ui.note(_("resolving %s\n") % fn)
1929 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1928 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1930 (fn, short(my), short(other), short(base)))
1929 (fn, short(my), short(other), short(base)))
1931
1930
1932 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1931 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1933 or "hgmerge")
1932 or "hgmerge")
1934 r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=self.root,
1933 r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=self.root,
1935 environ={'HG_FILE': fn,
1934 environ={'HG_FILE': fn,
1936 'HG_MY_NODE': p1,
1935 'HG_MY_NODE': p1,
1937 'HG_OTHER_NODE': p2,
1936 'HG_OTHER_NODE': p2,
1938 'HG_FILE_MY_NODE': hex(my),
1937 'HG_FILE_MY_NODE': hex(my),
1939 'HG_FILE_OTHER_NODE': hex(other),
1938 'HG_FILE_OTHER_NODE': hex(other),
1940 'HG_FILE_BASE_NODE': hex(base)})
1939 'HG_FILE_BASE_NODE': hex(base)})
1941 if r:
1940 if r:
1942 self.ui.warn(_("merging %s failed!\n") % fn)
1941 self.ui.warn(_("merging %s failed!\n") % fn)
1943
1942
1944 os.unlink(b)
1943 os.unlink(b)
1945 os.unlink(c)
1944 os.unlink(c)
1946 return r
1945 return r
1947
1946
1948 def verify(self):
1947 def verify(self):
1949 filelinkrevs = {}
1948 filelinkrevs = {}
1950 filenodes = {}
1949 filenodes = {}
1951 changesets = revisions = files = 0
1950 changesets = revisions = files = 0
1952 errors = [0]
1951 errors = [0]
1953 warnings = [0]
1952 warnings = [0]
1954 neededmanifests = {}
1953 neededmanifests = {}
1955
1954
1956 def err(msg):
1955 def err(msg):
1957 self.ui.warn(msg + "\n")
1956 self.ui.warn(msg + "\n")
1958 errors[0] += 1
1957 errors[0] += 1
1959
1958
1960 def warn(msg):
1959 def warn(msg):
1961 self.ui.warn(msg + "\n")
1960 self.ui.warn(msg + "\n")
1962 warnings[0] += 1
1961 warnings[0] += 1
1963
1962
1964 def checksize(obj, name):
1963 def checksize(obj, name):
1965 d = obj.checksize()
1964 d = obj.checksize()
1966 if d[0]:
1965 if d[0]:
1967 err(_("%s data length off by %d bytes") % (name, d[0]))
1966 err(_("%s data length off by %d bytes") % (name, d[0]))
1968 if d[1]:
1967 if d[1]:
1969 err(_("%s index contains %d extra bytes") % (name, d[1]))
1968 err(_("%s index contains %d extra bytes") % (name, d[1]))
1970
1969
1971 def checkversion(obj, name):
1970 def checkversion(obj, name):
1972 if obj.version != revlog.REVLOGV0:
1971 if obj.version != revlog.REVLOGV0:
1973 if not revlogv1:
1972 if not revlogv1:
1974 warn(_("warning: `%s' uses revlog format 1") % name)
1973 warn(_("warning: `%s' uses revlog format 1") % name)
1975 elif revlogv1:
1974 elif revlogv1:
1976 warn(_("warning: `%s' uses revlog format 0") % name)
1975 warn(_("warning: `%s' uses revlog format 0") % name)
1977
1976
1978 revlogv1 = self.revlogversion != revlog.REVLOGV0
1977 revlogv1 = self.revlogversion != revlog.REVLOGV0
1979 if self.ui.verbose or revlogv1 != self.revlogv1:
1978 if self.ui.verbose or revlogv1 != self.revlogv1:
1980 self.ui.status(_("repository uses revlog format %d\n") %
1979 self.ui.status(_("repository uses revlog format %d\n") %
1981 (revlogv1 and 1 or 0))
1980 (revlogv1 and 1 or 0))
1982
1981
1983 seen = {}
1982 seen = {}
1984 self.ui.status(_("checking changesets\n"))
1983 self.ui.status(_("checking changesets\n"))
1985 checksize(self.changelog, "changelog")
1984 checksize(self.changelog, "changelog")
1986
1985
1987 for i in range(self.changelog.count()):
1986 for i in range(self.changelog.count()):
1988 changesets += 1
1987 changesets += 1
1989 n = self.changelog.node(i)
1988 n = self.changelog.node(i)
1990 l = self.changelog.linkrev(n)
1989 l = self.changelog.linkrev(n)
1991 if l != i:
1990 if l != i:
1992 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1991 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1993 if n in seen:
1992 if n in seen:
1994 err(_("duplicate changeset at revision %d") % i)
1993 err(_("duplicate changeset at revision %d") % i)
1995 seen[n] = 1
1994 seen[n] = 1
1996
1995
1997 for p in self.changelog.parents(n):
1996 for p in self.changelog.parents(n):
1998 if p not in self.changelog.nodemap:
1997 if p not in self.changelog.nodemap:
1999 err(_("changeset %s has unknown parent %s") %
1998 err(_("changeset %s has unknown parent %s") %
2000 (short(n), short(p)))
1999 (short(n), short(p)))
2001 try:
2000 try:
2002 changes = self.changelog.read(n)
2001 changes = self.changelog.read(n)
2003 except KeyboardInterrupt:
2002 except KeyboardInterrupt:
2004 self.ui.warn(_("interrupted"))
2003 self.ui.warn(_("interrupted"))
2005 raise
2004 raise
2006 except Exception, inst:
2005 except Exception, inst:
2007 err(_("unpacking changeset %s: %s") % (short(n), inst))
2006 err(_("unpacking changeset %s: %s") % (short(n), inst))
2008 continue
2007 continue
2009
2008
2010 neededmanifests[changes[0]] = n
2009 neededmanifests[changes[0]] = n
2011
2010
2012 for f in changes[3]:
2011 for f in changes[3]:
2013 filelinkrevs.setdefault(f, []).append(i)
2012 filelinkrevs.setdefault(f, []).append(i)
2014
2013
2015 seen = {}
2014 seen = {}
2016 self.ui.status(_("checking manifests\n"))
2015 self.ui.status(_("checking manifests\n"))
2017 checkversion(self.manifest, "manifest")
2016 checkversion(self.manifest, "manifest")
2018 checksize(self.manifest, "manifest")
2017 checksize(self.manifest, "manifest")
2019
2018
2020 for i in range(self.manifest.count()):
2019 for i in range(self.manifest.count()):
2021 n = self.manifest.node(i)
2020 n = self.manifest.node(i)
2022 l = self.manifest.linkrev(n)
2021 l = self.manifest.linkrev(n)
2023
2022
2024 if l < 0 or l >= self.changelog.count():
2023 if l < 0 or l >= self.changelog.count():
2025 err(_("bad manifest link (%d) at revision %d") % (l, i))
2024 err(_("bad manifest link (%d) at revision %d") % (l, i))
2026
2025
2027 if n in neededmanifests:
2026 if n in neededmanifests:
2028 del neededmanifests[n]
2027 del neededmanifests[n]
2029
2028
2030 if n in seen:
2029 if n in seen:
2031 err(_("duplicate manifest at revision %d") % i)
2030 err(_("duplicate manifest at revision %d") % i)
2032
2031
2033 seen[n] = 1
2032 seen[n] = 1
2034
2033
2035 for p in self.manifest.parents(n):
2034 for p in self.manifest.parents(n):
2036 if p not in self.manifest.nodemap:
2035 if p not in self.manifest.nodemap:
2037 err(_("manifest %s has unknown parent %s") %
2036 err(_("manifest %s has unknown parent %s") %
2038 (short(n), short(p)))
2037 (short(n), short(p)))
2039
2038
2040 try:
2039 try:
2041 delta = mdiff.patchtext(self.manifest.delta(n))
2040 delta = mdiff.patchtext(self.manifest.delta(n))
2042 except KeyboardInterrupt:
2041 except KeyboardInterrupt:
2043 self.ui.warn(_("interrupted"))
2042 self.ui.warn(_("interrupted"))
2044 raise
2043 raise
2045 except Exception, inst:
2044 except Exception, inst:
2046 err(_("unpacking manifest %s: %s") % (short(n), inst))
2045 err(_("unpacking manifest %s: %s") % (short(n), inst))
2047 continue
2046 continue
2048
2047
2049 try:
2048 try:
2050 ff = [ l.split('\0') for l in delta.splitlines() ]
2049 ff = [ l.split('\0') for l in delta.splitlines() ]
2051 for f, fn in ff:
2050 for f, fn in ff:
2052 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
2051 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
2053 except (ValueError, TypeError), inst:
2052 except (ValueError, TypeError), inst:
2054 err(_("broken delta in manifest %s: %s") % (short(n), inst))
2053 err(_("broken delta in manifest %s: %s") % (short(n), inst))
2055
2054
2056 self.ui.status(_("crosschecking files in changesets and manifests\n"))
2055 self.ui.status(_("crosschecking files in changesets and manifests\n"))
2057
2056
2058 for m, c in neededmanifests.items():
2057 for m, c in neededmanifests.items():
2059 err(_("Changeset %s refers to unknown manifest %s") %
2058 err(_("Changeset %s refers to unknown manifest %s") %
2060 (short(m), short(c)))
2059 (short(m), short(c)))
2061 del neededmanifests
2060 del neededmanifests
2062
2061
2063 for f in filenodes:
2062 for f in filenodes:
2064 if f not in filelinkrevs:
2063 if f not in filelinkrevs:
2065 err(_("file %s in manifest but not in changesets") % f)
2064 err(_("file %s in manifest but not in changesets") % f)
2066
2065
2067 for f in filelinkrevs:
2066 for f in filelinkrevs:
2068 if f not in filenodes:
2067 if f not in filenodes:
2069 err(_("file %s in changeset but not in manifest") % f)
2068 err(_("file %s in changeset but not in manifest") % f)
2070
2069
2071 self.ui.status(_("checking files\n"))
2070 self.ui.status(_("checking files\n"))
2072 ff = filenodes.keys()
2071 ff = filenodes.keys()
2073 ff.sort()
2072 ff.sort()
2074 for f in ff:
2073 for f in ff:
2075 if f == "/dev/null":
2074 if f == "/dev/null":
2076 continue
2075 continue
2077 files += 1
2076 files += 1
2078 if not f:
2077 if not f:
2079 err(_("file without name in manifest %s") % short(n))
2078 err(_("file without name in manifest %s") % short(n))
2080 continue
2079 continue
2081 fl = self.file(f)
2080 fl = self.file(f)
2082 checkversion(fl, f)
2081 checkversion(fl, f)
2083 checksize(fl, f)
2082 checksize(fl, f)
2084
2083
2085 nodes = {nullid: 1}
2084 nodes = {nullid: 1}
2086 seen = {}
2085 seen = {}
2087 for i in range(fl.count()):
2086 for i in range(fl.count()):
2088 revisions += 1
2087 revisions += 1
2089 n = fl.node(i)
2088 n = fl.node(i)
2090
2089
2091 if n in seen:
2090 if n in seen:
2092 err(_("%s: duplicate revision %d") % (f, i))
2091 err(_("%s: duplicate revision %d") % (f, i))
2093 if n not in filenodes[f]:
2092 if n not in filenodes[f]:
2094 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
2093 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
2095 else:
2094 else:
2096 del filenodes[f][n]
2095 del filenodes[f][n]
2097
2096
2098 flr = fl.linkrev(n)
2097 flr = fl.linkrev(n)
2099 if flr not in filelinkrevs.get(f, []):
2098 if flr not in filelinkrevs.get(f, []):
2100 err(_("%s:%s points to unexpected changeset %d")
2099 err(_("%s:%s points to unexpected changeset %d")
2101 % (f, short(n), flr))
2100 % (f, short(n), flr))
2102 else:
2101 else:
2103 filelinkrevs[f].remove(flr)
2102 filelinkrevs[f].remove(flr)
2104
2103
2105 # verify contents
2104 # verify contents
2106 try:
2105 try:
2107 t = fl.read(n)
2106 t = fl.read(n)
2108 except KeyboardInterrupt:
2107 except KeyboardInterrupt:
2109 self.ui.warn(_("interrupted"))
2108 self.ui.warn(_("interrupted"))
2110 raise
2109 raise
2111 except Exception, inst:
2110 except Exception, inst:
2112 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
2111 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
2113
2112
2114 # verify parents
2113 # verify parents
2115 (p1, p2) = fl.parents(n)
2114 (p1, p2) = fl.parents(n)
2116 if p1 not in nodes:
2115 if p1 not in nodes:
2117 err(_("file %s:%s unknown parent 1 %s") %
2116 err(_("file %s:%s unknown parent 1 %s") %
2118 (f, short(n), short(p1)))
2117 (f, short(n), short(p1)))
2119 if p2 not in nodes:
2118 if p2 not in nodes:
2120 err(_("file %s:%s unknown parent 2 %s") %
2119 err(_("file %s:%s unknown parent 2 %s") %
2121 (f, short(n), short(p1)))
2120 (f, short(n), short(p1)))
2122 nodes[n] = 1
2121 nodes[n] = 1
2123
2122
2124 # cross-check
2123 # cross-check
2125 for node in filenodes[f]:
2124 for node in filenodes[f]:
2126 err(_("node %s in manifests not in %s") % (hex(node), f))
2125 err(_("node %s in manifests not in %s") % (hex(node), f))
2127
2126
2128 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
2127 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
2129 (files, changesets, revisions))
2128 (files, changesets, revisions))
2130
2129
2131 if warnings[0]:
2130 if warnings[0]:
2132 self.ui.warn(_("%d warnings encountered!\n") % warnings[0])
2131 self.ui.warn(_("%d warnings encountered!\n") % warnings[0])
2133 if errors[0]:
2132 if errors[0]:
2134 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
2133 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
2135 return 1
2134 return 1
2136
2135
2137 # used to avoid circular references so destructors work
2136 # used to avoid circular references so destructors work
2138 def aftertrans(base):
2137 def aftertrans(base):
2139 p = base
2138 p = base
2140 def a():
2139 def a():
2141 util.rename(os.path.join(p, "journal"), os.path.join(p, "undo"))
2140 util.rename(os.path.join(p, "journal"), os.path.join(p, "undo"))
2142 util.rename(os.path.join(p, "journal.dirstate"),
2141 util.rename(os.path.join(p, "journal.dirstate"),
2143 os.path.join(p, "undo.dirstate"))
2142 os.path.join(p, "undo.dirstate"))
2144 return a
2143 return a
2145
2144
@@ -1,189 +1,188 b''
1 # manifest.py - manifest revision class for mercurial
1 # manifest.py - manifest revision class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import struct
9 from revlog import *
8 from revlog import *
10 from i18n import gettext as _
9 from i18n import gettext as _
11 from demandload import *
10 from demandload import *
12 demandload(globals(), "bisect array")
11 demandload(globals(), "array bisect struct")
13
12
14 class manifest(revlog):
13 class manifest(revlog):
15 def __init__(self, opener, defversion=REVLOGV0):
14 def __init__(self, opener, defversion=REVLOGV0):
16 self.mapcache = None
15 self.mapcache = None
17 self.listcache = None
16 self.listcache = None
18 revlog.__init__(self, opener, "00manifest.i", "00manifest.d",
17 revlog.__init__(self, opener, "00manifest.i", "00manifest.d",
19 defversion)
18 defversion)
20
19
21 def read(self, node):
20 def read(self, node):
22 if node == nullid: return {} # don't upset local cache
21 if node == nullid: return {} # don't upset local cache
23 if self.mapcache and self.mapcache[0] == node:
22 if self.mapcache and self.mapcache[0] == node:
24 return self.mapcache[1]
23 return self.mapcache[1]
25 text = self.revision(node)
24 text = self.revision(node)
26 map = {}
25 map = {}
27 flag = {}
26 flag = {}
28 self.listcache = array.array('c', text)
27 self.listcache = array.array('c', text)
29 lines = text.splitlines(1)
28 lines = text.splitlines(1)
30 for l in lines:
29 for l in lines:
31 (f, n) = l.split('\0')
30 (f, n) = l.split('\0')
32 map[f] = bin(n[:40])
31 map[f] = bin(n[:40])
33 flag[f] = (n[40:-1] == "x")
32 flag[f] = (n[40:-1] == "x")
34 self.mapcache = (node, map, flag)
33 self.mapcache = (node, map, flag)
35 return map
34 return map
36
35
37 def readflags(self, node):
36 def readflags(self, node):
38 if node == nullid: return {} # don't upset local cache
37 if node == nullid: return {} # don't upset local cache
39 if not self.mapcache or self.mapcache[0] != node:
38 if not self.mapcache or self.mapcache[0] != node:
40 self.read(node)
39 self.read(node)
41 return self.mapcache[2]
40 return self.mapcache[2]
42
41
43 def diff(self, a, b):
42 def diff(self, a, b):
44 return mdiff.textdiff(str(a), str(b))
43 return mdiff.textdiff(str(a), str(b))
45
44
46 def _search(self, m, s, lo=0, hi=None):
45 def _search(self, m, s, lo=0, hi=None):
47 '''return a tuple (start, end) that says where to find s within m.
46 '''return a tuple (start, end) that says where to find s within m.
48
47
49 If the string is found m[start:end] are the line containing
48 If the string is found m[start:end] are the line containing
50 that string. If start == end the string was not found and
49 that string. If start == end the string was not found and
51 they indicate the proper sorted insertion point. This was
50 they indicate the proper sorted insertion point. This was
52 taken from bisect_left, and modified to find line start/end as
51 taken from bisect_left, and modified to find line start/end as
53 it goes along.
52 it goes along.
54
53
55 m should be a buffer or a string
54 m should be a buffer or a string
56 s is a string'''
55 s is a string'''
57 def advance(i, c):
56 def advance(i, c):
58 while i < lenm and m[i] != c:
57 while i < lenm and m[i] != c:
59 i += 1
58 i += 1
60 return i
59 return i
61 lenm = len(m)
60 lenm = len(m)
62 if not hi:
61 if not hi:
63 hi = lenm
62 hi = lenm
64 while lo < hi:
63 while lo < hi:
65 mid = (lo + hi) // 2
64 mid = (lo + hi) // 2
66 start = mid
65 start = mid
67 while start > 0 and m[start-1] != '\n':
66 while start > 0 and m[start-1] != '\n':
68 start -= 1
67 start -= 1
69 end = advance(start, '\0')
68 end = advance(start, '\0')
70 if m[start:end] < s:
69 if m[start:end] < s:
71 # we know that after the null there are 40 bytes of sha1
70 # we know that after the null there are 40 bytes of sha1
72 # this translates to the bisect lo = mid + 1
71 # this translates to the bisect lo = mid + 1
73 lo = advance(end + 40, '\n') + 1
72 lo = advance(end + 40, '\n') + 1
74 else:
73 else:
75 # this translates to the bisect hi = mid
74 # this translates to the bisect hi = mid
76 hi = start
75 hi = start
77 end = advance(lo, '\0')
76 end = advance(lo, '\0')
78 found = m[lo:end]
77 found = m[lo:end]
79 if cmp(s, found) == 0:
78 if cmp(s, found) == 0:
80 # we know that after the null there are 40 bytes of sha1
79 # we know that after the null there are 40 bytes of sha1
81 end = advance(end + 40, '\n')
80 end = advance(end + 40, '\n')
82 return (lo, end+1)
81 return (lo, end+1)
83 else:
82 else:
84 return (lo, lo)
83 return (lo, lo)
85
84
86 def find(self, node, f):
85 def find(self, node, f):
87 '''look up entry for a single file efficiently.
86 '''look up entry for a single file efficiently.
88 return (node, flag) pair if found, (None, None) if not.'''
87 return (node, flag) pair if found, (None, None) if not.'''
89 if self.mapcache and node == self.mapcache[0]:
88 if self.mapcache and node == self.mapcache[0]:
90 return self.mapcache[1].get(f), self.mapcache[2].get(f)
89 return self.mapcache[1].get(f), self.mapcache[2].get(f)
91 text = self.revision(node)
90 text = self.revision(node)
92 start, end = self._search(text, f)
91 start, end = self._search(text, f)
93 if start == end:
92 if start == end:
94 return None, None
93 return None, None
95 l = text[start:end]
94 l = text[start:end]
96 f, n = l.split('\0')
95 f, n = l.split('\0')
97 return bin(n[:40]), n[40:-1] == 'x'
96 return bin(n[:40]), n[40:-1] == 'x'
98
97
99 def add(self, map, flags, transaction, link, p1=None, p2=None,
98 def add(self, map, flags, transaction, link, p1=None, p2=None,
100 changed=None):
99 changed=None):
101 # apply the changes collected during the bisect loop to our addlist
100 # apply the changes collected during the bisect loop to our addlist
102 # return a delta suitable for addrevision
101 # return a delta suitable for addrevision
103 def addlistdelta(addlist, x):
102 def addlistdelta(addlist, x):
104 # start from the bottom up
103 # start from the bottom up
105 # so changes to the offsets don't mess things up.
104 # so changes to the offsets don't mess things up.
106 i = len(x)
105 i = len(x)
107 while i > 0:
106 while i > 0:
108 i -= 1
107 i -= 1
109 start = x[i][0]
108 start = x[i][0]
110 end = x[i][1]
109 end = x[i][1]
111 if x[i][2]:
110 if x[i][2]:
112 addlist[start:end] = array.array('c', x[i][2])
111 addlist[start:end] = array.array('c', x[i][2])
113 else:
112 else:
114 del addlist[start:end]
113 del addlist[start:end]
115 return "".join([struct.pack(">lll", d[0], d[1], len(d[2])) + d[2] \
114 return "".join([struct.pack(">lll", d[0], d[1], len(d[2])) + d[2] \
116 for d in x ])
115 for d in x ])
117
116
118 # if we're using the listcache, make sure it is valid and
117 # if we're using the listcache, make sure it is valid and
119 # parented by the same node we're diffing against
118 # parented by the same node we're diffing against
120 if not changed or not self.listcache or not p1 or \
119 if not changed or not self.listcache or not p1 or \
121 self.mapcache[0] != p1:
120 self.mapcache[0] != p1:
122 files = map.keys()
121 files = map.keys()
123 files.sort()
122 files.sort()
124
123
125 # if this is changed to support newlines in filenames,
124 # if this is changed to support newlines in filenames,
126 # be sure to check the templates/ dir again (especially *-raw.tmpl)
125 # be sure to check the templates/ dir again (especially *-raw.tmpl)
127 text = ["%s\000%s%s\n" %
126 text = ["%s\000%s%s\n" %
128 (f, hex(map[f]), flags[f] and "x" or '')
127 (f, hex(map[f]), flags[f] and "x" or '')
129 for f in files]
128 for f in files]
130 self.listcache = array.array('c', "".join(text))
129 self.listcache = array.array('c', "".join(text))
131 cachedelta = None
130 cachedelta = None
132 else:
131 else:
133 addlist = self.listcache
132 addlist = self.listcache
134
133
135 # combine the changed lists into one list for sorting
134 # combine the changed lists into one list for sorting
136 work = [[x, 0] for x in changed[0]]
135 work = [[x, 0] for x in changed[0]]
137 work[len(work):] = [[x, 1] for x in changed[1]]
136 work[len(work):] = [[x, 1] for x in changed[1]]
138 work.sort()
137 work.sort()
139
138
140 delta = []
139 delta = []
141 dstart = None
140 dstart = None
142 dend = None
141 dend = None
143 dline = [""]
142 dline = [""]
144 start = 0
143 start = 0
145 # zero copy representation of addlist as a buffer
144 # zero copy representation of addlist as a buffer
146 addbuf = buffer(addlist)
145 addbuf = buffer(addlist)
147
146
148 # start with a readonly loop that finds the offset of
147 # start with a readonly loop that finds the offset of
149 # each line and creates the deltas
148 # each line and creates the deltas
150 for w in work:
149 for w in work:
151 f = w[0]
150 f = w[0]
152 # bs will either be the index of the item or the insert point
151 # bs will either be the index of the item or the insert point
153 start, end = self._search(addbuf, f, start)
152 start, end = self._search(addbuf, f, start)
154 if w[1] == 0:
153 if w[1] == 0:
155 l = "%s\000%s%s\n" % (f, hex(map[f]),
154 l = "%s\000%s%s\n" % (f, hex(map[f]),
156 flags[f] and "x" or '')
155 flags[f] and "x" or '')
157 else:
156 else:
158 l = ""
157 l = ""
159 if start == end and w[1] == 1:
158 if start == end and w[1] == 1:
160 # item we want to delete was not found, error out
159 # item we want to delete was not found, error out
161 raise AssertionError(
160 raise AssertionError(
162 _("failed to remove %s from manifest\n") % f)
161 _("failed to remove %s from manifest\n") % f)
163 if dstart != None and dstart <= start and dend >= start:
162 if dstart != None and dstart <= start and dend >= start:
164 if dend < end:
163 if dend < end:
165 dend = end
164 dend = end
166 if l:
165 if l:
167 dline.append(l)
166 dline.append(l)
168 else:
167 else:
169 if dstart != None:
168 if dstart != None:
170 delta.append([dstart, dend, "".join(dline)])
169 delta.append([dstart, dend, "".join(dline)])
171 dstart = start
170 dstart = start
172 dend = end
171 dend = end
173 dline = [l]
172 dline = [l]
174
173
175 if dstart != None:
174 if dstart != None:
176 delta.append([dstart, dend, "".join(dline)])
175 delta.append([dstart, dend, "".join(dline)])
177 # apply the delta to the addlist, and get a delta for addrevision
176 # apply the delta to the addlist, and get a delta for addrevision
178 cachedelta = addlistdelta(addlist, delta)
177 cachedelta = addlistdelta(addlist, delta)
179
178
180 # the delta is only valid if we've been processing the tip revision
179 # the delta is only valid if we've been processing the tip revision
181 if self.mapcache[0] != self.tip():
180 if self.mapcache[0] != self.tip():
182 cachedelta = None
181 cachedelta = None
183 self.listcache = addlist
182 self.listcache = addlist
184
183
185 n = self.addrevision(buffer(self.listcache), transaction, link, p1, \
184 n = self.addrevision(buffer(self.listcache), transaction, link, p1, \
186 p2, cachedelta)
185 p2, cachedelta)
187 self.mapcache = (n, map, flags)
186 self.mapcache = (n, map, flags)
188
187
189 return n
188 return n
@@ -1,205 +1,205 b''
1 # mdiff.py - diff and patch routines for mercurial
1 # mdiff.py - diff and patch routines for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from demandload import demandload
8 from demandload import demandload
9 import struct, bdiff, util, mpatch
9 import bdiff, mpatch
10 demandload(globals(), "re")
10 demandload(globals(), "re struct util")
11
11
12 def splitnewlines(text):
12 def splitnewlines(text):
13 '''like str.splitlines, but only split on newlines.'''
13 '''like str.splitlines, but only split on newlines.'''
14 lines = [l + '\n' for l in text.split('\n')]
14 lines = [l + '\n' for l in text.split('\n')]
15 if lines:
15 if lines:
16 if lines[-1] == '\n':
16 if lines[-1] == '\n':
17 lines.pop()
17 lines.pop()
18 else:
18 else:
19 lines[-1] = lines[-1][:-1]
19 lines[-1] = lines[-1][:-1]
20 return lines
20 return lines
21
21
22 def unidiff(a, ad, b, bd, fn, r=None, text=False,
22 def unidiff(a, ad, b, bd, fn, r=None, text=False,
23 showfunc=False, ignorews=False):
23 showfunc=False, ignorews=False):
24
24
25 if not a and not b: return ""
25 if not a and not b: return ""
26 epoch = util.datestr((0, 0))
26 epoch = util.datestr((0, 0))
27
27
28 if not text and (util.binary(a) or util.binary(b)):
28 if not text and (util.binary(a) or util.binary(b)):
29 l = ['Binary file %s has changed\n' % fn]
29 l = ['Binary file %s has changed\n' % fn]
30 elif not a:
30 elif not a:
31 b = splitnewlines(b)
31 b = splitnewlines(b)
32 if a is None:
32 if a is None:
33 l1 = "--- %s\t%s\n" % ("/dev/null", epoch)
33 l1 = "--- %s\t%s\n" % ("/dev/null", epoch)
34 else:
34 else:
35 l1 = "--- %s\t%s\n" % ("a/" + fn, ad)
35 l1 = "--- %s\t%s\n" % ("a/" + fn, ad)
36 l2 = "+++ %s\t%s\n" % ("b/" + fn, bd)
36 l2 = "+++ %s\t%s\n" % ("b/" + fn, bd)
37 l3 = "@@ -0,0 +1,%d @@\n" % len(b)
37 l3 = "@@ -0,0 +1,%d @@\n" % len(b)
38 l = [l1, l2, l3] + ["+" + e for e in b]
38 l = [l1, l2, l3] + ["+" + e for e in b]
39 elif not b:
39 elif not b:
40 a = splitnewlines(a)
40 a = splitnewlines(a)
41 l1 = "--- %s\t%s\n" % ("a/" + fn, ad)
41 l1 = "--- %s\t%s\n" % ("a/" + fn, ad)
42 if b is None:
42 if b is None:
43 l2 = "+++ %s\t%s\n" % ("/dev/null", epoch)
43 l2 = "+++ %s\t%s\n" % ("/dev/null", epoch)
44 else:
44 else:
45 l2 = "+++ %s\t%s\n" % ("b/" + fn, bd)
45 l2 = "+++ %s\t%s\n" % ("b/" + fn, bd)
46 l3 = "@@ -1,%d +0,0 @@\n" % len(a)
46 l3 = "@@ -1,%d +0,0 @@\n" % len(a)
47 l = [l1, l2, l3] + ["-" + e for e in a]
47 l = [l1, l2, l3] + ["-" + e for e in a]
48 else:
48 else:
49 al = splitnewlines(a)
49 al = splitnewlines(a)
50 bl = splitnewlines(b)
50 bl = splitnewlines(b)
51 l = list(bunidiff(a, b, al, bl, "a/" + fn, "b/" + fn,
51 l = list(bunidiff(a, b, al, bl, "a/" + fn, "b/" + fn,
52 showfunc=showfunc, ignorews=ignorews))
52 showfunc=showfunc, ignorews=ignorews))
53 if not l: return ""
53 if not l: return ""
54 # difflib uses a space, rather than a tab
54 # difflib uses a space, rather than a tab
55 l[0] = "%s\t%s\n" % (l[0][:-2], ad)
55 l[0] = "%s\t%s\n" % (l[0][:-2], ad)
56 l[1] = "%s\t%s\n" % (l[1][:-2], bd)
56 l[1] = "%s\t%s\n" % (l[1][:-2], bd)
57
57
58 for ln in xrange(len(l)):
58 for ln in xrange(len(l)):
59 if l[ln][-1] != '\n':
59 if l[ln][-1] != '\n':
60 l[ln] += "\n\ No newline at end of file\n"
60 l[ln] += "\n\ No newline at end of file\n"
61
61
62 if r:
62 if r:
63 l.insert(0, "diff %s %s\n" %
63 l.insert(0, "diff %s %s\n" %
64 (' '.join(["-r %s" % rev for rev in r]), fn))
64 (' '.join(["-r %s" % rev for rev in r]), fn))
65
65
66 return "".join(l)
66 return "".join(l)
67
67
68 # somewhat self contained replacement for difflib.unified_diff
68 # somewhat self contained replacement for difflib.unified_diff
69 # t1 and t2 are the text to be diffed
69 # t1 and t2 are the text to be diffed
70 # l1 and l2 are the text broken up into lines
70 # l1 and l2 are the text broken up into lines
71 # header1 and header2 are the filenames for the diff output
71 # header1 and header2 are the filenames for the diff output
72 # context is the number of context lines
72 # context is the number of context lines
73 # showfunc enables diff -p output
73 # showfunc enables diff -p output
74 # ignorews ignores all whitespace changes in the diff
74 # ignorews ignores all whitespace changes in the diff
75 def bunidiff(t1, t2, l1, l2, header1, header2, context=3, showfunc=False,
75 def bunidiff(t1, t2, l1, l2, header1, header2, context=3, showfunc=False,
76 ignorews=False):
76 ignorews=False):
77 def contextend(l, len):
77 def contextend(l, len):
78 ret = l + context
78 ret = l + context
79 if ret > len:
79 if ret > len:
80 ret = len
80 ret = len
81 return ret
81 return ret
82
82
83 def contextstart(l):
83 def contextstart(l):
84 ret = l - context
84 ret = l - context
85 if ret < 0:
85 if ret < 0:
86 return 0
86 return 0
87 return ret
87 return ret
88
88
89 def yieldhunk(hunk, header):
89 def yieldhunk(hunk, header):
90 if header:
90 if header:
91 for x in header:
91 for x in header:
92 yield x
92 yield x
93 (astart, a2, bstart, b2, delta) = hunk
93 (astart, a2, bstart, b2, delta) = hunk
94 aend = contextend(a2, len(l1))
94 aend = contextend(a2, len(l1))
95 alen = aend - astart
95 alen = aend - astart
96 blen = b2 - bstart + aend - a2
96 blen = b2 - bstart + aend - a2
97
97
98 func = ""
98 func = ""
99 if showfunc:
99 if showfunc:
100 # walk backwards from the start of the context
100 # walk backwards from the start of the context
101 # to find a line starting with an alphanumeric char.
101 # to find a line starting with an alphanumeric char.
102 for x in xrange(astart, -1, -1):
102 for x in xrange(astart, -1, -1):
103 t = l1[x].rstrip()
103 t = l1[x].rstrip()
104 if funcre.match(t):
104 if funcre.match(t):
105 func = ' ' + t[:40]
105 func = ' ' + t[:40]
106 break
106 break
107
107
108 yield "@@ -%d,%d +%d,%d @@%s\n" % (astart + 1, alen,
108 yield "@@ -%d,%d +%d,%d @@%s\n" % (astart + 1, alen,
109 bstart + 1, blen, func)
109 bstart + 1, blen, func)
110 for x in delta:
110 for x in delta:
111 yield x
111 yield x
112 for x in xrange(a2, aend):
112 for x in xrange(a2, aend):
113 yield ' ' + l1[x]
113 yield ' ' + l1[x]
114
114
115 header = [ "--- %s\t\n" % header1, "+++ %s\t\n" % header2 ]
115 header = [ "--- %s\t\n" % header1, "+++ %s\t\n" % header2 ]
116
116
117 if showfunc:
117 if showfunc:
118 funcre = re.compile('\w')
118 funcre = re.compile('\w')
119 if ignorews:
119 if ignorews:
120 wsre = re.compile('[ \t]')
120 wsre = re.compile('[ \t]')
121
121
122 # bdiff.blocks gives us the matching sequences in the files. The loop
122 # bdiff.blocks gives us the matching sequences in the files. The loop
123 # below finds the spaces between those matching sequences and translates
123 # below finds the spaces between those matching sequences and translates
124 # them into diff output.
124 # them into diff output.
125 #
125 #
126 diff = bdiff.blocks(t1, t2)
126 diff = bdiff.blocks(t1, t2)
127 hunk = None
127 hunk = None
128 for i in xrange(len(diff)):
128 for i in xrange(len(diff)):
129 # The first match is special.
129 # The first match is special.
130 # we've either found a match starting at line 0 or a match later
130 # we've either found a match starting at line 0 or a match later
131 # in the file. If it starts later, old and new below will both be
131 # in the file. If it starts later, old and new below will both be
132 # empty and we'll continue to the next match.
132 # empty and we'll continue to the next match.
133 if i > 0:
133 if i > 0:
134 s = diff[i-1]
134 s = diff[i-1]
135 else:
135 else:
136 s = [0, 0, 0, 0]
136 s = [0, 0, 0, 0]
137 delta = []
137 delta = []
138 s1 = diff[i]
138 s1 = diff[i]
139 a1 = s[1]
139 a1 = s[1]
140 a2 = s1[0]
140 a2 = s1[0]
141 b1 = s[3]
141 b1 = s[3]
142 b2 = s1[2]
142 b2 = s1[2]
143
143
144 old = l1[a1:a2]
144 old = l1[a1:a2]
145 new = l2[b1:b2]
145 new = l2[b1:b2]
146
146
147 # bdiff sometimes gives huge matches past eof, this check eats them,
147 # bdiff sometimes gives huge matches past eof, this check eats them,
148 # and deals with the special first match case described above
148 # and deals with the special first match case described above
149 if not old and not new:
149 if not old and not new:
150 continue
150 continue
151
151
152 if ignorews:
152 if ignorews:
153 wsold = wsre.sub('', "".join(old))
153 wsold = wsre.sub('', "".join(old))
154 wsnew = wsre.sub('', "".join(new))
154 wsnew = wsre.sub('', "".join(new))
155 if wsold == wsnew:
155 if wsold == wsnew:
156 continue
156 continue
157
157
158 astart = contextstart(a1)
158 astart = contextstart(a1)
159 bstart = contextstart(b1)
159 bstart = contextstart(b1)
160 prev = None
160 prev = None
161 if hunk:
161 if hunk:
162 # join with the previous hunk if it falls inside the context
162 # join with the previous hunk if it falls inside the context
163 if astart < hunk[1] + context + 1:
163 if astart < hunk[1] + context + 1:
164 prev = hunk
164 prev = hunk
165 astart = hunk[1]
165 astart = hunk[1]
166 bstart = hunk[3]
166 bstart = hunk[3]
167 else:
167 else:
168 for x in yieldhunk(hunk, header):
168 for x in yieldhunk(hunk, header):
169 yield x
169 yield x
170 # we only want to yield the header if the files differ, and
170 # we only want to yield the header if the files differ, and
171 # we only want to yield it once.
171 # we only want to yield it once.
172 header = None
172 header = None
173 if prev:
173 if prev:
174 # we've joined the previous hunk, record the new ending points.
174 # we've joined the previous hunk, record the new ending points.
175 hunk[1] = a2
175 hunk[1] = a2
176 hunk[3] = b2
176 hunk[3] = b2
177 delta = hunk[4]
177 delta = hunk[4]
178 else:
178 else:
179 # create a new hunk
179 # create a new hunk
180 hunk = [ astart, a2, bstart, b2, delta ]
180 hunk = [ astart, a2, bstart, b2, delta ]
181
181
182 delta[len(delta):] = [ ' ' + x for x in l1[astart:a1] ]
182 delta[len(delta):] = [ ' ' + x for x in l1[astart:a1] ]
183 delta[len(delta):] = [ '-' + x for x in old ]
183 delta[len(delta):] = [ '-' + x for x in old ]
184 delta[len(delta):] = [ '+' + x for x in new ]
184 delta[len(delta):] = [ '+' + x for x in new ]
185
185
186 if hunk:
186 if hunk:
187 for x in yieldhunk(hunk, header):
187 for x in yieldhunk(hunk, header):
188 yield x
188 yield x
189
189
190 def patchtext(bin):
190 def patchtext(bin):
191 pos = 0
191 pos = 0
192 t = []
192 t = []
193 while pos < len(bin):
193 while pos < len(bin):
194 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
194 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
195 pos += 12
195 pos += 12
196 t.append(bin[pos:pos + l])
196 t.append(bin[pos:pos + l])
197 pos += l
197 pos += l
198 return "".join(t)
198 return "".join(t)
199
199
200 def patch(a, bin):
200 def patch(a, bin):
201 return mpatch.patches(a, [bin])
201 return mpatch.patches(a, [bin])
202
202
203 patches = mpatch.patches
203 patches = mpatch.patches
204 patchedsize = mpatch.patchedsize
204 patchedsize = mpatch.patchedsize
205 textdiff = bdiff.bdiff
205 textdiff = bdiff.bdiff
@@ -1,21 +1,22 b''
1 """
1 """
2 node.py - basic nodeid manipulation for mercurial
2 node.py - basic nodeid manipulation for mercurial
3
3
4 Copyright 2005 Matt Mackall <mpm@selenic.com>
4 Copyright 2005 Matt Mackall <mpm@selenic.com>
5
5
6 This software may be used and distributed according to the terms
6 This software may be used and distributed according to the terms
7 of the GNU General Public License, incorporated herein by reference.
7 of the GNU General Public License, incorporated herein by reference.
8 """
8 """
9
9
10 import binascii
10 from demandload import demandload
11 demandload(globals(), "binascii")
11
12
12 nullid = "\0" * 20
13 nullid = "\0" * 20
13
14
14 def hex(node):
15 def hex(node):
15 return binascii.hexlify(node)
16 return binascii.hexlify(node)
16
17
17 def bin(node):
18 def bin(node):
18 return binascii.unhexlify(node)
19 return binascii.unhexlify(node)
19
20
20 def short(node):
21 def short(node):
21 return hex(node[:6])
22 return hex(node[:6])
@@ -1,515 +1,519 b''
1 # templater.py - template expansion for output
1 # templater.py - template expansion for output
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import re
9 from demandload import demandload
8 from demandload import demandload
10 from i18n import gettext as _
9 from i18n import gettext as _
11 from node import *
10 from node import *
12 demandload(globals(), "cStringIO cgi re sys os time urllib util textwrap")
11 demandload(globals(), "cStringIO cgi re sys os time urllib util textwrap")
13
12
14 esctable = {
13 esctable = {
15 '\\': '\\',
14 '\\': '\\',
16 'r': '\r',
15 'r': '\r',
17 't': '\t',
16 't': '\t',
18 'n': '\n',
17 'n': '\n',
19 'v': '\v',
18 'v': '\v',
20 }
19 }
21
20
22 def parsestring(s, quoted=True):
21 def parsestring(s, quoted=True):
23 '''parse a string using simple c-like syntax.
22 '''parse a string using simple c-like syntax.
24 string must be in quotes if quoted is True.'''
23 string must be in quotes if quoted is True.'''
25 fp = cStringIO.StringIO()
24 fp = cStringIO.StringIO()
26 if quoted:
25 if quoted:
27 first = s[0]
26 first = s[0]
28 if len(s) < 2: raise SyntaxError(_('string too short'))
27 if len(s) < 2: raise SyntaxError(_('string too short'))
29 if first not in "'\"": raise SyntaxError(_('invalid quote'))
28 if first not in "'\"": raise SyntaxError(_('invalid quote'))
30 if s[-1] != first: raise SyntaxError(_('unmatched quotes'))
29 if s[-1] != first: raise SyntaxError(_('unmatched quotes'))
31 s = s[1:-1]
30 s = s[1:-1]
32 escape = False
31 escape = False
33 for c in s:
32 for c in s:
34 if escape:
33 if escape:
35 fp.write(esctable.get(c, c))
34 fp.write(esctable.get(c, c))
36 escape = False
35 escape = False
37 elif c == '\\': escape = True
36 elif c == '\\': escape = True
38 elif quoted and c == first: raise SyntaxError(_('string ends early'))
37 elif quoted and c == first: raise SyntaxError(_('string ends early'))
39 else: fp.write(c)
38 else: fp.write(c)
40 if escape: raise SyntaxError(_('unterminated escape'))
39 if escape: raise SyntaxError(_('unterminated escape'))
41 return fp.getvalue()
40 return fp.getvalue()
42
41
43 class templater(object):
42 class templater(object):
44 '''template expansion engine.
43 '''template expansion engine.
45
44
46 template expansion works like this. a map file contains key=value
45 template expansion works like this. a map file contains key=value
47 pairs. if value is quoted, it is treated as string. otherwise, it
46 pairs. if value is quoted, it is treated as string. otherwise, it
48 is treated as name of template file.
47 is treated as name of template file.
49
48
50 templater is asked to expand a key in map. it looks up key, and
49 templater is asked to expand a key in map. it looks up key, and
51 looks for atrings like this: {foo}. it expands {foo} by looking up
50 looks for atrings like this: {foo}. it expands {foo} by looking up
52 foo in map, and substituting it. expansion is recursive: it stops
51 foo in map, and substituting it. expansion is recursive: it stops
53 when there is no more {foo} to replace.
52 when there is no more {foo} to replace.
54
53
55 expansion also allows formatting and filtering.
54 expansion also allows formatting and filtering.
56
55
57 format uses key to expand each item in list. syntax is
56 format uses key to expand each item in list. syntax is
58 {key%format}.
57 {key%format}.
59
58
60 filter uses function to transform value. syntax is
59 filter uses function to transform value. syntax is
61 {key|filter1|filter2|...}.'''
60 {key|filter1|filter2|...}.'''
62
61
63 def __init__(self, mapfile, filters={}, defaults={}, cache={}):
62 def __init__(self, mapfile, filters={}, defaults={}, cache={}):
64 '''set up template engine.
63 '''set up template engine.
65 mapfile is name of file to read map definitions from.
64 mapfile is name of file to read map definitions from.
66 filters is dict of functions. each transforms a value into another.
65 filters is dict of functions. each transforms a value into another.
67 defaults is dict of default map definitions.'''
66 defaults is dict of default map definitions.'''
68 self.mapfile = mapfile or 'template'
67 self.mapfile = mapfile or 'template'
69 self.cache = cache.copy()
68 self.cache = cache.copy()
70 self.map = {}
69 self.map = {}
71 self.base = (mapfile and os.path.dirname(mapfile)) or ''
70 self.base = (mapfile and os.path.dirname(mapfile)) or ''
72 self.filters = filters
71 self.filters = filters
73 self.defaults = defaults
72 self.defaults = defaults
74
73
75 if not mapfile:
74 if not mapfile:
76 return
75 return
77 i = 0
76 i = 0
78 for l in file(mapfile):
77 for l in file(mapfile):
79 l = l.strip()
78 l = l.strip()
80 i += 1
79 i += 1
81 if not l or l[0] in '#;': continue
80 if not l or l[0] in '#;': continue
82 m = re.match(r'([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+)$', l)
81 m = re.match(r'([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+)$', l)
83 if m:
82 if m:
84 key, val = m.groups()
83 key, val = m.groups()
85 if val[0] in "'\"":
84 if val[0] in "'\"":
86 try:
85 try:
87 self.cache[key] = parsestring(val)
86 self.cache[key] = parsestring(val)
88 except SyntaxError, inst:
87 except SyntaxError, inst:
89 raise SyntaxError('%s:%s: %s' %
88 raise SyntaxError('%s:%s: %s' %
90 (mapfile, i, inst.args[0]))
89 (mapfile, i, inst.args[0]))
91 else:
90 else:
92 self.map[key] = os.path.join(self.base, val)
91 self.map[key] = os.path.join(self.base, val)
93 else:
92 else:
94 raise SyntaxError(_("%s:%s: parse error") % (mapfile, i))
93 raise SyntaxError(_("%s:%s: parse error") % (mapfile, i))
95
94
96 def __contains__(self, key):
95 def __contains__(self, key):
97 return key in self.cache
96 return key in self.cache
98
97
99 def __call__(self, t, **map):
98 def __call__(self, t, **map):
100 '''perform expansion.
99 '''perform expansion.
101 t is name of map element to expand.
100 t is name of map element to expand.
102 map is added elements to use during expansion.'''
101 map is added elements to use during expansion.'''
103 m = self.defaults.copy()
102 m = self.defaults.copy()
104 m.update(map)
103 m.update(map)
105 try:
104 try:
106 tmpl = self.cache[t]
105 tmpl = self.cache[t]
107 except KeyError:
106 except KeyError:
108 try:
107 try:
109 tmpl = self.cache[t] = file(self.map[t]).read()
108 tmpl = self.cache[t] = file(self.map[t]).read()
110 except IOError, inst:
109 except IOError, inst:
111 raise IOError(inst.args[0], _('template file %s: %s') %
110 raise IOError(inst.args[0], _('template file %s: %s') %
112 (self.map[t], inst.args[1]))
111 (self.map[t], inst.args[1]))
113 return self.template(tmpl, self.filters, **m)
112 return self.template(tmpl, self.filters, **m)
114
113
115 template_re = re.compile(r"[#{]([a-zA-Z_][a-zA-Z0-9_]*)"
114 template_re = re.compile(r"[#{]([a-zA-Z_][a-zA-Z0-9_]*)"
116 r"((%[a-zA-Z_][a-zA-Z0-9_]*)*)"
115 r"((%[a-zA-Z_][a-zA-Z0-9_]*)*)"
117 r"((\|[a-zA-Z_][a-zA-Z0-9_]*)*)[#}]")
116 r"((\|[a-zA-Z_][a-zA-Z0-9_]*)*)[#}]")
118
117
119 def template(self, tmpl, filters={}, **map):
118 def template(self, tmpl, filters={}, **map):
120 lm = map.copy()
119 lm = map.copy()
121 while tmpl:
120 while tmpl:
122 m = self.template_re.search(tmpl)
121 m = self.template_re.search(tmpl)
123 if m:
122 if m:
124 start, end = m.span(0)
123 start, end = m.span(0)
125 s, e = tmpl[start], tmpl[end - 1]
124 s, e = tmpl[start], tmpl[end - 1]
126 key = m.group(1)
125 key = m.group(1)
127 if ((s == '#' and e != '#') or (s == '{' and e != '}')):
126 if ((s == '#' and e != '#') or (s == '{' and e != '}')):
128 raise SyntaxError(_("'%s'/'%s' mismatch expanding '%s'") %
127 raise SyntaxError(_("'%s'/'%s' mismatch expanding '%s'") %
129 (s, e, key))
128 (s, e, key))
130 if start:
129 if start:
131 yield tmpl[:start]
130 yield tmpl[:start]
132 v = map.get(key, "")
131 v = map.get(key, "")
133 v = callable(v) and v(**map) or v
132 v = callable(v) and v(**map) or v
134
133
135 format = m.group(2)
134 format = m.group(2)
136 fl = m.group(4)
135 fl = m.group(4)
137
136
138 if format:
137 if format:
139 q = v.__iter__
138 q = v.__iter__
140 for i in q():
139 for i in q():
141 lm.update(i)
140 lm.update(i)
142 yield self(format[1:], **lm)
141 yield self(format[1:], **lm)
143
142
144 v = ""
143 v = ""
145
144
146 elif fl:
145 elif fl:
147 for f in fl.split("|")[1:]:
146 for f in fl.split("|")[1:]:
148 v = filters[f](v)
147 v = filters[f](v)
149
148
150 yield v
149 yield v
151 tmpl = tmpl[end:]
150 tmpl = tmpl[end:]
152 else:
151 else:
153 yield tmpl
152 yield tmpl
154 break
153 break
155
154
156 agescales = [("second", 1),
155 agescales = [("second", 1),
157 ("minute", 60),
156 ("minute", 60),
158 ("hour", 3600),
157 ("hour", 3600),
159 ("day", 3600 * 24),
158 ("day", 3600 * 24),
160 ("week", 3600 * 24 * 7),
159 ("week", 3600 * 24 * 7),
161 ("month", 3600 * 24 * 30),
160 ("month", 3600 * 24 * 30),
162 ("year", 3600 * 24 * 365)]
161 ("year", 3600 * 24 * 365)]
163
162
164 agescales.reverse()
163 agescales.reverse()
165
164
166 def age(date):
165 def age(date):
167 '''turn a (timestamp, tzoff) tuple into an age string.'''
166 '''turn a (timestamp, tzoff) tuple into an age string.'''
168
167
169 def plural(t, c):
168 def plural(t, c):
170 if c == 1:
169 if c == 1:
171 return t
170 return t
172 return t + "s"
171 return t + "s"
173 def fmt(t, c):
172 def fmt(t, c):
174 return "%d %s" % (c, plural(t, c))
173 return "%d %s" % (c, plural(t, c))
175
174
176 now = time.time()
175 now = time.time()
177 then = date[0]
176 then = date[0]
178 delta = max(1, int(now - then))
177 delta = max(1, int(now - then))
179
178
180 for t, s in agescales:
179 for t, s in agescales:
181 n = delta / s
180 n = delta / s
182 if n >= 2 or s == 1:
181 if n >= 2 or s == 1:
183 return fmt(t, n)
182 return fmt(t, n)
184
183
185 def stringify(thing):
184 def stringify(thing):
186 '''turn nested template iterator into string.'''
185 '''turn nested template iterator into string.'''
187 cs = cStringIO.StringIO()
186 cs = cStringIO.StringIO()
188 def walk(things):
187 def walk(things):
189 for t in things:
188 for t in things:
190 if hasattr(t, '__iter__'):
189 if hasattr(t, '__iter__'):
191 walk(t)
190 walk(t)
192 else:
191 else:
193 cs.write(t)
192 cs.write(t)
194 walk(thing)
193 walk(thing)
195 return cs.getvalue()
194 return cs.getvalue()
196
195
197 para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M)
196 para_re = None
198 space_re = re.compile(r' +')
197 space_re = None
199
198
200 def fill(text, width):
199 def fill(text, width):
201 '''fill many paragraphs.'''
200 '''fill many paragraphs.'''
201 global para_re, space_re
202 if para_re is None:
203 para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M)
204 space_re = re.compile(r' +')
205
202 def findparas():
206 def findparas():
203 start = 0
207 start = 0
204 while True:
208 while True:
205 m = para_re.search(text, start)
209 m = para_re.search(text, start)
206 if not m:
210 if not m:
207 w = len(text)
211 w = len(text)
208 while w > start and text[w-1].isspace(): w -= 1
212 while w > start and text[w-1].isspace(): w -= 1
209 yield text[start:w], text[w:]
213 yield text[start:w], text[w:]
210 break
214 break
211 yield text[start:m.start(0)], m.group(1)
215 yield text[start:m.start(0)], m.group(1)
212 start = m.end(1)
216 start = m.end(1)
213
217
214 fp = cStringIO.StringIO()
218 fp = cStringIO.StringIO()
215 for para, rest in findparas():
219 for para, rest in findparas():
216 fp.write(space_re.sub(' ', textwrap.fill(para, width)))
220 fp.write(space_re.sub(' ', textwrap.fill(para, width)))
217 fp.write(rest)
221 fp.write(rest)
218 return fp.getvalue()
222 return fp.getvalue()
219
223
220 def isodate(date):
224 def isodate(date):
221 '''turn a (timestamp, tzoff) tuple into an iso 8631 date and time.'''
225 '''turn a (timestamp, tzoff) tuple into an iso 8631 date and time.'''
222 return util.datestr(date, format='%Y-%m-%d %H:%M')
226 return util.datestr(date, format='%Y-%m-%d %H:%M')
223
227
224 def nl2br(text):
228 def nl2br(text):
225 '''replace raw newlines with xhtml line breaks.'''
229 '''replace raw newlines with xhtml line breaks.'''
226 return text.replace('\n', '<br/>\n')
230 return text.replace('\n', '<br/>\n')
227
231
228 def obfuscate(text):
232 def obfuscate(text):
229 return ''.join(['&#%d;' % ord(c) for c in text])
233 return ''.join(['&#%d;' % ord(c) for c in text])
230
234
231 def domain(author):
235 def domain(author):
232 '''get domain of author, or empty string if none.'''
236 '''get domain of author, or empty string if none.'''
233 f = author.find('@')
237 f = author.find('@')
234 if f == -1: return ''
238 if f == -1: return ''
235 author = author[f+1:]
239 author = author[f+1:]
236 f = author.find('>')
240 f = author.find('>')
237 if f >= 0: author = author[:f]
241 if f >= 0: author = author[:f]
238 return author
242 return author
239
243
240 def email(author):
244 def email(author):
241 '''get email of author.'''
245 '''get email of author.'''
242 r = author.find('>')
246 r = author.find('>')
243 if r == -1: r = None
247 if r == -1: r = None
244 return author[author.find('<')+1:r]
248 return author[author.find('<')+1:r]
245
249
246 def person(author):
250 def person(author):
247 '''get name of author, or else username.'''
251 '''get name of author, or else username.'''
248 f = author.find('<')
252 f = author.find('<')
249 if f == -1: return util.shortuser(author)
253 if f == -1: return util.shortuser(author)
250 return author[:f].rstrip()
254 return author[:f].rstrip()
251
255
252 def shortdate(date):
256 def shortdate(date):
253 '''turn (timestamp, tzoff) tuple into iso 8631 date.'''
257 '''turn (timestamp, tzoff) tuple into iso 8631 date.'''
254 return util.datestr(date, format='%Y-%m-%d', timezone=False)
258 return util.datestr(date, format='%Y-%m-%d', timezone=False)
255
259
256 def indent(text, prefix):
260 def indent(text, prefix):
257 '''indent each non-empty line of text after first with prefix.'''
261 '''indent each non-empty line of text after first with prefix.'''
258 fp = cStringIO.StringIO()
262 fp = cStringIO.StringIO()
259 lines = text.splitlines()
263 lines = text.splitlines()
260 num_lines = len(lines)
264 num_lines = len(lines)
261 for i in xrange(num_lines):
265 for i in xrange(num_lines):
262 l = lines[i]
266 l = lines[i]
263 if i and l.strip(): fp.write(prefix)
267 if i and l.strip(): fp.write(prefix)
264 fp.write(l)
268 fp.write(l)
265 if i < num_lines - 1 or text.endswith('\n'):
269 if i < num_lines - 1 or text.endswith('\n'):
266 fp.write('\n')
270 fp.write('\n')
267 return fp.getvalue()
271 return fp.getvalue()
268
272
269 common_filters = {
273 common_filters = {
270 "addbreaks": nl2br,
274 "addbreaks": nl2br,
271 "basename": os.path.basename,
275 "basename": os.path.basename,
272 "age": age,
276 "age": age,
273 "date": lambda x: util.datestr(x),
277 "date": lambda x: util.datestr(x),
274 "domain": domain,
278 "domain": domain,
275 "email": email,
279 "email": email,
276 "escape": lambda x: cgi.escape(x, True),
280 "escape": lambda x: cgi.escape(x, True),
277 "fill68": lambda x: fill(x, width=68),
281 "fill68": lambda x: fill(x, width=68),
278 "fill76": lambda x: fill(x, width=76),
282 "fill76": lambda x: fill(x, width=76),
279 "firstline": lambda x: x.splitlines(1)[0].rstrip('\r\n'),
283 "firstline": lambda x: x.splitlines(1)[0].rstrip('\r\n'),
280 "tabindent": lambda x: indent(x, '\t'),
284 "tabindent": lambda x: indent(x, '\t'),
281 "isodate": isodate,
285 "isodate": isodate,
282 "obfuscate": obfuscate,
286 "obfuscate": obfuscate,
283 "permissions": lambda x: x and "-rwxr-xr-x" or "-rw-r--r--",
287 "permissions": lambda x: x and "-rwxr-xr-x" or "-rw-r--r--",
284 "person": person,
288 "person": person,
285 "rfc822date": lambda x: util.datestr(x, "%a, %d %b %Y %H:%M:%S"),
289 "rfc822date": lambda x: util.datestr(x, "%a, %d %b %Y %H:%M:%S"),
286 "short": lambda x: x[:12],
290 "short": lambda x: x[:12],
287 "shortdate": shortdate,
291 "shortdate": shortdate,
288 "stringify": stringify,
292 "stringify": stringify,
289 "strip": lambda x: x.strip(),
293 "strip": lambda x: x.strip(),
290 "urlescape": lambda x: urllib.quote(x),
294 "urlescape": lambda x: urllib.quote(x),
291 "user": lambda x: util.shortuser(x),
295 "user": lambda x: util.shortuser(x),
292 }
296 }
293
297
294 def templatepath(name=None):
298 def templatepath(name=None):
295 '''return location of template file or directory (if no name).
299 '''return location of template file or directory (if no name).
296 returns None if not found.'''
300 returns None if not found.'''
297
301
298 # executable version (py2exe) doesn't support __file__
302 # executable version (py2exe) doesn't support __file__
299 if hasattr(sys, 'frozen'):
303 if hasattr(sys, 'frozen'):
300 module = sys.executable
304 module = sys.executable
301 else:
305 else:
302 module = __file__
306 module = __file__
303 for f in 'templates', '../templates':
307 for f in 'templates', '../templates':
304 fl = f.split('/')
308 fl = f.split('/')
305 if name: fl.append(name)
309 if name: fl.append(name)
306 p = os.path.join(os.path.dirname(module), *fl)
310 p = os.path.join(os.path.dirname(module), *fl)
307 if (name and os.path.exists(p)) or os.path.isdir(p):
311 if (name and os.path.exists(p)) or os.path.isdir(p):
308 return os.path.normpath(p)
312 return os.path.normpath(p)
309
313
310 class changeset_templater(object):
314 class changeset_templater(object):
311 '''format changeset information.'''
315 '''format changeset information.'''
312
316
313 def __init__(self, ui, repo, mapfile, dest=None):
317 def __init__(self, ui, repo, mapfile, dest=None):
314 self.t = templater(mapfile, common_filters,
318 self.t = templater(mapfile, common_filters,
315 cache={'parent': '{rev}:{node|short} ',
319 cache={'parent': '{rev}:{node|short} ',
316 'manifest': '{rev}:{node|short}'})
320 'manifest': '{rev}:{node|short}'})
317 self.ui = ui
321 self.ui = ui
318 self.dest = dest
322 self.dest = dest
319 self.repo = repo
323 self.repo = repo
320
324
321 def use_template(self, t):
325 def use_template(self, t):
322 '''set template string to use'''
326 '''set template string to use'''
323 self.t.cache['changeset'] = t
327 self.t.cache['changeset'] = t
324
328
325 def write(self, thing, header=False):
329 def write(self, thing, header=False):
326 '''write expanded template.
330 '''write expanded template.
327 uses in-order recursive traverse of iterators.'''
331 uses in-order recursive traverse of iterators.'''
328 dest = self.dest or self.ui
332 dest = self.dest or self.ui
329 for t in thing:
333 for t in thing:
330 if hasattr(t, '__iter__'):
334 if hasattr(t, '__iter__'):
331 self.write(t, header=header)
335 self.write(t, header=header)
332 elif header:
336 elif header:
333 dest.write_header(t)
337 dest.write_header(t)
334 else:
338 else:
335 dest.write(t)
339 dest.write(t)
336
340
337 def write_header(self, thing):
341 def write_header(self, thing):
338 self.write(thing, header=True)
342 self.write(thing, header=True)
339
343
340 def show(self, rev=0, changenode=None, brinfo=None, changes=None,
344 def show(self, rev=0, changenode=None, brinfo=None, changes=None,
341 **props):
345 **props):
342 '''show a single changeset or file revision'''
346 '''show a single changeset or file revision'''
343 log = self.repo.changelog
347 log = self.repo.changelog
344 if changenode is None:
348 if changenode is None:
345 changenode = log.node(rev)
349 changenode = log.node(rev)
346 elif not rev:
350 elif not rev:
347 rev = log.rev(changenode)
351 rev = log.rev(changenode)
348 if changes is None:
352 if changes is None:
349 changes = log.read(changenode)
353 changes = log.read(changenode)
350
354
351 def showlist(name, values, plural=None, **args):
355 def showlist(name, values, plural=None, **args):
352 '''expand set of values.
356 '''expand set of values.
353 name is name of key in template map.
357 name is name of key in template map.
354 values is list of strings or dicts.
358 values is list of strings or dicts.
355 plural is plural of name, if not simply name + 's'.
359 plural is plural of name, if not simply name + 's'.
356
360
357 expansion works like this, given name 'foo'.
361 expansion works like this, given name 'foo'.
358
362
359 if values is empty, expand 'no_foos'.
363 if values is empty, expand 'no_foos'.
360
364
361 if 'foo' not in template map, return values as a string,
365 if 'foo' not in template map, return values as a string,
362 joined by space.
366 joined by space.
363
367
364 expand 'start_foos'.
368 expand 'start_foos'.
365
369
366 for each value, expand 'foo'. if 'last_foo' in template
370 for each value, expand 'foo'. if 'last_foo' in template
367 map, expand it instead of 'foo' for last key.
371 map, expand it instead of 'foo' for last key.
368
372
369 expand 'end_foos'.
373 expand 'end_foos'.
370 '''
374 '''
371 if plural: names = plural
375 if plural: names = plural
372 else: names = name + 's'
376 else: names = name + 's'
373 if not values:
377 if not values:
374 noname = 'no_' + names
378 noname = 'no_' + names
375 if noname in self.t:
379 if noname in self.t:
376 yield self.t(noname, **args)
380 yield self.t(noname, **args)
377 return
381 return
378 if name not in self.t:
382 if name not in self.t:
379 if isinstance(values[0], str):
383 if isinstance(values[0], str):
380 yield ' '.join(values)
384 yield ' '.join(values)
381 else:
385 else:
382 for v in values:
386 for v in values:
383 yield dict(v, **args)
387 yield dict(v, **args)
384 return
388 return
385 startname = 'start_' + names
389 startname = 'start_' + names
386 if startname in self.t:
390 if startname in self.t:
387 yield self.t(startname, **args)
391 yield self.t(startname, **args)
388 vargs = args.copy()
392 vargs = args.copy()
389 def one(v, tag=name):
393 def one(v, tag=name):
390 try:
394 try:
391 vargs.update(v)
395 vargs.update(v)
392 except (AttributeError, ValueError):
396 except (AttributeError, ValueError):
393 try:
397 try:
394 for a, b in v:
398 for a, b in v:
395 vargs[a] = b
399 vargs[a] = b
396 except ValueError:
400 except ValueError:
397 vargs[name] = v
401 vargs[name] = v
398 return self.t(tag, **vargs)
402 return self.t(tag, **vargs)
399 lastname = 'last_' + name
403 lastname = 'last_' + name
400 if lastname in self.t:
404 if lastname in self.t:
401 last = values.pop()
405 last = values.pop()
402 else:
406 else:
403 last = None
407 last = None
404 for v in values:
408 for v in values:
405 yield one(v)
409 yield one(v)
406 if last is not None:
410 if last is not None:
407 yield one(last, tag=lastname)
411 yield one(last, tag=lastname)
408 endname = 'end_' + names
412 endname = 'end_' + names
409 if endname in self.t:
413 if endname in self.t:
410 yield self.t(endname, **args)
414 yield self.t(endname, **args)
411
415
412 if brinfo:
416 if brinfo:
413 def showbranches(**args):
417 def showbranches(**args):
414 if changenode in brinfo:
418 if changenode in brinfo:
415 for x in showlist('branch', brinfo[changenode],
419 for x in showlist('branch', brinfo[changenode],
416 plural='branches', **args):
420 plural='branches', **args):
417 yield x
421 yield x
418 else:
422 else:
419 showbranches = ''
423 showbranches = ''
420
424
421 if self.ui.debugflag:
425 if self.ui.debugflag:
422 def showmanifest(**args):
426 def showmanifest(**args):
423 args = args.copy()
427 args = args.copy()
424 args.update(dict(rev=self.repo.manifest.rev(changes[0]),
428 args.update(dict(rev=self.repo.manifest.rev(changes[0]),
425 node=hex(changes[0])))
429 node=hex(changes[0])))
426 yield self.t('manifest', **args)
430 yield self.t('manifest', **args)
427 else:
431 else:
428 showmanifest = ''
432 showmanifest = ''
429
433
430 def showparents(**args):
434 def showparents(**args):
431 parents = [[('rev', log.rev(p)), ('node', hex(p))]
435 parents = [[('rev', log.rev(p)), ('node', hex(p))]
432 for p in log.parents(changenode)
436 for p in log.parents(changenode)
433 if self.ui.debugflag or p != nullid]
437 if self.ui.debugflag or p != nullid]
434 if (not self.ui.debugflag and len(parents) == 1 and
438 if (not self.ui.debugflag and len(parents) == 1 and
435 parents[0][0][1] == rev - 1):
439 parents[0][0][1] == rev - 1):
436 return
440 return
437 for x in showlist('parent', parents, **args):
441 for x in showlist('parent', parents, **args):
438 yield x
442 yield x
439
443
440 def showtags(**args):
444 def showtags(**args):
441 for x in showlist('tag', self.repo.nodetags(changenode), **args):
445 for x in showlist('tag', self.repo.nodetags(changenode), **args):
442 yield x
446 yield x
443
447
444 if self.ui.debugflag:
448 if self.ui.debugflag:
445 files = self.repo.changes(log.parents(changenode)[0], changenode)
449 files = self.repo.changes(log.parents(changenode)[0], changenode)
446 def showfiles(**args):
450 def showfiles(**args):
447 for x in showlist('file', files[0], **args): yield x
451 for x in showlist('file', files[0], **args): yield x
448 def showadds(**args):
452 def showadds(**args):
449 for x in showlist('file_add', files[1], **args): yield x
453 for x in showlist('file_add', files[1], **args): yield x
450 def showdels(**args):
454 def showdels(**args):
451 for x in showlist('file_del', files[2], **args): yield x
455 for x in showlist('file_del', files[2], **args): yield x
452 else:
456 else:
453 def showfiles(**args):
457 def showfiles(**args):
454 for x in showlist('file', changes[3], **args): yield x
458 for x in showlist('file', changes[3], **args): yield x
455 showadds = ''
459 showadds = ''
456 showdels = ''
460 showdels = ''
457
461
458 defprops = {
462 defprops = {
459 'author': changes[1],
463 'author': changes[1],
460 'branches': showbranches,
464 'branches': showbranches,
461 'date': changes[2],
465 'date': changes[2],
462 'desc': changes[4],
466 'desc': changes[4],
463 'file_adds': showadds,
467 'file_adds': showadds,
464 'file_dels': showdels,
468 'file_dels': showdels,
465 'files': showfiles,
469 'files': showfiles,
466 'manifest': showmanifest,
470 'manifest': showmanifest,
467 'node': hex(changenode),
471 'node': hex(changenode),
468 'parents': showparents,
472 'parents': showparents,
469 'rev': rev,
473 'rev': rev,
470 'tags': showtags,
474 'tags': showtags,
471 }
475 }
472 props = props.copy()
476 props = props.copy()
473 props.update(defprops)
477 props.update(defprops)
474
478
475 try:
479 try:
476 if self.ui.debugflag and 'header_debug' in self.t:
480 if self.ui.debugflag and 'header_debug' in self.t:
477 key = 'header_debug'
481 key = 'header_debug'
478 elif self.ui.quiet and 'header_quiet' in self.t:
482 elif self.ui.quiet and 'header_quiet' in self.t:
479 key = 'header_quiet'
483 key = 'header_quiet'
480 elif self.ui.verbose and 'header_verbose' in self.t:
484 elif self.ui.verbose and 'header_verbose' in self.t:
481 key = 'header_verbose'
485 key = 'header_verbose'
482 elif 'header' in self.t:
486 elif 'header' in self.t:
483 key = 'header'
487 key = 'header'
484 else:
488 else:
485 key = ''
489 key = ''
486 if key:
490 if key:
487 self.write_header(self.t(key, **props))
491 self.write_header(self.t(key, **props))
488 if self.ui.debugflag and 'changeset_debug' in self.t:
492 if self.ui.debugflag and 'changeset_debug' in self.t:
489 key = 'changeset_debug'
493 key = 'changeset_debug'
490 elif self.ui.quiet and 'changeset_quiet' in self.t:
494 elif self.ui.quiet and 'changeset_quiet' in self.t:
491 key = 'changeset_quiet'
495 key = 'changeset_quiet'
492 elif self.ui.verbose and 'changeset_verbose' in self.t:
496 elif self.ui.verbose and 'changeset_verbose' in self.t:
493 key = 'changeset_verbose'
497 key = 'changeset_verbose'
494 else:
498 else:
495 key = 'changeset'
499 key = 'changeset'
496 self.write(self.t(key, **props))
500 self.write(self.t(key, **props))
497 except KeyError, inst:
501 except KeyError, inst:
498 raise util.Abort(_("%s: no key named '%s'") % (self.t.mapfile,
502 raise util.Abort(_("%s: no key named '%s'") % (self.t.mapfile,
499 inst.args[0]))
503 inst.args[0]))
500 except SyntaxError, inst:
504 except SyntaxError, inst:
501 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
505 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
502
506
503 class stringio(object):
507 class stringio(object):
504 '''wrap cStringIO for use by changeset_templater.'''
508 '''wrap cStringIO for use by changeset_templater.'''
505 def __init__(self):
509 def __init__(self):
506 self.fp = cStringIO.StringIO()
510 self.fp = cStringIO.StringIO()
507
511
508 def write(self, *args):
512 def write(self, *args):
509 for a in args:
513 for a in args:
510 self.fp.write(a)
514 self.fp.write(a)
511
515
512 write_header = write
516 write_header = write
513
517
514 def __getattr__(self, key):
518 def __getattr__(self, key):
515 return getattr(self.fp, key)
519 return getattr(self.fp, key)
@@ -1,106 +1,107 b''
1 # transaction.py - simple journalling scheme for mercurial
1 # transaction.py - simple journalling scheme for mercurial
2 #
2 #
3 # This transaction scheme is intended to gracefully handle program
3 # This transaction scheme is intended to gracefully handle program
4 # errors and interruptions. More serious failures like system crashes
4 # errors and interruptions. More serious failures like system crashes
5 # can be recovered with an fsck-like tool. As the whole repository is
5 # can be recovered with an fsck-like tool. As the whole repository is
6 # effectively log-structured, this should amount to simply truncating
6 # effectively log-structured, this should amount to simply truncating
7 # anything that isn't referenced in the changelog.
7 # anything that isn't referenced in the changelog.
8 #
8 #
9 # Copyright 2005 Matt Mackall <mpm@selenic.com>
9 # Copyright 2005 Matt Mackall <mpm@selenic.com>
10 #
10 #
11 # This software may be used and distributed according to the terms
11 # This software may be used and distributed according to the terms
12 # of the GNU General Public License, incorporated herein by reference.
12 # of the GNU General Public License, incorporated herein by reference.
13
13
14 import os
14 from demandload import demandload
15 from i18n import gettext as _
15 from i18n import gettext as _
16 demandload(globals(), 'os')
16
17
17 class transaction(object):
18 class transaction(object):
18 def __init__(self, report, opener, journal, after=None):
19 def __init__(self, report, opener, journal, after=None):
19 self.journal = None
20 self.journal = None
20
21
21 # abort here if the journal already exists
22 # abort here if the journal already exists
22 if os.path.exists(journal):
23 if os.path.exists(journal):
23 raise AssertionError(_("journal already exists - run hg recover"))
24 raise AssertionError(_("journal already exists - run hg recover"))
24
25
25 self.count = 1
26 self.count = 1
26 self.report = report
27 self.report = report
27 self.opener = opener
28 self.opener = opener
28 self.after = after
29 self.after = after
29 self.entries = []
30 self.entries = []
30 self.map = {}
31 self.map = {}
31 self.journal = journal
32 self.journal = journal
32
33
33 self.file = open(self.journal, "w")
34 self.file = open(self.journal, "w")
34
35
35 def __del__(self):
36 def __del__(self):
36 if self.journal:
37 if self.journal:
37 if self.entries: self.abort()
38 if self.entries: self.abort()
38 self.file.close()
39 self.file.close()
39 try: os.unlink(self.journal)
40 try: os.unlink(self.journal)
40 except: pass
41 except: pass
41
42
42 def add(self, file, offset, data=None):
43 def add(self, file, offset, data=None):
43 if file in self.map: return
44 if file in self.map: return
44 self.entries.append((file, offset, data))
45 self.entries.append((file, offset, data))
45 self.map[file] = len(self.entries) - 1
46 self.map[file] = len(self.entries) - 1
46 # add enough data to the journal to do the truncate
47 # add enough data to the journal to do the truncate
47 self.file.write("%s\0%d\n" % (file, offset))
48 self.file.write("%s\0%d\n" % (file, offset))
48 self.file.flush()
49 self.file.flush()
49
50
50 def find(self, file):
51 def find(self, file):
51 if file in self.map:
52 if file in self.map:
52 return self.entries[self.map[file]]
53 return self.entries[self.map[file]]
53 return None
54 return None
54
55
55 def replace(self, file, offset, data=None):
56 def replace(self, file, offset, data=None):
56 if file not in self.map:
57 if file not in self.map:
57 raise KeyError(file)
58 raise KeyError(file)
58 index = self.map[file]
59 index = self.map[file]
59 self.entries[index] = (file, offset, data)
60 self.entries[index] = (file, offset, data)
60 self.file.write("%s\0%d\n" % (file, offset))
61 self.file.write("%s\0%d\n" % (file, offset))
61 self.file.flush()
62 self.file.flush()
62
63
63 def nest(self):
64 def nest(self):
64 self.count += 1
65 self.count += 1
65 return self
66 return self
66
67
67 def running(self):
68 def running(self):
68 return self.count > 0
69 return self.count > 0
69
70
70 def close(self):
71 def close(self):
71 self.count -= 1
72 self.count -= 1
72 if self.count != 0:
73 if self.count != 0:
73 return
74 return
74 self.file.close()
75 self.file.close()
75 self.entries = []
76 self.entries = []
76 if self.after:
77 if self.after:
77 self.after()
78 self.after()
78 else:
79 else:
79 os.unlink(self.journal)
80 os.unlink(self.journal)
80 self.journal = None
81 self.journal = None
81
82
82 def abort(self):
83 def abort(self):
83 if not self.entries: return
84 if not self.entries: return
84
85
85 self.report(_("transaction abort!\n"))
86 self.report(_("transaction abort!\n"))
86
87
87 for f, o, ignore in self.entries:
88 for f, o, ignore in self.entries:
88 try:
89 try:
89 self.opener(f, "a").truncate(o)
90 self.opener(f, "a").truncate(o)
90 except:
91 except:
91 self.report(_("failed to truncate %s\n") % f)
92 self.report(_("failed to truncate %s\n") % f)
92
93
93 self.entries = []
94 self.entries = []
94
95
95 self.report(_("rollback completed\n"))
96 self.report(_("rollback completed\n"))
96
97
97 def rollback(opener, file):
98 def rollback(opener, file):
98 files = {}
99 files = {}
99 for l in open(file).readlines():
100 for l in open(file).readlines():
100 f, o = l.split('\0')
101 f, o = l.split('\0')
101 files[f] = o
102 files[f] = o
102 for f in files:
103 for f in files:
103 o = files[f]
104 o = files[f]
104 opener(f, "a").truncate(int(o))
105 opener(f, "a").truncate(int(o))
105 os.unlink(file)
106 os.unlink(file)
106
107
@@ -1,344 +1,343 b''
1 # ui.py - user interface bits for mercurial
1 # ui.py - user interface bits for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import ConfigParser
9 from i18n import gettext as _
8 from i18n import gettext as _
10 from demandload import *
9 from demandload import *
11 demandload(globals(), "errno getpass os re smtplib socket sys tempfile")
10 demandload(globals(), "errno getpass os re smtplib socket sys tempfile")
12 demandload(globals(), "templater traceback util")
11 demandload(globals(), "ConfigParser templater traceback util")
13
12
14 class ui(object):
13 class ui(object):
15 def __init__(self, verbose=False, debug=False, quiet=False,
14 def __init__(self, verbose=False, debug=False, quiet=False,
16 interactive=True, traceback=False, parentui=None):
15 interactive=True, traceback=False, parentui=None):
17 self.overlay = {}
16 self.overlay = {}
18 if parentui is None:
17 if parentui is None:
19 # this is the parent of all ui children
18 # this is the parent of all ui children
20 self.parentui = None
19 self.parentui = None
21 self.cdata = ConfigParser.SafeConfigParser()
20 self.cdata = ConfigParser.SafeConfigParser()
22 self.readconfig(util.rcpath())
21 self.readconfig(util.rcpath())
23
22
24 self.quiet = self.configbool("ui", "quiet")
23 self.quiet = self.configbool("ui", "quiet")
25 self.verbose = self.configbool("ui", "verbose")
24 self.verbose = self.configbool("ui", "verbose")
26 self.debugflag = self.configbool("ui", "debug")
25 self.debugflag = self.configbool("ui", "debug")
27 self.interactive = self.configbool("ui", "interactive", True)
26 self.interactive = self.configbool("ui", "interactive", True)
28 self.traceback = traceback
27 self.traceback = traceback
29
28
30 self.updateopts(verbose, debug, quiet, interactive)
29 self.updateopts(verbose, debug, quiet, interactive)
31 self.diffcache = None
30 self.diffcache = None
32 self.header = []
31 self.header = []
33 self.prev_header = []
32 self.prev_header = []
34 self.revlogopts = self.configrevlog()
33 self.revlogopts = self.configrevlog()
35 else:
34 else:
36 # parentui may point to an ui object which is already a child
35 # parentui may point to an ui object which is already a child
37 self.parentui = parentui.parentui or parentui
36 self.parentui = parentui.parentui or parentui
38 parent_cdata = self.parentui.cdata
37 parent_cdata = self.parentui.cdata
39 self.cdata = ConfigParser.SafeConfigParser(parent_cdata.defaults())
38 self.cdata = ConfigParser.SafeConfigParser(parent_cdata.defaults())
40 # make interpolation work
39 # make interpolation work
41 for section in parent_cdata.sections():
40 for section in parent_cdata.sections():
42 self.cdata.add_section(section)
41 self.cdata.add_section(section)
43 for name, value in parent_cdata.items(section, raw=True):
42 for name, value in parent_cdata.items(section, raw=True):
44 self.cdata.set(section, name, value)
43 self.cdata.set(section, name, value)
45
44
46 def __getattr__(self, key):
45 def __getattr__(self, key):
47 return getattr(self.parentui, key)
46 return getattr(self.parentui, key)
48
47
49 def updateopts(self, verbose=False, debug=False, quiet=False,
48 def updateopts(self, verbose=False, debug=False, quiet=False,
50 interactive=True, traceback=False, config=[]):
49 interactive=True, traceback=False, config=[]):
51 self.quiet = (self.quiet or quiet) and not verbose and not debug
50 self.quiet = (self.quiet or quiet) and not verbose and not debug
52 self.verbose = (self.verbose or verbose) or debug
51 self.verbose = (self.verbose or verbose) or debug
53 self.debugflag = (self.debugflag or debug)
52 self.debugflag = (self.debugflag or debug)
54 self.interactive = (self.interactive and interactive)
53 self.interactive = (self.interactive and interactive)
55 self.traceback = self.traceback or traceback
54 self.traceback = self.traceback or traceback
56 for cfg in config:
55 for cfg in config:
57 try:
56 try:
58 name, value = cfg.split('=', 1)
57 name, value = cfg.split('=', 1)
59 section, name = name.split('.', 1)
58 section, name = name.split('.', 1)
60 if not self.cdata.has_section(section):
59 if not self.cdata.has_section(section):
61 self.cdata.add_section(section)
60 self.cdata.add_section(section)
62 if not section or not name:
61 if not section or not name:
63 raise IndexError
62 raise IndexError
64 self.cdata.set(section, name, value)
63 self.cdata.set(section, name, value)
65 except (IndexError, ValueError):
64 except (IndexError, ValueError):
66 raise util.Abort(_('malformed --config option: %s') % cfg)
65 raise util.Abort(_('malformed --config option: %s') % cfg)
67
66
68 def readconfig(self, fn, root=None):
67 def readconfig(self, fn, root=None):
69 if isinstance(fn, basestring):
68 if isinstance(fn, basestring):
70 fn = [fn]
69 fn = [fn]
71 for f in fn:
70 for f in fn:
72 try:
71 try:
73 self.cdata.read(f)
72 self.cdata.read(f)
74 except ConfigParser.ParsingError, inst:
73 except ConfigParser.ParsingError, inst:
75 raise util.Abort(_("Failed to parse %s\n%s") % (f, inst))
74 raise util.Abort(_("Failed to parse %s\n%s") % (f, inst))
76 # translate paths relative to root (or home) into absolute paths
75 # translate paths relative to root (or home) into absolute paths
77 if root is None:
76 if root is None:
78 root = os.path.expanduser('~')
77 root = os.path.expanduser('~')
79 for name, path in self.configitems("paths"):
78 for name, path in self.configitems("paths"):
80 if path and path.find("://") == -1 and not os.path.isabs(path):
79 if path and path.find("://") == -1 and not os.path.isabs(path):
81 self.cdata.set("paths", name, os.path.join(root, path))
80 self.cdata.set("paths", name, os.path.join(root, path))
82
81
83 def setconfig(self, section, name, val):
82 def setconfig(self, section, name, val):
84 self.overlay[(section, name)] = val
83 self.overlay[(section, name)] = val
85
84
86 def config(self, section, name, default=None):
85 def config(self, section, name, default=None):
87 if self.overlay.has_key((section, name)):
86 if self.overlay.has_key((section, name)):
88 return self.overlay[(section, name)]
87 return self.overlay[(section, name)]
89 if self.cdata.has_option(section, name):
88 if self.cdata.has_option(section, name):
90 try:
89 try:
91 return self.cdata.get(section, name)
90 return self.cdata.get(section, name)
92 except ConfigParser.InterpolationError, inst:
91 except ConfigParser.InterpolationError, inst:
93 raise util.Abort(_("Error in configuration:\n%s") % inst)
92 raise util.Abort(_("Error in configuration:\n%s") % inst)
94 if self.parentui is None:
93 if self.parentui is None:
95 return default
94 return default
96 else:
95 else:
97 return self.parentui.config(section, name, default)
96 return self.parentui.config(section, name, default)
98
97
99 def configbool(self, section, name, default=False):
98 def configbool(self, section, name, default=False):
100 if self.overlay.has_key((section, name)):
99 if self.overlay.has_key((section, name)):
101 return self.overlay[(section, name)]
100 return self.overlay[(section, name)]
102 if self.cdata.has_option(section, name):
101 if self.cdata.has_option(section, name):
103 try:
102 try:
104 return self.cdata.getboolean(section, name)
103 return self.cdata.getboolean(section, name)
105 except ConfigParser.InterpolationError, inst:
104 except ConfigParser.InterpolationError, inst:
106 raise util.Abort(_("Error in configuration:\n%s") % inst)
105 raise util.Abort(_("Error in configuration:\n%s") % inst)
107 if self.parentui is None:
106 if self.parentui is None:
108 return default
107 return default
109 else:
108 else:
110 return self.parentui.configbool(section, name, default)
109 return self.parentui.configbool(section, name, default)
111
110
112 def has_config(self, section):
111 def has_config(self, section):
113 '''tell whether section exists in config.'''
112 '''tell whether section exists in config.'''
114 return self.cdata.has_section(section)
113 return self.cdata.has_section(section)
115
114
116 def configitems(self, section):
115 def configitems(self, section):
117 items = {}
116 items = {}
118 if self.parentui is not None:
117 if self.parentui is not None:
119 items = dict(self.parentui.configitems(section))
118 items = dict(self.parentui.configitems(section))
120 if self.cdata.has_section(section):
119 if self.cdata.has_section(section):
121 try:
120 try:
122 items.update(dict(self.cdata.items(section)))
121 items.update(dict(self.cdata.items(section)))
123 except ConfigParser.InterpolationError, inst:
122 except ConfigParser.InterpolationError, inst:
124 raise util.Abort(_("Error in configuration:\n%s") % inst)
123 raise util.Abort(_("Error in configuration:\n%s") % inst)
125 x = items.items()
124 x = items.items()
126 x.sort()
125 x.sort()
127 return x
126 return x
128
127
129 def walkconfig(self, seen=None):
128 def walkconfig(self, seen=None):
130 if seen is None:
129 if seen is None:
131 seen = {}
130 seen = {}
132 for (section, name), value in self.overlay.iteritems():
131 for (section, name), value in self.overlay.iteritems():
133 yield section, name, value
132 yield section, name, value
134 seen[section, name] = 1
133 seen[section, name] = 1
135 for section in self.cdata.sections():
134 for section in self.cdata.sections():
136 for name, value in self.cdata.items(section):
135 for name, value in self.cdata.items(section):
137 if (section, name) in seen: continue
136 if (section, name) in seen: continue
138 yield section, name, value.replace('\n', '\\n')
137 yield section, name, value.replace('\n', '\\n')
139 seen[section, name] = 1
138 seen[section, name] = 1
140 if self.parentui is not None:
139 if self.parentui is not None:
141 for parent in self.parentui.walkconfig(seen):
140 for parent in self.parentui.walkconfig(seen):
142 yield parent
141 yield parent
143
142
144 def extensions(self):
143 def extensions(self):
145 result = self.configitems("extensions")
144 result = self.configitems("extensions")
146 for i, (key, value) in enumerate(result):
145 for i, (key, value) in enumerate(result):
147 if value:
146 if value:
148 result[i] = (key, os.path.expanduser(value))
147 result[i] = (key, os.path.expanduser(value))
149 return result
148 return result
150
149
151 def hgignorefiles(self):
150 def hgignorefiles(self):
152 result = []
151 result = []
153 for key, value in self.configitems("ui"):
152 for key, value in self.configitems("ui"):
154 if key == 'ignore' or key.startswith('ignore.'):
153 if key == 'ignore' or key.startswith('ignore.'):
155 result.append(os.path.expanduser(value))
154 result.append(os.path.expanduser(value))
156 return result
155 return result
157
156
158 def configrevlog(self):
157 def configrevlog(self):
159 result = {}
158 result = {}
160 for key, value in self.configitems("revlog"):
159 for key, value in self.configitems("revlog"):
161 result[key.lower()] = value
160 result[key.lower()] = value
162 return result
161 return result
163
162
164 def diffopts(self):
163 def diffopts(self):
165 if self.diffcache:
164 if self.diffcache:
166 return self.diffcache
165 return self.diffcache
167 result = {'showfunc': True, 'ignorews': False}
166 result = {'showfunc': True, 'ignorews': False}
168 for key, value in self.configitems("diff"):
167 for key, value in self.configitems("diff"):
169 if value:
168 if value:
170 result[key.lower()] = (value.lower() == 'true')
169 result[key.lower()] = (value.lower() == 'true')
171 self.diffcache = result
170 self.diffcache = result
172 return result
171 return result
173
172
174 def username(self):
173 def username(self):
175 """Return default username to be used in commits.
174 """Return default username to be used in commits.
176
175
177 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
176 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
178 and stop searching if one of these is set.
177 and stop searching if one of these is set.
179 Abort if found username is an empty string to force specifying
178 Abort if found username is an empty string to force specifying
180 the commit user elsewhere, e.g. with line option or repo hgrc.
179 the commit user elsewhere, e.g. with line option or repo hgrc.
181 If not found, use ($LOGNAME or $USER or $LNAME or
180 If not found, use ($LOGNAME or $USER or $LNAME or
182 $USERNAME) +"@full.hostname".
181 $USERNAME) +"@full.hostname".
183 """
182 """
184 user = os.environ.get("HGUSER")
183 user = os.environ.get("HGUSER")
185 if user is None:
184 if user is None:
186 user = self.config("ui", "username")
185 user = self.config("ui", "username")
187 if user is None:
186 if user is None:
188 user = os.environ.get("EMAIL")
187 user = os.environ.get("EMAIL")
189 if user is None:
188 if user is None:
190 try:
189 try:
191 user = '%s@%s' % (getpass.getuser(), socket.getfqdn())
190 user = '%s@%s' % (getpass.getuser(), socket.getfqdn())
192 except KeyError:
191 except KeyError:
193 raise util.Abort(_("Please specify a username."))
192 raise util.Abort(_("Please specify a username."))
194 return user
193 return user
195
194
196 def shortuser(self, user):
195 def shortuser(self, user):
197 """Return a short representation of a user name or email address."""
196 """Return a short representation of a user name or email address."""
198 if not self.verbose: user = util.shortuser(user)
197 if not self.verbose: user = util.shortuser(user)
199 return user
198 return user
200
199
201 def expandpath(self, loc):
200 def expandpath(self, loc):
202 """Return repository location relative to cwd or from [paths]"""
201 """Return repository location relative to cwd or from [paths]"""
203 if loc.find("://") != -1 or os.path.exists(loc):
202 if loc.find("://") != -1 or os.path.exists(loc):
204 return loc
203 return loc
205
204
206 return self.config("paths", loc, loc)
205 return self.config("paths", loc, loc)
207
206
208 def write(self, *args):
207 def write(self, *args):
209 if self.header:
208 if self.header:
210 if self.header != self.prev_header:
209 if self.header != self.prev_header:
211 self.prev_header = self.header
210 self.prev_header = self.header
212 self.write(*self.header)
211 self.write(*self.header)
213 self.header = []
212 self.header = []
214 for a in args:
213 for a in args:
215 sys.stdout.write(str(a))
214 sys.stdout.write(str(a))
216
215
217 def write_header(self, *args):
216 def write_header(self, *args):
218 for a in args:
217 for a in args:
219 self.header.append(str(a))
218 self.header.append(str(a))
220
219
221 def write_err(self, *args):
220 def write_err(self, *args):
222 try:
221 try:
223 if not sys.stdout.closed: sys.stdout.flush()
222 if not sys.stdout.closed: sys.stdout.flush()
224 for a in args:
223 for a in args:
225 sys.stderr.write(str(a))
224 sys.stderr.write(str(a))
226 except IOError, inst:
225 except IOError, inst:
227 if inst.errno != errno.EPIPE:
226 if inst.errno != errno.EPIPE:
228 raise
227 raise
229
228
230 def flush(self):
229 def flush(self):
231 try: sys.stdout.flush()
230 try: sys.stdout.flush()
232 except: pass
231 except: pass
233 try: sys.stderr.flush()
232 try: sys.stderr.flush()
234 except: pass
233 except: pass
235
234
236 def readline(self):
235 def readline(self):
237 return sys.stdin.readline()[:-1]
236 return sys.stdin.readline()[:-1]
238 def prompt(self, msg, pat=None, default="y"):
237 def prompt(self, msg, pat=None, default="y"):
239 if not self.interactive: return default
238 if not self.interactive: return default
240 while 1:
239 while 1:
241 self.write(msg, " ")
240 self.write(msg, " ")
242 r = self.readline()
241 r = self.readline()
243 if not pat or re.match(pat, r):
242 if not pat or re.match(pat, r):
244 return r
243 return r
245 else:
244 else:
246 self.write(_("unrecognized response\n"))
245 self.write(_("unrecognized response\n"))
247 def getpass(self, prompt=None, default=None):
246 def getpass(self, prompt=None, default=None):
248 if not self.interactive: return default
247 if not self.interactive: return default
249 return getpass.getpass(prompt or _('password: '))
248 return getpass.getpass(prompt or _('password: '))
250 def status(self, *msg):
249 def status(self, *msg):
251 if not self.quiet: self.write(*msg)
250 if not self.quiet: self.write(*msg)
252 def warn(self, *msg):
251 def warn(self, *msg):
253 self.write_err(*msg)
252 self.write_err(*msg)
254 def note(self, *msg):
253 def note(self, *msg):
255 if self.verbose: self.write(*msg)
254 if self.verbose: self.write(*msg)
256 def debug(self, *msg):
255 def debug(self, *msg):
257 if self.debugflag: self.write(*msg)
256 if self.debugflag: self.write(*msg)
258 def edit(self, text, user):
257 def edit(self, text, user):
259 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
258 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
260 text=True)
259 text=True)
261 try:
260 try:
262 f = os.fdopen(fd, "w")
261 f = os.fdopen(fd, "w")
263 f.write(text)
262 f.write(text)
264 f.close()
263 f.close()
265
264
266 editor = (os.environ.get("HGEDITOR") or
265 editor = (os.environ.get("HGEDITOR") or
267 self.config("ui", "editor") or
266 self.config("ui", "editor") or
268 os.environ.get("EDITOR", "vi"))
267 os.environ.get("EDITOR", "vi"))
269
268
270 util.system("%s \"%s\"" % (editor, name),
269 util.system("%s \"%s\"" % (editor, name),
271 environ={'HGUSER': user},
270 environ={'HGUSER': user},
272 onerr=util.Abort, errprefix=_("edit failed"))
271 onerr=util.Abort, errprefix=_("edit failed"))
273
272
274 f = open(name)
273 f = open(name)
275 t = f.read()
274 t = f.read()
276 f.close()
275 f.close()
277 t = re.sub("(?m)^HG:.*\n", "", t)
276 t = re.sub("(?m)^HG:.*\n", "", t)
278 finally:
277 finally:
279 os.unlink(name)
278 os.unlink(name)
280
279
281 return t
280 return t
282
281
283 def sendmail(self):
282 def sendmail(self):
284 '''send mail message. object returned has one method, sendmail.
283 '''send mail message. object returned has one method, sendmail.
285 call as sendmail(sender, list-of-recipients, msg).'''
284 call as sendmail(sender, list-of-recipients, msg).'''
286
285
287 def smtp():
286 def smtp():
288 '''send mail using smtp.'''
287 '''send mail using smtp.'''
289
288
290 s = smtplib.SMTP()
289 s = smtplib.SMTP()
291 mailhost = self.config('smtp', 'host')
290 mailhost = self.config('smtp', 'host')
292 if not mailhost:
291 if not mailhost:
293 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
292 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
294 mailport = int(self.config('smtp', 'port', 25))
293 mailport = int(self.config('smtp', 'port', 25))
295 self.note(_('sending mail: smtp host %s, port %s\n') %
294 self.note(_('sending mail: smtp host %s, port %s\n') %
296 (mailhost, mailport))
295 (mailhost, mailport))
297 s.connect(host=mailhost, port=mailport)
296 s.connect(host=mailhost, port=mailport)
298 if self.configbool('smtp', 'tls'):
297 if self.configbool('smtp', 'tls'):
299 self.note(_('(using tls)\n'))
298 self.note(_('(using tls)\n'))
300 s.ehlo()
299 s.ehlo()
301 s.starttls()
300 s.starttls()
302 s.ehlo()
301 s.ehlo()
303 username = self.config('smtp', 'username')
302 username = self.config('smtp', 'username')
304 password = self.config('smtp', 'password')
303 password = self.config('smtp', 'password')
305 if username and password:
304 if username and password:
306 self.note(_('(authenticating to mail server as %s)\n') %
305 self.note(_('(authenticating to mail server as %s)\n') %
307 (username))
306 (username))
308 s.login(username, password)
307 s.login(username, password)
309 return s
308 return s
310
309
311 class sendmail(object):
310 class sendmail(object):
312 '''send mail using sendmail.'''
311 '''send mail using sendmail.'''
313
312
314 def __init__(self, ui, program):
313 def __init__(self, ui, program):
315 self.ui = ui
314 self.ui = ui
316 self.program = program
315 self.program = program
317
316
318 def sendmail(self, sender, recipients, msg):
317 def sendmail(self, sender, recipients, msg):
319 cmdline = '%s -f %s %s' % (
318 cmdline = '%s -f %s %s' % (
320 self.program, templater.email(sender),
319 self.program, templater.email(sender),
321 ' '.join(map(templater.email, recipients)))
320 ' '.join(map(templater.email, recipients)))
322 self.ui.note(_('sending mail: %s\n') % cmdline)
321 self.ui.note(_('sending mail: %s\n') % cmdline)
323 fp = os.popen(cmdline, 'w')
322 fp = os.popen(cmdline, 'w')
324 fp.write(msg)
323 fp.write(msg)
325 ret = fp.close()
324 ret = fp.close()
326 if ret:
325 if ret:
327 raise util.Abort('%s %s' % (
326 raise util.Abort('%s %s' % (
328 os.path.basename(self.program.split(None, 1)[0]),
327 os.path.basename(self.program.split(None, 1)[0]),
329 util.explain_exit(ret)[0]))
328 util.explain_exit(ret)[0]))
330
329
331 method = self.config('email', 'method', 'smtp')
330 method = self.config('email', 'method', 'smtp')
332 if method == 'smtp':
331 if method == 'smtp':
333 mail = smtp()
332 mail = smtp()
334 else:
333 else:
335 mail = sendmail(self, method)
334 mail = sendmail(self, method)
336 return mail
335 return mail
337
336
338 def print_exc(self):
337 def print_exc(self):
339 '''print exception traceback if traceback printing enabled.
338 '''print exception traceback if traceback printing enabled.
340 only to call in exception handler. returns true if traceback
339 only to call in exception handler. returns true if traceback
341 printed.'''
340 printed.'''
342 if self.traceback:
341 if self.traceback:
343 traceback.print_exc()
342 traceback.print_exc()
344 return self.traceback
343 return self.traceback
@@ -1,900 +1,899 b''
1 """
1 """
2 util.py - Mercurial utility functions and platform specfic implementations
2 util.py - Mercurial utility functions and platform specfic implementations
3
3
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
5
5
6 This software may be used and distributed according to the terms
6 This software may be used and distributed according to the terms
7 of the GNU General Public License, incorporated herein by reference.
7 of the GNU General Public License, incorporated herein by reference.
8
8
9 This contains helper routines that are independent of the SCM core and hide
9 This contains helper routines that are independent of the SCM core and hide
10 platform-specific details from the core.
10 platform-specific details from the core.
11 """
11 """
12
12
13 import os, errno
14 from i18n import gettext as _
13 from i18n import gettext as _
15 from demandload import *
14 from demandload import *
16 demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
15 demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
17 demandload(globals(), "threading time")
16 demandload(globals(), "os threading time")
18
17
19 class SignalInterrupt(Exception):
18 class SignalInterrupt(Exception):
20 """Exception raised on SIGTERM and SIGHUP."""
19 """Exception raised on SIGTERM and SIGHUP."""
21
20
22 def pipefilter(s, cmd):
21 def pipefilter(s, cmd):
23 '''filter string S through command CMD, returning its output'''
22 '''filter string S through command CMD, returning its output'''
24 (pout, pin) = popen2.popen2(cmd, -1, 'b')
23 (pout, pin) = popen2.popen2(cmd, -1, 'b')
25 def writer():
24 def writer():
26 try:
25 try:
27 pin.write(s)
26 pin.write(s)
28 pin.close()
27 pin.close()
29 except IOError, inst:
28 except IOError, inst:
30 if inst.errno != errno.EPIPE:
29 if inst.errno != errno.EPIPE:
31 raise
30 raise
32
31
33 # we should use select instead on UNIX, but this will work on most
32 # we should use select instead on UNIX, but this will work on most
34 # systems, including Windows
33 # systems, including Windows
35 w = threading.Thread(target=writer)
34 w = threading.Thread(target=writer)
36 w.start()
35 w.start()
37 f = pout.read()
36 f = pout.read()
38 pout.close()
37 pout.close()
39 w.join()
38 w.join()
40 return f
39 return f
41
40
42 def tempfilter(s, cmd):
41 def tempfilter(s, cmd):
43 '''filter string S through a pair of temporary files with CMD.
42 '''filter string S through a pair of temporary files with CMD.
44 CMD is used as a template to create the real command to be run,
43 CMD is used as a template to create the real command to be run,
45 with the strings INFILE and OUTFILE replaced by the real names of
44 with the strings INFILE and OUTFILE replaced by the real names of
46 the temporary files generated.'''
45 the temporary files generated.'''
47 inname, outname = None, None
46 inname, outname = None, None
48 try:
47 try:
49 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
48 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
50 fp = os.fdopen(infd, 'wb')
49 fp = os.fdopen(infd, 'wb')
51 fp.write(s)
50 fp.write(s)
52 fp.close()
51 fp.close()
53 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
52 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
54 os.close(outfd)
53 os.close(outfd)
55 cmd = cmd.replace('INFILE', inname)
54 cmd = cmd.replace('INFILE', inname)
56 cmd = cmd.replace('OUTFILE', outname)
55 cmd = cmd.replace('OUTFILE', outname)
57 code = os.system(cmd)
56 code = os.system(cmd)
58 if code: raise Abort(_("command '%s' failed: %s") %
57 if code: raise Abort(_("command '%s' failed: %s") %
59 (cmd, explain_exit(code)))
58 (cmd, explain_exit(code)))
60 return open(outname, 'rb').read()
59 return open(outname, 'rb').read()
61 finally:
60 finally:
62 try:
61 try:
63 if inname: os.unlink(inname)
62 if inname: os.unlink(inname)
64 except: pass
63 except: pass
65 try:
64 try:
66 if outname: os.unlink(outname)
65 if outname: os.unlink(outname)
67 except: pass
66 except: pass
68
67
69 filtertable = {
68 filtertable = {
70 'tempfile:': tempfilter,
69 'tempfile:': tempfilter,
71 'pipe:': pipefilter,
70 'pipe:': pipefilter,
72 }
71 }
73
72
74 def filter(s, cmd):
73 def filter(s, cmd):
75 "filter a string through a command that transforms its input to its output"
74 "filter a string through a command that transforms its input to its output"
76 for name, fn in filtertable.iteritems():
75 for name, fn in filtertable.iteritems():
77 if cmd.startswith(name):
76 if cmd.startswith(name):
78 return fn(s, cmd[len(name):].lstrip())
77 return fn(s, cmd[len(name):].lstrip())
79 return pipefilter(s, cmd)
78 return pipefilter(s, cmd)
80
79
81 def find_in_path(name, path, default=None):
80 def find_in_path(name, path, default=None):
82 '''find name in search path. path can be string (will be split
81 '''find name in search path. path can be string (will be split
83 with os.pathsep), or iterable thing that returns strings. if name
82 with os.pathsep), or iterable thing that returns strings. if name
84 found, return path to name. else return default.'''
83 found, return path to name. else return default.'''
85 if isinstance(path, str):
84 if isinstance(path, str):
86 path = path.split(os.pathsep)
85 path = path.split(os.pathsep)
87 for p in path:
86 for p in path:
88 p_name = os.path.join(p, name)
87 p_name = os.path.join(p, name)
89 if os.path.exists(p_name):
88 if os.path.exists(p_name):
90 return p_name
89 return p_name
91 return default
90 return default
92
91
93 def patch(strip, patchname, ui):
92 def patch(strip, patchname, ui):
94 """apply the patch <patchname> to the working directory.
93 """apply the patch <patchname> to the working directory.
95 a list of patched files is returned"""
94 a list of patched files is returned"""
96 patcher = find_in_path('gpatch', os.environ.get('PATH', ''), 'patch')
95 patcher = find_in_path('gpatch', os.environ.get('PATH', ''), 'patch')
97 fp = os.popen('%s -p%d < "%s"' % (patcher, strip, patchname))
96 fp = os.popen('%s -p%d < "%s"' % (patcher, strip, patchname))
98 files = {}
97 files = {}
99 for line in fp:
98 for line in fp:
100 line = line.rstrip()
99 line = line.rstrip()
101 ui.status("%s\n" % line)
100 ui.status("%s\n" % line)
102 if line.startswith('patching file '):
101 if line.startswith('patching file '):
103 pf = parse_patch_output(line)
102 pf = parse_patch_output(line)
104 files.setdefault(pf, 1)
103 files.setdefault(pf, 1)
105 code = fp.close()
104 code = fp.close()
106 if code:
105 if code:
107 raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
106 raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
108 return files.keys()
107 return files.keys()
109
108
110 def binary(s):
109 def binary(s):
111 """return true if a string is binary data using diff's heuristic"""
110 """return true if a string is binary data using diff's heuristic"""
112 if s and '\0' in s[:4096]:
111 if s and '\0' in s[:4096]:
113 return True
112 return True
114 return False
113 return False
115
114
116 def unique(g):
115 def unique(g):
117 """return the uniq elements of iterable g"""
116 """return the uniq elements of iterable g"""
118 seen = {}
117 seen = {}
119 for f in g:
118 for f in g:
120 if f not in seen:
119 if f not in seen:
121 seen[f] = 1
120 seen[f] = 1
122 yield f
121 yield f
123
122
124 class Abort(Exception):
123 class Abort(Exception):
125 """Raised if a command needs to print an error and exit."""
124 """Raised if a command needs to print an error and exit."""
126
125
127 def always(fn): return True
126 def always(fn): return True
128 def never(fn): return False
127 def never(fn): return False
129
128
130 def patkind(name, dflt_pat='glob'):
129 def patkind(name, dflt_pat='glob'):
131 """Split a string into an optional pattern kind prefix and the
130 """Split a string into an optional pattern kind prefix and the
132 actual pattern."""
131 actual pattern."""
133 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
132 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
134 if name.startswith(prefix + ':'): return name.split(':', 1)
133 if name.startswith(prefix + ':'): return name.split(':', 1)
135 return dflt_pat, name
134 return dflt_pat, name
136
135
137 def globre(pat, head='^', tail='$'):
136 def globre(pat, head='^', tail='$'):
138 "convert a glob pattern into a regexp"
137 "convert a glob pattern into a regexp"
139 i, n = 0, len(pat)
138 i, n = 0, len(pat)
140 res = ''
139 res = ''
141 group = False
140 group = False
142 def peek(): return i < n and pat[i]
141 def peek(): return i < n and pat[i]
143 while i < n:
142 while i < n:
144 c = pat[i]
143 c = pat[i]
145 i = i+1
144 i = i+1
146 if c == '*':
145 if c == '*':
147 if peek() == '*':
146 if peek() == '*':
148 i += 1
147 i += 1
149 res += '.*'
148 res += '.*'
150 else:
149 else:
151 res += '[^/]*'
150 res += '[^/]*'
152 elif c == '?':
151 elif c == '?':
153 res += '.'
152 res += '.'
154 elif c == '[':
153 elif c == '[':
155 j = i
154 j = i
156 if j < n and pat[j] in '!]':
155 if j < n and pat[j] in '!]':
157 j += 1
156 j += 1
158 while j < n and pat[j] != ']':
157 while j < n and pat[j] != ']':
159 j += 1
158 j += 1
160 if j >= n:
159 if j >= n:
161 res += '\\['
160 res += '\\['
162 else:
161 else:
163 stuff = pat[i:j].replace('\\','\\\\')
162 stuff = pat[i:j].replace('\\','\\\\')
164 i = j + 1
163 i = j + 1
165 if stuff[0] == '!':
164 if stuff[0] == '!':
166 stuff = '^' + stuff[1:]
165 stuff = '^' + stuff[1:]
167 elif stuff[0] == '^':
166 elif stuff[0] == '^':
168 stuff = '\\' + stuff
167 stuff = '\\' + stuff
169 res = '%s[%s]' % (res, stuff)
168 res = '%s[%s]' % (res, stuff)
170 elif c == '{':
169 elif c == '{':
171 group = True
170 group = True
172 res += '(?:'
171 res += '(?:'
173 elif c == '}' and group:
172 elif c == '}' and group:
174 res += ')'
173 res += ')'
175 group = False
174 group = False
176 elif c == ',' and group:
175 elif c == ',' and group:
177 res += '|'
176 res += '|'
178 elif c == '\\':
177 elif c == '\\':
179 p = peek()
178 p = peek()
180 if p:
179 if p:
181 i += 1
180 i += 1
182 res += re.escape(p)
181 res += re.escape(p)
183 else:
182 else:
184 res += re.escape(c)
183 res += re.escape(c)
185 else:
184 else:
186 res += re.escape(c)
185 res += re.escape(c)
187 return head + res + tail
186 return head + res + tail
188
187
189 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
188 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
190
189
191 def pathto(n1, n2):
190 def pathto(n1, n2):
192 '''return the relative path from one place to another.
191 '''return the relative path from one place to another.
193 this returns a path in the form used by the local filesystem, not hg.'''
192 this returns a path in the form used by the local filesystem, not hg.'''
194 if not n1: return localpath(n2)
193 if not n1: return localpath(n2)
195 a, b = n1.split('/'), n2.split('/')
194 a, b = n1.split('/'), n2.split('/')
196 a.reverse()
195 a.reverse()
197 b.reverse()
196 b.reverse()
198 while a and b and a[-1] == b[-1]:
197 while a and b and a[-1] == b[-1]:
199 a.pop()
198 a.pop()
200 b.pop()
199 b.pop()
201 b.reverse()
200 b.reverse()
202 return os.sep.join((['..'] * len(a)) + b)
201 return os.sep.join((['..'] * len(a)) + b)
203
202
204 def canonpath(root, cwd, myname):
203 def canonpath(root, cwd, myname):
205 """return the canonical path of myname, given cwd and root"""
204 """return the canonical path of myname, given cwd and root"""
206 if root == os.sep:
205 if root == os.sep:
207 rootsep = os.sep
206 rootsep = os.sep
208 elif root.endswith(os.sep):
207 elif root.endswith(os.sep):
209 rootsep = root
208 rootsep = root
210 else:
209 else:
211 rootsep = root + os.sep
210 rootsep = root + os.sep
212 name = myname
211 name = myname
213 if not os.path.isabs(name):
212 if not os.path.isabs(name):
214 name = os.path.join(root, cwd, name)
213 name = os.path.join(root, cwd, name)
215 name = os.path.normpath(name)
214 name = os.path.normpath(name)
216 if name != rootsep and name.startswith(rootsep):
215 if name != rootsep and name.startswith(rootsep):
217 name = name[len(rootsep):]
216 name = name[len(rootsep):]
218 audit_path(name)
217 audit_path(name)
219 return pconvert(name)
218 return pconvert(name)
220 elif name == root:
219 elif name == root:
221 return ''
220 return ''
222 else:
221 else:
223 # Determine whether `name' is in the hierarchy at or beneath `root',
222 # Determine whether `name' is in the hierarchy at or beneath `root',
224 # by iterating name=dirname(name) until that causes no change (can't
223 # by iterating name=dirname(name) until that causes no change (can't
225 # check name == '/', because that doesn't work on windows). For each
224 # check name == '/', because that doesn't work on windows). For each
226 # `name', compare dev/inode numbers. If they match, the list `rel'
225 # `name', compare dev/inode numbers. If they match, the list `rel'
227 # holds the reversed list of components making up the relative file
226 # holds the reversed list of components making up the relative file
228 # name we want.
227 # name we want.
229 root_st = os.stat(root)
228 root_st = os.stat(root)
230 rel = []
229 rel = []
231 while True:
230 while True:
232 try:
231 try:
233 name_st = os.stat(name)
232 name_st = os.stat(name)
234 except OSError:
233 except OSError:
235 break
234 break
236 if samestat(name_st, root_st):
235 if samestat(name_st, root_st):
237 rel.reverse()
236 rel.reverse()
238 name = os.path.join(*rel)
237 name = os.path.join(*rel)
239 audit_path(name)
238 audit_path(name)
240 return pconvert(name)
239 return pconvert(name)
241 dirname, basename = os.path.split(name)
240 dirname, basename = os.path.split(name)
242 rel.append(basename)
241 rel.append(basename)
243 if dirname == name:
242 if dirname == name:
244 break
243 break
245 name = dirname
244 name = dirname
246
245
247 raise Abort('%s not under root' % myname)
246 raise Abort('%s not under root' % myname)
248
247
249 def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
248 def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
250 return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
249 return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
251
250
252 def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
251 def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
253 if os.name == 'nt':
252 if os.name == 'nt':
254 dflt_pat = 'glob'
253 dflt_pat = 'glob'
255 else:
254 else:
256 dflt_pat = 'relpath'
255 dflt_pat = 'relpath'
257 return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
256 return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
258
257
259 def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
258 def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
260 """build a function to match a set of file patterns
259 """build a function to match a set of file patterns
261
260
262 arguments:
261 arguments:
263 canonroot - the canonical root of the tree you're matching against
262 canonroot - the canonical root of the tree you're matching against
264 cwd - the current working directory, if relevant
263 cwd - the current working directory, if relevant
265 names - patterns to find
264 names - patterns to find
266 inc - patterns to include
265 inc - patterns to include
267 exc - patterns to exclude
266 exc - patterns to exclude
268 head - a regex to prepend to patterns to control whether a match is rooted
267 head - a regex to prepend to patterns to control whether a match is rooted
269
268
270 a pattern is one of:
269 a pattern is one of:
271 'glob:<rooted glob>'
270 'glob:<rooted glob>'
272 're:<rooted regexp>'
271 're:<rooted regexp>'
273 'path:<rooted path>'
272 'path:<rooted path>'
274 'relglob:<relative glob>'
273 'relglob:<relative glob>'
275 'relpath:<relative path>'
274 'relpath:<relative path>'
276 'relre:<relative regexp>'
275 'relre:<relative regexp>'
277 '<rooted path or regexp>'
276 '<rooted path or regexp>'
278
277
279 returns:
278 returns:
280 a 3-tuple containing
279 a 3-tuple containing
281 - list of explicit non-pattern names passed in
280 - list of explicit non-pattern names passed in
282 - a bool match(filename) function
281 - a bool match(filename) function
283 - a bool indicating if any patterns were passed in
282 - a bool indicating if any patterns were passed in
284
283
285 todo:
284 todo:
286 make head regex a rooted bool
285 make head regex a rooted bool
287 """
286 """
288
287
289 def contains_glob(name):
288 def contains_glob(name):
290 for c in name:
289 for c in name:
291 if c in _globchars: return True
290 if c in _globchars: return True
292 return False
291 return False
293
292
294 def regex(kind, name, tail):
293 def regex(kind, name, tail):
295 '''convert a pattern into a regular expression'''
294 '''convert a pattern into a regular expression'''
296 if kind == 're':
295 if kind == 're':
297 return name
296 return name
298 elif kind == 'path':
297 elif kind == 'path':
299 return '^' + re.escape(name) + '(?:/|$)'
298 return '^' + re.escape(name) + '(?:/|$)'
300 elif kind == 'relglob':
299 elif kind == 'relglob':
301 return head + globre(name, '(?:|.*/)', tail)
300 return head + globre(name, '(?:|.*/)', tail)
302 elif kind == 'relpath':
301 elif kind == 'relpath':
303 return head + re.escape(name) + tail
302 return head + re.escape(name) + tail
304 elif kind == 'relre':
303 elif kind == 'relre':
305 if name.startswith('^'):
304 if name.startswith('^'):
306 return name
305 return name
307 return '.*' + name
306 return '.*' + name
308 return head + globre(name, '', tail)
307 return head + globre(name, '', tail)
309
308
310 def matchfn(pats, tail):
309 def matchfn(pats, tail):
311 """build a matching function from a set of patterns"""
310 """build a matching function from a set of patterns"""
312 if not pats:
311 if not pats:
313 return
312 return
314 matches = []
313 matches = []
315 for k, p in pats:
314 for k, p in pats:
316 try:
315 try:
317 pat = '(?:%s)' % regex(k, p, tail)
316 pat = '(?:%s)' % regex(k, p, tail)
318 matches.append(re.compile(pat).match)
317 matches.append(re.compile(pat).match)
319 except re.error:
318 except re.error:
320 if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
319 if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
321 else: raise Abort("invalid pattern (%s): %s" % (k, p))
320 else: raise Abort("invalid pattern (%s): %s" % (k, p))
322
321
323 def buildfn(text):
322 def buildfn(text):
324 for m in matches:
323 for m in matches:
325 r = m(text)
324 r = m(text)
326 if r:
325 if r:
327 return r
326 return r
328
327
329 return buildfn
328 return buildfn
330
329
331 def globprefix(pat):
330 def globprefix(pat):
332 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
331 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
333 root = []
332 root = []
334 for p in pat.split(os.sep):
333 for p in pat.split(os.sep):
335 if contains_glob(p): break
334 if contains_glob(p): break
336 root.append(p)
335 root.append(p)
337 return '/'.join(root)
336 return '/'.join(root)
338
337
339 pats = []
338 pats = []
340 files = []
339 files = []
341 roots = []
340 roots = []
342 for kind, name in [patkind(p, dflt_pat) for p in names]:
341 for kind, name in [patkind(p, dflt_pat) for p in names]:
343 if kind in ('glob', 'relpath'):
342 if kind in ('glob', 'relpath'):
344 name = canonpath(canonroot, cwd, name)
343 name = canonpath(canonroot, cwd, name)
345 if name == '':
344 if name == '':
346 kind, name = 'glob', '**'
345 kind, name = 'glob', '**'
347 if kind in ('glob', 'path', 're'):
346 if kind in ('glob', 'path', 're'):
348 pats.append((kind, name))
347 pats.append((kind, name))
349 if kind == 'glob':
348 if kind == 'glob':
350 root = globprefix(name)
349 root = globprefix(name)
351 if root: roots.append(root)
350 if root: roots.append(root)
352 elif kind == 'relpath':
351 elif kind == 'relpath':
353 files.append((kind, name))
352 files.append((kind, name))
354 roots.append(name)
353 roots.append(name)
355
354
356 patmatch = matchfn(pats, '$') or always
355 patmatch = matchfn(pats, '$') or always
357 filematch = matchfn(files, '(?:/|$)') or always
356 filematch = matchfn(files, '(?:/|$)') or always
358 incmatch = always
357 incmatch = always
359 if inc:
358 if inc:
360 incmatch = matchfn(map(patkind, inc), '(?:/|$)')
359 incmatch = matchfn(map(patkind, inc), '(?:/|$)')
361 excmatch = lambda fn: False
360 excmatch = lambda fn: False
362 if exc:
361 if exc:
363 excmatch = matchfn(map(patkind, exc), '(?:/|$)')
362 excmatch = matchfn(map(patkind, exc), '(?:/|$)')
364
363
365 return (roots,
364 return (roots,
366 lambda fn: (incmatch(fn) and not excmatch(fn) and
365 lambda fn: (incmatch(fn) and not excmatch(fn) and
367 (fn.endswith('/') or
366 (fn.endswith('/') or
368 (not pats and not files) or
367 (not pats and not files) or
369 (pats and patmatch(fn)) or
368 (pats and patmatch(fn)) or
370 (files and filematch(fn)))),
369 (files and filematch(fn)))),
371 (inc or exc or (pats and pats != [('glob', '**')])) and True)
370 (inc or exc or (pats and pats != [('glob', '**')])) and True)
372
371
373 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
372 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
374 '''enhanced shell command execution.
373 '''enhanced shell command execution.
375 run with environment maybe modified, maybe in different dir.
374 run with environment maybe modified, maybe in different dir.
376
375
377 if command fails and onerr is None, return status. if ui object,
376 if command fails and onerr is None, return status. if ui object,
378 print error message and return status, else raise onerr object as
377 print error message and return status, else raise onerr object as
379 exception.'''
378 exception.'''
380 oldenv = {}
379 oldenv = {}
381 for k in environ:
380 for k in environ:
382 oldenv[k] = os.environ.get(k)
381 oldenv[k] = os.environ.get(k)
383 if cwd is not None:
382 if cwd is not None:
384 oldcwd = os.getcwd()
383 oldcwd = os.getcwd()
385 try:
384 try:
386 for k, v in environ.iteritems():
385 for k, v in environ.iteritems():
387 os.environ[k] = str(v)
386 os.environ[k] = str(v)
388 if cwd is not None and oldcwd != cwd:
387 if cwd is not None and oldcwd != cwd:
389 os.chdir(cwd)
388 os.chdir(cwd)
390 rc = os.system(cmd)
389 rc = os.system(cmd)
391 if rc and onerr:
390 if rc and onerr:
392 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
391 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
393 explain_exit(rc)[0])
392 explain_exit(rc)[0])
394 if errprefix:
393 if errprefix:
395 errmsg = '%s: %s' % (errprefix, errmsg)
394 errmsg = '%s: %s' % (errprefix, errmsg)
396 try:
395 try:
397 onerr.warn(errmsg + '\n')
396 onerr.warn(errmsg + '\n')
398 except AttributeError:
397 except AttributeError:
399 raise onerr(errmsg)
398 raise onerr(errmsg)
400 return rc
399 return rc
401 finally:
400 finally:
402 for k, v in oldenv.iteritems():
401 for k, v in oldenv.iteritems():
403 if v is None:
402 if v is None:
404 del os.environ[k]
403 del os.environ[k]
405 else:
404 else:
406 os.environ[k] = v
405 os.environ[k] = v
407 if cwd is not None and oldcwd != cwd:
406 if cwd is not None and oldcwd != cwd:
408 os.chdir(oldcwd)
407 os.chdir(oldcwd)
409
408
410 def rename(src, dst):
409 def rename(src, dst):
411 """forcibly rename a file"""
410 """forcibly rename a file"""
412 try:
411 try:
413 os.rename(src, dst)
412 os.rename(src, dst)
414 except OSError, err:
413 except OSError, err:
415 # on windows, rename to existing file is not allowed, so we
414 # on windows, rename to existing file is not allowed, so we
416 # must delete destination first. but if file is open, unlink
415 # must delete destination first. but if file is open, unlink
417 # schedules it for delete but does not delete it. rename
416 # schedules it for delete but does not delete it. rename
418 # happens immediately even for open files, so we create
417 # happens immediately even for open files, so we create
419 # temporary file, delete it, rename destination to that name,
418 # temporary file, delete it, rename destination to that name,
420 # then delete that. then rename is safe to do.
419 # then delete that. then rename is safe to do.
421 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
420 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
422 os.close(fd)
421 os.close(fd)
423 os.unlink(temp)
422 os.unlink(temp)
424 os.rename(dst, temp)
423 os.rename(dst, temp)
425 os.unlink(temp)
424 os.unlink(temp)
426 os.rename(src, dst)
425 os.rename(src, dst)
427
426
428 def unlink(f):
427 def unlink(f):
429 """unlink and remove the directory if it is empty"""
428 """unlink and remove the directory if it is empty"""
430 os.unlink(f)
429 os.unlink(f)
431 # try removing directories that might now be empty
430 # try removing directories that might now be empty
432 try:
431 try:
433 os.removedirs(os.path.dirname(f))
432 os.removedirs(os.path.dirname(f))
434 except OSError:
433 except OSError:
435 pass
434 pass
436
435
437 def copyfiles(src, dst, hardlink=None):
436 def copyfiles(src, dst, hardlink=None):
438 """Copy a directory tree using hardlinks if possible"""
437 """Copy a directory tree using hardlinks if possible"""
439
438
440 if hardlink is None:
439 if hardlink is None:
441 hardlink = (os.stat(src).st_dev ==
440 hardlink = (os.stat(src).st_dev ==
442 os.stat(os.path.dirname(dst)).st_dev)
441 os.stat(os.path.dirname(dst)).st_dev)
443
442
444 if os.path.isdir(src):
443 if os.path.isdir(src):
445 os.mkdir(dst)
444 os.mkdir(dst)
446 for name in os.listdir(src):
445 for name in os.listdir(src):
447 srcname = os.path.join(src, name)
446 srcname = os.path.join(src, name)
448 dstname = os.path.join(dst, name)
447 dstname = os.path.join(dst, name)
449 copyfiles(srcname, dstname, hardlink)
448 copyfiles(srcname, dstname, hardlink)
450 else:
449 else:
451 if hardlink:
450 if hardlink:
452 try:
451 try:
453 os_link(src, dst)
452 os_link(src, dst)
454 except (IOError, OSError):
453 except (IOError, OSError):
455 hardlink = False
454 hardlink = False
456 shutil.copy(src, dst)
455 shutil.copy(src, dst)
457 else:
456 else:
458 shutil.copy(src, dst)
457 shutil.copy(src, dst)
459
458
460 def audit_path(path):
459 def audit_path(path):
461 """Abort if path contains dangerous components"""
460 """Abort if path contains dangerous components"""
462 parts = os.path.normcase(path).split(os.sep)
461 parts = os.path.normcase(path).split(os.sep)
463 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
462 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
464 or os.pardir in parts):
463 or os.pardir in parts):
465 raise Abort(_("path contains illegal component: %s\n") % path)
464 raise Abort(_("path contains illegal component: %s\n") % path)
466
465
467 def _makelock_file(info, pathname):
466 def _makelock_file(info, pathname):
468 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
467 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
469 os.write(ld, info)
468 os.write(ld, info)
470 os.close(ld)
469 os.close(ld)
471
470
472 def _readlock_file(pathname):
471 def _readlock_file(pathname):
473 return posixfile(pathname).read()
472 return posixfile(pathname).read()
474
473
475 def nlinks(pathname):
474 def nlinks(pathname):
476 """Return number of hardlinks for the given file."""
475 """Return number of hardlinks for the given file."""
477 return os.lstat(pathname).st_nlink
476 return os.lstat(pathname).st_nlink
478
477
479 if hasattr(os, 'link'):
478 if hasattr(os, 'link'):
480 os_link = os.link
479 os_link = os.link
481 else:
480 else:
482 def os_link(src, dst):
481 def os_link(src, dst):
483 raise OSError(0, _("Hardlinks not supported"))
482 raise OSError(0, _("Hardlinks not supported"))
484
483
485 def fstat(fp):
484 def fstat(fp):
486 '''stat file object that may not have fileno method.'''
485 '''stat file object that may not have fileno method.'''
487 try:
486 try:
488 return os.fstat(fp.fileno())
487 return os.fstat(fp.fileno())
489 except AttributeError:
488 except AttributeError:
490 return os.stat(fp.name)
489 return os.stat(fp.name)
491
490
492 posixfile = file
491 posixfile = file
493
492
494 def is_win_9x():
493 def is_win_9x():
495 '''return true if run on windows 95, 98 or me.'''
494 '''return true if run on windows 95, 98 or me.'''
496 try:
495 try:
497 return sys.getwindowsversion()[3] == 1
496 return sys.getwindowsversion()[3] == 1
498 except AttributeError:
497 except AttributeError:
499 return os.name == 'nt' and 'command' in os.environ.get('comspec', '')
498 return os.name == 'nt' and 'command' in os.environ.get('comspec', '')
500
499
501 # Platform specific variants
500 # Platform specific variants
502 if os.name == 'nt':
501 if os.name == 'nt':
503 demandload(globals(), "msvcrt")
502 demandload(globals(), "msvcrt")
504 nulldev = 'NUL:'
503 nulldev = 'NUL:'
505
504
506 class winstdout:
505 class winstdout:
507 '''stdout on windows misbehaves if sent through a pipe'''
506 '''stdout on windows misbehaves if sent through a pipe'''
508
507
509 def __init__(self, fp):
508 def __init__(self, fp):
510 self.fp = fp
509 self.fp = fp
511
510
512 def __getattr__(self, key):
511 def __getattr__(self, key):
513 return getattr(self.fp, key)
512 return getattr(self.fp, key)
514
513
515 def close(self):
514 def close(self):
516 try:
515 try:
517 self.fp.close()
516 self.fp.close()
518 except: pass
517 except: pass
519
518
520 def write(self, s):
519 def write(self, s):
521 try:
520 try:
522 return self.fp.write(s)
521 return self.fp.write(s)
523 except IOError, inst:
522 except IOError, inst:
524 if inst.errno != 0: raise
523 if inst.errno != 0: raise
525 self.close()
524 self.close()
526 raise IOError(errno.EPIPE, 'Broken pipe')
525 raise IOError(errno.EPIPE, 'Broken pipe')
527
526
528 sys.stdout = winstdout(sys.stdout)
527 sys.stdout = winstdout(sys.stdout)
529
528
530 def system_rcpath():
529 def system_rcpath():
531 try:
530 try:
532 return system_rcpath_win32()
531 return system_rcpath_win32()
533 except:
532 except:
534 return [r'c:\mercurial\mercurial.ini']
533 return [r'c:\mercurial\mercurial.ini']
535
534
536 def os_rcpath():
535 def os_rcpath():
537 '''return default os-specific hgrc search path'''
536 '''return default os-specific hgrc search path'''
538 path = system_rcpath()
537 path = system_rcpath()
539 path.append(user_rcpath())
538 path.append(user_rcpath())
540 userprofile = os.environ.get('USERPROFILE')
539 userprofile = os.environ.get('USERPROFILE')
541 if userprofile:
540 if userprofile:
542 path.append(os.path.join(userprofile, 'mercurial.ini'))
541 path.append(os.path.join(userprofile, 'mercurial.ini'))
543 return path
542 return path
544
543
545 def user_rcpath():
544 def user_rcpath():
546 '''return os-specific hgrc search path to the user dir'''
545 '''return os-specific hgrc search path to the user dir'''
547 return os.path.join(os.path.expanduser('~'), 'mercurial.ini')
546 return os.path.join(os.path.expanduser('~'), 'mercurial.ini')
548
547
549 def parse_patch_output(output_line):
548 def parse_patch_output(output_line):
550 """parses the output produced by patch and returns the file name"""
549 """parses the output produced by patch and returns the file name"""
551 pf = output_line[14:]
550 pf = output_line[14:]
552 if pf[0] == '`':
551 if pf[0] == '`':
553 pf = pf[1:-1] # Remove the quotes
552 pf = pf[1:-1] # Remove the quotes
554 return pf
553 return pf
555
554
556 def testpid(pid):
555 def testpid(pid):
557 '''return False if pid dead, True if running or not known'''
556 '''return False if pid dead, True if running or not known'''
558 return True
557 return True
559
558
560 def is_exec(f, last):
559 def is_exec(f, last):
561 return last
560 return last
562
561
563 def set_exec(f, mode):
562 def set_exec(f, mode):
564 pass
563 pass
565
564
566 def set_binary(fd):
565 def set_binary(fd):
567 msvcrt.setmode(fd.fileno(), os.O_BINARY)
566 msvcrt.setmode(fd.fileno(), os.O_BINARY)
568
567
569 def pconvert(path):
568 def pconvert(path):
570 return path.replace("\\", "/")
569 return path.replace("\\", "/")
571
570
572 def localpath(path):
571 def localpath(path):
573 return path.replace('/', '\\')
572 return path.replace('/', '\\')
574
573
575 def normpath(path):
574 def normpath(path):
576 return pconvert(os.path.normpath(path))
575 return pconvert(os.path.normpath(path))
577
576
578 makelock = _makelock_file
577 makelock = _makelock_file
579 readlock = _readlock_file
578 readlock = _readlock_file
580
579
581 def samestat(s1, s2):
580 def samestat(s1, s2):
582 return False
581 return False
583
582
584 def explain_exit(code):
583 def explain_exit(code):
585 return _("exited with status %d") % code, code
584 return _("exited with status %d") % code, code
586
585
587 try:
586 try:
588 # override functions with win32 versions if possible
587 # override functions with win32 versions if possible
589 from util_win32 import *
588 from util_win32 import *
590 if not is_win_9x():
589 if not is_win_9x():
591 posixfile = posixfile_nt
590 posixfile = posixfile_nt
592 except ImportError:
591 except ImportError:
593 pass
592 pass
594
593
595 else:
594 else:
596 nulldev = '/dev/null'
595 nulldev = '/dev/null'
597
596
598 def rcfiles(path):
597 def rcfiles(path):
599 rcs = [os.path.join(path, 'hgrc')]
598 rcs = [os.path.join(path, 'hgrc')]
600 rcdir = os.path.join(path, 'hgrc.d')
599 rcdir = os.path.join(path, 'hgrc.d')
601 try:
600 try:
602 rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
601 rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
603 if f.endswith(".rc")])
602 if f.endswith(".rc")])
604 except OSError, inst: pass
603 except OSError, inst: pass
605 return rcs
604 return rcs
606
605
607 def os_rcpath():
606 def os_rcpath():
608 '''return default os-specific hgrc search path'''
607 '''return default os-specific hgrc search path'''
609 path = []
608 path = []
610 # old mod_python does not set sys.argv
609 # old mod_python does not set sys.argv
611 if len(getattr(sys, 'argv', [])) > 0:
610 if len(getattr(sys, 'argv', [])) > 0:
612 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
611 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
613 '/../etc/mercurial'))
612 '/../etc/mercurial'))
614 path.extend(rcfiles('/etc/mercurial'))
613 path.extend(rcfiles('/etc/mercurial'))
615 path.append(os.path.expanduser('~/.hgrc'))
614 path.append(os.path.expanduser('~/.hgrc'))
616 path = [os.path.normpath(f) for f in path]
615 path = [os.path.normpath(f) for f in path]
617 return path
616 return path
618
617
619 def parse_patch_output(output_line):
618 def parse_patch_output(output_line):
620 """parses the output produced by patch and returns the file name"""
619 """parses the output produced by patch and returns the file name"""
621 pf = output_line[14:]
620 pf = output_line[14:]
622 if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
621 if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
623 pf = pf[1:-1] # Remove the quotes
622 pf = pf[1:-1] # Remove the quotes
624 return pf
623 return pf
625
624
626 def is_exec(f, last):
625 def is_exec(f, last):
627 """check whether a file is executable"""
626 """check whether a file is executable"""
628 return (os.lstat(f).st_mode & 0100 != 0)
627 return (os.lstat(f).st_mode & 0100 != 0)
629
628
630 def set_exec(f, mode):
629 def set_exec(f, mode):
631 s = os.lstat(f).st_mode
630 s = os.lstat(f).st_mode
632 if (s & 0100 != 0) == mode:
631 if (s & 0100 != 0) == mode:
633 return
632 return
634 if mode:
633 if mode:
635 # Turn on +x for every +r bit when making a file executable
634 # Turn on +x for every +r bit when making a file executable
636 # and obey umask.
635 # and obey umask.
637 umask = os.umask(0)
636 umask = os.umask(0)
638 os.umask(umask)
637 os.umask(umask)
639 os.chmod(f, s | (s & 0444) >> 2 & ~umask)
638 os.chmod(f, s | (s & 0444) >> 2 & ~umask)
640 else:
639 else:
641 os.chmod(f, s & 0666)
640 os.chmod(f, s & 0666)
642
641
643 def set_binary(fd):
642 def set_binary(fd):
644 pass
643 pass
645
644
646 def pconvert(path):
645 def pconvert(path):
647 return path
646 return path
648
647
649 def localpath(path):
648 def localpath(path):
650 return path
649 return path
651
650
652 normpath = os.path.normpath
651 normpath = os.path.normpath
653 samestat = os.path.samestat
652 samestat = os.path.samestat
654
653
655 def makelock(info, pathname):
654 def makelock(info, pathname):
656 try:
655 try:
657 os.symlink(info, pathname)
656 os.symlink(info, pathname)
658 except OSError, why:
657 except OSError, why:
659 if why.errno == errno.EEXIST:
658 if why.errno == errno.EEXIST:
660 raise
659 raise
661 else:
660 else:
662 _makelock_file(info, pathname)
661 _makelock_file(info, pathname)
663
662
664 def readlock(pathname):
663 def readlock(pathname):
665 try:
664 try:
666 return os.readlink(pathname)
665 return os.readlink(pathname)
667 except OSError, why:
666 except OSError, why:
668 if why.errno == errno.EINVAL:
667 if why.errno == errno.EINVAL:
669 return _readlock_file(pathname)
668 return _readlock_file(pathname)
670 else:
669 else:
671 raise
670 raise
672
671
673 def testpid(pid):
672 def testpid(pid):
674 '''return False if pid dead, True if running or not sure'''
673 '''return False if pid dead, True if running or not sure'''
675 try:
674 try:
676 os.kill(pid, 0)
675 os.kill(pid, 0)
677 return True
676 return True
678 except OSError, inst:
677 except OSError, inst:
679 return inst.errno != errno.ESRCH
678 return inst.errno != errno.ESRCH
680
679
681 def explain_exit(code):
680 def explain_exit(code):
682 """return a 2-tuple (desc, code) describing a process's status"""
681 """return a 2-tuple (desc, code) describing a process's status"""
683 if os.WIFEXITED(code):
682 if os.WIFEXITED(code):
684 val = os.WEXITSTATUS(code)
683 val = os.WEXITSTATUS(code)
685 return _("exited with status %d") % val, val
684 return _("exited with status %d") % val, val
686 elif os.WIFSIGNALED(code):
685 elif os.WIFSIGNALED(code):
687 val = os.WTERMSIG(code)
686 val = os.WTERMSIG(code)
688 return _("killed by signal %d") % val, val
687 return _("killed by signal %d") % val, val
689 elif os.WIFSTOPPED(code):
688 elif os.WIFSTOPPED(code):
690 val = os.WSTOPSIG(code)
689 val = os.WSTOPSIG(code)
691 return _("stopped by signal %d") % val, val
690 return _("stopped by signal %d") % val, val
692 raise ValueError(_("invalid exit code"))
691 raise ValueError(_("invalid exit code"))
693
692
694 def opener(base, audit=True):
693 def opener(base, audit=True):
695 """
694 """
696 return a function that opens files relative to base
695 return a function that opens files relative to base
697
696
698 this function is used to hide the details of COW semantics and
697 this function is used to hide the details of COW semantics and
699 remote file access from higher level code.
698 remote file access from higher level code.
700 """
699 """
701 p = base
700 p = base
702 audit_p = audit
701 audit_p = audit
703
702
704 def mktempcopy(name):
703 def mktempcopy(name):
705 d, fn = os.path.split(name)
704 d, fn = os.path.split(name)
706 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
705 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
707 os.close(fd)
706 os.close(fd)
708 ofp = posixfile(temp, "wb")
707 ofp = posixfile(temp, "wb")
709 try:
708 try:
710 try:
709 try:
711 ifp = posixfile(name, "rb")
710 ifp = posixfile(name, "rb")
712 except IOError, inst:
711 except IOError, inst:
713 if not getattr(inst, 'filename', None):
712 if not getattr(inst, 'filename', None):
714 inst.filename = name
713 inst.filename = name
715 raise
714 raise
716 for chunk in filechunkiter(ifp):
715 for chunk in filechunkiter(ifp):
717 ofp.write(chunk)
716 ofp.write(chunk)
718 ifp.close()
717 ifp.close()
719 ofp.close()
718 ofp.close()
720 except:
719 except:
721 try: os.unlink(temp)
720 try: os.unlink(temp)
722 except: pass
721 except: pass
723 raise
722 raise
724 st = os.lstat(name)
723 st = os.lstat(name)
725 os.chmod(temp, st.st_mode)
724 os.chmod(temp, st.st_mode)
726 return temp
725 return temp
727
726
728 class atomictempfile(posixfile):
727 class atomictempfile(posixfile):
729 """the file will only be copied when rename is called"""
728 """the file will only be copied when rename is called"""
730 def __init__(self, name, mode):
729 def __init__(self, name, mode):
731 self.__name = name
730 self.__name = name
732 self.temp = mktempcopy(name)
731 self.temp = mktempcopy(name)
733 posixfile.__init__(self, self.temp, mode)
732 posixfile.__init__(self, self.temp, mode)
734 def rename(self):
733 def rename(self):
735 if not self.closed:
734 if not self.closed:
736 posixfile.close(self)
735 posixfile.close(self)
737 rename(self.temp, localpath(self.__name))
736 rename(self.temp, localpath(self.__name))
738 def __del__(self):
737 def __del__(self):
739 if not self.closed:
738 if not self.closed:
740 try:
739 try:
741 os.unlink(self.temp)
740 os.unlink(self.temp)
742 except: pass
741 except: pass
743 posixfile.close(self)
742 posixfile.close(self)
744
743
745 class atomicfile(atomictempfile):
744 class atomicfile(atomictempfile):
746 """the file will only be copied on close"""
745 """the file will only be copied on close"""
747 def __init__(self, name, mode):
746 def __init__(self, name, mode):
748 atomictempfile.__init__(self, name, mode)
747 atomictempfile.__init__(self, name, mode)
749 def close(self):
748 def close(self):
750 self.rename()
749 self.rename()
751 def __del__(self):
750 def __del__(self):
752 self.rename()
751 self.rename()
753
752
754 def o(path, mode="r", text=False, atomic=False, atomictemp=False):
753 def o(path, mode="r", text=False, atomic=False, atomictemp=False):
755 if audit_p:
754 if audit_p:
756 audit_path(path)
755 audit_path(path)
757 f = os.path.join(p, path)
756 f = os.path.join(p, path)
758
757
759 if not text:
758 if not text:
760 mode += "b" # for that other OS
759 mode += "b" # for that other OS
761
760
762 if mode[0] != "r":
761 if mode[0] != "r":
763 try:
762 try:
764 nlink = nlinks(f)
763 nlink = nlinks(f)
765 except OSError:
764 except OSError:
766 d = os.path.dirname(f)
765 d = os.path.dirname(f)
767 if not os.path.isdir(d):
766 if not os.path.isdir(d):
768 os.makedirs(d)
767 os.makedirs(d)
769 else:
768 else:
770 if atomic:
769 if atomic:
771 return atomicfile(f, mode)
770 return atomicfile(f, mode)
772 elif atomictemp:
771 elif atomictemp:
773 return atomictempfile(f, mode)
772 return atomictempfile(f, mode)
774 if nlink > 1:
773 if nlink > 1:
775 rename(mktempcopy(f), f)
774 rename(mktempcopy(f), f)
776 return posixfile(f, mode)
775 return posixfile(f, mode)
777
776
778 return o
777 return o
779
778
780 class chunkbuffer(object):
779 class chunkbuffer(object):
781 """Allow arbitrary sized chunks of data to be efficiently read from an
780 """Allow arbitrary sized chunks of data to be efficiently read from an
782 iterator over chunks of arbitrary size."""
781 iterator over chunks of arbitrary size."""
783
782
784 def __init__(self, in_iter, targetsize = 2**16):
783 def __init__(self, in_iter, targetsize = 2**16):
785 """in_iter is the iterator that's iterating over the input chunks.
784 """in_iter is the iterator that's iterating over the input chunks.
786 targetsize is how big a buffer to try to maintain."""
785 targetsize is how big a buffer to try to maintain."""
787 self.in_iter = iter(in_iter)
786 self.in_iter = iter(in_iter)
788 self.buf = ''
787 self.buf = ''
789 self.targetsize = int(targetsize)
788 self.targetsize = int(targetsize)
790 if self.targetsize <= 0:
789 if self.targetsize <= 0:
791 raise ValueError(_("targetsize must be greater than 0, was %d") %
790 raise ValueError(_("targetsize must be greater than 0, was %d") %
792 targetsize)
791 targetsize)
793 self.iterempty = False
792 self.iterempty = False
794
793
795 def fillbuf(self):
794 def fillbuf(self):
796 """Ignore target size; read every chunk from iterator until empty."""
795 """Ignore target size; read every chunk from iterator until empty."""
797 if not self.iterempty:
796 if not self.iterempty:
798 collector = cStringIO.StringIO()
797 collector = cStringIO.StringIO()
799 collector.write(self.buf)
798 collector.write(self.buf)
800 for ch in self.in_iter:
799 for ch in self.in_iter:
801 collector.write(ch)
800 collector.write(ch)
802 self.buf = collector.getvalue()
801 self.buf = collector.getvalue()
803 self.iterempty = True
802 self.iterempty = True
804
803
805 def read(self, l):
804 def read(self, l):
806 """Read L bytes of data from the iterator of chunks of data.
805 """Read L bytes of data from the iterator of chunks of data.
807 Returns less than L bytes if the iterator runs dry."""
806 Returns less than L bytes if the iterator runs dry."""
808 if l > len(self.buf) and not self.iterempty:
807 if l > len(self.buf) and not self.iterempty:
809 # Clamp to a multiple of self.targetsize
808 # Clamp to a multiple of self.targetsize
810 targetsize = self.targetsize * ((l // self.targetsize) + 1)
809 targetsize = self.targetsize * ((l // self.targetsize) + 1)
811 collector = cStringIO.StringIO()
810 collector = cStringIO.StringIO()
812 collector.write(self.buf)
811 collector.write(self.buf)
813 collected = len(self.buf)
812 collected = len(self.buf)
814 for chunk in self.in_iter:
813 for chunk in self.in_iter:
815 collector.write(chunk)
814 collector.write(chunk)
816 collected += len(chunk)
815 collected += len(chunk)
817 if collected >= targetsize:
816 if collected >= targetsize:
818 break
817 break
819 if collected < targetsize:
818 if collected < targetsize:
820 self.iterempty = True
819 self.iterempty = True
821 self.buf = collector.getvalue()
820 self.buf = collector.getvalue()
822 s, self.buf = self.buf[:l], buffer(self.buf, l)
821 s, self.buf = self.buf[:l], buffer(self.buf, l)
823 return s
822 return s
824
823
825 def filechunkiter(f, size = 65536):
824 def filechunkiter(f, size = 65536):
826 """Create a generator that produces all the data in the file size
825 """Create a generator that produces all the data in the file size
827 (default 65536) bytes at a time. Chunks may be less than size
826 (default 65536) bytes at a time. Chunks may be less than size
828 bytes if the chunk is the last chunk in the file, or the file is a
827 bytes if the chunk is the last chunk in the file, or the file is a
829 socket or some other type of file that sometimes reads less data
828 socket or some other type of file that sometimes reads less data
830 than is requested."""
829 than is requested."""
831 s = f.read(size)
830 s = f.read(size)
832 while len(s) > 0:
831 while len(s) > 0:
833 yield s
832 yield s
834 s = f.read(size)
833 s = f.read(size)
835
834
836 def makedate():
835 def makedate():
837 lt = time.localtime()
836 lt = time.localtime()
838 if lt[8] == 1 and time.daylight:
837 if lt[8] == 1 and time.daylight:
839 tz = time.altzone
838 tz = time.altzone
840 else:
839 else:
841 tz = time.timezone
840 tz = time.timezone
842 return time.mktime(lt), tz
841 return time.mktime(lt), tz
843
842
844 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
843 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
845 """represent a (unixtime, offset) tuple as a localized time.
844 """represent a (unixtime, offset) tuple as a localized time.
846 unixtime is seconds since the epoch, and offset is the time zone's
845 unixtime is seconds since the epoch, and offset is the time zone's
847 number of seconds away from UTC. if timezone is false, do not
846 number of seconds away from UTC. if timezone is false, do not
848 append time zone to string."""
847 append time zone to string."""
849 t, tz = date or makedate()
848 t, tz = date or makedate()
850 s = time.strftime(format, time.gmtime(float(t) - tz))
849 s = time.strftime(format, time.gmtime(float(t) - tz))
851 if timezone:
850 if timezone:
852 s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
851 s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
853 return s
852 return s
854
853
855 def shortuser(user):
854 def shortuser(user):
856 """Return a short representation of a user name or email address."""
855 """Return a short representation of a user name or email address."""
857 f = user.find('@')
856 f = user.find('@')
858 if f >= 0:
857 if f >= 0:
859 user = user[:f]
858 user = user[:f]
860 f = user.find('<')
859 f = user.find('<')
861 if f >= 0:
860 if f >= 0:
862 user = user[f+1:]
861 user = user[f+1:]
863 return user
862 return user
864
863
865 def walkrepos(path):
864 def walkrepos(path):
866 '''yield every hg repository under path, recursively.'''
865 '''yield every hg repository under path, recursively.'''
867 def errhandler(err):
866 def errhandler(err):
868 if err.filename == path:
867 if err.filename == path:
869 raise err
868 raise err
870
869
871 for root, dirs, files in os.walk(path, onerror=errhandler):
870 for root, dirs, files in os.walk(path, onerror=errhandler):
872 for d in dirs:
871 for d in dirs:
873 if d == '.hg':
872 if d == '.hg':
874 yield root
873 yield root
875 dirs[:] = []
874 dirs[:] = []
876 break
875 break
877
876
878 _rcpath = None
877 _rcpath = None
879
878
880 def rcpath():
879 def rcpath():
881 '''return hgrc search path. if env var HGRCPATH is set, use it.
880 '''return hgrc search path. if env var HGRCPATH is set, use it.
882 for each item in path, if directory, use files ending in .rc,
881 for each item in path, if directory, use files ending in .rc,
883 else use item.
882 else use item.
884 make HGRCPATH empty to only look in .hg/hgrc of current repo.
883 make HGRCPATH empty to only look in .hg/hgrc of current repo.
885 if no HGRCPATH, use default os-specific path.'''
884 if no HGRCPATH, use default os-specific path.'''
886 global _rcpath
885 global _rcpath
887 if _rcpath is None:
886 if _rcpath is None:
888 if 'HGRCPATH' in os.environ:
887 if 'HGRCPATH' in os.environ:
889 _rcpath = []
888 _rcpath = []
890 for p in os.environ['HGRCPATH'].split(os.pathsep):
889 for p in os.environ['HGRCPATH'].split(os.pathsep):
891 if not p: continue
890 if not p: continue
892 if os.path.isdir(p):
891 if os.path.isdir(p):
893 for f in os.listdir(p):
892 for f in os.listdir(p):
894 if f.endswith('.rc'):
893 if f.endswith('.rc'):
895 _rcpath.append(os.path.join(p, f))
894 _rcpath.append(os.path.join(p, f))
896 else:
895 else:
897 _rcpath.append(p)
896 _rcpath.append(p)
898 else:
897 else:
899 _rcpath = os_rcpath()
898 _rcpath = os_rcpath()
900 return _rcpath
899 return _rcpath
General Comments 0
You need to be logged in to leave comments. Login now