##// END OF EJS Templates
use xrange instead of range
Benoit Boissinot -
r3473:0e68608b default
parent child Browse files
Show More
@@ -1,309 +1,309 b''
1 1 # Minimal support for git commands on an hg repository
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from mercurial.demandload import *
9 9 demandload(globals(), 'time sys signal os')
10 10 demandload(globals(), 'mercurial:hg,fancyopts,commands,ui,util,patch,revlog')
11 11
12 12 def difftree(ui, repo, node1=None, node2=None, *files, **opts):
13 13 """diff trees from two commits"""
14 14 def __difftree(repo, node1, node2, files=[]):
15 15 if node2:
16 16 change = repo.changelog.read(node2)
17 17 mmap2 = repo.manifest.read(change[0])
18 18 status = repo.status(node1, node2, files=files)[:5]
19 19 modified, added, removed, deleted, unknown = status
20 20 else:
21 21 status = repo.status(node1, files=files)[:5]
22 22 modified, added, removed, deleted, unknown = status
23 23 if not node1:
24 24 node1 = repo.dirstate.parents()[0]
25 25
26 26 change = repo.changelog.read(node1)
27 27 mmap = repo.manifest.read(change[0])
28 28 empty = hg.short(hg.nullid)
29 29
30 30 for f in modified:
31 31 # TODO get file permissions
32 32 print ":100664 100664 %s %s M\t%s\t%s" % (hg.short(mmap[f]),
33 33 hg.short(mmap2[f]),
34 34 f, f)
35 35 for f in added:
36 36 print ":000000 100664 %s %s N\t%s\t%s" % (empty,
37 37 hg.short(mmap2[f]),
38 38 f, f)
39 39 for f in removed:
40 40 print ":100664 000000 %s %s D\t%s\t%s" % (hg.short(mmap[f]),
41 41 empty,
42 42 f, f)
43 43 ##
44 44
45 45 while True:
46 46 if opts['stdin']:
47 47 try:
48 48 line = raw_input().split(' ')
49 49 node1 = line[0]
50 50 if len(line) > 1:
51 51 node2 = line[1]
52 52 else:
53 53 node2 = None
54 54 except EOFError:
55 55 break
56 56 node1 = repo.lookup(node1)
57 57 if node2:
58 58 node2 = repo.lookup(node2)
59 59 else:
60 60 node2 = node1
61 61 node1 = repo.changelog.parents(node1)[0]
62 62 if opts['patch']:
63 63 if opts['pretty']:
64 64 catcommit(repo, node2, "")
65 65 patch.diff(repo, node1, node2,
66 66 files=files,
67 67 opts=patch.diffopts(ui, {'git': True}))
68 68 else:
69 69 __difftree(repo, node1, node2, files=files)
70 70 if not opts['stdin']:
71 71 break
72 72
73 73 def catcommit(repo, n, prefix, changes=None):
74 74 nlprefix = '\n' + prefix;
75 75 (p1, p2) = repo.changelog.parents(n)
76 76 (h, h1, h2) = map(hg.short, (n, p1, p2))
77 77 (i1, i2) = map(repo.changelog.rev, (p1, p2))
78 78 if not changes:
79 79 changes = repo.changelog.read(n)
80 80 print "tree %s" % (hg.short(changes[0]))
81 81 if i1 != -1: print "parent %s" % (h1)
82 82 if i2 != -1: print "parent %s" % (h2)
83 83 date_ar = changes[2]
84 84 date = int(float(date_ar[0]))
85 85 lines = changes[4].splitlines()
86 86 if lines and lines[-1].startswith('committer:'):
87 87 committer = lines[-1].split(': ')[1].rstrip()
88 88 else:
89 89 committer = changes[1]
90 90
91 91 print "author %s %s %s" % (changes[1], date, date_ar[1])
92 92 print "committer %s %s %s" % (committer, date, date_ar[1])
93 93 print "revision %d" % repo.changelog.rev(n)
94 94 print ""
95 95 if prefix != "":
96 96 print "%s%s" % (prefix, changes[4].replace('\n', nlprefix).strip())
97 97 else:
98 98 print changes[4]
99 99 if prefix:
100 100 sys.stdout.write('\0')
101 101
102 102 def base(ui, repo, node1, node2):
103 103 """Output common ancestor information"""
104 104 node1 = repo.lookup(node1)
105 105 node2 = repo.lookup(node2)
106 106 n = repo.changelog.ancestor(node1, node2)
107 107 print hg.short(n)
108 108
109 109 def catfile(ui, repo, type=None, r=None, **opts):
110 110 """cat a specific revision"""
111 111 # in stdin mode, every line except the commit is prefixed with two
112 112 # spaces. This way the our caller can find the commit without magic
113 113 # strings
114 114 #
115 115 prefix = ""
116 116 if opts['stdin']:
117 117 try:
118 118 (type, r) = raw_input().split(' ');
119 119 prefix = " "
120 120 except EOFError:
121 121 return
122 122
123 123 else:
124 124 if not type or not r:
125 125 ui.warn("cat-file: type or revision not supplied\n")
126 126 commands.help_(ui, 'cat-file')
127 127
128 128 while r:
129 129 if type != "commit":
130 130 sys.stderr.write("aborting hg cat-file only understands commits\n")
131 131 sys.exit(1);
132 132 n = repo.lookup(r)
133 133 catcommit(repo, n, prefix)
134 134 if opts['stdin']:
135 135 try:
136 136 (type, r) = raw_input().split(' ');
137 137 except EOFError:
138 138 break
139 139 else:
140 140 break
141 141
142 142 # git rev-tree is a confusing thing. You can supply a number of
143 143 # commit sha1s on the command line, and it walks the commit history
144 144 # telling you which commits are reachable from the supplied ones via
145 145 # a bitmask based on arg position.
146 146 # you can specify a commit to stop at by starting the sha1 with ^
147 147 def revtree(args, repo, full="tree", maxnr=0, parents=False):
148 148 def chlogwalk():
149 149 ch = repo.changelog
150 150 count = ch.count()
151 151 i = count
152 152 l = [0] * 100
153 153 chunk = 100
154 154 while True:
155 155 if chunk > i:
156 156 chunk = i
157 157 i = 0
158 158 else:
159 159 i -= chunk
160 160
161 161 for x in xrange(0, chunk):
162 162 if i + x >= count:
163 163 l[chunk - x:] = [0] * (chunk - x)
164 164 break
165 165 if full != None:
166 166 l[x] = ch.read(ch.node(i + x))
167 167 else:
168 168 l[x] = 1
169 169 for x in xrange(chunk-1, -1, -1):
170 170 if l[x] != 0:
171 171 yield (i + x, full != None and l[x] or None)
172 172 if i == 0:
173 173 break
174 174
175 175 # calculate and return the reachability bitmask for sha
176 176 def is_reachable(ar, reachable, sha):
177 177 if len(ar) == 0:
178 178 return 1
179 179 mask = 0
180 for i in range(len(ar)):
180 for i in xrange(len(ar)):
181 181 if sha in reachable[i]:
182 182 mask |= 1 << i
183 183
184 184 return mask
185 185
186 186 reachable = []
187 187 stop_sha1 = []
188 188 want_sha1 = []
189 189 count = 0
190 190
191 191 # figure out which commits they are asking for and which ones they
192 192 # want us to stop on
193 for i in range(len(args)):
193 for i in xrange(len(args)):
194 194 if args[i].startswith('^'):
195 195 s = repo.lookup(args[i][1:])
196 196 stop_sha1.append(s)
197 197 want_sha1.append(s)
198 198 elif args[i] != 'HEAD':
199 199 want_sha1.append(repo.lookup(args[i]))
200 200
201 201 # calculate the graph for the supplied commits
202 for i in range(len(want_sha1)):
202 for i in xrange(len(want_sha1)):
203 203 reachable.append({});
204 204 n = want_sha1[i];
205 205 visit = [n];
206 206 reachable[i][n] = 1
207 207 while visit:
208 208 n = visit.pop(0)
209 209 if n in stop_sha1:
210 210 continue
211 211 for p in repo.changelog.parents(n):
212 212 if p not in reachable[i]:
213 213 reachable[i][p] = 1
214 214 visit.append(p)
215 215 if p in stop_sha1:
216 216 continue
217 217
218 218 # walk the repository looking for commits that are in our
219 219 # reachability graph
220 220 for i, changes in chlogwalk():
221 221 n = repo.changelog.node(i)
222 222 mask = is_reachable(want_sha1, reachable, n)
223 223 if mask:
224 224 parentstr = ""
225 225 if parents:
226 226 pp = repo.changelog.parents(n)
227 227 if pp[0] != hg.nullid:
228 228 parentstr += " " + hg.short(pp[0])
229 229 if pp[1] != hg.nullid:
230 230 parentstr += " " + hg.short(pp[1])
231 231 if not full:
232 232 print hg.short(n) + parentstr
233 233 elif full == "commit":
234 234 print hg.short(n) + parentstr
235 235 catcommit(repo, n, ' ', changes)
236 236 else:
237 237 (p1, p2) = repo.changelog.parents(n)
238 238 (h, h1, h2) = map(hg.short, (n, p1, p2))
239 239 (i1, i2) = map(repo.changelog.rev, (p1, p2))
240 240
241 241 date = changes[2][0]
242 242 print "%s %s:%s" % (date, h, mask),
243 243 mask = is_reachable(want_sha1, reachable, p1)
244 244 if i1 != -1 and mask > 0:
245 245 print "%s:%s " % (h1, mask),
246 246 mask = is_reachable(want_sha1, reachable, p2)
247 247 if i2 != -1 and mask > 0:
248 248 print "%s:%s " % (h2, mask),
249 249 print ""
250 250 if maxnr and count >= maxnr:
251 251 break
252 252 count += 1
253 253
254 254 def revparse(ui, repo, *revs, **opts):
255 255 """Parse given revisions"""
256 256 def revstr(rev):
257 257 if rev == 'HEAD':
258 258 rev = 'tip'
259 259 return revlog.hex(repo.lookup(rev))
260 260
261 261 for r in revs:
262 262 revrange = r.split(':', 1)
263 263 ui.write('%s\n' % revstr(revrange[0]))
264 264 if len(revrange) == 2:
265 265 ui.write('^%s\n' % revstr(revrange[1]))
266 266
267 267 # git rev-list tries to order things by date, and has the ability to stop
268 268 # at a given commit without walking the whole repo. TODO add the stop
269 269 # parameter
270 270 def revlist(ui, repo, *revs, **opts):
271 271 """print revisions"""
272 272 if opts['header']:
273 273 full = "commit"
274 274 else:
275 275 full = None
276 276 copy = [x for x in revs]
277 277 revtree(copy, repo, full, opts['max_count'], opts['parents'])
278 278
279 279 def view(ui, repo, *etc, **opts):
280 280 "start interactive history viewer"
281 281 os.chdir(repo.root)
282 282 optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
283 283 cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, " ".join(etc))
284 284 ui.debug("running %s\n" % cmd)
285 285 os.system(cmd)
286 286
287 287 cmdtable = {
288 288 "view": (view,
289 289 [('l', 'limit', '', 'limit number of changes displayed')],
290 290 'hg view [-l LIMIT] [REVRANGE]'),
291 291 "debug-diff-tree": (difftree, [('p', 'patch', None, 'generate patch'),
292 292 ('r', 'recursive', None, 'recursive'),
293 293 ('P', 'pretty', None, 'pretty'),
294 294 ('s', 'stdin', None, 'stdin'),
295 295 ('C', 'copy', None, 'detect copies'),
296 296 ('S', 'search', "", 'search')],
297 297 "hg git-diff-tree [options] node1 node2 [files...]"),
298 298 "debug-cat-file": (catfile, [('s', 'stdin', None, 'stdin')],
299 299 "hg debug-cat-file [options] type file"),
300 300 "debug-merge-base": (base, [], "hg debug-merge-base node node"),
301 301 'debug-rev-parse': (revparse,
302 302 [('', 'default', '', 'ignored')],
303 303 "hg debug-rev-parse rev"),
304 304 "debug-rev-list": (revlist, [('H', 'header', None, 'header'),
305 305 ('t', 'topo-order', None, 'topo-order'),
306 306 ('p', 'parents', None, 'parents'),
307 307 ('n', 'max-count', 0, 'max-count')],
308 308 "hg debug-rev-list [options] revs"),
309 309 }
@@ -1,2128 +1,2128 b''
1 1 # queue.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 '''patch management and development
9 9
10 10 This extension lets you work with a stack of patches in a Mercurial
11 11 repository. It manages two stacks of patches - all known patches, and
12 12 applied patches (subset of known patches).
13 13
14 14 Known patches are represented as patch files in the .hg/patches
15 15 directory. Applied patches are both patch files and changesets.
16 16
17 17 Common tasks (use "hg help command" for more details):
18 18
19 19 prepare repository to work with patches qinit
20 20 create new patch qnew
21 21 import existing patch qimport
22 22
23 23 print patch series qseries
24 24 print applied patches qapplied
25 25 print name of top applied patch qtop
26 26
27 27 add known patch to applied stack qpush
28 28 remove patch from applied stack qpop
29 29 refresh contents of top applied patch qrefresh
30 30 '''
31 31
32 32 from mercurial.demandload import *
33 33 from mercurial.i18n import gettext as _
34 34 from mercurial import commands
35 35 demandload(globals(), "os sys re struct traceback errno bz2")
36 36 demandload(globals(), "mercurial:cmdutil,hg,patch,revlog,ui,util")
37 37
38 38 commands.norepo += " qclone qversion"
39 39
40 40 class statusentry:
41 41 def __init__(self, rev, name=None):
42 42 if not name:
43 43 fields = rev.split(':', 1)
44 44 if len(fields) == 2:
45 45 self.rev, self.name = fields
46 46 else:
47 47 self.rev, self.name = None, None
48 48 else:
49 49 self.rev, self.name = rev, name
50 50
51 51 def __str__(self):
52 52 return self.rev + ':' + self.name
53 53
54 54 class queue:
55 55 def __init__(self, ui, path, patchdir=None):
56 56 self.basepath = path
57 57 self.path = patchdir or os.path.join(path, "patches")
58 58 self.opener = util.opener(self.path)
59 59 self.ui = ui
60 60 self.applied = []
61 61 self.full_series = []
62 62 self.applied_dirty = 0
63 63 self.series_dirty = 0
64 64 self.series_path = "series"
65 65 self.status_path = "status"
66 66 self.guards_path = "guards"
67 67 self.active_guards = None
68 68 self.guards_dirty = False
69 69 self._diffopts = None
70 70
71 71 if os.path.exists(self.join(self.series_path)):
72 72 self.full_series = self.opener(self.series_path).read().splitlines()
73 73 self.parse_series()
74 74
75 75 if os.path.exists(self.join(self.status_path)):
76 76 lines = self.opener(self.status_path).read().splitlines()
77 77 self.applied = [statusentry(l) for l in lines]
78 78
79 79 def diffopts(self):
80 80 if self._diffopts is None:
81 81 self._diffopts = patch.diffopts(self.ui)
82 82 return self._diffopts
83 83
84 84 def join(self, *p):
85 85 return os.path.join(self.path, *p)
86 86
87 87 def find_series(self, patch):
88 88 pre = re.compile("(\s*)([^#]+)")
89 89 index = 0
90 90 for l in self.full_series:
91 91 m = pre.match(l)
92 92 if m:
93 93 s = m.group(2)
94 94 s = s.rstrip()
95 95 if s == patch:
96 96 return index
97 97 index += 1
98 98 return None
99 99
100 100 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
101 101
102 102 def parse_series(self):
103 103 self.series = []
104 104 self.series_guards = []
105 105 for l in self.full_series:
106 106 h = l.find('#')
107 107 if h == -1:
108 108 patch = l
109 109 comment = ''
110 110 elif h == 0:
111 111 continue
112 112 else:
113 113 patch = l[:h]
114 114 comment = l[h:]
115 115 patch = patch.strip()
116 116 if patch:
117 117 if patch in self.series:
118 118 raise util.Abort(_('%s appears more than once in %s') %
119 119 (patch, self.join(self.series_path)))
120 120 self.series.append(patch)
121 121 self.series_guards.append(self.guard_re.findall(comment))
122 122
123 123 def check_guard(self, guard):
124 124 bad_chars = '# \t\r\n\f'
125 125 first = guard[0]
126 126 for c in '-+':
127 127 if first == c:
128 128 return (_('guard %r starts with invalid character: %r') %
129 129 (guard, c))
130 130 for c in bad_chars:
131 131 if c in guard:
132 132 return _('invalid character in guard %r: %r') % (guard, c)
133 133
134 134 def set_active(self, guards):
135 135 for guard in guards:
136 136 bad = self.check_guard(guard)
137 137 if bad:
138 138 raise util.Abort(bad)
139 139 guards = dict.fromkeys(guards).keys()
140 140 guards.sort()
141 141 self.ui.debug('active guards: %s\n' % ' '.join(guards))
142 142 self.active_guards = guards
143 143 self.guards_dirty = True
144 144
145 145 def active(self):
146 146 if self.active_guards is None:
147 147 self.active_guards = []
148 148 try:
149 149 guards = self.opener(self.guards_path).read().split()
150 150 except IOError, err:
151 151 if err.errno != errno.ENOENT: raise
152 152 guards = []
153 153 for i, guard in enumerate(guards):
154 154 bad = self.check_guard(guard)
155 155 if bad:
156 156 self.ui.warn('%s:%d: %s\n' %
157 157 (self.join(self.guards_path), i + 1, bad))
158 158 else:
159 159 self.active_guards.append(guard)
160 160 return self.active_guards
161 161
162 162 def set_guards(self, idx, guards):
163 163 for g in guards:
164 164 if len(g) < 2:
165 165 raise util.Abort(_('guard %r too short') % g)
166 166 if g[0] not in '-+':
167 167 raise util.Abort(_('guard %r starts with invalid char') % g)
168 168 bad = self.check_guard(g[1:])
169 169 if bad:
170 170 raise util.Abort(bad)
171 171 drop = self.guard_re.sub('', self.full_series[idx])
172 172 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
173 173 self.parse_series()
174 174 self.series_dirty = True
175 175
176 176 def pushable(self, idx):
177 177 if isinstance(idx, str):
178 178 idx = self.series.index(idx)
179 179 patchguards = self.series_guards[idx]
180 180 if not patchguards:
181 181 return True, None
182 182 default = False
183 183 guards = self.active()
184 184 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
185 185 if exactneg:
186 186 return False, exactneg[0]
187 187 pos = [g for g in patchguards if g[0] == '+']
188 188 exactpos = [g for g in pos if g[1:] in guards]
189 189 if pos:
190 190 if exactpos:
191 191 return True, exactpos[0]
192 192 return False, pos
193 193 return True, ''
194 194
195 195 def explain_pushable(self, idx, all_patches=False):
196 196 write = all_patches and self.ui.write or self.ui.warn
197 197 if all_patches or self.ui.verbose:
198 198 if isinstance(idx, str):
199 199 idx = self.series.index(idx)
200 200 pushable, why = self.pushable(idx)
201 201 if all_patches and pushable:
202 202 if why is None:
203 203 write(_('allowing %s - no guards in effect\n') %
204 204 self.series[idx])
205 205 else:
206 206 if not why:
207 207 write(_('allowing %s - no matching negative guards\n') %
208 208 self.series[idx])
209 209 else:
210 210 write(_('allowing %s - guarded by %r\n') %
211 211 (self.series[idx], why))
212 212 if not pushable:
213 213 if why:
214 214 write(_('skipping %s - guarded by %r\n') %
215 215 (self.series[idx], ' '.join(why)))
216 216 else:
217 217 write(_('skipping %s - no matching guards\n') %
218 218 self.series[idx])
219 219
220 220 def save_dirty(self):
221 221 def write_list(items, path):
222 222 fp = self.opener(path, 'w')
223 223 for i in items:
224 224 print >> fp, i
225 225 fp.close()
226 226 if self.applied_dirty: write_list(map(str, self.applied), self.status_path)
227 227 if self.series_dirty: write_list(self.full_series, self.series_path)
228 228 if self.guards_dirty: write_list(self.active_guards, self.guards_path)
229 229
230 230 def readheaders(self, patch):
231 231 def eatdiff(lines):
232 232 while lines:
233 233 l = lines[-1]
234 234 if (l.startswith("diff -") or
235 235 l.startswith("Index:") or
236 236 l.startswith("===========")):
237 237 del lines[-1]
238 238 else:
239 239 break
240 240 def eatempty(lines):
241 241 while lines:
242 242 l = lines[-1]
243 243 if re.match('\s*$', l):
244 244 del lines[-1]
245 245 else:
246 246 break
247 247
248 248 pf = self.join(patch)
249 249 message = []
250 250 comments = []
251 251 user = None
252 252 date = None
253 253 format = None
254 254 subject = None
255 255 diffstart = 0
256 256
257 257 for line in file(pf):
258 258 line = line.rstrip()
259 259 if line.startswith('diff --git'):
260 260 diffstart = 2
261 261 break
262 262 if diffstart:
263 263 if line.startswith('+++ '):
264 264 diffstart = 2
265 265 break
266 266 if line.startswith("--- "):
267 267 diffstart = 1
268 268 continue
269 269 elif format == "hgpatch":
270 270 # parse values when importing the result of an hg export
271 271 if line.startswith("# User "):
272 272 user = line[7:]
273 273 elif line.startswith("# Date "):
274 274 date = line[7:]
275 275 elif not line.startswith("# ") and line:
276 276 message.append(line)
277 277 format = None
278 278 elif line == '# HG changeset patch':
279 279 format = "hgpatch"
280 280 elif (format != "tagdone" and (line.startswith("Subject: ") or
281 281 line.startswith("subject: "))):
282 282 subject = line[9:]
283 283 format = "tag"
284 284 elif (format != "tagdone" and (line.startswith("From: ") or
285 285 line.startswith("from: "))):
286 286 user = line[6:]
287 287 format = "tag"
288 288 elif format == "tag" and line == "":
289 289 # when looking for tags (subject: from: etc) they
290 290 # end once you find a blank line in the source
291 291 format = "tagdone"
292 292 elif message or line:
293 293 message.append(line)
294 294 comments.append(line)
295 295
296 296 eatdiff(message)
297 297 eatdiff(comments)
298 298 eatempty(message)
299 299 eatempty(comments)
300 300
301 301 # make sure message isn't empty
302 302 if format and format.startswith("tag") and subject:
303 303 message.insert(0, "")
304 304 message.insert(0, subject)
305 305 return (message, comments, user, date, diffstart > 1)
306 306
307 307 def printdiff(self, repo, node1, node2=None, files=None,
308 308 fp=None, changes=None, opts={}):
309 309 fns, matchfn, anypats = cmdutil.matchpats(repo, files, opts)
310 310
311 311 patch.diff(repo, node1, node2, fns, match=matchfn,
312 312 fp=fp, changes=changes, opts=self.diffopts())
313 313
314 314 def mergeone(self, repo, mergeq, head, patch, rev, wlock):
315 315 # first try just applying the patch
316 316 (err, n) = self.apply(repo, [ patch ], update_status=False,
317 317 strict=True, merge=rev, wlock=wlock)
318 318
319 319 if err == 0:
320 320 return (err, n)
321 321
322 322 if n is None:
323 323 raise util.Abort(_("apply failed for patch %s") % patch)
324 324
325 325 self.ui.warn("patch didn't work out, merging %s\n" % patch)
326 326
327 327 # apply failed, strip away that rev and merge.
328 328 hg.clean(repo, head, wlock=wlock)
329 329 self.strip(repo, n, update=False, backup='strip', wlock=wlock)
330 330
331 331 c = repo.changelog.read(rev)
332 332 ret = hg.merge(repo, rev, wlock=wlock)
333 333 if ret:
334 334 raise util.Abort(_("update returned %d") % ret)
335 335 n = repo.commit(None, c[4], c[1], force=1, wlock=wlock)
336 336 if n == None:
337 337 raise util.Abort(_("repo commit failed"))
338 338 try:
339 339 message, comments, user, date, patchfound = mergeq.readheaders(patch)
340 340 except:
341 341 raise util.Abort(_("unable to read %s") % patch)
342 342
343 343 patchf = self.opener(patch, "w")
344 344 if comments:
345 345 comments = "\n".join(comments) + '\n\n'
346 346 patchf.write(comments)
347 347 self.printdiff(repo, head, n, fp=patchf)
348 348 patchf.close()
349 349 return (0, n)
350 350
351 351 def qparents(self, repo, rev=None):
352 352 if rev is None:
353 353 (p1, p2) = repo.dirstate.parents()
354 354 if p2 == revlog.nullid:
355 355 return p1
356 356 if len(self.applied) == 0:
357 357 return None
358 358 return revlog.bin(self.applied[-1].rev)
359 359 pp = repo.changelog.parents(rev)
360 360 if pp[1] != revlog.nullid:
361 361 arevs = [ x.rev for x in self.applied ]
362 362 p0 = revlog.hex(pp[0])
363 363 p1 = revlog.hex(pp[1])
364 364 if p0 in arevs:
365 365 return pp[0]
366 366 if p1 in arevs:
367 367 return pp[1]
368 368 return pp[0]
369 369
370 370 def mergepatch(self, repo, mergeq, series, wlock):
371 371 if len(self.applied) == 0:
372 372 # each of the patches merged in will have two parents. This
373 373 # can confuse the qrefresh, qdiff, and strip code because it
374 374 # needs to know which parent is actually in the patch queue.
375 375 # so, we insert a merge marker with only one parent. This way
376 376 # the first patch in the queue is never a merge patch
377 377 #
378 378 pname = ".hg.patches.merge.marker"
379 379 n = repo.commit(None, '[mq]: merge marker', user=None, force=1,
380 380 wlock=wlock)
381 381 self.applied.append(statusentry(revlog.hex(n), pname))
382 382 self.applied_dirty = 1
383 383
384 384 head = self.qparents(repo)
385 385
386 386 for patch in series:
387 387 patch = mergeq.lookup(patch, strict=True)
388 388 if not patch:
389 389 self.ui.warn("patch %s does not exist\n" % patch)
390 390 return (1, None)
391 391 pushable, reason = self.pushable(patch)
392 392 if not pushable:
393 393 self.explain_pushable(patch, all_patches=True)
394 394 continue
395 395 info = mergeq.isapplied(patch)
396 396 if not info:
397 397 self.ui.warn("patch %s is not applied\n" % patch)
398 398 return (1, None)
399 399 rev = revlog.bin(info[1])
400 400 (err, head) = self.mergeone(repo, mergeq, head, patch, rev, wlock)
401 401 if head:
402 402 self.applied.append(statusentry(revlog.hex(head), patch))
403 403 self.applied_dirty = 1
404 404 if err:
405 405 return (err, head)
406 406 return (0, head)
407 407
408 408 def patch(self, repo, patchfile):
409 409 '''Apply patchfile to the working directory.
410 410 patchfile: file name of patch'''
411 411 files = {}
412 412 try:
413 413 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
414 414 files=files)
415 415 except Exception, inst:
416 416 self.ui.note(str(inst) + '\n')
417 417 if not self.ui.verbose:
418 418 self.ui.warn("patch failed, unable to continue (try -v)\n")
419 419 return (False, files, False)
420 420
421 421 return (True, files, fuzz)
422 422
423 423 def apply(self, repo, series, list=False, update_status=True,
424 424 strict=False, patchdir=None, merge=None, wlock=None):
425 425 # TODO unify with commands.py
426 426 if not patchdir:
427 427 patchdir = self.path
428 428 err = 0
429 429 if not wlock:
430 430 wlock = repo.wlock()
431 431 lock = repo.lock()
432 432 tr = repo.transaction()
433 433 n = None
434 434 for patchname in series:
435 435 pushable, reason = self.pushable(patchname)
436 436 if not pushable:
437 437 self.explain_pushable(patchname, all_patches=True)
438 438 continue
439 439 self.ui.warn("applying %s\n" % patchname)
440 440 pf = os.path.join(patchdir, patchname)
441 441
442 442 try:
443 443 message, comments, user, date, patchfound = self.readheaders(patchname)
444 444 except:
445 445 self.ui.warn("Unable to read %s\n" % patchname)
446 446 err = 1
447 447 break
448 448
449 449 if not message:
450 450 message = "imported patch %s\n" % patchname
451 451 else:
452 452 if list:
453 453 message.append("\nimported patch %s" % patchname)
454 454 message = '\n'.join(message)
455 455
456 456 (patcherr, files, fuzz) = self.patch(repo, pf)
457 457 patcherr = not patcherr
458 458
459 459 if merge and files:
460 460 # Mark as merged and update dirstate parent info
461 461 repo.dirstate.update(repo.dirstate.filterfiles(files.keys()), 'm')
462 462 p1, p2 = repo.dirstate.parents()
463 463 repo.dirstate.setparents(p1, merge)
464 464 files = patch.updatedir(self.ui, repo, files, wlock=wlock)
465 465 n = repo.commit(files, message, user, date, force=1, lock=lock,
466 466 wlock=wlock)
467 467
468 468 if n == None:
469 469 raise util.Abort(_("repo commit failed"))
470 470
471 471 if update_status:
472 472 self.applied.append(statusentry(revlog.hex(n), patchname))
473 473
474 474 if patcherr:
475 475 if not patchfound:
476 476 self.ui.warn("patch %s is empty\n" % patchname)
477 477 err = 0
478 478 else:
479 479 self.ui.warn("patch failed, rejects left in working dir\n")
480 480 err = 1
481 481 break
482 482
483 483 if fuzz and strict:
484 484 self.ui.warn("fuzz found when applying patch, stopping\n")
485 485 err = 1
486 486 break
487 487 tr.close()
488 488 return (err, n)
489 489
490 490 def delete(self, repo, patches, opts):
491 491 realpatches = []
492 492 for patch in patches:
493 493 patch = self.lookup(patch, strict=True)
494 494 info = self.isapplied(patch)
495 495 if info:
496 496 raise util.Abort(_("cannot delete applied patch %s") % patch)
497 497 if patch not in self.series:
498 498 raise util.Abort(_("patch %s not in series file") % patch)
499 499 realpatches.append(patch)
500 500
501 501 appliedbase = 0
502 502 if opts.get('rev'):
503 503 if not self.applied:
504 504 raise util.Abort(_('no patches applied'))
505 505 revs = [int(r) for r in cmdutil.revrange(ui, repo, opts['rev'])]
506 506 if len(revs) > 1 and revs[0] > revs[1]:
507 507 revs.reverse()
508 508 for rev in revs:
509 509 if appliedbase >= len(self.applied):
510 510 raise util.Abort(_("revision %d is not managed") % rev)
511 511
512 512 base = revlog.bin(self.applied[appliedbase].rev)
513 513 node = repo.changelog.node(rev)
514 514 if node != base:
515 515 raise util.Abort(_("cannot delete revision %d above "
516 516 "applied patches") % rev)
517 517 realpatches.append(self.applied[appliedbase].name)
518 518 appliedbase += 1
519 519
520 520 if not opts.get('keep'):
521 521 r = self.qrepo()
522 522 if r:
523 523 r.remove(realpatches, True)
524 524 else:
525 525 for p in realpatches:
526 526 os.unlink(self.join(p))
527 527
528 528 if appliedbase:
529 529 del self.applied[:appliedbase]
530 530 self.applied_dirty = 1
531 531 indices = [self.find_series(p) for p in realpatches]
532 532 indices.sort()
533 533 for i in indices[-1::-1]:
534 534 del self.full_series[i]
535 535 self.parse_series()
536 536 self.series_dirty = 1
537 537
538 538 def check_toppatch(self, repo):
539 539 if len(self.applied) > 0:
540 540 top = revlog.bin(self.applied[-1].rev)
541 541 pp = repo.dirstate.parents()
542 542 if top not in pp:
543 543 raise util.Abort(_("queue top not at same revision as working directory"))
544 544 return top
545 545 return None
546 546 def check_localchanges(self, repo, force=False, refresh=True):
547 547 m, a, r, d = repo.status()[:4]
548 548 if m or a or r or d:
549 549 if not force:
550 550 if refresh:
551 551 raise util.Abort(_("local changes found, refresh first"))
552 552 else:
553 553 raise util.Abort(_("local changes found"))
554 554 return m, a, r, d
555 555 def new(self, repo, patch, msg=None, force=None):
556 556 if os.path.exists(self.join(patch)):
557 557 raise util.Abort(_('patch "%s" already exists') % patch)
558 558 m, a, r, d = self.check_localchanges(repo, force)
559 559 commitfiles = m + a + r
560 560 self.check_toppatch(repo)
561 561 wlock = repo.wlock()
562 562 insert = self.full_series_end()
563 563 if msg:
564 564 n = repo.commit(commitfiles, "[mq]: %s" % msg, force=True,
565 565 wlock=wlock)
566 566 else:
567 567 n = repo.commit(commitfiles,
568 568 "New patch: %s" % patch, force=True, wlock=wlock)
569 569 if n == None:
570 570 raise util.Abort(_("repo commit failed"))
571 571 self.full_series[insert:insert] = [patch]
572 572 self.applied.append(statusentry(revlog.hex(n), patch))
573 573 self.parse_series()
574 574 self.series_dirty = 1
575 575 self.applied_dirty = 1
576 576 p = self.opener(patch, "w")
577 577 if msg:
578 578 msg = msg + "\n"
579 579 p.write(msg)
580 580 p.close()
581 581 wlock = None
582 582 r = self.qrepo()
583 583 if r: r.add([patch])
584 584 if commitfiles:
585 585 self.refresh(repo, short=True)
586 586
587 587 def strip(self, repo, rev, update=True, backup="all", wlock=None):
588 588 def limitheads(chlog, stop):
589 589 """return the list of all nodes that have no children"""
590 590 p = {}
591 591 h = []
592 592 stoprev = 0
593 593 if stop in chlog.nodemap:
594 594 stoprev = chlog.rev(stop)
595 595
596 for r in range(chlog.count() - 1, -1, -1):
596 for r in xrange(chlog.count() - 1, -1, -1):
597 597 n = chlog.node(r)
598 598 if n not in p:
599 599 h.append(n)
600 600 if n == stop:
601 601 break
602 602 if r < stoprev:
603 603 break
604 604 for pn in chlog.parents(n):
605 605 p[pn] = 1
606 606 return h
607 607
608 608 def bundle(cg):
609 609 backupdir = repo.join("strip-backup")
610 610 if not os.path.isdir(backupdir):
611 611 os.mkdir(backupdir)
612 612 name = os.path.join(backupdir, "%s" % revlog.short(rev))
613 613 name = savename(name)
614 614 self.ui.warn("saving bundle to %s\n" % name)
615 615 # TODO, exclusive open
616 616 f = open(name, "wb")
617 617 try:
618 618 f.write("HG10")
619 619 z = bz2.BZ2Compressor(9)
620 620 while 1:
621 621 chunk = cg.read(4096)
622 622 if not chunk:
623 623 break
624 624 f.write(z.compress(chunk))
625 625 f.write(z.flush())
626 626 except:
627 627 os.unlink(name)
628 628 raise
629 629 f.close()
630 630 return name
631 631
632 632 def stripall(rev, revnum):
633 633 cl = repo.changelog
634 634 c = cl.read(rev)
635 635 mm = repo.manifest.read(c[0])
636 636 seen = {}
637 637
638 638 for x in xrange(revnum, cl.count()):
639 639 c = cl.read(cl.node(x))
640 640 for f in c[3]:
641 641 if f in seen:
642 642 continue
643 643 seen[f] = 1
644 644 if f in mm:
645 645 filerev = mm[f]
646 646 else:
647 647 filerev = 0
648 648 seen[f] = filerev
649 649 # we go in two steps here so the strip loop happens in a
650 650 # sensible order. When stripping many files, this helps keep
651 651 # our disk access patterns under control.
652 652 seen_list = seen.keys()
653 653 seen_list.sort()
654 654 for f in seen_list:
655 655 ff = repo.file(f)
656 656 filerev = seen[f]
657 657 if filerev != 0:
658 658 if filerev in ff.nodemap:
659 659 filerev = ff.rev(filerev)
660 660 else:
661 661 filerev = 0
662 662 ff.strip(filerev, revnum)
663 663
664 664 if not wlock:
665 665 wlock = repo.wlock()
666 666 lock = repo.lock()
667 667 chlog = repo.changelog
668 668 # TODO delete the undo files, and handle undo of merge sets
669 669 pp = chlog.parents(rev)
670 670 revnum = chlog.rev(rev)
671 671
672 672 if update:
673 673 self.check_localchanges(repo, refresh=False)
674 674 urev = self.qparents(repo, rev)
675 675 hg.clean(repo, urev, wlock=wlock)
676 676 repo.dirstate.write()
677 677
678 678 # save is a list of all the branches we are truncating away
679 679 # that we actually want to keep. changegroup will be used
680 680 # to preserve them and add them back after the truncate
681 681 saveheads = []
682 682 savebases = {}
683 683
684 684 heads = limitheads(chlog, rev)
685 685 seen = {}
686 686
687 687 # search through all the heads, finding those where the revision
688 688 # we want to strip away is an ancestor. Also look for merges
689 689 # that might be turned into new heads by the strip.
690 690 while heads:
691 691 h = heads.pop()
692 692 n = h
693 693 while True:
694 694 seen[n] = 1
695 695 pp = chlog.parents(n)
696 696 if pp[1] != revlog.nullid and chlog.rev(pp[1]) > revnum:
697 697 if pp[1] not in seen:
698 698 heads.append(pp[1])
699 699 if pp[0] == revlog.nullid:
700 700 break
701 701 if chlog.rev(pp[0]) < revnum:
702 702 break
703 703 n = pp[0]
704 704 if n == rev:
705 705 break
706 706 r = chlog.reachable(h, rev)
707 707 if rev not in r:
708 708 saveheads.append(h)
709 709 for x in r:
710 710 if chlog.rev(x) > revnum:
711 711 savebases[x] = 1
712 712
713 713 # create a changegroup for all the branches we need to keep
714 714 if backup == "all":
715 715 backupch = repo.changegroupsubset([rev], chlog.heads(), 'strip')
716 716 bundle(backupch)
717 717 if saveheads:
718 718 backupch = repo.changegroupsubset(savebases.keys(), saveheads, 'strip')
719 719 chgrpfile = bundle(backupch)
720 720
721 721 stripall(rev, revnum)
722 722
723 723 change = chlog.read(rev)
724 724 chlog.strip(revnum, revnum)
725 725 repo.manifest.strip(repo.manifest.rev(change[0]), revnum)
726 726 if saveheads:
727 727 self.ui.status("adding branch\n")
728 728 commands.unbundle(self.ui, repo, chgrpfile, update=False)
729 729 if backup != "strip":
730 730 os.unlink(chgrpfile)
731 731
732 732 def isapplied(self, patch):
733 733 """returns (index, rev, patch)"""
734 734 for i in xrange(len(self.applied)):
735 735 a = self.applied[i]
736 736 if a.name == patch:
737 737 return (i, a.rev, a.name)
738 738 return None
739 739
740 740 # if the exact patch name does not exist, we try a few
741 741 # variations. If strict is passed, we try only #1
742 742 #
743 743 # 1) a number to indicate an offset in the series file
744 744 # 2) a unique substring of the patch name was given
745 745 # 3) patchname[-+]num to indicate an offset in the series file
746 746 def lookup(self, patch, strict=False):
747 747 patch = patch and str(patch)
748 748
749 749 def partial_name(s):
750 750 if s in self.series:
751 751 return s
752 752 matches = [x for x in self.series if s in x]
753 753 if len(matches) > 1:
754 754 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
755 755 for m in matches:
756 756 self.ui.warn(' %s\n' % m)
757 757 return None
758 758 if matches:
759 759 return matches[0]
760 760 if len(self.series) > 0 and len(self.applied) > 0:
761 761 if s == 'qtip':
762 762 return self.series[self.series_end()-1]
763 763 if s == 'qbase':
764 764 return self.series[0]
765 765 return None
766 766 if patch == None:
767 767 return None
768 768
769 769 # we don't want to return a partial match until we make
770 770 # sure the file name passed in does not exist (checked below)
771 771 res = partial_name(patch)
772 772 if res and res == patch:
773 773 return res
774 774
775 775 if not os.path.isfile(self.join(patch)):
776 776 try:
777 777 sno = int(patch)
778 778 except(ValueError, OverflowError):
779 779 pass
780 780 else:
781 781 if sno < len(self.series):
782 782 return self.series[sno]
783 783 if not strict:
784 784 # return any partial match made above
785 785 if res:
786 786 return res
787 787 minus = patch.rfind('-')
788 788 if minus >= 0:
789 789 res = partial_name(patch[:minus])
790 790 if res:
791 791 i = self.series.index(res)
792 792 try:
793 793 off = int(patch[minus+1:] or 1)
794 794 except(ValueError, OverflowError):
795 795 pass
796 796 else:
797 797 if i - off >= 0:
798 798 return self.series[i - off]
799 799 plus = patch.rfind('+')
800 800 if plus >= 0:
801 801 res = partial_name(patch[:plus])
802 802 if res:
803 803 i = self.series.index(res)
804 804 try:
805 805 off = int(patch[plus+1:] or 1)
806 806 except(ValueError, OverflowError):
807 807 pass
808 808 else:
809 809 if i + off < len(self.series):
810 810 return self.series[i + off]
811 811 raise util.Abort(_("patch %s not in series") % patch)
812 812
813 813 def push(self, repo, patch=None, force=False, list=False,
814 814 mergeq=None, wlock=None):
815 815 if not wlock:
816 816 wlock = repo.wlock()
817 817 patch = self.lookup(patch)
818 818 if patch and self.isapplied(patch):
819 819 raise util.Abort(_("patch %s is already applied") % patch)
820 820 if self.series_end() == len(self.series):
821 821 raise util.Abort(_("patch series fully applied"))
822 822 if not force:
823 823 self.check_localchanges(repo)
824 824
825 825 self.applied_dirty = 1;
826 826 start = self.series_end()
827 827 if start > 0:
828 828 self.check_toppatch(repo)
829 829 if not patch:
830 830 patch = self.series[start]
831 831 end = start + 1
832 832 else:
833 833 end = self.series.index(patch, start) + 1
834 834 s = self.series[start:end]
835 835 if mergeq:
836 836 ret = self.mergepatch(repo, mergeq, s, wlock)
837 837 else:
838 838 ret = self.apply(repo, s, list, wlock=wlock)
839 839 top = self.applied[-1].name
840 840 if ret[0]:
841 841 self.ui.write("Errors during apply, please fix and refresh %s\n" %
842 842 top)
843 843 else:
844 844 self.ui.write("Now at: %s\n" % top)
845 845 return ret[0]
846 846
847 847 def pop(self, repo, patch=None, force=False, update=True, all=False,
848 848 wlock=None):
849 849 def getfile(f, rev):
850 850 t = repo.file(f).read(rev)
851 851 try:
852 852 repo.wfile(f, "w").write(t)
853 853 except IOError:
854 854 try:
855 855 os.makedirs(os.path.dirname(repo.wjoin(f)))
856 856 except OSError, err:
857 857 if err.errno != errno.EEXIST: raise
858 858 repo.wfile(f, "w").write(t)
859 859
860 860 if not wlock:
861 861 wlock = repo.wlock()
862 862 if patch:
863 863 # index, rev, patch
864 864 info = self.isapplied(patch)
865 865 if not info:
866 866 patch = self.lookup(patch)
867 867 info = self.isapplied(patch)
868 868 if not info:
869 869 raise util.Abort(_("patch %s is not applied") % patch)
870 870 if len(self.applied) == 0:
871 871 raise util.Abort(_("no patches applied"))
872 872
873 873 if not update:
874 874 parents = repo.dirstate.parents()
875 875 rr = [ revlog.bin(x.rev) for x in self.applied ]
876 876 for p in parents:
877 877 if p in rr:
878 878 self.ui.warn("qpop: forcing dirstate update\n")
879 879 update = True
880 880
881 881 if not force and update:
882 882 self.check_localchanges(repo)
883 883
884 884 self.applied_dirty = 1;
885 885 end = len(self.applied)
886 886 if not patch:
887 887 if all:
888 888 popi = 0
889 889 else:
890 890 popi = len(self.applied) - 1
891 891 else:
892 892 popi = info[0] + 1
893 893 if popi >= end:
894 894 self.ui.warn("qpop: %s is already at the top\n" % patch)
895 895 return
896 896 info = [ popi ] + [self.applied[popi].rev, self.applied[popi].name]
897 897
898 898 start = info[0]
899 899 rev = revlog.bin(info[1])
900 900
901 901 # we know there are no local changes, so we can make a simplified
902 902 # form of hg.update.
903 903 if update:
904 904 top = self.check_toppatch(repo)
905 905 qp = self.qparents(repo, rev)
906 906 changes = repo.changelog.read(qp)
907 907 mmap = repo.manifest.read(changes[0])
908 908 m, a, r, d, u = repo.status(qp, top)[:5]
909 909 if d:
910 910 raise util.Abort("deletions found between repo revs")
911 911 for f in m:
912 912 getfile(f, mmap[f])
913 913 for f in r:
914 914 getfile(f, mmap[f])
915 915 util.set_exec(repo.wjoin(f), mmap.execf(f))
916 916 repo.dirstate.update(m + r, 'n')
917 917 for f in a:
918 918 try: os.unlink(repo.wjoin(f))
919 919 except: raise
920 920 try: os.removedirs(os.path.dirname(repo.wjoin(f)))
921 921 except: pass
922 922 if a:
923 923 repo.dirstate.forget(a)
924 924 repo.dirstate.setparents(qp, revlog.nullid)
925 925 self.strip(repo, rev, update=False, backup='strip', wlock=wlock)
926 926 del self.applied[start:end]
927 927 if len(self.applied):
928 928 self.ui.write("Now at: %s\n" % self.applied[-1].name)
929 929 else:
930 930 self.ui.write("Patch queue now empty\n")
931 931
932 932 def diff(self, repo, pats, opts):
933 933 top = self.check_toppatch(repo)
934 934 if not top:
935 935 self.ui.write("No patches applied\n")
936 936 return
937 937 qp = self.qparents(repo, top)
938 938 self.printdiff(repo, qp, files=pats, opts=opts)
939 939
940 940 def refresh(self, repo, pats=None, **opts):
941 941 if len(self.applied) == 0:
942 942 self.ui.write("No patches applied\n")
943 943 return 1
944 944 wlock = repo.wlock()
945 945 self.check_toppatch(repo)
946 946 (top, patchfn) = (self.applied[-1].rev, self.applied[-1].name)
947 947 top = revlog.bin(top)
948 948 cparents = repo.changelog.parents(top)
949 949 patchparent = self.qparents(repo, top)
950 950 message, comments, user, date, patchfound = self.readheaders(patchfn)
951 951
952 952 patchf = self.opener(patchfn, "w")
953 953 msg = opts.get('msg', '').rstrip()
954 954 if msg:
955 955 if comments:
956 956 # Remove existing message.
957 957 ci = 0
958 for mi in range(len(message)):
958 for mi in xrange(len(message)):
959 959 while message[mi] != comments[ci]:
960 960 ci += 1
961 961 del comments[ci]
962 962 comments.append(msg)
963 963 if comments:
964 964 comments = "\n".join(comments) + '\n\n'
965 965 patchf.write(comments)
966 966
967 967 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
968 968 tip = repo.changelog.tip()
969 969 if top == tip:
970 970 # if the top of our patch queue is also the tip, there is an
971 971 # optimization here. We update the dirstate in place and strip
972 972 # off the tip commit. Then just commit the current directory
973 973 # tree. We can also send repo.commit the list of files
974 974 # changed to speed up the diff
975 975 #
976 976 # in short mode, we only diff the files included in the
977 977 # patch already
978 978 #
979 979 # this should really read:
980 980 # mm, dd, aa, aa2, uu = repo.status(tip, patchparent)[:5]
981 981 # but we do it backwards to take advantage of manifest/chlog
982 982 # caching against the next repo.status call
983 983 #
984 984 mm, aa, dd, aa2, uu = repo.status(patchparent, tip)[:5]
985 985 if opts.get('short'):
986 986 filelist = mm + aa + dd
987 987 else:
988 988 filelist = None
989 989 m, a, r, d, u = repo.status(files=filelist)[:5]
990 990
991 991 # we might end up with files that were added between tip and
992 992 # the dirstate parent, but then changed in the local dirstate.
993 993 # in this case, we want them to only show up in the added section
994 994 for x in m:
995 995 if x not in aa:
996 996 mm.append(x)
997 997 # we might end up with files added by the local dirstate that
998 998 # were deleted by the patch. In this case, they should only
999 999 # show up in the changed section.
1000 1000 for x in a:
1001 1001 if x in dd:
1002 1002 del dd[dd.index(x)]
1003 1003 mm.append(x)
1004 1004 else:
1005 1005 aa.append(x)
1006 1006 # make sure any files deleted in the local dirstate
1007 1007 # are not in the add or change column of the patch
1008 1008 forget = []
1009 1009 for x in d + r:
1010 1010 if x in aa:
1011 1011 del aa[aa.index(x)]
1012 1012 forget.append(x)
1013 1013 continue
1014 1014 elif x in mm:
1015 1015 del mm[mm.index(x)]
1016 1016 dd.append(x)
1017 1017
1018 1018 m = list(util.unique(mm))
1019 1019 r = list(util.unique(dd))
1020 1020 a = list(util.unique(aa))
1021 1021 filelist = filter(matchfn, util.unique(m + r + a))
1022 1022 if opts.get('git'):
1023 1023 self.diffopts().git = True
1024 1024 patch.diff(repo, patchparent, files=filelist, match=matchfn,
1025 1025 fp=patchf, changes=(m, a, r, [], u),
1026 1026 opts=self.diffopts())
1027 1027 patchf.close()
1028 1028
1029 1029 changes = repo.changelog.read(tip)
1030 1030 repo.dirstate.setparents(*cparents)
1031 1031 copies = [(f, repo.dirstate.copied(f)) for f in a]
1032 1032 repo.dirstate.update(a, 'a')
1033 1033 for dst, src in copies:
1034 1034 repo.dirstate.copy(src, dst)
1035 1035 repo.dirstate.update(r, 'r')
1036 1036 # if the patch excludes a modified file, mark that file with mtime=0
1037 1037 # so status can see it.
1038 1038 mm = []
1039 for i in range(len(m)-1, -1, -1):
1039 for i in xrange(len(m)-1, -1, -1):
1040 1040 if not matchfn(m[i]):
1041 1041 mm.append(m[i])
1042 1042 del m[i]
1043 1043 repo.dirstate.update(m, 'n')
1044 1044 repo.dirstate.update(mm, 'n', st_mtime=0)
1045 1045 repo.dirstate.forget(forget)
1046 1046
1047 1047 if not msg:
1048 1048 if not message:
1049 1049 message = "patch queue: %s\n" % patchfn
1050 1050 else:
1051 1051 message = "\n".join(message)
1052 1052 else:
1053 1053 message = msg
1054 1054
1055 1055 self.strip(repo, top, update=False, backup='strip', wlock=wlock)
1056 1056 n = repo.commit(filelist, message, changes[1], force=1, wlock=wlock)
1057 1057 self.applied[-1] = statusentry(revlog.hex(n), patchfn)
1058 1058 self.applied_dirty = 1
1059 1059 else:
1060 1060 self.printdiff(repo, patchparent, fp=patchf)
1061 1061 patchf.close()
1062 1062 self.pop(repo, force=True, wlock=wlock)
1063 1063 self.push(repo, force=True, wlock=wlock)
1064 1064
1065 1065 def init(self, repo, create=False):
1066 1066 if os.path.isdir(self.path):
1067 1067 raise util.Abort(_("patch queue directory already exists"))
1068 1068 os.mkdir(self.path)
1069 1069 if create:
1070 1070 return self.qrepo(create=True)
1071 1071
1072 1072 def unapplied(self, repo, patch=None):
1073 1073 if patch and patch not in self.series:
1074 1074 raise util.Abort(_("patch %s is not in series file") % patch)
1075 1075 if not patch:
1076 1076 start = self.series_end()
1077 1077 else:
1078 1078 start = self.series.index(patch) + 1
1079 1079 unapplied = []
1080 1080 for i in xrange(start, len(self.series)):
1081 1081 pushable, reason = self.pushable(i)
1082 1082 if pushable:
1083 1083 unapplied.append((i, self.series[i]))
1084 1084 self.explain_pushable(i)
1085 1085 return unapplied
1086 1086
1087 1087 def qseries(self, repo, missing=None, start=0, length=0, status=None,
1088 1088 summary=False):
1089 1089 def displayname(patchname):
1090 1090 if summary:
1091 1091 msg = self.readheaders(patchname)[0]
1092 1092 msg = msg and ': ' + msg[0] or ': '
1093 1093 else:
1094 1094 msg = ''
1095 1095 return '%s%s' % (patchname, msg)
1096 1096
1097 1097 def pname(i):
1098 1098 if status == 'A':
1099 1099 return self.applied[i].name
1100 1100 else:
1101 1101 return self.series[i]
1102 1102
1103 1103 unapplied = self.series_end(all_patches=True)
1104 1104 if not length:
1105 1105 length = len(self.series) - start
1106 1106 if not missing:
1107 for i in range(start, start+length):
1107 for i in xrange(start, start+length):
1108 1108 pfx = ''
1109 1109 patch = pname(i)
1110 1110 if self.ui.verbose:
1111 1111 if i < unapplied:
1112 1112 status = 'A'
1113 1113 elif self.pushable(i)[0]:
1114 1114 status = 'U'
1115 1115 else:
1116 1116 status = 'G'
1117 1117 pfx = '%d %s ' % (i, status)
1118 1118 self.ui.write('%s%s\n' % (pfx, displayname(patch)))
1119 1119 else:
1120 1120 msng_list = []
1121 1121 for root, dirs, files in os.walk(self.path):
1122 1122 d = root[len(self.path) + 1:]
1123 1123 for f in files:
1124 1124 fl = os.path.join(d, f)
1125 1125 if (fl not in self.series and
1126 1126 fl not in (self.status_path, self.series_path)
1127 1127 and not fl.startswith('.')):
1128 1128 msng_list.append(fl)
1129 1129 msng_list.sort()
1130 1130 for x in msng_list:
1131 1131 pfx = self.ui.verbose and ('D ') or ''
1132 1132 self.ui.write("%s%s\n" % (pfx, displayname(x)))
1133 1133
1134 1134 def issaveline(self, l):
1135 1135 if l.name == '.hg.patches.save.line':
1136 1136 return True
1137 1137
1138 1138 def qrepo(self, create=False):
1139 1139 if create or os.path.isdir(self.join(".hg")):
1140 1140 return hg.repository(self.ui, path=self.path, create=create)
1141 1141
1142 1142 def restore(self, repo, rev, delete=None, qupdate=None):
1143 1143 c = repo.changelog.read(rev)
1144 1144 desc = c[4].strip()
1145 1145 lines = desc.splitlines()
1146 1146 i = 0
1147 1147 datastart = None
1148 1148 series = []
1149 1149 applied = []
1150 1150 qpp = None
1151 1151 for i in xrange(0, len(lines)):
1152 1152 if lines[i] == 'Patch Data:':
1153 1153 datastart = i + 1
1154 1154 elif lines[i].startswith('Dirstate:'):
1155 1155 l = lines[i].rstrip()
1156 1156 l = l[10:].split(' ')
1157 1157 qpp = [ hg.bin(x) for x in l ]
1158 1158 elif datastart != None:
1159 1159 l = lines[i].rstrip()
1160 1160 se = statusentry(l)
1161 1161 file_ = se.name
1162 1162 if se.rev:
1163 1163 applied.append(se)
1164 1164 else:
1165 1165 series.append(file_)
1166 1166 if datastart == None:
1167 1167 self.ui.warn("No saved patch data found\n")
1168 1168 return 1
1169 1169 self.ui.warn("restoring status: %s\n" % lines[0])
1170 1170 self.full_series = series
1171 1171 self.applied = applied
1172 1172 self.parse_series()
1173 1173 self.series_dirty = 1
1174 1174 self.applied_dirty = 1
1175 1175 heads = repo.changelog.heads()
1176 1176 if delete:
1177 1177 if rev not in heads:
1178 1178 self.ui.warn("save entry has children, leaving it alone\n")
1179 1179 else:
1180 1180 self.ui.warn("removing save entry %s\n" % hg.short(rev))
1181 1181 pp = repo.dirstate.parents()
1182 1182 if rev in pp:
1183 1183 update = True
1184 1184 else:
1185 1185 update = False
1186 1186 self.strip(repo, rev, update=update, backup='strip')
1187 1187 if qpp:
1188 1188 self.ui.warn("saved queue repository parents: %s %s\n" %
1189 1189 (hg.short(qpp[0]), hg.short(qpp[1])))
1190 1190 if qupdate:
1191 1191 print "queue directory updating"
1192 1192 r = self.qrepo()
1193 1193 if not r:
1194 1194 self.ui.warn("Unable to load queue repository\n")
1195 1195 return 1
1196 1196 hg.clean(r, qpp[0])
1197 1197
1198 1198 def save(self, repo, msg=None):
1199 1199 if len(self.applied) == 0:
1200 1200 self.ui.warn("save: no patches applied, exiting\n")
1201 1201 return 1
1202 1202 if self.issaveline(self.applied[-1]):
1203 1203 self.ui.warn("status is already saved\n")
1204 1204 return 1
1205 1205
1206 1206 ar = [ ':' + x for x in self.full_series ]
1207 1207 if not msg:
1208 1208 msg = "hg patches saved state"
1209 1209 else:
1210 1210 msg = "hg patches: " + msg.rstrip('\r\n')
1211 1211 r = self.qrepo()
1212 1212 if r:
1213 1213 pp = r.dirstate.parents()
1214 1214 msg += "\nDirstate: %s %s" % (hg.hex(pp[0]), hg.hex(pp[1]))
1215 1215 msg += "\n\nPatch Data:\n"
1216 1216 text = msg + "\n".join([str(x) for x in self.applied]) + '\n' + (ar and
1217 1217 "\n".join(ar) + '\n' or "")
1218 1218 n = repo.commit(None, text, user=None, force=1)
1219 1219 if not n:
1220 1220 self.ui.warn("repo commit failed\n")
1221 1221 return 1
1222 1222 self.applied.append(statusentry(revlog.hex(n),'.hg.patches.save.line'))
1223 1223 self.applied_dirty = 1
1224 1224
1225 1225 def full_series_end(self):
1226 1226 if len(self.applied) > 0:
1227 1227 p = self.applied[-1].name
1228 1228 end = self.find_series(p)
1229 1229 if end == None:
1230 1230 return len(self.full_series)
1231 1231 return end + 1
1232 1232 return 0
1233 1233
1234 1234 def series_end(self, all_patches=False):
1235 1235 end = 0
1236 1236 def next(start):
1237 1237 if all_patches:
1238 1238 return start
1239 1239 i = start
1240 1240 while i < len(self.series):
1241 1241 p, reason = self.pushable(i)
1242 1242 if p:
1243 1243 break
1244 1244 self.explain_pushable(i)
1245 1245 i += 1
1246 1246 return i
1247 1247 if len(self.applied) > 0:
1248 1248 p = self.applied[-1].name
1249 1249 try:
1250 1250 end = self.series.index(p)
1251 1251 except ValueError:
1252 1252 return 0
1253 1253 return next(end + 1)
1254 1254 return next(end)
1255 1255
1256 1256 def appliedname(self, index):
1257 1257 pname = self.applied[index].name
1258 1258 if not self.ui.verbose:
1259 1259 p = pname
1260 1260 else:
1261 1261 p = str(self.series.index(pname)) + " " + pname
1262 1262 return p
1263 1263
1264 1264 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1265 1265 force=None):
1266 1266 def checkseries(patchname):
1267 1267 if patchname in self.series:
1268 1268 raise util.Abort(_('patch %s is already in the series file')
1269 1269 % patchname)
1270 1270 def checkfile(patchname):
1271 1271 if not force and os.path.exists(self.join(patchname)):
1272 1272 raise util.Abort(_('patch "%s" already exists')
1273 1273 % patchname)
1274 1274
1275 1275 if rev:
1276 1276 if files:
1277 1277 raise util.Abort(_('option "-r" not valid when importing '
1278 1278 'files'))
1279 1279 rev = [int(r) for r in cmdutil.revrange(self.ui, repo, rev)]
1280 1280 rev.sort(lambda x, y: cmp(y, x))
1281 1281 if (len(files) > 1 or len(rev) > 1) and patchname:
1282 1282 raise util.Abort(_('option "-n" not valid when importing multiple '
1283 1283 'patches'))
1284 1284 i = 0
1285 1285 added = []
1286 1286 if rev:
1287 1287 # If mq patches are applied, we can only import revisions
1288 1288 # that form a linear path to qbase.
1289 1289 # Otherwise, they should form a linear path to a head.
1290 1290 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1291 1291 if len(heads) > 1:
1292 1292 raise util.Abort(_('revision %d is the root of more than one '
1293 1293 'branch') % rev[-1])
1294 1294 if self.applied:
1295 1295 base = revlog.hex(repo.changelog.node(rev[0]))
1296 1296 if base in [n.rev for n in self.applied]:
1297 1297 raise util.Abort(_('revision %d is already managed')
1298 1298 % rev[0])
1299 1299 if heads != [revlog.bin(self.applied[-1].rev)]:
1300 1300 raise util.Abort(_('revision %d is not the parent of '
1301 1301 'the queue') % rev[0])
1302 1302 base = repo.changelog.rev(revlog.bin(self.applied[0].rev))
1303 1303 lastparent = repo.changelog.parentrevs(base)[0]
1304 1304 else:
1305 1305 if heads != [repo.changelog.node(rev[0])]:
1306 1306 raise util.Abort(_('revision %d has unmanaged children')
1307 1307 % rev[0])
1308 1308 lastparent = None
1309 1309
1310 1310 for r in rev:
1311 1311 p1, p2 = repo.changelog.parentrevs(r)
1312 1312 n = repo.changelog.node(r)
1313 1313 if p2 != -1:
1314 1314 raise util.Abort(_('cannot import merge revision %d') % r)
1315 1315 if lastparent and lastparent != r:
1316 1316 raise util.Abort(_('revision %d is not the parent of %d')
1317 1317 % (r, lastparent))
1318 1318 lastparent = p1
1319 1319
1320 1320 if not patchname:
1321 1321 patchname = '%d.diff' % r
1322 1322 checkseries(patchname)
1323 1323 checkfile(patchname)
1324 1324 self.full_series.insert(0, patchname)
1325 1325
1326 1326 patchf = self.opener(patchname, "w")
1327 1327 patch.export(repo, [n], fp=patchf, opts=self.diffopts())
1328 1328 patchf.close()
1329 1329
1330 1330 se = statusentry(revlog.hex(n), patchname)
1331 1331 self.applied.insert(0, se)
1332 1332
1333 1333 added.append(patchname)
1334 1334 patchname = None
1335 1335 self.parse_series()
1336 1336 self.applied_dirty = 1
1337 1337
1338 1338 for filename in files:
1339 1339 if existing:
1340 1340 if not patchname:
1341 1341 patchname = filename
1342 1342 if not os.path.isfile(self.join(patchname)):
1343 1343 raise util.Abort(_("patch %s does not exist") % patchname)
1344 1344 else:
1345 1345 try:
1346 1346 text = file(filename).read()
1347 1347 except IOError:
1348 1348 raise util.Abort(_("unable to read %s") % patchname)
1349 1349 if not patchname:
1350 1350 patchname = os.path.basename(filename)
1351 1351 checkfile(patchname)
1352 1352 patchf = self.opener(patchname, "w")
1353 1353 patchf.write(text)
1354 1354 checkseries(patchname)
1355 1355 index = self.full_series_end() + i
1356 1356 self.full_series[index:index] = [patchname]
1357 1357 self.parse_series()
1358 1358 self.ui.warn("adding %s to series file\n" % patchname)
1359 1359 i += 1
1360 1360 added.append(patchname)
1361 1361 patchname = None
1362 1362 self.series_dirty = 1
1363 1363 qrepo = self.qrepo()
1364 1364 if qrepo:
1365 1365 qrepo.add(added)
1366 1366
1367 1367 def delete(ui, repo, *patches, **opts):
1368 1368 """remove patches from queue
1369 1369
1370 1370 With --rev, mq will stop managing the named revisions. The
1371 1371 patches must be applied and at the base of the stack. This option
1372 1372 is useful when the patches have been applied upstream.
1373 1373
1374 1374 Otherwise, the patches must not be applied.
1375 1375
1376 1376 With --keep, the patch files are preserved in the patch directory."""
1377 1377 q = repo.mq
1378 1378 q.delete(repo, patches, opts)
1379 1379 q.save_dirty()
1380 1380 return 0
1381 1381
1382 1382 def applied(ui, repo, patch=None, **opts):
1383 1383 """print the patches already applied"""
1384 1384 q = repo.mq
1385 1385 if patch:
1386 1386 if patch not in q.series:
1387 1387 raise util.Abort(_("patch %s is not in series file") % patch)
1388 1388 end = q.series.index(patch) + 1
1389 1389 else:
1390 1390 end = len(q.applied)
1391 1391 if not end:
1392 1392 return
1393 1393
1394 1394 return q.qseries(repo, length=end, status='A', summary=opts.get('summary'))
1395 1395
1396 1396 def unapplied(ui, repo, patch=None, **opts):
1397 1397 """print the patches not yet applied"""
1398 1398 q = repo.mq
1399 1399 if patch:
1400 1400 if patch not in q.series:
1401 1401 raise util.Abort(_("patch %s is not in series file") % patch)
1402 1402 start = q.series.index(patch) + 1
1403 1403 else:
1404 1404 start = q.series_end()
1405 1405 q.qseries(repo, start=start, summary=opts.get('summary'))
1406 1406
1407 1407 def qimport(ui, repo, *filename, **opts):
1408 1408 """import a patch
1409 1409
1410 1410 The patch will have the same name as its source file unless you
1411 1411 give it a new one with --name.
1412 1412
1413 1413 You can register an existing patch inside the patch directory
1414 1414 with the --existing flag.
1415 1415
1416 1416 With --force, an existing patch of the same name will be overwritten.
1417 1417
1418 1418 An existing changeset may be placed under mq control with --rev
1419 1419 (e.g. qimport --rev tip -n patch will place tip under mq control).
1420 1420 """
1421 1421 q = repo.mq
1422 1422 q.qimport(repo, filename, patchname=opts['name'],
1423 1423 existing=opts['existing'], force=opts['force'], rev=opts['rev'])
1424 1424 q.save_dirty()
1425 1425 return 0
1426 1426
1427 1427 def init(ui, repo, **opts):
1428 1428 """init a new queue repository
1429 1429
1430 1430 The queue repository is unversioned by default. If -c is
1431 1431 specified, qinit will create a separate nested repository
1432 1432 for patches. Use qcommit to commit changes to this queue
1433 1433 repository."""
1434 1434 q = repo.mq
1435 1435 r = q.init(repo, create=opts['create_repo'])
1436 1436 q.save_dirty()
1437 1437 if r:
1438 1438 fp = r.wopener('.hgignore', 'w')
1439 1439 print >> fp, 'syntax: glob'
1440 1440 print >> fp, 'status'
1441 1441 fp.close()
1442 1442 r.wopener('series', 'w').close()
1443 1443 r.add(['.hgignore', 'series'])
1444 1444 return 0
1445 1445
1446 1446 def clone(ui, source, dest=None, **opts):
1447 1447 '''clone main and patch repository at same time
1448 1448
1449 1449 If source is local, destination will have no patches applied. If
1450 1450 source is remote, this command can not check if patches are
1451 1451 applied in source, so cannot guarantee that patches are not
1452 1452 applied in destination. If you clone remote repository, be sure
1453 1453 before that it has no patches applied.
1454 1454
1455 1455 Source patch repository is looked for in <src>/.hg/patches by
1456 1456 default. Use -p <url> to change.
1457 1457 '''
1458 1458 commands.setremoteconfig(ui, opts)
1459 1459 if dest is None:
1460 1460 dest = hg.defaultdest(source)
1461 1461 sr = hg.repository(ui, ui.expandpath(source))
1462 1462 qbase, destrev = None, None
1463 1463 if sr.local():
1464 1464 reposetup(ui, sr)
1465 1465 if sr.mq.applied:
1466 1466 qbase = revlog.bin(sr.mq.applied[0].rev)
1467 1467 if not hg.islocal(dest):
1468 1468 destrev = sr.parents(qbase)[0]
1469 1469 ui.note(_('cloning main repo\n'))
1470 1470 sr, dr = hg.clone(ui, sr, dest,
1471 1471 pull=opts['pull'],
1472 1472 rev=destrev,
1473 1473 update=False,
1474 1474 stream=opts['uncompressed'])
1475 1475 ui.note(_('cloning patch repo\n'))
1476 1476 spr, dpr = hg.clone(ui, opts['patches'] or (sr.url() + '/.hg/patches'),
1477 1477 dr.url() + '/.hg/patches',
1478 1478 pull=opts['pull'],
1479 1479 update=not opts['noupdate'],
1480 1480 stream=opts['uncompressed'])
1481 1481 if dr.local():
1482 1482 if qbase:
1483 1483 ui.note(_('stripping applied patches from destination repo\n'))
1484 1484 reposetup(ui, dr)
1485 1485 dr.mq.strip(dr, qbase, update=False, backup=None)
1486 1486 if not opts['noupdate']:
1487 1487 ui.note(_('updating destination repo\n'))
1488 1488 hg.update(dr, dr.changelog.tip())
1489 1489
1490 1490 def commit(ui, repo, *pats, **opts):
1491 1491 """commit changes in the queue repository"""
1492 1492 q = repo.mq
1493 1493 r = q.qrepo()
1494 1494 if not r: raise util.Abort('no queue repository')
1495 1495 commands.commit(r.ui, r, *pats, **opts)
1496 1496
1497 1497 def series(ui, repo, **opts):
1498 1498 """print the entire series file"""
1499 1499 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1500 1500 return 0
1501 1501
1502 1502 def top(ui, repo, **opts):
1503 1503 """print the name of the current patch"""
1504 1504 q = repo.mq
1505 1505 t = len(q.applied)
1506 1506 if t:
1507 1507 return q.qseries(repo, start=t-1, length=1, status='A',
1508 1508 summary=opts.get('summary'))
1509 1509 else:
1510 1510 ui.write("No patches applied\n")
1511 1511 return 1
1512 1512
1513 1513 def next(ui, repo, **opts):
1514 1514 """print the name of the next patch"""
1515 1515 q = repo.mq
1516 1516 end = q.series_end()
1517 1517 if end == len(q.series):
1518 1518 ui.write("All patches applied\n")
1519 1519 return 1
1520 1520 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1521 1521
1522 1522 def prev(ui, repo, **opts):
1523 1523 """print the name of the previous patch"""
1524 1524 q = repo.mq
1525 1525 l = len(q.applied)
1526 1526 if l == 1:
1527 1527 ui.write("Only one patch applied\n")
1528 1528 return 1
1529 1529 if not l:
1530 1530 ui.write("No patches applied\n")
1531 1531 return 1
1532 1532 return q.qseries(repo, start=l-2, length=1, status='A',
1533 1533 summary=opts.get('summary'))
1534 1534
1535 1535 def new(ui, repo, patch, **opts):
1536 1536 """create a new patch
1537 1537
1538 1538 qnew creates a new patch on top of the currently-applied patch
1539 1539 (if any). It will refuse to run if there are any outstanding
1540 1540 changes unless -f is specified, in which case the patch will
1541 1541 be initialised with them.
1542 1542
1543 1543 -e, -m or -l set the patch header as well as the commit message.
1544 1544 If none is specified, the patch header is empty and the
1545 1545 commit message is 'New patch: PATCH'"""
1546 1546 q = repo.mq
1547 1547 message = commands.logmessage(opts)
1548 1548 if opts['edit']:
1549 1549 message = ui.edit(message, ui.username())
1550 1550 q.new(repo, patch, msg=message, force=opts['force'])
1551 1551 q.save_dirty()
1552 1552 return 0
1553 1553
1554 1554 def refresh(ui, repo, *pats, **opts):
1555 1555 """update the current patch
1556 1556
1557 1557 If any file patterns are provided, the refreshed patch will contain only
1558 1558 the modifications that match those patterns; the remaining modifications
1559 1559 will remain in the working directory.
1560 1560 """
1561 1561 q = repo.mq
1562 1562 message = commands.logmessage(opts)
1563 1563 if opts['edit']:
1564 1564 if message:
1565 1565 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1566 1566 patch = q.applied[-1].name
1567 1567 (message, comment, user, date, hasdiff) = q.readheaders(patch)
1568 1568 message = ui.edit('\n'.join(message), user or ui.username())
1569 1569 ret = q.refresh(repo, pats, msg=message, **opts)
1570 1570 q.save_dirty()
1571 1571 return ret
1572 1572
1573 1573 def diff(ui, repo, *pats, **opts):
1574 1574 """diff of the current patch"""
1575 1575 repo.mq.diff(repo, pats, opts)
1576 1576 return 0
1577 1577
1578 1578 def fold(ui, repo, *files, **opts):
1579 1579 """fold the named patches into the current patch
1580 1580
1581 1581 Patches must not yet be applied. Each patch will be successively
1582 1582 applied to the current patch in the order given. If all the
1583 1583 patches apply successfully, the current patch will be refreshed
1584 1584 with the new cumulative patch, and the folded patches will
1585 1585 be deleted. With -k/--keep, the folded patch files will not
1586 1586 be removed afterwards.
1587 1587
1588 1588 The header for each folded patch will be concatenated with
1589 1589 the current patch header, separated by a line of '* * *'."""
1590 1590
1591 1591 q = repo.mq
1592 1592
1593 1593 if not files:
1594 1594 raise util.Abort(_('qfold requires at least one patch name'))
1595 1595 if not q.check_toppatch(repo):
1596 1596 raise util.Abort(_('No patches applied'))
1597 1597
1598 1598 message = commands.logmessage(opts)
1599 1599 if opts['edit']:
1600 1600 if message:
1601 1601 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1602 1602
1603 1603 parent = q.lookup('qtip')
1604 1604 patches = []
1605 1605 messages = []
1606 1606 for f in files:
1607 1607 p = q.lookup(f)
1608 1608 if p in patches or p == parent:
1609 1609 ui.warn(_('Skipping already folded patch %s') % p)
1610 1610 if q.isapplied(p):
1611 1611 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
1612 1612 patches.append(p)
1613 1613
1614 1614 for p in patches:
1615 1615 if not message:
1616 1616 messages.append(q.readheaders(p)[0])
1617 1617 pf = q.join(p)
1618 1618 (patchsuccess, files, fuzz) = q.patch(repo, pf)
1619 1619 if not patchsuccess:
1620 1620 raise util.Abort(_('Error folding patch %s') % p)
1621 1621 patch.updatedir(ui, repo, files)
1622 1622
1623 1623 if not message:
1624 1624 message, comments, user = q.readheaders(parent)[0:3]
1625 1625 for msg in messages:
1626 1626 message.append('* * *')
1627 1627 message.extend(msg)
1628 1628 message = '\n'.join(message)
1629 1629
1630 1630 if opts['edit']:
1631 1631 message = ui.edit(message, user or ui.username())
1632 1632
1633 1633 q.refresh(repo, msg=message)
1634 1634 q.delete(repo, patches, opts)
1635 1635 q.save_dirty()
1636 1636
1637 1637 def guard(ui, repo, *args, **opts):
1638 1638 '''set or print guards for a patch
1639 1639
1640 1640 Guards control whether a patch can be pushed. A patch with no
1641 1641 guards is always pushed. A patch with a positive guard ("+foo") is
1642 1642 pushed only if the qselect command has activated it. A patch with
1643 1643 a negative guard ("-foo") is never pushed if the qselect command
1644 1644 has activated it.
1645 1645
1646 1646 With no arguments, print the currently active guards.
1647 1647 With arguments, set guards for the named patch.
1648 1648
1649 1649 To set a negative guard "-foo" on topmost patch ("--" is needed so
1650 1650 hg will not interpret "-foo" as an option):
1651 1651 hg qguard -- -foo
1652 1652
1653 1653 To set guards on another patch:
1654 1654 hg qguard other.patch +2.6.17 -stable
1655 1655 '''
1656 1656 def status(idx):
1657 1657 guards = q.series_guards[idx] or ['unguarded']
1658 1658 ui.write('%s: %s\n' % (q.series[idx], ' '.join(guards)))
1659 1659 q = repo.mq
1660 1660 patch = None
1661 1661 args = list(args)
1662 1662 if opts['list']:
1663 1663 if args or opts['none']:
1664 1664 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
1665 1665 for i in xrange(len(q.series)):
1666 1666 status(i)
1667 1667 return
1668 1668 if not args or args[0][0:1] in '-+':
1669 1669 if not q.applied:
1670 1670 raise util.Abort(_('no patches applied'))
1671 1671 patch = q.applied[-1].name
1672 1672 if patch is None and args[0][0:1] not in '-+':
1673 1673 patch = args.pop(0)
1674 1674 if patch is None:
1675 1675 raise util.Abort(_('no patch to work with'))
1676 1676 if args or opts['none']:
1677 1677 q.set_guards(q.find_series(patch), args)
1678 1678 q.save_dirty()
1679 1679 else:
1680 1680 status(q.series.index(q.lookup(patch)))
1681 1681
1682 1682 def header(ui, repo, patch=None):
1683 1683 """Print the header of the topmost or specified patch"""
1684 1684 q = repo.mq
1685 1685
1686 1686 if patch:
1687 1687 patch = q.lookup(patch)
1688 1688 else:
1689 1689 if not q.applied:
1690 1690 ui.write('No patches applied\n')
1691 1691 return 1
1692 1692 patch = q.lookup('qtip')
1693 1693 message = repo.mq.readheaders(patch)[0]
1694 1694
1695 1695 ui.write('\n'.join(message) + '\n')
1696 1696
1697 1697 def lastsavename(path):
1698 1698 (directory, base) = os.path.split(path)
1699 1699 names = os.listdir(directory)
1700 1700 namere = re.compile("%s.([0-9]+)" % base)
1701 1701 maxindex = None
1702 1702 maxname = None
1703 1703 for f in names:
1704 1704 m = namere.match(f)
1705 1705 if m:
1706 1706 index = int(m.group(1))
1707 1707 if maxindex == None or index > maxindex:
1708 1708 maxindex = index
1709 1709 maxname = f
1710 1710 if maxname:
1711 1711 return (os.path.join(directory, maxname), maxindex)
1712 1712 return (None, None)
1713 1713
1714 1714 def savename(path):
1715 1715 (last, index) = lastsavename(path)
1716 1716 if last is None:
1717 1717 index = 0
1718 1718 newpath = path + ".%d" % (index + 1)
1719 1719 return newpath
1720 1720
1721 1721 def push(ui, repo, patch=None, **opts):
1722 1722 """push the next patch onto the stack"""
1723 1723 q = repo.mq
1724 1724 mergeq = None
1725 1725
1726 1726 if opts['all']:
1727 1727 patch = q.series[-1]
1728 1728 if opts['merge']:
1729 1729 if opts['name']:
1730 1730 newpath = opts['name']
1731 1731 else:
1732 1732 newpath, i = lastsavename(q.path)
1733 1733 if not newpath:
1734 1734 ui.warn("no saved queues found, please use -n\n")
1735 1735 return 1
1736 1736 mergeq = queue(ui, repo.join(""), newpath)
1737 1737 ui.warn("merging with queue at: %s\n" % mergeq.path)
1738 1738 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
1739 1739 mergeq=mergeq)
1740 1740 q.save_dirty()
1741 1741 return ret
1742 1742
1743 1743 def pop(ui, repo, patch=None, **opts):
1744 1744 """pop the current patch off the stack"""
1745 1745 localupdate = True
1746 1746 if opts['name']:
1747 1747 q = queue(ui, repo.join(""), repo.join(opts['name']))
1748 1748 ui.warn('using patch queue: %s\n' % q.path)
1749 1749 localupdate = False
1750 1750 else:
1751 1751 q = repo.mq
1752 1752 q.pop(repo, patch, force=opts['force'], update=localupdate, all=opts['all'])
1753 1753 q.save_dirty()
1754 1754 return 0
1755 1755
1756 1756 def rename(ui, repo, patch, name=None, **opts):
1757 1757 """rename a patch
1758 1758
1759 1759 With one argument, renames the current patch to PATCH1.
1760 1760 With two arguments, renames PATCH1 to PATCH2."""
1761 1761
1762 1762 q = repo.mq
1763 1763
1764 1764 if not name:
1765 1765 name = patch
1766 1766 patch = None
1767 1767
1768 1768 if patch:
1769 1769 patch = q.lookup(patch)
1770 1770 else:
1771 1771 if not q.applied:
1772 1772 ui.write(_('No patches applied\n'))
1773 1773 return
1774 1774 patch = q.lookup('qtip')
1775 1775 absdest = q.join(name)
1776 1776 if os.path.isdir(absdest):
1777 1777 name = os.path.join(name, os.path.basename(patch))
1778 1778 absdest = q.join(name)
1779 1779 if os.path.exists(absdest):
1780 1780 raise util.Abort(_('%s already exists') % absdest)
1781 1781
1782 1782 if name in q.series:
1783 1783 raise util.Abort(_('A patch named %s already exists in the series file') % name)
1784 1784
1785 1785 if ui.verbose:
1786 1786 ui.write('Renaming %s to %s\n' % (patch, name))
1787 1787 i = q.find_series(patch)
1788 1788 q.full_series[i] = name
1789 1789 q.parse_series()
1790 1790 q.series_dirty = 1
1791 1791
1792 1792 info = q.isapplied(patch)
1793 1793 if info:
1794 1794 q.applied[info[0]] = statusentry(info[1], name)
1795 1795 q.applied_dirty = 1
1796 1796
1797 1797 util.rename(q.join(patch), absdest)
1798 1798 r = q.qrepo()
1799 1799 if r:
1800 1800 wlock = r.wlock()
1801 1801 if r.dirstate.state(name) == 'r':
1802 1802 r.undelete([name], wlock)
1803 1803 r.copy(patch, name, wlock)
1804 1804 r.remove([patch], False, wlock)
1805 1805
1806 1806 q.save_dirty()
1807 1807
1808 1808 def restore(ui, repo, rev, **opts):
1809 1809 """restore the queue state saved by a rev"""
1810 1810 rev = repo.lookup(rev)
1811 1811 q = repo.mq
1812 1812 q.restore(repo, rev, delete=opts['delete'],
1813 1813 qupdate=opts['update'])
1814 1814 q.save_dirty()
1815 1815 return 0
1816 1816
1817 1817 def save(ui, repo, **opts):
1818 1818 """save current queue state"""
1819 1819 q = repo.mq
1820 1820 message = commands.logmessage(opts)
1821 1821 ret = q.save(repo, msg=message)
1822 1822 if ret:
1823 1823 return ret
1824 1824 q.save_dirty()
1825 1825 if opts['copy']:
1826 1826 path = q.path
1827 1827 if opts['name']:
1828 1828 newpath = os.path.join(q.basepath, opts['name'])
1829 1829 if os.path.exists(newpath):
1830 1830 if not os.path.isdir(newpath):
1831 1831 raise util.Abort(_('destination %s exists and is not '
1832 1832 'a directory') % newpath)
1833 1833 if not opts['force']:
1834 1834 raise util.Abort(_('destination %s exists, '
1835 1835 'use -f to force') % newpath)
1836 1836 else:
1837 1837 newpath = savename(path)
1838 1838 ui.warn("copy %s to %s\n" % (path, newpath))
1839 1839 util.copyfiles(path, newpath)
1840 1840 if opts['empty']:
1841 1841 try:
1842 1842 os.unlink(q.join(q.status_path))
1843 1843 except:
1844 1844 pass
1845 1845 return 0
1846 1846
1847 1847 def strip(ui, repo, rev, **opts):
1848 1848 """strip a revision and all later revs on the same branch"""
1849 1849 rev = repo.lookup(rev)
1850 1850 backup = 'all'
1851 1851 if opts['backup']:
1852 1852 backup = 'strip'
1853 1853 elif opts['nobackup']:
1854 1854 backup = 'none'
1855 1855 update = repo.dirstate.parents()[0] != revlog.nullid
1856 1856 repo.mq.strip(repo, rev, backup=backup, update=update)
1857 1857 return 0
1858 1858
1859 1859 def select(ui, repo, *args, **opts):
1860 1860 '''set or print guarded patches to push
1861 1861
1862 1862 Use the qguard command to set or print guards on patch, then use
1863 1863 qselect to tell mq which guards to use. A patch will be pushed if it
1864 1864 has no guards or any positive guards match the currently selected guard,
1865 1865 but will not be pushed if any negative guards match the current guard.
1866 1866 For example:
1867 1867
1868 1868 qguard foo.patch -stable (negative guard)
1869 1869 qguard bar.patch +stable (positive guard)
1870 1870 qselect stable
1871 1871
1872 1872 This activates the "stable" guard. mq will skip foo.patch (because
1873 1873 it has a negative match) but push bar.patch (because it
1874 1874 has a positive match).
1875 1875
1876 1876 With no arguments, prints the currently active guards.
1877 1877 With one argument, sets the active guard.
1878 1878
1879 1879 Use -n/--none to deactivate guards (no other arguments needed).
1880 1880 When no guards are active, patches with positive guards are skipped
1881 1881 and patches with negative guards are pushed.
1882 1882
1883 1883 qselect can change the guards on applied patches. It does not pop
1884 1884 guarded patches by default. Use --pop to pop back to the last applied
1885 1885 patch that is not guarded. Use --reapply (which implies --pop) to push
1886 1886 back to the current patch afterwards, but skip guarded patches.
1887 1887
1888 1888 Use -s/--series to print a list of all guards in the series file (no
1889 1889 other arguments needed). Use -v for more information.'''
1890 1890
1891 1891 q = repo.mq
1892 1892 guards = q.active()
1893 1893 if args or opts['none']:
1894 1894 old_unapplied = q.unapplied(repo)
1895 1895 old_guarded = [i for i in xrange(len(q.applied)) if
1896 1896 not q.pushable(i)[0]]
1897 1897 q.set_active(args)
1898 1898 q.save_dirty()
1899 1899 if not args:
1900 1900 ui.status(_('guards deactivated\n'))
1901 1901 if not opts['pop'] and not opts['reapply']:
1902 1902 unapplied = q.unapplied(repo)
1903 1903 guarded = [i for i in xrange(len(q.applied))
1904 1904 if not q.pushable(i)[0]]
1905 1905 if len(unapplied) != len(old_unapplied):
1906 1906 ui.status(_('number of unguarded, unapplied patches has '
1907 1907 'changed from %d to %d\n') %
1908 1908 (len(old_unapplied), len(unapplied)))
1909 1909 if len(guarded) != len(old_guarded):
1910 1910 ui.status(_('number of guarded, applied patches has changed '
1911 1911 'from %d to %d\n') %
1912 1912 (len(old_guarded), len(guarded)))
1913 1913 elif opts['series']:
1914 1914 guards = {}
1915 1915 noguards = 0
1916 1916 for gs in q.series_guards:
1917 1917 if not gs:
1918 1918 noguards += 1
1919 1919 for g in gs:
1920 1920 guards.setdefault(g, 0)
1921 1921 guards[g] += 1
1922 1922 if ui.verbose:
1923 1923 guards['NONE'] = noguards
1924 1924 guards = guards.items()
1925 1925 guards.sort(lambda a, b: cmp(a[0][1:], b[0][1:]))
1926 1926 if guards:
1927 1927 ui.note(_('guards in series file:\n'))
1928 1928 for guard, count in guards:
1929 1929 ui.note('%2d ' % count)
1930 1930 ui.write(guard, '\n')
1931 1931 else:
1932 1932 ui.note(_('no guards in series file\n'))
1933 1933 else:
1934 1934 if guards:
1935 1935 ui.note(_('active guards:\n'))
1936 1936 for g in guards:
1937 1937 ui.write(g, '\n')
1938 1938 else:
1939 1939 ui.write(_('no active guards\n'))
1940 1940 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
1941 1941 popped = False
1942 1942 if opts['pop'] or opts['reapply']:
1943 1943 for i in xrange(len(q.applied)):
1944 1944 pushable, reason = q.pushable(i)
1945 1945 if not pushable:
1946 1946 ui.status(_('popping guarded patches\n'))
1947 1947 popped = True
1948 1948 if i == 0:
1949 1949 q.pop(repo, all=True)
1950 1950 else:
1951 1951 q.pop(repo, i-1)
1952 1952 break
1953 1953 if popped:
1954 1954 try:
1955 1955 if reapply:
1956 1956 ui.status(_('reapplying unguarded patches\n'))
1957 1957 q.push(repo, reapply)
1958 1958 finally:
1959 1959 q.save_dirty()
1960 1960
1961 1961 def reposetup(ui, repo):
1962 1962 class mqrepo(repo.__class__):
1963 1963 def abort_if_wdir_patched(self, errmsg, force=False):
1964 1964 if self.mq.applied and not force:
1965 1965 parent = revlog.hex(self.dirstate.parents()[0])
1966 1966 if parent in [s.rev for s in self.mq.applied]:
1967 1967 raise util.Abort(errmsg)
1968 1968
1969 1969 def commit(self, *args, **opts):
1970 1970 if len(args) >= 6:
1971 1971 force = args[5]
1972 1972 else:
1973 1973 force = opts.get('force')
1974 1974 self.abort_if_wdir_patched(
1975 1975 _('cannot commit over an applied mq patch'),
1976 1976 force)
1977 1977
1978 1978 return super(mqrepo, self).commit(*args, **opts)
1979 1979
1980 1980 def push(self, remote, force=False, revs=None):
1981 1981 if self.mq.applied and not force:
1982 1982 raise util.Abort(_('source has mq patches applied'))
1983 1983 return super(mqrepo, self).push(remote, force, revs)
1984 1984
1985 1985 def tags(self):
1986 1986 if self.tagscache:
1987 1987 return self.tagscache
1988 1988
1989 1989 tagscache = super(mqrepo, self).tags()
1990 1990
1991 1991 q = self.mq
1992 1992 if not q.applied:
1993 1993 return tagscache
1994 1994
1995 1995 mqtags = [(patch.rev, patch.name) for patch in q.applied]
1996 1996 mqtags.append((mqtags[-1][0], 'qtip'))
1997 1997 mqtags.append((mqtags[0][0], 'qbase'))
1998 1998 for patch in mqtags:
1999 1999 if patch[1] in tagscache:
2000 2000 self.ui.warn('Tag %s overrides mq patch of the same name\n' % patch[1])
2001 2001 else:
2002 2002 tagscache[patch[1]] = revlog.bin(patch[0])
2003 2003
2004 2004 return tagscache
2005 2005
2006 2006 if repo.local():
2007 2007 repo.__class__ = mqrepo
2008 2008 repo.mq = queue(ui, repo.join(""))
2009 2009
2010 2010 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2011 2011
2012 2012 cmdtable = {
2013 2013 "qapplied": (applied, [] + seriesopts, 'hg qapplied [-s] [PATCH]'),
2014 2014 "qclone": (clone,
2015 2015 [('', 'pull', None, _('use pull protocol to copy metadata')),
2016 2016 ('U', 'noupdate', None, _('do not update the new working directories')),
2017 2017 ('', 'uncompressed', None,
2018 2018 _('use uncompressed transfer (fast over LAN)')),
2019 2019 ('e', 'ssh', '', _('specify ssh command to use')),
2020 2020 ('p', 'patches', '', _('location of source patch repo')),
2021 2021 ('', 'remotecmd', '',
2022 2022 _('specify hg command to run on the remote side'))],
2023 2023 'hg qclone [OPTION]... SOURCE [DEST]'),
2024 2024 "qcommit|qci":
2025 2025 (commit,
2026 2026 commands.table["^commit|ci"][1],
2027 2027 'hg qcommit [OPTION]... [FILE]...'),
2028 2028 "^qdiff": (diff,
2029 2029 [('I', 'include', [], _('include names matching the given patterns')),
2030 2030 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2031 2031 'hg qdiff [-I] [-X] [FILE]...'),
2032 2032 "qdelete|qremove|qrm":
2033 2033 (delete,
2034 2034 [('k', 'keep', None, _('keep patch file')),
2035 2035 ('r', 'rev', [], _('stop managing a revision'))],
2036 2036 'hg qdelete [-k] [-r REV]... PATCH...'),
2037 2037 'qfold':
2038 2038 (fold,
2039 2039 [('e', 'edit', None, _('edit patch header')),
2040 2040 ('k', 'keep', None, _('keep folded patch files')),
2041 2041 ('m', 'message', '', _('set patch header to <text>')),
2042 2042 ('l', 'logfile', '', _('set patch header to contents of <file>'))],
2043 2043 'hg qfold [-e] [-m <text>] [-l <file] PATCH...'),
2044 2044 'qguard': (guard, [('l', 'list', None, _('list all patches and guards')),
2045 2045 ('n', 'none', None, _('drop all guards'))],
2046 2046 'hg qguard [PATCH] [+GUARD...] [-GUARD...]'),
2047 2047 'qheader': (header, [],
2048 2048 _('hg qheader [PATCH]')),
2049 2049 "^qimport":
2050 2050 (qimport,
2051 2051 [('e', 'existing', None, 'import file in patch dir'),
2052 2052 ('n', 'name', '', 'patch file name'),
2053 2053 ('f', 'force', None, 'overwrite existing files'),
2054 2054 ('r', 'rev', [], 'place existing revisions under mq control')],
2055 2055 'hg qimport [-e] [-n NAME] [-f] [-r REV]... FILE...'),
2056 2056 "^qinit":
2057 2057 (init,
2058 2058 [('c', 'create-repo', None, 'create queue repository')],
2059 2059 'hg qinit [-c]'),
2060 2060 "qnew":
2061 2061 (new,
2062 2062 [('e', 'edit', None, _('edit commit message')),
2063 2063 ('m', 'message', '', _('use <text> as commit message')),
2064 2064 ('l', 'logfile', '', _('read the commit message from <file>')),
2065 2065 ('f', 'force', None, _('import uncommitted changes into patch'))],
2066 2066 'hg qnew [-e] [-m TEXT] [-l FILE] [-f] PATCH'),
2067 2067 "qnext": (next, [] + seriesopts, 'hg qnext [-s]'),
2068 2068 "qprev": (prev, [] + seriesopts, 'hg qprev [-s]'),
2069 2069 "^qpop":
2070 2070 (pop,
2071 2071 [('a', 'all', None, 'pop all patches'),
2072 2072 ('n', 'name', '', 'queue name to pop'),
2073 2073 ('f', 'force', None, 'forget any local changes')],
2074 2074 'hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]'),
2075 2075 "^qpush":
2076 2076 (push,
2077 2077 [('f', 'force', None, 'apply if the patch has rejects'),
2078 2078 ('l', 'list', None, 'list patch name in commit text'),
2079 2079 ('a', 'all', None, 'apply all patches'),
2080 2080 ('m', 'merge', None, 'merge from another queue'),
2081 2081 ('n', 'name', '', 'merge queue name')],
2082 2082 'hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]'),
2083 2083 "^qrefresh":
2084 2084 (refresh,
2085 2085 [('e', 'edit', None, _('edit commit message')),
2086 2086 ('m', 'message', '', _('change commit message with <text>')),
2087 2087 ('l', 'logfile', '', _('change commit message with <file> content')),
2088 2088 ('g', 'git', None, _('use git extended diff format')),
2089 2089 ('s', 'short', None, 'short refresh'),
2090 2090 ('I', 'include', [], _('include names matching the given patterns')),
2091 2091 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2092 2092 'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] FILES...'),
2093 2093 'qrename|qmv':
2094 2094 (rename, [], 'hg qrename PATCH1 [PATCH2]'),
2095 2095 "qrestore":
2096 2096 (restore,
2097 2097 [('d', 'delete', None, 'delete save entry'),
2098 2098 ('u', 'update', None, 'update queue working dir')],
2099 2099 'hg qrestore [-d] [-u] REV'),
2100 2100 "qsave":
2101 2101 (save,
2102 2102 [('m', 'message', '', _('use <text> as commit message')),
2103 2103 ('l', 'logfile', '', _('read the commit message from <file>')),
2104 2104 ('c', 'copy', None, 'copy patch directory'),
2105 2105 ('n', 'name', '', 'copy directory name'),
2106 2106 ('e', 'empty', None, 'clear queue status file'),
2107 2107 ('f', 'force', None, 'force copy')],
2108 2108 'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
2109 2109 "qselect": (select,
2110 2110 [('n', 'none', None, _('disable all guards')),
2111 2111 ('s', 'series', None, _('list all guards in series file')),
2112 2112 ('', 'pop', None,
2113 2113 _('pop to before first guarded applied patch')),
2114 2114 ('', 'reapply', None, _('pop, then reapply patches'))],
2115 2115 'hg qselect [OPTION...] [GUARD...]'),
2116 2116 "qseries":
2117 2117 (series,
2118 2118 [('m', 'missing', None, 'print patches not in series')] + seriesopts,
2119 2119 'hg qseries [-ms]'),
2120 2120 "^strip":
2121 2121 (strip,
2122 2122 [('f', 'force', None, 'force multi-head removal'),
2123 2123 ('b', 'backup', None, 'bundle unrelated changesets'),
2124 2124 ('n', 'nobackup', None, 'no backups')],
2125 2125 'hg strip [-f] [-b] [-n] REV'),
2126 2126 "qtop": (top, [] + seriesopts, 'hg qtop [-s]'),
2127 2127 "qunapplied": (unapplied, [] + seriesopts, 'hg qunapplied [-s] [PATCH]'),
2128 2128 }
@@ -1,320 +1,320 b''
1 1 # Command for sending a collection of Mercurial changesets as a series
2 2 # of patch emails.
3 3 #
4 4 # The series is started off with a "[PATCH 0 of N]" introduction,
5 5 # which describes the series as a whole.
6 6 #
7 7 # Each patch email has a Subject line of "[PATCH M of N] ...", using
8 8 # the first line of the changeset description as the subject text.
9 9 # The message contains two or three body parts:
10 10 #
11 11 # The remainder of the changeset description.
12 12 #
13 13 # [Optional] If the diffstat program is installed, the result of
14 14 # running diffstat on the patch.
15 15 #
16 16 # The patch itself, as generated by "hg export".
17 17 #
18 18 # Each message refers to all of its predecessors using the In-Reply-To
19 19 # and References headers, so they will show up as a sequence in
20 20 # threaded mail and news readers, and in mail archives.
21 21 #
22 22 # For each changeset, you will be prompted with a diffstat summary and
23 23 # the changeset summary, so you can be sure you are sending the right
24 24 # changes.
25 25 #
26 26 # To enable this extension:
27 27 #
28 28 # [extensions]
29 29 # hgext.patchbomb =
30 30 #
31 31 # To configure other defaults, add a section like this to your hgrc
32 32 # file:
33 33 #
34 34 # [email]
35 35 # from = My Name <my@email>
36 36 # to = recipient1, recipient2, ...
37 37 # cc = cc1, cc2, ...
38 38 # bcc = bcc1, bcc2, ...
39 39 #
40 40 # Then you can use the "hg email" command to mail a series of changesets
41 41 # as a patchbomb.
42 42 #
43 43 # To avoid sending patches prematurely, it is a good idea to first run
44 44 # the "email" command with the "-n" option (test only). You will be
45 45 # prompted for an email recipient address, a subject an an introductory
46 46 # message describing the patches of your patchbomb. Then when all is
47 47 # done, your pager will be fired up once for each patchbomb message, so
48 48 # you can verify everything is alright.
49 49 #
50 50 # The "-m" (mbox) option is also very useful. Instead of previewing
51 51 # each patchbomb message in a pager or sending the messages directly,
52 52 # it will create a UNIX mailbox file with the patch emails. This
53 53 # mailbox file can be previewed with any mail user agent which supports
54 54 # UNIX mbox files, i.e. with mutt:
55 55 #
56 56 # % mutt -R -f mbox
57 57 #
58 58 # When you are previewing the patchbomb messages, you can use `formail'
59 59 # (a utility that is commonly installed as part of the procmail package),
60 60 # to send each message out:
61 61 #
62 62 # % formail -s sendmail -bm -t < mbox
63 63 #
64 64 # That should be all. Now your patchbomb is on its way out.
65 65
66 66 from mercurial.demandload import *
67 67 demandload(globals(), '''email.MIMEMultipart email.MIMEText email.Utils
68 68 mercurial:cmdutil,commands,hg,mail,ui,patch
69 69 os errno popen2 socket sys tempfile time''')
70 70 from mercurial.i18n import gettext as _
71 71 from mercurial.node import *
72 72
73 73 try:
74 74 # readline gives raw_input editing capabilities, but is not
75 75 # present on windows
76 76 import readline
77 77 except ImportError: pass
78 78
79 79 def patchbomb(ui, repo, *revs, **opts):
80 80 '''send changesets as a series of patch emails
81 81
82 82 The series starts with a "[PATCH 0 of N]" introduction, which
83 83 describes the series as a whole.
84 84
85 85 Each patch email has a Subject line of "[PATCH M of N] ...", using
86 86 the first line of the changeset description as the subject text.
87 87 The message contains two or three body parts. First, the rest of
88 88 the changeset description. Next, (optionally) if the diffstat
89 89 program is installed, the result of running diffstat on the patch.
90 90 Finally, the patch itself, as generated by "hg export".'''
91 91 def prompt(prompt, default = None, rest = ': ', empty_ok = False):
92 92 if default: prompt += ' [%s]' % default
93 93 prompt += rest
94 94 while True:
95 95 r = raw_input(prompt)
96 96 if r: return r
97 97 if default is not None: return default
98 98 if empty_ok: return r
99 99 ui.warn(_('Please enter a valid value.\n'))
100 100
101 101 def confirm(s):
102 102 if not prompt(s, default = 'y', rest = '? ').lower().startswith('y'):
103 103 raise ValueError
104 104
105 105 def cdiffstat(summary, patchlines):
106 106 s = patch.diffstat(patchlines)
107 107 if s:
108 108 if summary:
109 109 ui.write(summary, '\n')
110 110 ui.write(s, '\n')
111 111 confirm(_('Does the diffstat above look okay'))
112 112 return s
113 113
114 114 def makepatch(patch, idx, total):
115 115 desc = []
116 116 node = None
117 117 body = ''
118 118 for line in patch:
119 119 if line.startswith('#'):
120 120 if line.startswith('# Node ID'): node = line.split()[-1]
121 121 continue
122 122 if (line.startswith('diff -r')
123 123 or line.startswith('diff --git')):
124 124 break
125 125 desc.append(line)
126 126 if not node: raise ValueError
127 127
128 128 #body = ('\n'.join(desc[1:]).strip() or
129 129 # 'Patch subject is complete summary.')
130 130 #body += '\n\n\n'
131 131
132 132 if opts['plain']:
133 133 while patch and patch[0].startswith('# '): patch.pop(0)
134 134 if patch: patch.pop(0)
135 135 while patch and not patch[0].strip(): patch.pop(0)
136 136 if opts['diffstat']:
137 137 body += cdiffstat('\n'.join(desc), patch) + '\n\n'
138 138 if opts['attach']:
139 139 msg = email.MIMEMultipart.MIMEMultipart()
140 140 if body: msg.attach(email.MIMEText.MIMEText(body, 'plain'))
141 141 p = email.MIMEText.MIMEText('\n'.join(patch), 'x-patch')
142 142 binnode = bin(node)
143 143 # if node is mq patch, it will have patch file name as tag
144 144 patchname = [t for t in repo.nodetags(binnode)
145 145 if t.endswith('.patch') or t.endswith('.diff')]
146 146 if patchname:
147 147 patchname = patchname[0]
148 148 elif total > 1:
149 149 patchname = cmdutil.make_filename(repo, '%b-%n.patch',
150 150 binnode, idx, total)
151 151 else:
152 152 patchname = cmdutil.make_filename(repo, '%b.patch', binnode)
153 153 p['Content-Disposition'] = 'inline; filename=' + patchname
154 154 msg.attach(p)
155 155 else:
156 156 body += '\n'.join(patch)
157 157 msg = email.MIMEText.MIMEText(body)
158 158 if total == 1:
159 159 subj = '[PATCH] ' + desc[0].strip()
160 160 else:
161 161 tlen = len(str(total))
162 162 subj = '[PATCH %0*d of %d] %s' % (tlen, idx, total, desc[0].strip())
163 163 if subj.endswith('.'): subj = subj[:-1]
164 164 msg['Subject'] = subj
165 165 msg['X-Mercurial-Node'] = node
166 166 return msg
167 167
168 168 start_time = int(time.time())
169 169
170 170 def genmsgid(id):
171 171 return '<%s.%s@%s>' % (id[:20], start_time, socket.getfqdn())
172 172
173 173 patches = []
174 174
175 175 class exportee:
176 176 def __init__(self, container):
177 177 self.lines = []
178 178 self.container = container
179 179 self.name = 'email'
180 180
181 181 def write(self, data):
182 182 self.lines.append(data)
183 183
184 184 def close(self):
185 185 self.container.append(''.join(self.lines).split('\n'))
186 186 self.lines = []
187 187
188 188 commands.export(ui, repo, *revs, **{'output': exportee(patches),
189 189 'switch_parent': False,
190 190 'text': None,
191 191 'git': opts.get('git')})
192 192
193 193 jumbo = []
194 194 msgs = []
195 195
196 196 ui.write(_('This patch series consists of %d patches.\n\n') % len(patches))
197 197
198 for p, i in zip(patches, range(len(patches))):
198 for p, i in zip(patches, xrange(len(patches))):
199 199 jumbo.extend(p)
200 200 msgs.append(makepatch(p, i + 1, len(patches)))
201 201
202 202 sender = (opts['from'] or ui.config('email', 'from') or
203 203 ui.config('patchbomb', 'from') or
204 204 prompt('From', ui.username()))
205 205
206 206 def getaddrs(opt, prpt, default = None):
207 207 addrs = opts[opt] or (ui.config('email', opt) or
208 208 ui.config('patchbomb', opt) or
209 209 prompt(prpt, default = default)).split(',')
210 210 return [a.strip() for a in addrs if a.strip()]
211 211 to = getaddrs('to', 'To')
212 212 cc = getaddrs('cc', 'Cc', '')
213 213
214 214 bcc = opts['bcc'] or (ui.config('email', 'bcc') or
215 215 ui.config('patchbomb', 'bcc') or '').split(',')
216 216 bcc = [a.strip() for a in bcc if a.strip()]
217 217
218 218 if len(patches) > 1:
219 219 ui.write(_('\nWrite the introductory message for the patch series.\n\n'))
220 220
221 221 tlen = len(str(len(patches)))
222 222
223 223 subj = '[PATCH %0*d of %d] %s' % (
224 224 tlen, 0,
225 225 len(patches),
226 226 opts['subject'] or
227 227 prompt('Subject:', rest = ' [PATCH %0*d of %d] ' % (tlen, 0,
228 228 len(patches))))
229 229
230 230 ui.write(_('Finish with ^D or a dot on a line by itself.\n\n'))
231 231
232 232 body = []
233 233
234 234 while True:
235 235 try: l = raw_input()
236 236 except EOFError: break
237 237 if l == '.': break
238 238 body.append(l)
239 239
240 240 if opts['diffstat']:
241 241 d = cdiffstat(_('Final summary:\n'), jumbo)
242 242 if d: body.append('\n' + d)
243 243
244 244 body = '\n'.join(body) + '\n'
245 245
246 246 msg = email.MIMEText.MIMEText(body)
247 247 msg['Subject'] = subj
248 248
249 249 msgs.insert(0, msg)
250 250
251 251 ui.write('\n')
252 252
253 253 if not opts['test'] and not opts['mbox']:
254 254 mailer = mail.connect(ui)
255 255 parent = None
256 256
257 257 # Calculate UTC offset
258 258 if time.daylight: offset = time.altzone
259 259 else: offset = time.timezone
260 260 if offset <= 0: sign, offset = '+', -offset
261 261 else: sign = '-'
262 262 offset = '%s%02d%02d' % (sign, offset / 3600, (offset % 3600) / 60)
263 263
264 264 sender_addr = email.Utils.parseaddr(sender)[1]
265 265 for m in msgs:
266 266 try:
267 267 m['Message-Id'] = genmsgid(m['X-Mercurial-Node'])
268 268 except TypeError:
269 269 m['Message-Id'] = genmsgid('patchbomb')
270 270 if parent:
271 271 m['In-Reply-To'] = parent
272 272 else:
273 273 parent = m['Message-Id']
274 274 m['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(start_time)) + ' ' + offset
275 275
276 276 start_time += 1
277 277 m['From'] = sender
278 278 m['To'] = ', '.join(to)
279 279 if cc: m['Cc'] = ', '.join(cc)
280 280 if bcc: m['Bcc'] = ', '.join(bcc)
281 281 if opts['test']:
282 282 ui.status('Displaying ', m['Subject'], ' ...\n')
283 283 fp = os.popen(os.getenv('PAGER', 'more'), 'w')
284 284 try:
285 285 fp.write(m.as_string(0))
286 286 fp.write('\n')
287 287 except IOError, inst:
288 288 if inst.errno != errno.EPIPE:
289 289 raise
290 290 fp.close()
291 291 elif opts['mbox']:
292 292 ui.status('Writing ', m['Subject'], ' ...\n')
293 293 fp = open(opts['mbox'], m.has_key('In-Reply-To') and 'ab+' or 'wb+')
294 294 date = time.asctime(time.localtime(start_time))
295 295 fp.write('From %s %s\n' % (sender_addr, date))
296 296 fp.write(m.as_string(0))
297 297 fp.write('\n\n')
298 298 fp.close()
299 299 else:
300 300 ui.status('Sending ', m['Subject'], ' ...\n')
301 301 # Exim does not remove the Bcc field
302 302 del m['Bcc']
303 303 mailer.sendmail(sender, to + bcc + cc, m.as_string(0))
304 304
305 305 cmdtable = {
306 306 'email':
307 307 (patchbomb,
308 308 [('a', 'attach', None, 'send patches as inline attachments'),
309 309 ('', 'bcc', [], 'email addresses of blind copy recipients'),
310 310 ('c', 'cc', [], 'email addresses of copy recipients'),
311 311 ('d', 'diffstat', None, 'add diffstat output to messages'),
312 312 ('g', 'git', None, _('use git extended diff format')),
313 313 ('f', 'from', '', 'email address of sender'),
314 314 ('', 'plain', None, 'omit hg patch header'),
315 315 ('n', 'test', None, 'print messages that would be sent'),
316 316 ('m', 'mbox', '', 'write messages to mbox file instead of sending them'),
317 317 ('s', 'subject', '', 'subject of introductory message'),
318 318 ('t', 'to', [], 'email addresses of recipients')],
319 319 "hg email [OPTION]... [REV]...")
320 320 }
@@ -1,1088 +1,1088 b''
1 1 # hgweb/hgweb_mod.py - Web interface for a repository.
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms
7 7 # of the GNU General Public License, incorporated herein by reference.
8 8
9 9 import os
10 10 import os.path
11 11 import mimetypes
12 12 from mercurial.demandload import demandload
13 13 demandload(globals(), "re zlib ConfigParser mimetools cStringIO sys tempfile")
14 14 demandload(globals(), 'urllib')
15 15 demandload(globals(), "mercurial:mdiff,ui,hg,util,archival,streamclone,patch")
16 16 demandload(globals(), "mercurial:revlog,templater")
17 17 demandload(globals(), "mercurial.hgweb.common:get_mtime,staticfile,style_map")
18 18 from mercurial.node import *
19 19 from mercurial.i18n import gettext as _
20 20
21 21 def _up(p):
22 22 if p[0] != "/":
23 23 p = "/" + p
24 24 if p[-1] == "/":
25 25 p = p[:-1]
26 26 up = os.path.dirname(p)
27 27 if up == "/":
28 28 return "/"
29 29 return up + "/"
30 30
31 31 def revnavgen(pos, pagelen, limit, nodefunc):
32 32 def seq(factor, limit=None):
33 33 if limit:
34 34 yield limit
35 35 if limit >= 20 and limit <= 40:
36 36 yield 50
37 37 else:
38 38 yield 1 * factor
39 39 yield 3 * factor
40 40 for f in seq(factor * 10):
41 41 yield f
42 42
43 43 def nav(**map):
44 44 l = []
45 45 last = 0
46 46 for f in seq(1, pagelen):
47 47 if f < pagelen or f <= last:
48 48 continue
49 49 if f > limit:
50 50 break
51 51 last = f
52 52 if pos + f < limit:
53 53 l.append(("+%d" % f, hex(nodefunc(pos + f).node())))
54 54 if pos - f >= 0:
55 55 l.insert(0, ("-%d" % f, hex(nodefunc(pos - f).node())))
56 56
57 57 try:
58 58 yield {"label": "(0)", "node": hex(nodefunc('0').node())}
59 59
60 60 for label, node in l:
61 61 yield {"label": label, "node": node}
62 62
63 63 yield {"label": "tip", "node": "tip"}
64 64 except hg.RepoError:
65 65 pass
66 66
67 67 return nav
68 68
69 69 class hgweb(object):
70 70 def __init__(self, repo, name=None):
71 71 if type(repo) == type(""):
72 72 self.repo = hg.repository(ui.ui(), repo)
73 73 else:
74 74 self.repo = repo
75 75
76 76 self.mtime = -1
77 77 self.reponame = name
78 78 self.archives = 'zip', 'gz', 'bz2'
79 79 self.stripecount = 1
80 80 self.templatepath = self.repo.ui.config("web", "templates",
81 81 templater.templatepath())
82 82
83 83 def refresh(self):
84 84 mtime = get_mtime(self.repo.root)
85 85 if mtime != self.mtime:
86 86 self.mtime = mtime
87 87 self.repo = hg.repository(self.repo.ui, self.repo.root)
88 88 self.maxchanges = int(self.repo.ui.config("web", "maxchanges", 10))
89 89 self.stripecount = int(self.repo.ui.config("web", "stripes", 1))
90 90 self.maxshortchanges = int(self.repo.ui.config("web", "maxshortchanges", 60))
91 91 self.maxfiles = int(self.repo.ui.config("web", "maxfiles", 10))
92 92 self.allowpull = self.repo.ui.configbool("web", "allowpull", True)
93 93
94 94 def archivelist(self, nodeid):
95 95 allowed = self.repo.ui.configlist("web", "allow_archive")
96 96 for i, spec in self.archive_specs.iteritems():
97 97 if i in allowed or self.repo.ui.configbool("web", "allow" + i):
98 98 yield {"type" : i, "extension" : spec[2], "node" : nodeid}
99 99
100 100 def listfilediffs(self, files, changeset):
101 101 for f in files[:self.maxfiles]:
102 102 yield self.t("filedifflink", node=hex(changeset), file=f)
103 103 if len(files) > self.maxfiles:
104 104 yield self.t("fileellipses")
105 105
106 106 def siblings(self, siblings=[], hiderev=None, **args):
107 107 siblings = [s for s in siblings if s.node() != nullid]
108 108 if len(siblings) == 1 and siblings[0].rev() == hiderev:
109 109 return
110 110 for s in siblings:
111 111 d = {'node': hex(s.node()), 'rev': s.rev()}
112 112 if hasattr(s, 'path'):
113 113 d['file'] = s.path()
114 114 d.update(args)
115 115 yield d
116 116
117 117 def renamelink(self, fl, node):
118 118 r = fl.renamed(node)
119 119 if r:
120 120 return [dict(file=r[0], node=hex(r[1]))]
121 121 return []
122 122
123 123 def showtag(self, t1, node=nullid, **args):
124 124 for t in self.repo.nodetags(node):
125 125 yield self.t(t1, tag=t, **args)
126 126
127 127 def diff(self, node1, node2, files):
128 128 def filterfiles(filters, files):
129 129 l = [x for x in files if x in filters]
130 130
131 131 for t in filters:
132 132 if t and t[-1] != os.sep:
133 133 t += os.sep
134 134 l += [x for x in files if x.startswith(t)]
135 135 return l
136 136
137 137 parity = [0]
138 138 def diffblock(diff, f, fn):
139 139 yield self.t("diffblock",
140 140 lines=prettyprintlines(diff),
141 141 parity=parity[0],
142 142 file=f,
143 143 filenode=hex(fn or nullid))
144 144 parity[0] = 1 - parity[0]
145 145
146 146 def prettyprintlines(diff):
147 147 for l in diff.splitlines(1):
148 148 if l.startswith('+'):
149 149 yield self.t("difflineplus", line=l)
150 150 elif l.startswith('-'):
151 151 yield self.t("difflineminus", line=l)
152 152 elif l.startswith('@'):
153 153 yield self.t("difflineat", line=l)
154 154 else:
155 155 yield self.t("diffline", line=l)
156 156
157 157 r = self.repo
158 158 cl = r.changelog
159 159 mf = r.manifest
160 160 change1 = cl.read(node1)
161 161 change2 = cl.read(node2)
162 162 mmap1 = mf.read(change1[0])
163 163 mmap2 = mf.read(change2[0])
164 164 date1 = util.datestr(change1[2])
165 165 date2 = util.datestr(change2[2])
166 166
167 167 modified, added, removed, deleted, unknown = r.status(node1, node2)[:5]
168 168 if files:
169 169 modified, added, removed = map(lambda x: filterfiles(files, x),
170 170 (modified, added, removed))
171 171
172 172 diffopts = patch.diffopts(self.repo.ui)
173 173 for f in modified:
174 174 to = r.file(f).read(mmap1[f])
175 175 tn = r.file(f).read(mmap2[f])
176 176 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
177 177 opts=diffopts), f, tn)
178 178 for f in added:
179 179 to = None
180 180 tn = r.file(f).read(mmap2[f])
181 181 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
182 182 opts=diffopts), f, tn)
183 183 for f in removed:
184 184 to = r.file(f).read(mmap1[f])
185 185 tn = None
186 186 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
187 187 opts=diffopts), f, tn)
188 188
189 189 def changelog(self, ctx, shortlog=False):
190 190 def changelist(**map):
191 191 parity = (start - end) & 1
192 192 cl = self.repo.changelog
193 193 l = [] # build a list in forward order for efficiency
194 for i in range(start, end):
194 for i in xrange(start, end):
195 195 ctx = self.repo.changectx(i)
196 196 n = ctx.node()
197 197
198 198 l.insert(0, {"parity": parity,
199 199 "author": ctx.user(),
200 200 "parent": self.siblings(ctx.parents(), i - 1),
201 201 "child": self.siblings(ctx.children(), i + 1),
202 202 "changelogtag": self.showtag("changelogtag",n),
203 203 "desc": ctx.description(),
204 204 "date": ctx.date(),
205 205 "files": self.listfilediffs(ctx.files(), n),
206 206 "rev": i,
207 207 "node": hex(n)})
208 208 parity = 1 - parity
209 209
210 210 for e in l:
211 211 yield e
212 212
213 213 maxchanges = shortlog and self.maxshortchanges or self.maxchanges
214 214 cl = self.repo.changelog
215 215 count = cl.count()
216 216 pos = ctx.rev()
217 217 start = max(0, pos - maxchanges + 1)
218 218 end = min(count, start + maxchanges)
219 219 pos = end - 1
220 220
221 221 changenav = revnavgen(pos, maxchanges, count, self.repo.changectx)
222 222
223 223 yield self.t(shortlog and 'shortlog' or 'changelog',
224 224 changenav=changenav,
225 225 node=hex(cl.tip()),
226 226 rev=pos, changesets=count, entries=changelist,
227 227 archives=self.archivelist("tip"))
228 228
229 229 def search(self, query):
230 230
231 231 def changelist(**map):
232 232 cl = self.repo.changelog
233 233 count = 0
234 234 qw = query.lower().split()
235 235
236 236 def revgen():
237 for i in range(cl.count() - 1, 0, -100):
237 for i in xrange(cl.count() - 1, 0, -100):
238 238 l = []
239 for j in range(max(0, i - 100), i):
239 for j in xrange(max(0, i - 100), i):
240 240 ctx = self.repo.changectx(j)
241 241 l.append(ctx)
242 242 l.reverse()
243 243 for e in l:
244 244 yield e
245 245
246 246 for ctx in revgen():
247 247 miss = 0
248 248 for q in qw:
249 249 if not (q in ctx.user().lower() or
250 250 q in ctx.description().lower() or
251 251 q in " ".join(ctx.files()[:20]).lower()):
252 252 miss = 1
253 253 break
254 254 if miss:
255 255 continue
256 256
257 257 count += 1
258 258 n = ctx.node()
259 259
260 260 yield self.t('searchentry',
261 261 parity=self.stripes(count),
262 262 author=ctx.user(),
263 263 parent=self.siblings(ctx.parents()),
264 264 child=self.siblings(ctx.children()),
265 265 changelogtag=self.showtag("changelogtag",n),
266 266 desc=ctx.description(),
267 267 date=ctx.date(),
268 268 files=self.listfilediffs(ctx.files(), n),
269 269 rev=ctx.rev(),
270 270 node=hex(n))
271 271
272 272 if count >= self.maxchanges:
273 273 break
274 274
275 275 cl = self.repo.changelog
276 276
277 277 yield self.t('search',
278 278 query=query,
279 279 node=hex(cl.tip()),
280 280 entries=changelist)
281 281
282 282 def changeset(self, ctx):
283 283 n = ctx.node()
284 284 parents = ctx.parents()
285 285 p1 = parents[0].node()
286 286
287 287 files = []
288 288 parity = 0
289 289 for f in ctx.files():
290 290 files.append(self.t("filenodelink",
291 291 node=hex(n), file=f,
292 292 parity=parity))
293 293 parity = 1 - parity
294 294
295 295 def diff(**map):
296 296 yield self.diff(p1, n, None)
297 297
298 298 yield self.t('changeset',
299 299 diff=diff,
300 300 rev=ctx.rev(),
301 301 node=hex(n),
302 302 parent=self.siblings(parents),
303 303 child=self.siblings(ctx.children()),
304 304 changesettag=self.showtag("changesettag",n),
305 305 author=ctx.user(),
306 306 desc=ctx.description(),
307 307 date=ctx.date(),
308 308 files=files,
309 309 archives=self.archivelist(hex(n)))
310 310
311 311 def filelog(self, fctx):
312 312 f = fctx.path()
313 313 fl = fctx.filelog()
314 314 count = fl.count()
315 315 pagelen = self.maxshortchanges
316 316 pos = fctx.filerev()
317 317 start = max(0, pos - pagelen + 1)
318 318 end = min(count, start + pagelen)
319 319 pos = end - 1
320 320
321 321 def entries(**map):
322 322 l = []
323 323 parity = (count - 1) & 1
324 324
325 for i in range(start, end):
325 for i in xrange(start, end):
326 326 ctx = fctx.filectx(i)
327 327 n = fl.node(i)
328 328
329 329 l.insert(0, {"parity": parity,
330 330 "filerev": i,
331 331 "file": f,
332 332 "node": hex(ctx.node()),
333 333 "author": ctx.user(),
334 334 "date": ctx.date(),
335 335 "rename": self.renamelink(fl, n),
336 336 "parent": self.siblings(fctx.parents()),
337 337 "child": self.siblings(fctx.children()),
338 338 "desc": ctx.description()})
339 339 parity = 1 - parity
340 340
341 341 for e in l:
342 342 yield e
343 343
344 344 nodefunc = lambda x: fctx.filectx(fileid=x)
345 345 nav = revnavgen(pos, pagelen, count, nodefunc)
346 346 yield self.t("filelog", file=f, node=hex(fctx.node()), nav=nav,
347 347 entries=entries)
348 348
349 349 def filerevision(self, fctx):
350 350 f = fctx.path()
351 351 text = fctx.data()
352 352 fl = fctx.filelog()
353 353 n = fctx.filenode()
354 354
355 355 mt = mimetypes.guess_type(f)[0]
356 356 rawtext = text
357 357 if util.binary(text):
358 358 mt = mt or 'application/octet-stream'
359 359 text = "(binary:%s)" % mt
360 360 mt = mt or 'text/plain'
361 361
362 362 def lines():
363 363 for l, t in enumerate(text.splitlines(1)):
364 364 yield {"line": t,
365 365 "linenumber": "% 6d" % (l + 1),
366 366 "parity": self.stripes(l)}
367 367
368 368 yield self.t("filerevision",
369 369 file=f,
370 370 path=_up(f),
371 371 text=lines(),
372 372 raw=rawtext,
373 373 mimetype=mt,
374 374 rev=fctx.rev(),
375 375 node=hex(fctx.node()),
376 376 author=fctx.user(),
377 377 date=fctx.date(),
378 378 desc=fctx.description(),
379 379 parent=self.siblings(fctx.parents()),
380 380 child=self.siblings(fctx.children()),
381 381 rename=self.renamelink(fl, n),
382 382 permissions=fctx.manifest().execf(f))
383 383
384 384 def fileannotate(self, fctx):
385 385 f = fctx.path()
386 386 n = fctx.filenode()
387 387 fl = fctx.filelog()
388 388
389 389 def annotate(**map):
390 390 parity = 0
391 391 last = None
392 392 for f, l in fctx.annotate(follow=True):
393 393 fnode = f.filenode()
394 394 name = self.repo.ui.shortuser(f.user())
395 395
396 396 if last != fnode:
397 397 parity = 1 - parity
398 398 last = fnode
399 399
400 400 yield {"parity": parity,
401 401 "node": hex(f.node()),
402 402 "rev": f.rev(),
403 403 "author": name,
404 404 "file": f.path(),
405 405 "line": l}
406 406
407 407 yield self.t("fileannotate",
408 408 file=f,
409 409 annotate=annotate,
410 410 path=_up(f),
411 411 rev=fctx.rev(),
412 412 node=hex(fctx.node()),
413 413 author=fctx.user(),
414 414 date=fctx.date(),
415 415 desc=fctx.description(),
416 416 rename=self.renamelink(fl, n),
417 417 parent=self.siblings(fctx.parents()),
418 418 child=self.siblings(fctx.children()),
419 419 permissions=fctx.manifest().execf(f))
420 420
421 421 def manifest(self, ctx, path):
422 422 mf = ctx.manifest()
423 423 node = ctx.node()
424 424
425 425 files = {}
426 426
427 427 p = path[1:]
428 428 if p and p[-1] != "/":
429 429 p += "/"
430 430 l = len(p)
431 431
432 432 for f,n in mf.items():
433 433 if f[:l] != p:
434 434 continue
435 435 remain = f[l:]
436 436 if "/" in remain:
437 437 short = remain[:remain.index("/") + 1] # bleah
438 438 files[short] = (f, None)
439 439 else:
440 440 short = os.path.basename(remain)
441 441 files[short] = (f, n)
442 442
443 443 def filelist(**map):
444 444 parity = 0
445 445 fl = files.keys()
446 446 fl.sort()
447 447 for f in fl:
448 448 full, fnode = files[f]
449 449 if not fnode:
450 450 continue
451 451
452 452 yield {"file": full,
453 453 "parity": self.stripes(parity),
454 454 "basename": f,
455 455 "size": ctx.filectx(full).size(),
456 456 "permissions": mf.execf(full)}
457 457 parity += 1
458 458
459 459 def dirlist(**map):
460 460 parity = 0
461 461 fl = files.keys()
462 462 fl.sort()
463 463 for f in fl:
464 464 full, fnode = files[f]
465 465 if fnode:
466 466 continue
467 467
468 468 yield {"parity": self.stripes(parity),
469 469 "path": os.path.join(path, f),
470 470 "basename": f[:-1]}
471 471 parity += 1
472 472
473 473 yield self.t("manifest",
474 474 rev=ctx.rev(),
475 475 node=hex(node),
476 476 path=path,
477 477 up=_up(path),
478 478 fentries=filelist,
479 479 dentries=dirlist,
480 480 archives=self.archivelist(hex(node)))
481 481
482 482 def tags(self):
483 483 cl = self.repo.changelog
484 484
485 485 i = self.repo.tagslist()
486 486 i.reverse()
487 487
488 488 def entries(notip=False, **map):
489 489 parity = 0
490 490 for k,n in i:
491 491 if notip and k == "tip": continue
492 492 yield {"parity": self.stripes(parity),
493 493 "tag": k,
494 494 "date": cl.read(n)[2],
495 495 "node": hex(n)}
496 496 parity += 1
497 497
498 498 yield self.t("tags",
499 499 node=hex(self.repo.changelog.tip()),
500 500 entries=lambda **x: entries(False, **x),
501 501 entriesnotip=lambda **x: entries(True, **x))
502 502
503 503 def summary(self):
504 504 cl = self.repo.changelog
505 505
506 506 i = self.repo.tagslist()
507 507 i.reverse()
508 508
509 509 def tagentries(**map):
510 510 parity = 0
511 511 count = 0
512 512 for k,n in i:
513 513 if k == "tip": # skip tip
514 514 continue;
515 515
516 516 count += 1
517 517 if count > 10: # limit to 10 tags
518 518 break;
519 519
520 520 c = cl.read(n)
521 521 t = c[2]
522 522
523 523 yield self.t("tagentry",
524 524 parity = self.stripes(parity),
525 525 tag = k,
526 526 node = hex(n),
527 527 date = t)
528 528 parity += 1
529 529
530 530 def changelist(**map):
531 531 parity = 0
532 532 cl = self.repo.changelog
533 533 l = [] # build a list in forward order for efficiency
534 for i in range(start, end):
534 for i in xrange(start, end):
535 535 n = cl.node(i)
536 536 changes = cl.read(n)
537 537 hn = hex(n)
538 538 t = changes[2]
539 539
540 540 l.insert(0, self.t(
541 541 'shortlogentry',
542 542 parity = parity,
543 543 author = changes[1],
544 544 desc = changes[4],
545 545 date = t,
546 546 rev = i,
547 547 node = hn))
548 548 parity = 1 - parity
549 549
550 550 yield l
551 551
552 552 count = cl.count()
553 553 start = max(0, count - self.maxchanges)
554 554 end = min(count, start + self.maxchanges)
555 555
556 556 yield self.t("summary",
557 557 desc = self.repo.ui.config("web", "description", "unknown"),
558 558 owner = (self.repo.ui.config("ui", "username") or # preferred
559 559 self.repo.ui.config("web", "contact") or # deprecated
560 560 self.repo.ui.config("web", "author", "unknown")), # also
561 561 lastchange = cl.read(cl.tip())[2],
562 562 tags = tagentries,
563 563 shortlog = changelist,
564 564 node = hex(cl.tip()),
565 565 archives=self.archivelist("tip"))
566 566
567 567 def filediff(self, fctx):
568 568 n = fctx.node()
569 569 path = fctx.path()
570 570 parents = fctx.parents()
571 571 p1 = parents and parents[0].node() or nullid
572 572
573 573 def diff(**map):
574 574 yield self.diff(p1, n, [path])
575 575
576 576 yield self.t("filediff",
577 577 file=path,
578 578 node=hex(n),
579 579 rev=fctx.rev(),
580 580 parent=self.siblings(parents),
581 581 child=self.siblings(fctx.children()),
582 582 diff=diff)
583 583
584 584 archive_specs = {
585 585 'bz2': ('application/x-tar', 'tbz2', '.tar.bz2', None),
586 586 'gz': ('application/x-tar', 'tgz', '.tar.gz', None),
587 587 'zip': ('application/zip', 'zip', '.zip', None),
588 588 }
589 589
590 590 def archive(self, req, cnode, type_):
591 591 reponame = re.sub(r"\W+", "-", os.path.basename(self.reponame))
592 592 name = "%s-%s" % (reponame, short(cnode))
593 593 mimetype, artype, extension, encoding = self.archive_specs[type_]
594 594 headers = [('Content-type', mimetype),
595 595 ('Content-disposition', 'attachment; filename=%s%s' %
596 596 (name, extension))]
597 597 if encoding:
598 598 headers.append(('Content-encoding', encoding))
599 599 req.header(headers)
600 600 archival.archive(self.repo, req.out, cnode, artype, prefix=name)
601 601
602 602 # add tags to things
603 603 # tags -> list of changesets corresponding to tags
604 604 # find tag, changeset, file
605 605
606 606 def cleanpath(self, path):
607 607 return util.canonpath(self.repo.root, '', path)
608 608
609 609 def run(self):
610 610 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
611 611 raise RuntimeError("This function is only intended to be called while running as a CGI script.")
612 612 import mercurial.hgweb.wsgicgi as wsgicgi
613 613 from request import wsgiapplication
614 614 def make_web_app():
615 615 return self
616 616 wsgicgi.launch(wsgiapplication(make_web_app))
617 617
618 618 def run_wsgi(self, req):
619 619 def header(**map):
620 620 header_file = cStringIO.StringIO(''.join(self.t("header", **map)))
621 621 msg = mimetools.Message(header_file, 0)
622 622 req.header(msg.items())
623 623 yield header_file.read()
624 624
625 625 def rawfileheader(**map):
626 626 req.header([('Content-type', map['mimetype']),
627 627 ('Content-disposition', 'filename=%s' % map['file']),
628 628 ('Content-length', str(len(map['raw'])))])
629 629 yield ''
630 630
631 631 def footer(**map):
632 632 yield self.t("footer",
633 633 motd=self.repo.ui.config("web", "motd", ""),
634 634 **map)
635 635
636 636 def expand_form(form):
637 637 shortcuts = {
638 638 'cl': [('cmd', ['changelog']), ('rev', None)],
639 639 'sl': [('cmd', ['shortlog']), ('rev', None)],
640 640 'cs': [('cmd', ['changeset']), ('node', None)],
641 641 'f': [('cmd', ['file']), ('filenode', None)],
642 642 'fl': [('cmd', ['filelog']), ('filenode', None)],
643 643 'fd': [('cmd', ['filediff']), ('node', None)],
644 644 'fa': [('cmd', ['annotate']), ('filenode', None)],
645 645 'mf': [('cmd', ['manifest']), ('manifest', None)],
646 646 'ca': [('cmd', ['archive']), ('node', None)],
647 647 'tags': [('cmd', ['tags'])],
648 648 'tip': [('cmd', ['changeset']), ('node', ['tip'])],
649 649 'static': [('cmd', ['static']), ('file', None)]
650 650 }
651 651
652 652 for k in shortcuts.iterkeys():
653 653 if form.has_key(k):
654 654 for name, value in shortcuts[k]:
655 655 if value is None:
656 656 value = form[k]
657 657 form[name] = value
658 658 del form[k]
659 659
660 660 def rewrite_request(req):
661 661 '''translate new web interface to traditional format'''
662 662
663 663 def spliturl(req):
664 664 def firstitem(query):
665 665 return query.split('&', 1)[0].split(';', 1)[0]
666 666
667 667 def normurl(url):
668 668 inner = '/'.join([x for x in url.split('/') if x])
669 669 tl = len(url) > 1 and url.endswith('/') and '/' or ''
670 670
671 671 return '%s%s%s' % (url.startswith('/') and '/' or '',
672 672 inner, tl)
673 673
674 674 root = normurl(req.env.get('REQUEST_URI', '').split('?', 1)[0])
675 675 pi = normurl(req.env.get('PATH_INFO', ''))
676 676 if pi:
677 677 # strip leading /
678 678 pi = pi[1:]
679 679 if pi:
680 680 root = root[:-len(pi)]
681 681 if req.env.has_key('REPO_NAME'):
682 682 rn = req.env['REPO_NAME'] + '/'
683 683 root += rn
684 684 query = pi[len(rn):]
685 685 else:
686 686 query = pi
687 687 else:
688 688 root += '?'
689 689 query = firstitem(req.env['QUERY_STRING'])
690 690
691 691 return (root, query)
692 692
693 693 req.url, query = spliturl(req)
694 694
695 695 if req.form.has_key('cmd'):
696 696 # old style
697 697 return
698 698
699 699 args = query.split('/', 2)
700 700 if not args or not args[0]:
701 701 return
702 702
703 703 cmd = args.pop(0)
704 704 style = cmd.rfind('-')
705 705 if style != -1:
706 706 req.form['style'] = [cmd[:style]]
707 707 cmd = cmd[style+1:]
708 708 # avoid accepting e.g. style parameter as command
709 709 if hasattr(self, 'do_' + cmd):
710 710 req.form['cmd'] = [cmd]
711 711
712 712 if args and args[0]:
713 713 node = args.pop(0)
714 714 req.form['node'] = [node]
715 715 if args:
716 716 req.form['file'] = args
717 717
718 718 if cmd == 'static':
719 719 req.form['file'] = req.form['node']
720 720 elif cmd == 'archive':
721 721 fn = req.form['node'][0]
722 722 for type_, spec in self.archive_specs.iteritems():
723 723 ext = spec[2]
724 724 if fn.endswith(ext):
725 725 req.form['node'] = [fn[:-len(ext)]]
726 726 req.form['type'] = [type_]
727 727
728 728 def sessionvars(**map):
729 729 fields = []
730 730 if req.form.has_key('style'):
731 731 style = req.form['style'][0]
732 732 if style != self.repo.ui.config('web', 'style', ''):
733 733 fields.append(('style', style))
734 734
735 735 separator = req.url[-1] == '?' and ';' or '?'
736 736 for name, value in fields:
737 737 yield dict(name=name, value=value, separator=separator)
738 738 separator = ';'
739 739
740 740 self.refresh()
741 741
742 742 expand_form(req.form)
743 743 rewrite_request(req)
744 744
745 745 style = self.repo.ui.config("web", "style", "")
746 746 if req.form.has_key('style'):
747 747 style = req.form['style'][0]
748 748 mapfile = style_map(self.templatepath, style)
749 749
750 750 port = req.env["SERVER_PORT"]
751 751 port = port != "80" and (":" + port) or ""
752 752 urlbase = 'http://%s%s' % (req.env['SERVER_NAME'], port)
753 753
754 754 if not self.reponame:
755 755 self.reponame = (self.repo.ui.config("web", "name")
756 756 or req.env.get('REPO_NAME')
757 757 or req.url.strip('/') or self.repo.root)
758 758
759 759 self.t = templater.templater(mapfile, templater.common_filters,
760 760 defaults={"url": req.url,
761 761 "urlbase": urlbase,
762 762 "repo": self.reponame,
763 763 "header": header,
764 764 "footer": footer,
765 765 "rawfileheader": rawfileheader,
766 766 "sessionvars": sessionvars
767 767 })
768 768
769 769 if not req.form.has_key('cmd'):
770 770 req.form['cmd'] = [self.t.cache['default'],]
771 771
772 772 cmd = req.form['cmd'][0]
773 773
774 774 method = getattr(self, 'do_' + cmd, None)
775 775 if method:
776 776 try:
777 777 method(req)
778 778 except (hg.RepoError, revlog.RevlogError), inst:
779 779 req.write(self.t("error", error=str(inst)))
780 780 else:
781 781 req.write(self.t("error", error='No such method: ' + cmd))
782 782
783 783 def changectx(self, req):
784 784 if req.form.has_key('node'):
785 785 changeid = req.form['node'][0]
786 786 elif req.form.has_key('manifest'):
787 787 changeid = req.form['manifest'][0]
788 788 else:
789 789 changeid = self.repo.changelog.count() - 1
790 790
791 791 try:
792 792 ctx = self.repo.changectx(changeid)
793 793 except hg.RepoError:
794 794 man = self.repo.manifest
795 795 mn = man.lookup(changeid)
796 796 ctx = self.repo.changectx(man.linkrev(mn))
797 797
798 798 return ctx
799 799
800 800 def filectx(self, req):
801 801 path = self.cleanpath(req.form['file'][0])
802 802 if req.form.has_key('node'):
803 803 changeid = req.form['node'][0]
804 804 else:
805 805 changeid = req.form['filenode'][0]
806 806 try:
807 807 ctx = self.repo.changectx(changeid)
808 808 fctx = ctx.filectx(path)
809 809 except hg.RepoError:
810 810 fctx = self.repo.filectx(path, fileid=changeid)
811 811
812 812 return fctx
813 813
814 814 def stripes(self, parity):
815 815 "make horizontal stripes for easier reading"
816 816 if self.stripecount:
817 817 return (1 + parity / self.stripecount) & 1
818 818 else:
819 819 return 0
820 820
821 821 def do_log(self, req):
822 822 if req.form.has_key('file') and req.form['file'][0]:
823 823 self.do_filelog(req)
824 824 else:
825 825 self.do_changelog(req)
826 826
827 827 def do_rev(self, req):
828 828 self.do_changeset(req)
829 829
830 830 def do_file(self, req):
831 831 path = req.form.get('file', [''])[0]
832 832 if path:
833 833 try:
834 834 req.write(self.filerevision(self.filectx(req)))
835 835 return
836 836 except hg.RepoError:
837 837 pass
838 838 path = self.cleanpath(path)
839 839
840 840 req.write(self.manifest(self.changectx(req), '/' + path))
841 841
842 842 def do_diff(self, req):
843 843 self.do_filediff(req)
844 844
845 845 def do_changelog(self, req, shortlog = False):
846 846 if req.form.has_key('node'):
847 847 ctx = self.changectx(req)
848 848 else:
849 849 if req.form.has_key('rev'):
850 850 hi = req.form['rev'][0]
851 851 else:
852 852 hi = self.repo.changelog.count() - 1
853 853 try:
854 854 ctx = self.repo.changectx(hi)
855 855 except hg.RepoError:
856 856 req.write(self.search(hi)) # XXX redirect to 404 page?
857 857 return
858 858
859 859 req.write(self.changelog(ctx, shortlog = shortlog))
860 860
861 861 def do_shortlog(self, req):
862 862 self.do_changelog(req, shortlog = True)
863 863
864 864 def do_changeset(self, req):
865 865 req.write(self.changeset(self.changectx(req)))
866 866
867 867 def do_manifest(self, req):
868 868 req.write(self.manifest(self.changectx(req),
869 869 self.cleanpath(req.form['path'][0])))
870 870
871 871 def do_tags(self, req):
872 872 req.write(self.tags())
873 873
874 874 def do_summary(self, req):
875 875 req.write(self.summary())
876 876
877 877 def do_filediff(self, req):
878 878 req.write(self.filediff(self.filectx(req)))
879 879
880 880 def do_annotate(self, req):
881 881 req.write(self.fileannotate(self.filectx(req)))
882 882
883 883 def do_filelog(self, req):
884 884 req.write(self.filelog(self.filectx(req)))
885 885
886 886 def do_lookup(self, req):
887 887 try:
888 888 r = hex(self.repo.lookup(req.form['key'][0]))
889 889 success = 1
890 890 except Exception,inst:
891 891 r = str(inst)
892 892 success = 0
893 893 resp = "%s %s\n" % (success, r)
894 894 req.httphdr("application/mercurial-0.1", length=len(resp))
895 895 req.write(resp)
896 896
897 897 def do_heads(self, req):
898 898 resp = " ".join(map(hex, self.repo.heads())) + "\n"
899 899 req.httphdr("application/mercurial-0.1", length=len(resp))
900 900 req.write(resp)
901 901
902 902 def do_branches(self, req):
903 903 nodes = []
904 904 if req.form.has_key('nodes'):
905 905 nodes = map(bin, req.form['nodes'][0].split(" "))
906 906 resp = cStringIO.StringIO()
907 907 for b in self.repo.branches(nodes):
908 908 resp.write(" ".join(map(hex, b)) + "\n")
909 909 resp = resp.getvalue()
910 910 req.httphdr("application/mercurial-0.1", length=len(resp))
911 911 req.write(resp)
912 912
913 913 def do_between(self, req):
914 914 if req.form.has_key('pairs'):
915 915 pairs = [map(bin, p.split("-"))
916 916 for p in req.form['pairs'][0].split(" ")]
917 917 resp = cStringIO.StringIO()
918 918 for b in self.repo.between(pairs):
919 919 resp.write(" ".join(map(hex, b)) + "\n")
920 920 resp = resp.getvalue()
921 921 req.httphdr("application/mercurial-0.1", length=len(resp))
922 922 req.write(resp)
923 923
924 924 def do_changegroup(self, req):
925 925 req.httphdr("application/mercurial-0.1")
926 926 nodes = []
927 927 if not self.allowpull:
928 928 return
929 929
930 930 if req.form.has_key('roots'):
931 931 nodes = map(bin, req.form['roots'][0].split(" "))
932 932
933 933 z = zlib.compressobj()
934 934 f = self.repo.changegroup(nodes, 'serve')
935 935 while 1:
936 936 chunk = f.read(4096)
937 937 if not chunk:
938 938 break
939 939 req.write(z.compress(chunk))
940 940
941 941 req.write(z.flush())
942 942
943 943 def do_changegroupsubset(self, req):
944 944 req.httphdr("application/mercurial-0.1")
945 945 bases = []
946 946 heads = []
947 947 if not self.allowpull:
948 948 return
949 949
950 950 if req.form.has_key('bases'):
951 951 bases = [bin(x) for x in req.form['bases'][0].split(' ')]
952 952 if req.form.has_key('heads'):
953 953 heads = [bin(x) for x in req.form['heads'][0].split(' ')]
954 954
955 955 z = zlib.compressobj()
956 956 f = self.repo.changegroupsubset(bases, heads, 'serve')
957 957 while 1:
958 958 chunk = f.read(4096)
959 959 if not chunk:
960 960 break
961 961 req.write(z.compress(chunk))
962 962
963 963 req.write(z.flush())
964 964
965 965 def do_archive(self, req):
966 966 changeset = self.repo.lookup(req.form['node'][0])
967 967 type_ = req.form['type'][0]
968 968 allowed = self.repo.ui.configlist("web", "allow_archive")
969 969 if (type_ in self.archives and (type_ in allowed or
970 970 self.repo.ui.configbool("web", "allow" + type_, False))):
971 971 self.archive(req, changeset, type_)
972 972 return
973 973
974 974 req.write(self.t("error"))
975 975
976 976 def do_static(self, req):
977 977 fname = req.form['file'][0]
978 978 static = self.repo.ui.config("web", "static",
979 979 os.path.join(self.templatepath,
980 980 "static"))
981 981 req.write(staticfile(static, fname, req)
982 982 or self.t("error", error="%r not found" % fname))
983 983
984 984 def do_capabilities(self, req):
985 985 caps = ['unbundle', 'lookup', 'changegroupsubset']
986 986 if self.repo.ui.configbool('server', 'uncompressed'):
987 987 caps.append('stream=%d' % self.repo.revlogversion)
988 988 resp = ' '.join(caps)
989 989 req.httphdr("application/mercurial-0.1", length=len(resp))
990 990 req.write(resp)
991 991
992 992 def check_perm(self, req, op, default):
993 993 '''check permission for operation based on user auth.
994 994 return true if op allowed, else false.
995 995 default is policy to use if no config given.'''
996 996
997 997 user = req.env.get('REMOTE_USER')
998 998
999 999 deny = self.repo.ui.configlist('web', 'deny_' + op)
1000 1000 if deny and (not user or deny == ['*'] or user in deny):
1001 1001 return False
1002 1002
1003 1003 allow = self.repo.ui.configlist('web', 'allow_' + op)
1004 1004 return (allow and (allow == ['*'] or user in allow)) or default
1005 1005
1006 1006 def do_unbundle(self, req):
1007 1007 def bail(response, headers={}):
1008 1008 length = int(req.env['CONTENT_LENGTH'])
1009 1009 for s in util.filechunkiter(req, limit=length):
1010 1010 # drain incoming bundle, else client will not see
1011 1011 # response when run outside cgi script
1012 1012 pass
1013 1013 req.httphdr("application/mercurial-0.1", headers=headers)
1014 1014 req.write('0\n')
1015 1015 req.write(response)
1016 1016
1017 1017 # require ssl by default, auth info cannot be sniffed and
1018 1018 # replayed
1019 1019 ssl_req = self.repo.ui.configbool('web', 'push_ssl', True)
1020 1020 if ssl_req:
1021 1021 if not req.env.get('HTTPS'):
1022 1022 bail(_('ssl required\n'))
1023 1023 return
1024 1024 proto = 'https'
1025 1025 else:
1026 1026 proto = 'http'
1027 1027
1028 1028 # do not allow push unless explicitly allowed
1029 1029 if not self.check_perm(req, 'push', False):
1030 1030 bail(_('push not authorized\n'),
1031 1031 headers={'status': '401 Unauthorized'})
1032 1032 return
1033 1033
1034 1034 req.httphdr("application/mercurial-0.1")
1035 1035
1036 1036 their_heads = req.form['heads'][0].split(' ')
1037 1037
1038 1038 def check_heads():
1039 1039 heads = map(hex, self.repo.heads())
1040 1040 return their_heads == [hex('force')] or their_heads == heads
1041 1041
1042 1042 # fail early if possible
1043 1043 if not check_heads():
1044 1044 bail(_('unsynced changes\n'))
1045 1045 return
1046 1046
1047 1047 # do not lock repo until all changegroup data is
1048 1048 # streamed. save to temporary file.
1049 1049
1050 1050 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
1051 1051 fp = os.fdopen(fd, 'wb+')
1052 1052 try:
1053 1053 length = int(req.env['CONTENT_LENGTH'])
1054 1054 for s in util.filechunkiter(req, limit=length):
1055 1055 fp.write(s)
1056 1056
1057 1057 lock = self.repo.lock()
1058 1058 try:
1059 1059 if not check_heads():
1060 1060 req.write('0\n')
1061 1061 req.write(_('unsynced changes\n'))
1062 1062 return
1063 1063
1064 1064 fp.seek(0)
1065 1065
1066 1066 # send addchangegroup output to client
1067 1067
1068 1068 old_stdout = sys.stdout
1069 1069 sys.stdout = cStringIO.StringIO()
1070 1070
1071 1071 try:
1072 1072 url = 'remote:%s:%s' % (proto,
1073 1073 req.env.get('REMOTE_HOST', ''))
1074 1074 ret = self.repo.addchangegroup(fp, 'serve', url)
1075 1075 finally:
1076 1076 val = sys.stdout.getvalue()
1077 1077 sys.stdout = old_stdout
1078 1078 req.write('%d\n' % ret)
1079 1079 req.write(val)
1080 1080 finally:
1081 1081 lock.release()
1082 1082 finally:
1083 1083 fp.close()
1084 1084 os.unlink(tempname)
1085 1085
1086 1086 def do_stream_out(self, req):
1087 1087 req.httphdr("application/mercurial-0.1")
1088 1088 streamclone.stream_out(self.repo, req)
@@ -1,1817 +1,1817 b''
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from node import *
9 9 from i18n import gettext as _
10 10 from demandload import *
11 11 import repo
12 12 demandload(globals(), "appendfile changegroup")
13 13 demandload(globals(), "changelog dirstate filelog manifest context")
14 14 demandload(globals(), "re lock transaction tempfile stat mdiff errno ui")
15 15 demandload(globals(), "os revlog time util")
16 16
17 17 class localrepository(repo.repository):
18 18 capabilities = ('lookup', 'changegroupsubset')
19 19
20 20 def __del__(self):
21 21 self.transhandle = None
22 22 def __init__(self, parentui, path=None, create=0):
23 23 repo.repository.__init__(self)
24 24 if not path:
25 25 p = os.getcwd()
26 26 while not os.path.isdir(os.path.join(p, ".hg")):
27 27 oldp = p
28 28 p = os.path.dirname(p)
29 29 if p == oldp:
30 30 raise repo.RepoError(_("There is no Mercurial repository"
31 31 " here (.hg not found)"))
32 32 path = p
33 33 self.path = os.path.join(path, ".hg")
34 34
35 35 if not os.path.isdir(self.path):
36 36 if create:
37 37 if not os.path.exists(path):
38 38 os.mkdir(path)
39 39 os.mkdir(self.path)
40 40 os.mkdir(self.join("data"))
41 41 else:
42 42 raise repo.RepoError(_("repository %s not found") % path)
43 43 elif create:
44 44 raise repo.RepoError(_("repository %s already exists") % path)
45 45
46 46 self.root = os.path.abspath(path)
47 47 self.origroot = path
48 48 self.ui = ui.ui(parentui=parentui)
49 49 self.opener = util.opener(self.path)
50 50 self.wopener = util.opener(self.root)
51 51
52 52 try:
53 53 self.ui.readconfig(self.join("hgrc"), self.root)
54 54 except IOError:
55 55 pass
56 56
57 57 v = self.ui.configrevlog()
58 58 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
59 59 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
60 60 fl = v.get('flags', None)
61 61 flags = 0
62 62 if fl != None:
63 63 for x in fl.split():
64 64 flags |= revlog.flagstr(x)
65 65 elif self.revlogv1:
66 66 flags = revlog.REVLOG_DEFAULT_FLAGS
67 67
68 68 v = self.revlogversion | flags
69 69 self.manifest = manifest.manifest(self.opener, v)
70 70 self.changelog = changelog.changelog(self.opener, v)
71 71
72 72 # the changelog might not have the inline index flag
73 73 # on. If the format of the changelog is the same as found in
74 74 # .hgrc, apply any flags found in the .hgrc as well.
75 75 # Otherwise, just version from the changelog
76 76 v = self.changelog.version
77 77 if v == self.revlogversion:
78 78 v |= flags
79 79 self.revlogversion = v
80 80
81 81 self.tagscache = None
82 82 self.branchcache = None
83 83 self.nodetagscache = None
84 84 self.encodepats = None
85 85 self.decodepats = None
86 86 self.transhandle = None
87 87
88 88 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
89 89
90 90 def url(self):
91 91 return 'file:' + self.root
92 92
93 93 def hook(self, name, throw=False, **args):
94 94 def callhook(hname, funcname):
95 95 '''call python hook. hook is callable object, looked up as
96 96 name in python module. if callable returns "true", hook
97 97 fails, else passes. if hook raises exception, treated as
98 98 hook failure. exception propagates if throw is "true".
99 99
100 100 reason for "true" meaning "hook failed" is so that
101 101 unmodified commands (e.g. mercurial.commands.update) can
102 102 be run as hooks without wrappers to convert return values.'''
103 103
104 104 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
105 105 d = funcname.rfind('.')
106 106 if d == -1:
107 107 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
108 108 % (hname, funcname))
109 109 modname = funcname[:d]
110 110 try:
111 111 obj = __import__(modname)
112 112 except ImportError:
113 113 try:
114 114 # extensions are loaded with hgext_ prefix
115 115 obj = __import__("hgext_%s" % modname)
116 116 except ImportError:
117 117 raise util.Abort(_('%s hook is invalid '
118 118 '(import of "%s" failed)') %
119 119 (hname, modname))
120 120 try:
121 121 for p in funcname.split('.')[1:]:
122 122 obj = getattr(obj, p)
123 123 except AttributeError, err:
124 124 raise util.Abort(_('%s hook is invalid '
125 125 '("%s" is not defined)') %
126 126 (hname, funcname))
127 127 if not callable(obj):
128 128 raise util.Abort(_('%s hook is invalid '
129 129 '("%s" is not callable)') %
130 130 (hname, funcname))
131 131 try:
132 132 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
133 133 except (KeyboardInterrupt, util.SignalInterrupt):
134 134 raise
135 135 except Exception, exc:
136 136 if isinstance(exc, util.Abort):
137 137 self.ui.warn(_('error: %s hook failed: %s\n') %
138 138 (hname, exc.args[0]))
139 139 else:
140 140 self.ui.warn(_('error: %s hook raised an exception: '
141 141 '%s\n') % (hname, exc))
142 142 if throw:
143 143 raise
144 144 self.ui.print_exc()
145 145 return True
146 146 if r:
147 147 if throw:
148 148 raise util.Abort(_('%s hook failed') % hname)
149 149 self.ui.warn(_('warning: %s hook failed\n') % hname)
150 150 return r
151 151
152 152 def runhook(name, cmd):
153 153 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
154 154 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
155 155 r = util.system(cmd, environ=env, cwd=self.root)
156 156 if r:
157 157 desc, r = util.explain_exit(r)
158 158 if throw:
159 159 raise util.Abort(_('%s hook %s') % (name, desc))
160 160 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
161 161 return r
162 162
163 163 r = False
164 164 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
165 165 if hname.split(".", 1)[0] == name and cmd]
166 166 hooks.sort()
167 167 for hname, cmd in hooks:
168 168 if cmd.startswith('python:'):
169 169 r = callhook(hname, cmd[7:].strip()) or r
170 170 else:
171 171 r = runhook(hname, cmd) or r
172 172 return r
173 173
174 174 tag_disallowed = ':\r\n'
175 175
176 176 def tag(self, name, node, message, local, user, date):
177 177 '''tag a revision with a symbolic name.
178 178
179 179 if local is True, the tag is stored in a per-repository file.
180 180 otherwise, it is stored in the .hgtags file, and a new
181 181 changeset is committed with the change.
182 182
183 183 keyword arguments:
184 184
185 185 local: whether to store tag in non-version-controlled file
186 186 (default False)
187 187
188 188 message: commit message to use if committing
189 189
190 190 user: name of user to use if committing
191 191
192 192 date: date tuple to use if committing'''
193 193
194 194 for c in self.tag_disallowed:
195 195 if c in name:
196 196 raise util.Abort(_('%r cannot be used in a tag name') % c)
197 197
198 198 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
199 199
200 200 if local:
201 201 self.opener('localtags', 'a').write('%s %s\n' % (hex(node), name))
202 202 self.hook('tag', node=hex(node), tag=name, local=local)
203 203 return
204 204
205 205 for x in self.status()[:5]:
206 206 if '.hgtags' in x:
207 207 raise util.Abort(_('working copy of .hgtags is changed '
208 208 '(please commit .hgtags manually)'))
209 209
210 210 self.wfile('.hgtags', 'ab').write('%s %s\n' % (hex(node), name))
211 211 if self.dirstate.state('.hgtags') == '?':
212 212 self.add(['.hgtags'])
213 213
214 214 self.commit(['.hgtags'], message, user, date)
215 215 self.hook('tag', node=hex(node), tag=name, local=local)
216 216
217 217 def tags(self):
218 218 '''return a mapping of tag to node'''
219 219 if not self.tagscache:
220 220 self.tagscache = {}
221 221
222 222 def parsetag(line, context):
223 223 if not line:
224 224 return
225 225 s = l.split(" ", 1)
226 226 if len(s) != 2:
227 227 self.ui.warn(_("%s: cannot parse entry\n") % context)
228 228 return
229 229 node, key = s
230 230 key = key.strip()
231 231 try:
232 232 bin_n = bin(node)
233 233 except TypeError:
234 234 self.ui.warn(_("%s: node '%s' is not well formed\n") %
235 235 (context, node))
236 236 return
237 237 if bin_n not in self.changelog.nodemap:
238 238 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
239 239 (context, key))
240 240 return
241 241 self.tagscache[key] = bin_n
242 242
243 243 # read the tags file from each head, ending with the tip,
244 244 # and add each tag found to the map, with "newer" ones
245 245 # taking precedence
246 246 heads = self.heads()
247 247 heads.reverse()
248 248 fl = self.file(".hgtags")
249 249 for node in heads:
250 250 change = self.changelog.read(node)
251 251 rev = self.changelog.rev(node)
252 252 fn, ff = self.manifest.find(change[0], '.hgtags')
253 253 if fn is None: continue
254 254 count = 0
255 255 for l in fl.read(fn).splitlines():
256 256 count += 1
257 257 parsetag(l, _(".hgtags (rev %d:%s), line %d") %
258 258 (rev, short(node), count))
259 259 try:
260 260 f = self.opener("localtags")
261 261 count = 0
262 262 for l in f:
263 263 count += 1
264 264 parsetag(l, _("localtags, line %d") % count)
265 265 except IOError:
266 266 pass
267 267
268 268 self.tagscache['tip'] = self.changelog.tip()
269 269
270 270 return self.tagscache
271 271
272 272 def tagslist(self):
273 273 '''return a list of tags ordered by revision'''
274 274 l = []
275 275 for t, n in self.tags().items():
276 276 try:
277 277 r = self.changelog.rev(n)
278 278 except:
279 279 r = -2 # sort to the beginning of the list if unknown
280 280 l.append((r, t, n))
281 281 l.sort()
282 282 return [(t, n) for r, t, n in l]
283 283
284 284 def nodetags(self, node):
285 285 '''return the tags associated with a node'''
286 286 if not self.nodetagscache:
287 287 self.nodetagscache = {}
288 288 for t, n in self.tags().items():
289 289 self.nodetagscache.setdefault(n, []).append(t)
290 290 return self.nodetagscache.get(node, [])
291 291
292 292 def branchtags(self):
293 293 if self.branchcache != None:
294 294 return self.branchcache
295 295
296 296 self.branchcache = {} # avoid recursion in changectx
297 297
298 298 try:
299 299 f = self.opener("branches.cache")
300 300 last, lrev = f.readline().rstrip().split(" ", 1)
301 301 last, lrev = bin(last), int(lrev)
302 302 if (lrev < self.changelog.count() and
303 303 self.changelog.node(lrev) == last): # sanity check
304 304 for l in f:
305 305 node, label = l.rstrip().split(" ", 1)
306 306 self.branchcache[label] = bin(node)
307 307 else: # invalidate the cache
308 308 last, lrev = nullid, -1
309 309 f.close()
310 310 except IOError:
311 311 last, lrev = nullid, -1
312 312
313 313 tip = self.changelog.count() - 1
314 314 if lrev != tip:
315 315 for r in xrange(lrev + 1, tip + 1):
316 316 c = self.changectx(r)
317 317 b = c.branch()
318 318 if b:
319 319 self.branchcache[b] = c.node()
320 320 self._writebranchcache()
321 321
322 322 return self.branchcache
323 323
324 324 def _writebranchcache(self):
325 325 try:
326 326 f = self.opener("branches.cache", "w")
327 327 t = self.changelog.tip()
328 328 f.write("%s %s\n" % (hex(t), self.changelog.count() - 1))
329 329 for label, node in self.branchcache.iteritems():
330 330 f.write("%s %s\n" % (hex(node), label))
331 331 except IOError:
332 332 pass
333 333
334 334 def lookup(self, key):
335 335 if key == '.':
336 336 key = self.dirstate.parents()[0]
337 337 if key == nullid:
338 338 raise repo.RepoError(_("no revision checked out"))
339 339 if key in self.tags():
340 340 return self.tags()[key]
341 341 if key in self.branchtags():
342 342 return self.branchtags()[key]
343 343 try:
344 344 return self.changelog.lookup(key)
345 345 except:
346 346 raise repo.RepoError(_("unknown revision '%s'") % key)
347 347
348 348 def dev(self):
349 349 return os.lstat(self.path).st_dev
350 350
351 351 def local(self):
352 352 return True
353 353
354 354 def join(self, f):
355 355 return os.path.join(self.path, f)
356 356
357 357 def wjoin(self, f):
358 358 return os.path.join(self.root, f)
359 359
360 360 def file(self, f):
361 361 if f[0] == '/':
362 362 f = f[1:]
363 363 return filelog.filelog(self.opener, f, self.revlogversion)
364 364
365 365 def changectx(self, changeid=None):
366 366 return context.changectx(self, changeid)
367 367
368 368 def workingctx(self):
369 369 return context.workingctx(self)
370 370
371 371 def parents(self, changeid=None):
372 372 '''
373 373 get list of changectxs for parents of changeid or working directory
374 374 '''
375 375 if changeid is None:
376 376 pl = self.dirstate.parents()
377 377 else:
378 378 n = self.changelog.lookup(changeid)
379 379 pl = self.changelog.parents(n)
380 380 if pl[1] == nullid:
381 381 return [self.changectx(pl[0])]
382 382 return [self.changectx(pl[0]), self.changectx(pl[1])]
383 383
384 384 def filectx(self, path, changeid=None, fileid=None):
385 385 """changeid can be a changeset revision, node, or tag.
386 386 fileid can be a file revision or node."""
387 387 return context.filectx(self, path, changeid, fileid)
388 388
389 389 def getcwd(self):
390 390 return self.dirstate.getcwd()
391 391
392 392 def wfile(self, f, mode='r'):
393 393 return self.wopener(f, mode)
394 394
395 395 def wread(self, filename):
396 396 if self.encodepats == None:
397 397 l = []
398 398 for pat, cmd in self.ui.configitems("encode"):
399 399 mf = util.matcher(self.root, "", [pat], [], [])[1]
400 400 l.append((mf, cmd))
401 401 self.encodepats = l
402 402
403 403 data = self.wopener(filename, 'r').read()
404 404
405 405 for mf, cmd in self.encodepats:
406 406 if mf(filename):
407 407 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
408 408 data = util.filter(data, cmd)
409 409 break
410 410
411 411 return data
412 412
413 413 def wwrite(self, filename, data, fd=None):
414 414 if self.decodepats == None:
415 415 l = []
416 416 for pat, cmd in self.ui.configitems("decode"):
417 417 mf = util.matcher(self.root, "", [pat], [], [])[1]
418 418 l.append((mf, cmd))
419 419 self.decodepats = l
420 420
421 421 for mf, cmd in self.decodepats:
422 422 if mf(filename):
423 423 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
424 424 data = util.filter(data, cmd)
425 425 break
426 426
427 427 if fd:
428 428 return fd.write(data)
429 429 return self.wopener(filename, 'w').write(data)
430 430
431 431 def transaction(self):
432 432 tr = self.transhandle
433 433 if tr != None and tr.running():
434 434 return tr.nest()
435 435
436 436 # save dirstate for rollback
437 437 try:
438 438 ds = self.opener("dirstate").read()
439 439 except IOError:
440 440 ds = ""
441 441 self.opener("journal.dirstate", "w").write(ds)
442 442
443 443 tr = transaction.transaction(self.ui.warn, self.opener,
444 444 self.join("journal"),
445 445 aftertrans(self.path))
446 446 self.transhandle = tr
447 447 return tr
448 448
449 449 def recover(self):
450 450 l = self.lock()
451 451 if os.path.exists(self.join("journal")):
452 452 self.ui.status(_("rolling back interrupted transaction\n"))
453 453 transaction.rollback(self.opener, self.join("journal"))
454 454 self.reload()
455 455 return True
456 456 else:
457 457 self.ui.warn(_("no interrupted transaction available\n"))
458 458 return False
459 459
460 460 def rollback(self, wlock=None):
461 461 if not wlock:
462 462 wlock = self.wlock()
463 463 l = self.lock()
464 464 if os.path.exists(self.join("undo")):
465 465 self.ui.status(_("rolling back last transaction\n"))
466 466 transaction.rollback(self.opener, self.join("undo"))
467 467 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
468 468 self.reload()
469 469 self.wreload()
470 470 else:
471 471 self.ui.warn(_("no rollback information available\n"))
472 472
473 473 def wreload(self):
474 474 self.dirstate.read()
475 475
476 476 def reload(self):
477 477 self.changelog.load()
478 478 self.manifest.load()
479 479 self.tagscache = None
480 480 self.nodetagscache = None
481 481
482 482 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
483 483 desc=None):
484 484 try:
485 485 l = lock.lock(self.join(lockname), 0, releasefn, desc=desc)
486 486 except lock.LockHeld, inst:
487 487 if not wait:
488 488 raise
489 489 self.ui.warn(_("waiting for lock on %s held by %s\n") %
490 490 (desc, inst.args[0]))
491 491 # default to 600 seconds timeout
492 492 l = lock.lock(self.join(lockname),
493 493 int(self.ui.config("ui", "timeout") or 600),
494 494 releasefn, desc=desc)
495 495 if acquirefn:
496 496 acquirefn()
497 497 return l
498 498
499 499 def lock(self, wait=1):
500 500 return self.do_lock("lock", wait, acquirefn=self.reload,
501 501 desc=_('repository %s') % self.origroot)
502 502
503 503 def wlock(self, wait=1):
504 504 return self.do_lock("wlock", wait, self.dirstate.write,
505 505 self.wreload,
506 506 desc=_('working directory of %s') % self.origroot)
507 507
508 508 def filecommit(self, fn, manifest1, manifest2, linkrev, transaction, changelist):
509 509 """
510 510 commit an individual file as part of a larger transaction
511 511 """
512 512
513 513 t = self.wread(fn)
514 514 fl = self.file(fn)
515 515 fp1 = manifest1.get(fn, nullid)
516 516 fp2 = manifest2.get(fn, nullid)
517 517
518 518 meta = {}
519 519 cp = self.dirstate.copied(fn)
520 520 if cp:
521 521 meta["copy"] = cp
522 522 if not manifest2: # not a branch merge
523 523 meta["copyrev"] = hex(manifest1.get(cp, nullid))
524 524 fp2 = nullid
525 525 elif fp2 != nullid: # copied on remote side
526 526 meta["copyrev"] = hex(manifest1.get(cp, nullid))
527 527 else: # copied on local side, reversed
528 528 meta["copyrev"] = hex(manifest2.get(cp))
529 529 fp2 = nullid
530 530 self.ui.debug(_(" %s: copy %s:%s\n") %
531 531 (fn, cp, meta["copyrev"]))
532 532 fp1 = nullid
533 533 elif fp2 != nullid:
534 534 # is one parent an ancestor of the other?
535 535 fpa = fl.ancestor(fp1, fp2)
536 536 if fpa == fp1:
537 537 fp1, fp2 = fp2, nullid
538 538 elif fpa == fp2:
539 539 fp2 = nullid
540 540
541 541 # is the file unmodified from the parent? report existing entry
542 542 if fp2 == nullid and not fl.cmp(fp1, t):
543 543 return fp1
544 544
545 545 changelist.append(fn)
546 546 return fl.add(t, meta, transaction, linkrev, fp1, fp2)
547 547
548 548 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
549 549 orig_parent = self.dirstate.parents()[0] or nullid
550 550 p1 = p1 or self.dirstate.parents()[0] or nullid
551 551 p2 = p2 or self.dirstate.parents()[1] or nullid
552 552 c1 = self.changelog.read(p1)
553 553 c2 = self.changelog.read(p2)
554 554 m1 = self.manifest.read(c1[0]).copy()
555 555 m2 = self.manifest.read(c2[0])
556 556 changed = []
557 557 removed = []
558 558
559 559 if orig_parent == p1:
560 560 update_dirstate = 1
561 561 else:
562 562 update_dirstate = 0
563 563
564 564 if not wlock:
565 565 wlock = self.wlock()
566 566 l = self.lock()
567 567 tr = self.transaction()
568 568 linkrev = self.changelog.count()
569 569 for f in files:
570 570 try:
571 571 m1[f] = self.filecommit(f, m1, m2, linkrev, tr, changed)
572 572 m1.set(f, util.is_exec(self.wjoin(f), m1.execf(f)))
573 573 except IOError:
574 574 try:
575 575 del m1[f]
576 576 if update_dirstate:
577 577 self.dirstate.forget([f])
578 578 removed.append(f)
579 579 except:
580 580 # deleted from p2?
581 581 pass
582 582
583 583 mnode = self.manifest.add(m1, tr, linkrev, c1[0], c2[0])
584 584 user = user or self.ui.username()
585 585 n = self.changelog.add(mnode, changed + removed, text,
586 586 tr, p1, p2, user, date)
587 587 tr.close()
588 588 if update_dirstate:
589 589 self.dirstate.setparents(n, nullid)
590 590
591 591 def commit(self, files=None, text="", user=None, date=None,
592 592 match=util.always, force=False, lock=None, wlock=None,
593 593 force_editor=False):
594 594 commit = []
595 595 remove = []
596 596 changed = []
597 597
598 598 if files:
599 599 for f in files:
600 600 s = self.dirstate.state(f)
601 601 if s in 'nmai':
602 602 commit.append(f)
603 603 elif s == 'r':
604 604 remove.append(f)
605 605 else:
606 606 self.ui.warn(_("%s not tracked!\n") % f)
607 607 else:
608 608 modified, added, removed, deleted, unknown = self.status(match=match)[:5]
609 609 commit = modified + added
610 610 remove = removed
611 611
612 612 p1, p2 = self.dirstate.parents()
613 613 c1 = self.changelog.read(p1)
614 614 c2 = self.changelog.read(p2)
615 615 m1 = self.manifest.read(c1[0]).copy()
616 616 m2 = self.manifest.read(c2[0])
617 617
618 618 branchname = self.workingctx().branch()
619 619 oldname = c1[5].get("branch", "")
620 620
621 621 if not commit and not remove and not force and p2 == nullid and \
622 622 branchname == oldname:
623 623 self.ui.status(_("nothing changed\n"))
624 624 return None
625 625
626 626 xp1 = hex(p1)
627 627 if p2 == nullid: xp2 = ''
628 628 else: xp2 = hex(p2)
629 629
630 630 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
631 631
632 632 if not wlock:
633 633 wlock = self.wlock()
634 634 if not lock:
635 635 lock = self.lock()
636 636 tr = self.transaction()
637 637
638 638 # check in files
639 639 new = {}
640 640 linkrev = self.changelog.count()
641 641 commit.sort()
642 642 for f in commit:
643 643 self.ui.note(f + "\n")
644 644 try:
645 645 new[f] = self.filecommit(f, m1, m2, linkrev, tr, changed)
646 646 m1.set(f, util.is_exec(self.wjoin(f), m1.execf(f)))
647 647 except IOError:
648 648 self.ui.warn(_("trouble committing %s!\n") % f)
649 649 raise
650 650
651 651 # update manifest
652 652 m1.update(new)
653 653 for f in remove:
654 654 if f in m1:
655 655 del m1[f]
656 656 mn = self.manifest.add(m1, tr, linkrev, c1[0], c2[0], (new, remove))
657 657
658 658 # add changeset
659 659 new = new.keys()
660 660 new.sort()
661 661
662 662 user = user or self.ui.username()
663 663 if not text or force_editor:
664 664 edittext = []
665 665 if text:
666 666 edittext.append(text)
667 667 edittext.append("")
668 668 if p2 != nullid:
669 669 edittext.append("HG: branch merge")
670 670 edittext.extend(["HG: changed %s" % f for f in changed])
671 671 edittext.extend(["HG: removed %s" % f for f in remove])
672 672 if not changed and not remove:
673 673 edittext.append("HG: no files changed")
674 674 edittext.append("")
675 675 # run editor in the repository root
676 676 olddir = os.getcwd()
677 677 os.chdir(self.root)
678 678 text = self.ui.edit("\n".join(edittext), user)
679 679 os.chdir(olddir)
680 680
681 681 lines = [line.rstrip() for line in text.rstrip().splitlines()]
682 682 while lines and not lines[0]:
683 683 del lines[0]
684 684 if not lines:
685 685 return None
686 686 text = '\n'.join(lines)
687 687 extra = {}
688 688 if branchname:
689 689 extra["branch"] = branchname
690 690 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2,
691 691 user, date, extra)
692 692 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
693 693 parent2=xp2)
694 694 tr.close()
695 695
696 696 self.dirstate.setparents(n)
697 697 self.dirstate.update(new, "n")
698 698 self.dirstate.forget(remove)
699 699
700 700 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
701 701 return n
702 702
703 703 def walk(self, node=None, files=[], match=util.always, badmatch=None):
704 704 if node:
705 705 fdict = dict.fromkeys(files)
706 706 for fn in self.manifest.read(self.changelog.read(node)[0]):
707 707 for ffn in fdict:
708 708 # match if the file is the exact name or a directory
709 709 if ffn == fn or fn.startswith("%s/" % ffn):
710 710 del fdict[ffn]
711 711 break
712 712 if match(fn):
713 713 yield 'm', fn
714 714 for fn in fdict:
715 715 if badmatch and badmatch(fn):
716 716 if match(fn):
717 717 yield 'b', fn
718 718 else:
719 719 self.ui.warn(_('%s: No such file in rev %s\n') % (
720 720 util.pathto(self.getcwd(), fn), short(node)))
721 721 else:
722 722 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
723 723 yield src, fn
724 724
725 725 def status(self, node1=None, node2=None, files=[], match=util.always,
726 726 wlock=None, list_ignored=False, list_clean=False):
727 727 """return status of files between two nodes or node and working directory
728 728
729 729 If node1 is None, use the first dirstate parent instead.
730 730 If node2 is None, compare node1 with working directory.
731 731 """
732 732
733 733 def fcmp(fn, mf):
734 734 t1 = self.wread(fn)
735 735 return self.file(fn).cmp(mf.get(fn, nullid), t1)
736 736
737 737 def mfmatches(node):
738 738 change = self.changelog.read(node)
739 739 mf = self.manifest.read(change[0]).copy()
740 740 for fn in mf.keys():
741 741 if not match(fn):
742 742 del mf[fn]
743 743 return mf
744 744
745 745 modified, added, removed, deleted, unknown = [], [], [], [], []
746 746 ignored, clean = [], []
747 747
748 748 compareworking = False
749 749 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
750 750 compareworking = True
751 751
752 752 if not compareworking:
753 753 # read the manifest from node1 before the manifest from node2,
754 754 # so that we'll hit the manifest cache if we're going through
755 755 # all the revisions in parent->child order.
756 756 mf1 = mfmatches(node1)
757 757
758 758 # are we comparing the working directory?
759 759 if not node2:
760 760 if not wlock:
761 761 try:
762 762 wlock = self.wlock(wait=0)
763 763 except lock.LockException:
764 764 wlock = None
765 765 (lookup, modified, added, removed, deleted, unknown,
766 766 ignored, clean) = self.dirstate.status(files, match,
767 767 list_ignored, list_clean)
768 768
769 769 # are we comparing working dir against its parent?
770 770 if compareworking:
771 771 if lookup:
772 772 # do a full compare of any files that might have changed
773 773 mf2 = mfmatches(self.dirstate.parents()[0])
774 774 for f in lookup:
775 775 if fcmp(f, mf2):
776 776 modified.append(f)
777 777 else:
778 778 clean.append(f)
779 779 if wlock is not None:
780 780 self.dirstate.update([f], "n")
781 781 else:
782 782 # we are comparing working dir against non-parent
783 783 # generate a pseudo-manifest for the working dir
784 784 # XXX: create it in dirstate.py ?
785 785 mf2 = mfmatches(self.dirstate.parents()[0])
786 786 for f in lookup + modified + added:
787 787 mf2[f] = ""
788 788 mf2.set(f, execf=util.is_exec(self.wjoin(f), mf2.execf(f)))
789 789 for f in removed:
790 790 if f in mf2:
791 791 del mf2[f]
792 792 else:
793 793 # we are comparing two revisions
794 794 mf2 = mfmatches(node2)
795 795
796 796 if not compareworking:
797 797 # flush lists from dirstate before comparing manifests
798 798 modified, added, clean = [], [], []
799 799
800 800 # make sure to sort the files so we talk to the disk in a
801 801 # reasonable order
802 802 mf2keys = mf2.keys()
803 803 mf2keys.sort()
804 804 for fn in mf2keys:
805 805 if mf1.has_key(fn):
806 806 if mf1.flags(fn) != mf2.flags(fn) or \
807 807 (mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1))):
808 808 modified.append(fn)
809 809 elif list_clean:
810 810 clean.append(fn)
811 811 del mf1[fn]
812 812 else:
813 813 added.append(fn)
814 814
815 815 removed = mf1.keys()
816 816
817 817 # sort and return results:
818 818 for l in modified, added, removed, deleted, unknown, ignored, clean:
819 819 l.sort()
820 820 return (modified, added, removed, deleted, unknown, ignored, clean)
821 821
822 822 def add(self, list, wlock=None):
823 823 if not wlock:
824 824 wlock = self.wlock()
825 825 for f in list:
826 826 p = self.wjoin(f)
827 827 if not os.path.exists(p):
828 828 self.ui.warn(_("%s does not exist!\n") % f)
829 829 elif not os.path.isfile(p):
830 830 self.ui.warn(_("%s not added: only files supported currently\n")
831 831 % f)
832 832 elif self.dirstate.state(f) in 'an':
833 833 self.ui.warn(_("%s already tracked!\n") % f)
834 834 else:
835 835 self.dirstate.update([f], "a")
836 836
837 837 def forget(self, list, wlock=None):
838 838 if not wlock:
839 839 wlock = self.wlock()
840 840 for f in list:
841 841 if self.dirstate.state(f) not in 'ai':
842 842 self.ui.warn(_("%s not added!\n") % f)
843 843 else:
844 844 self.dirstate.forget([f])
845 845
846 846 def remove(self, list, unlink=False, wlock=None):
847 847 if unlink:
848 848 for f in list:
849 849 try:
850 850 util.unlink(self.wjoin(f))
851 851 except OSError, inst:
852 852 if inst.errno != errno.ENOENT:
853 853 raise
854 854 if not wlock:
855 855 wlock = self.wlock()
856 856 for f in list:
857 857 p = self.wjoin(f)
858 858 if os.path.exists(p):
859 859 self.ui.warn(_("%s still exists!\n") % f)
860 860 elif self.dirstate.state(f) == 'a':
861 861 self.dirstate.forget([f])
862 862 elif f not in self.dirstate:
863 863 self.ui.warn(_("%s not tracked!\n") % f)
864 864 else:
865 865 self.dirstate.update([f], "r")
866 866
867 867 def undelete(self, list, wlock=None):
868 868 p = self.dirstate.parents()[0]
869 869 mn = self.changelog.read(p)[0]
870 870 m = self.manifest.read(mn)
871 871 if not wlock:
872 872 wlock = self.wlock()
873 873 for f in list:
874 874 if self.dirstate.state(f) not in "r":
875 875 self.ui.warn("%s not removed!\n" % f)
876 876 else:
877 877 t = self.file(f).read(m[f])
878 878 self.wwrite(f, t)
879 879 util.set_exec(self.wjoin(f), m.execf(f))
880 880 self.dirstate.update([f], "n")
881 881
882 882 def copy(self, source, dest, wlock=None):
883 883 p = self.wjoin(dest)
884 884 if not os.path.exists(p):
885 885 self.ui.warn(_("%s does not exist!\n") % dest)
886 886 elif not os.path.isfile(p):
887 887 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
888 888 else:
889 889 if not wlock:
890 890 wlock = self.wlock()
891 891 if self.dirstate.state(dest) == '?':
892 892 self.dirstate.update([dest], "a")
893 893 self.dirstate.copy(source, dest)
894 894
895 895 def heads(self, start=None):
896 896 heads = self.changelog.heads(start)
897 897 # sort the output in rev descending order
898 898 heads = [(-self.changelog.rev(h), h) for h in heads]
899 899 heads.sort()
900 900 return [n for (r, n) in heads]
901 901
902 902 # branchlookup returns a dict giving a list of branches for
903 903 # each head. A branch is defined as the tag of a node or
904 904 # the branch of the node's parents. If a node has multiple
905 905 # branch tags, tags are eliminated if they are visible from other
906 906 # branch tags.
907 907 #
908 908 # So, for this graph: a->b->c->d->e
909 909 # \ /
910 910 # aa -----/
911 911 # a has tag 2.6.12
912 912 # d has tag 2.6.13
913 913 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
914 914 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
915 915 # from the list.
916 916 #
917 917 # It is possible that more than one head will have the same branch tag.
918 918 # callers need to check the result for multiple heads under the same
919 919 # branch tag if that is a problem for them (ie checkout of a specific
920 920 # branch).
921 921 #
922 922 # passing in a specific branch will limit the depth of the search
923 923 # through the parents. It won't limit the branches returned in the
924 924 # result though.
925 925 def branchlookup(self, heads=None, branch=None):
926 926 if not heads:
927 927 heads = self.heads()
928 928 headt = [ h for h in heads ]
929 929 chlog = self.changelog
930 930 branches = {}
931 931 merges = []
932 932 seenmerge = {}
933 933
934 934 # traverse the tree once for each head, recording in the branches
935 935 # dict which tags are visible from this head. The branches
936 936 # dict also records which tags are visible from each tag
937 937 # while we traverse.
938 938 while headt or merges:
939 939 if merges:
940 940 n, found = merges.pop()
941 941 visit = [n]
942 942 else:
943 943 h = headt.pop()
944 944 visit = [h]
945 945 found = [h]
946 946 seen = {}
947 947 while visit:
948 948 n = visit.pop()
949 949 if n in seen:
950 950 continue
951 951 pp = chlog.parents(n)
952 952 tags = self.nodetags(n)
953 953 if tags:
954 954 for x in tags:
955 955 if x == 'tip':
956 956 continue
957 957 for f in found:
958 958 branches.setdefault(f, {})[n] = 1
959 959 branches.setdefault(n, {})[n] = 1
960 960 break
961 961 if n not in found:
962 962 found.append(n)
963 963 if branch in tags:
964 964 continue
965 965 seen[n] = 1
966 966 if pp[1] != nullid and n not in seenmerge:
967 967 merges.append((pp[1], [x for x in found]))
968 968 seenmerge[n] = 1
969 969 if pp[0] != nullid:
970 970 visit.append(pp[0])
971 971 # traverse the branches dict, eliminating branch tags from each
972 972 # head that are visible from another branch tag for that head.
973 973 out = {}
974 974 viscache = {}
975 975 for h in heads:
976 976 def visible(node):
977 977 if node in viscache:
978 978 return viscache[node]
979 979 ret = {}
980 980 visit = [node]
981 981 while visit:
982 982 x = visit.pop()
983 983 if x in viscache:
984 984 ret.update(viscache[x])
985 985 elif x not in ret:
986 986 ret[x] = 1
987 987 if x in branches:
988 988 visit[len(visit):] = branches[x].keys()
989 989 viscache[node] = ret
990 990 return ret
991 991 if h not in branches:
992 992 continue
993 993 # O(n^2), but somewhat limited. This only searches the
994 994 # tags visible from a specific head, not all the tags in the
995 995 # whole repo.
996 996 for b in branches[h]:
997 997 vis = False
998 998 for bb in branches[h].keys():
999 999 if b != bb:
1000 1000 if b in visible(bb):
1001 1001 vis = True
1002 1002 break
1003 1003 if not vis:
1004 1004 l = out.setdefault(h, [])
1005 1005 l[len(l):] = self.nodetags(b)
1006 1006 return out
1007 1007
1008 1008 def branches(self, nodes):
1009 1009 if not nodes:
1010 1010 nodes = [self.changelog.tip()]
1011 1011 b = []
1012 1012 for n in nodes:
1013 1013 t = n
1014 1014 while 1:
1015 1015 p = self.changelog.parents(n)
1016 1016 if p[1] != nullid or p[0] == nullid:
1017 1017 b.append((t, n, p[0], p[1]))
1018 1018 break
1019 1019 n = p[0]
1020 1020 return b
1021 1021
1022 1022 def between(self, pairs):
1023 1023 r = []
1024 1024
1025 1025 for top, bottom in pairs:
1026 1026 n, l, i = top, [], 0
1027 1027 f = 1
1028 1028
1029 1029 while n != bottom:
1030 1030 p = self.changelog.parents(n)[0]
1031 1031 if i == f:
1032 1032 l.append(n)
1033 1033 f = f * 2
1034 1034 n = p
1035 1035 i += 1
1036 1036
1037 1037 r.append(l)
1038 1038
1039 1039 return r
1040 1040
1041 1041 def findincoming(self, remote, base=None, heads=None, force=False):
1042 1042 """Return list of roots of the subsets of missing nodes from remote
1043 1043
1044 1044 If base dict is specified, assume that these nodes and their parents
1045 1045 exist on the remote side and that no child of a node of base exists
1046 1046 in both remote and self.
1047 1047 Furthermore base will be updated to include the nodes that exists
1048 1048 in self and remote but no children exists in self and remote.
1049 1049 If a list of heads is specified, return only nodes which are heads
1050 1050 or ancestors of these heads.
1051 1051
1052 1052 All the ancestors of base are in self and in remote.
1053 1053 All the descendants of the list returned are missing in self.
1054 1054 (and so we know that the rest of the nodes are missing in remote, see
1055 1055 outgoing)
1056 1056 """
1057 1057 m = self.changelog.nodemap
1058 1058 search = []
1059 1059 fetch = {}
1060 1060 seen = {}
1061 1061 seenbranch = {}
1062 1062 if base == None:
1063 1063 base = {}
1064 1064
1065 1065 if not heads:
1066 1066 heads = remote.heads()
1067 1067
1068 1068 if self.changelog.tip() == nullid:
1069 1069 base[nullid] = 1
1070 1070 if heads != [nullid]:
1071 1071 return [nullid]
1072 1072 return []
1073 1073
1074 1074 # assume we're closer to the tip than the root
1075 1075 # and start by examining the heads
1076 1076 self.ui.status(_("searching for changes\n"))
1077 1077
1078 1078 unknown = []
1079 1079 for h in heads:
1080 1080 if h not in m:
1081 1081 unknown.append(h)
1082 1082 else:
1083 1083 base[h] = 1
1084 1084
1085 1085 if not unknown:
1086 1086 return []
1087 1087
1088 1088 req = dict.fromkeys(unknown)
1089 1089 reqcnt = 0
1090 1090
1091 1091 # search through remote branches
1092 1092 # a 'branch' here is a linear segment of history, with four parts:
1093 1093 # head, root, first parent, second parent
1094 1094 # (a branch always has two parents (or none) by definition)
1095 1095 unknown = remote.branches(unknown)
1096 1096 while unknown:
1097 1097 r = []
1098 1098 while unknown:
1099 1099 n = unknown.pop(0)
1100 1100 if n[0] in seen:
1101 1101 continue
1102 1102
1103 1103 self.ui.debug(_("examining %s:%s\n")
1104 1104 % (short(n[0]), short(n[1])))
1105 1105 if n[0] == nullid: # found the end of the branch
1106 1106 pass
1107 1107 elif n in seenbranch:
1108 1108 self.ui.debug(_("branch already found\n"))
1109 1109 continue
1110 1110 elif n[1] and n[1] in m: # do we know the base?
1111 1111 self.ui.debug(_("found incomplete branch %s:%s\n")
1112 1112 % (short(n[0]), short(n[1])))
1113 1113 search.append(n) # schedule branch range for scanning
1114 1114 seenbranch[n] = 1
1115 1115 else:
1116 1116 if n[1] not in seen and n[1] not in fetch:
1117 1117 if n[2] in m and n[3] in m:
1118 1118 self.ui.debug(_("found new changeset %s\n") %
1119 1119 short(n[1]))
1120 1120 fetch[n[1]] = 1 # earliest unknown
1121 1121 for p in n[2:4]:
1122 1122 if p in m:
1123 1123 base[p] = 1 # latest known
1124 1124
1125 1125 for p in n[2:4]:
1126 1126 if p not in req and p not in m:
1127 1127 r.append(p)
1128 1128 req[p] = 1
1129 1129 seen[n[0]] = 1
1130 1130
1131 1131 if r:
1132 1132 reqcnt += 1
1133 1133 self.ui.debug(_("request %d: %s\n") %
1134 1134 (reqcnt, " ".join(map(short, r))))
1135 for p in range(0, len(r), 10):
1135 for p in xrange(0, len(r), 10):
1136 1136 for b in remote.branches(r[p:p+10]):
1137 1137 self.ui.debug(_("received %s:%s\n") %
1138 1138 (short(b[0]), short(b[1])))
1139 1139 unknown.append(b)
1140 1140
1141 1141 # do binary search on the branches we found
1142 1142 while search:
1143 1143 n = search.pop(0)
1144 1144 reqcnt += 1
1145 1145 l = remote.between([(n[0], n[1])])[0]
1146 1146 l.append(n[1])
1147 1147 p = n[0]
1148 1148 f = 1
1149 1149 for i in l:
1150 1150 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1151 1151 if i in m:
1152 1152 if f <= 2:
1153 1153 self.ui.debug(_("found new branch changeset %s\n") %
1154 1154 short(p))
1155 1155 fetch[p] = 1
1156 1156 base[i] = 1
1157 1157 else:
1158 1158 self.ui.debug(_("narrowed branch search to %s:%s\n")
1159 1159 % (short(p), short(i)))
1160 1160 search.append((p, i))
1161 1161 break
1162 1162 p, f = i, f * 2
1163 1163
1164 1164 # sanity check our fetch list
1165 1165 for f in fetch.keys():
1166 1166 if f in m:
1167 1167 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1168 1168
1169 1169 if base.keys() == [nullid]:
1170 1170 if force:
1171 1171 self.ui.warn(_("warning: repository is unrelated\n"))
1172 1172 else:
1173 1173 raise util.Abort(_("repository is unrelated"))
1174 1174
1175 1175 self.ui.debug(_("found new changesets starting at ") +
1176 1176 " ".join([short(f) for f in fetch]) + "\n")
1177 1177
1178 1178 self.ui.debug(_("%d total queries\n") % reqcnt)
1179 1179
1180 1180 return fetch.keys()
1181 1181
1182 1182 def findoutgoing(self, remote, base=None, heads=None, force=False):
1183 1183 """Return list of nodes that are roots of subsets not in remote
1184 1184
1185 1185 If base dict is specified, assume that these nodes and their parents
1186 1186 exist on the remote side.
1187 1187 If a list of heads is specified, return only nodes which are heads
1188 1188 or ancestors of these heads, and return a second element which
1189 1189 contains all remote heads which get new children.
1190 1190 """
1191 1191 if base == None:
1192 1192 base = {}
1193 1193 self.findincoming(remote, base, heads, force=force)
1194 1194
1195 1195 self.ui.debug(_("common changesets up to ")
1196 1196 + " ".join(map(short, base.keys())) + "\n")
1197 1197
1198 1198 remain = dict.fromkeys(self.changelog.nodemap)
1199 1199
1200 1200 # prune everything remote has from the tree
1201 1201 del remain[nullid]
1202 1202 remove = base.keys()
1203 1203 while remove:
1204 1204 n = remove.pop(0)
1205 1205 if n in remain:
1206 1206 del remain[n]
1207 1207 for p in self.changelog.parents(n):
1208 1208 remove.append(p)
1209 1209
1210 1210 # find every node whose parents have been pruned
1211 1211 subset = []
1212 1212 # find every remote head that will get new children
1213 1213 updated_heads = {}
1214 1214 for n in remain:
1215 1215 p1, p2 = self.changelog.parents(n)
1216 1216 if p1 not in remain and p2 not in remain:
1217 1217 subset.append(n)
1218 1218 if heads:
1219 1219 if p1 in heads:
1220 1220 updated_heads[p1] = True
1221 1221 if p2 in heads:
1222 1222 updated_heads[p2] = True
1223 1223
1224 1224 # this is the set of all roots we have to push
1225 1225 if heads:
1226 1226 return subset, updated_heads.keys()
1227 1227 else:
1228 1228 return subset
1229 1229
1230 1230 def pull(self, remote, heads=None, force=False, lock=None):
1231 1231 mylock = False
1232 1232 if not lock:
1233 1233 lock = self.lock()
1234 1234 mylock = True
1235 1235
1236 1236 try:
1237 1237 fetch = self.findincoming(remote, force=force)
1238 1238 if fetch == [nullid]:
1239 1239 self.ui.status(_("requesting all changes\n"))
1240 1240
1241 1241 if not fetch:
1242 1242 self.ui.status(_("no changes found\n"))
1243 1243 return 0
1244 1244
1245 1245 if heads is None:
1246 1246 cg = remote.changegroup(fetch, 'pull')
1247 1247 else:
1248 1248 if 'changegroupsubset' not in remote.capabilities:
1249 1249 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1250 1250 cg = remote.changegroupsubset(fetch, heads, 'pull')
1251 1251 return self.addchangegroup(cg, 'pull', remote.url())
1252 1252 finally:
1253 1253 if mylock:
1254 1254 lock.release()
1255 1255
1256 1256 def push(self, remote, force=False, revs=None):
1257 1257 # there are two ways to push to remote repo:
1258 1258 #
1259 1259 # addchangegroup assumes local user can lock remote
1260 1260 # repo (local filesystem, old ssh servers).
1261 1261 #
1262 1262 # unbundle assumes local user cannot lock remote repo (new ssh
1263 1263 # servers, http servers).
1264 1264
1265 1265 if remote.capable('unbundle'):
1266 1266 return self.push_unbundle(remote, force, revs)
1267 1267 return self.push_addchangegroup(remote, force, revs)
1268 1268
1269 1269 def prepush(self, remote, force, revs):
1270 1270 base = {}
1271 1271 remote_heads = remote.heads()
1272 1272 inc = self.findincoming(remote, base, remote_heads, force=force)
1273 1273 if not force and inc:
1274 1274 self.ui.warn(_("abort: unsynced remote changes!\n"))
1275 1275 self.ui.status(_("(did you forget to sync?"
1276 1276 " use push -f to force)\n"))
1277 1277 return None, 1
1278 1278
1279 1279 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1280 1280 if revs is not None:
1281 1281 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1282 1282 else:
1283 1283 bases, heads = update, self.changelog.heads()
1284 1284
1285 1285 if not bases:
1286 1286 self.ui.status(_("no changes found\n"))
1287 1287 return None, 1
1288 1288 elif not force:
1289 1289 # FIXME we don't properly detect creation of new heads
1290 1290 # in the push -r case, assume the user knows what he's doing
1291 1291 if not revs and len(remote_heads) < len(heads) \
1292 1292 and remote_heads != [nullid]:
1293 1293 self.ui.warn(_("abort: push creates new remote branches!\n"))
1294 1294 self.ui.status(_("(did you forget to merge?"
1295 1295 " use push -f to force)\n"))
1296 1296 return None, 1
1297 1297
1298 1298 if revs is None:
1299 1299 cg = self.changegroup(update, 'push')
1300 1300 else:
1301 1301 cg = self.changegroupsubset(update, revs, 'push')
1302 1302 return cg, remote_heads
1303 1303
1304 1304 def push_addchangegroup(self, remote, force, revs):
1305 1305 lock = remote.lock()
1306 1306
1307 1307 ret = self.prepush(remote, force, revs)
1308 1308 if ret[0] is not None:
1309 1309 cg, remote_heads = ret
1310 1310 return remote.addchangegroup(cg, 'push', self.url())
1311 1311 return ret[1]
1312 1312
1313 1313 def push_unbundle(self, remote, force, revs):
1314 1314 # local repo finds heads on server, finds out what revs it
1315 1315 # must push. once revs transferred, if server finds it has
1316 1316 # different heads (someone else won commit/push race), server
1317 1317 # aborts.
1318 1318
1319 1319 ret = self.prepush(remote, force, revs)
1320 1320 if ret[0] is not None:
1321 1321 cg, remote_heads = ret
1322 1322 if force: remote_heads = ['force']
1323 1323 return remote.unbundle(cg, remote_heads, 'push')
1324 1324 return ret[1]
1325 1325
1326 1326 def changegroupsubset(self, bases, heads, source):
1327 1327 """This function generates a changegroup consisting of all the nodes
1328 1328 that are descendents of any of the bases, and ancestors of any of
1329 1329 the heads.
1330 1330
1331 1331 It is fairly complex as determining which filenodes and which
1332 1332 manifest nodes need to be included for the changeset to be complete
1333 1333 is non-trivial.
1334 1334
1335 1335 Another wrinkle is doing the reverse, figuring out which changeset in
1336 1336 the changegroup a particular filenode or manifestnode belongs to."""
1337 1337
1338 1338 self.hook('preoutgoing', throw=True, source=source)
1339 1339
1340 1340 # Set up some initial variables
1341 1341 # Make it easy to refer to self.changelog
1342 1342 cl = self.changelog
1343 1343 # msng is short for missing - compute the list of changesets in this
1344 1344 # changegroup.
1345 1345 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1346 1346 # Some bases may turn out to be superfluous, and some heads may be
1347 1347 # too. nodesbetween will return the minimal set of bases and heads
1348 1348 # necessary to re-create the changegroup.
1349 1349
1350 1350 # Known heads are the list of heads that it is assumed the recipient
1351 1351 # of this changegroup will know about.
1352 1352 knownheads = {}
1353 1353 # We assume that all parents of bases are known heads.
1354 1354 for n in bases:
1355 1355 for p in cl.parents(n):
1356 1356 if p != nullid:
1357 1357 knownheads[p] = 1
1358 1358 knownheads = knownheads.keys()
1359 1359 if knownheads:
1360 1360 # Now that we know what heads are known, we can compute which
1361 1361 # changesets are known. The recipient must know about all
1362 1362 # changesets required to reach the known heads from the null
1363 1363 # changeset.
1364 1364 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1365 1365 junk = None
1366 1366 # Transform the list into an ersatz set.
1367 1367 has_cl_set = dict.fromkeys(has_cl_set)
1368 1368 else:
1369 1369 # If there were no known heads, the recipient cannot be assumed to
1370 1370 # know about any changesets.
1371 1371 has_cl_set = {}
1372 1372
1373 1373 # Make it easy to refer to self.manifest
1374 1374 mnfst = self.manifest
1375 1375 # We don't know which manifests are missing yet
1376 1376 msng_mnfst_set = {}
1377 1377 # Nor do we know which filenodes are missing.
1378 1378 msng_filenode_set = {}
1379 1379
1380 1380 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1381 1381 junk = None
1382 1382
1383 1383 # A changeset always belongs to itself, so the changenode lookup
1384 1384 # function for a changenode is identity.
1385 1385 def identity(x):
1386 1386 return x
1387 1387
1388 1388 # A function generating function. Sets up an environment for the
1389 1389 # inner function.
1390 1390 def cmp_by_rev_func(revlog):
1391 1391 # Compare two nodes by their revision number in the environment's
1392 1392 # revision history. Since the revision number both represents the
1393 1393 # most efficient order to read the nodes in, and represents a
1394 1394 # topological sorting of the nodes, this function is often useful.
1395 1395 def cmp_by_rev(a, b):
1396 1396 return cmp(revlog.rev(a), revlog.rev(b))
1397 1397 return cmp_by_rev
1398 1398
1399 1399 # If we determine that a particular file or manifest node must be a
1400 1400 # node that the recipient of the changegroup will already have, we can
1401 1401 # also assume the recipient will have all the parents. This function
1402 1402 # prunes them from the set of missing nodes.
1403 1403 def prune_parents(revlog, hasset, msngset):
1404 1404 haslst = hasset.keys()
1405 1405 haslst.sort(cmp_by_rev_func(revlog))
1406 1406 for node in haslst:
1407 1407 parentlst = [p for p in revlog.parents(node) if p != nullid]
1408 1408 while parentlst:
1409 1409 n = parentlst.pop()
1410 1410 if n not in hasset:
1411 1411 hasset[n] = 1
1412 1412 p = [p for p in revlog.parents(n) if p != nullid]
1413 1413 parentlst.extend(p)
1414 1414 for n in hasset:
1415 1415 msngset.pop(n, None)
1416 1416
1417 1417 # This is a function generating function used to set up an environment
1418 1418 # for the inner function to execute in.
1419 1419 def manifest_and_file_collector(changedfileset):
1420 1420 # This is an information gathering function that gathers
1421 1421 # information from each changeset node that goes out as part of
1422 1422 # the changegroup. The information gathered is a list of which
1423 1423 # manifest nodes are potentially required (the recipient may
1424 1424 # already have them) and total list of all files which were
1425 1425 # changed in any changeset in the changegroup.
1426 1426 #
1427 1427 # We also remember the first changenode we saw any manifest
1428 1428 # referenced by so we can later determine which changenode 'owns'
1429 1429 # the manifest.
1430 1430 def collect_manifests_and_files(clnode):
1431 1431 c = cl.read(clnode)
1432 1432 for f in c[3]:
1433 1433 # This is to make sure we only have one instance of each
1434 1434 # filename string for each filename.
1435 1435 changedfileset.setdefault(f, f)
1436 1436 msng_mnfst_set.setdefault(c[0], clnode)
1437 1437 return collect_manifests_and_files
1438 1438
1439 1439 # Figure out which manifest nodes (of the ones we think might be part
1440 1440 # of the changegroup) the recipient must know about and remove them
1441 1441 # from the changegroup.
1442 1442 def prune_manifests():
1443 1443 has_mnfst_set = {}
1444 1444 for n in msng_mnfst_set:
1445 1445 # If a 'missing' manifest thinks it belongs to a changenode
1446 1446 # the recipient is assumed to have, obviously the recipient
1447 1447 # must have that manifest.
1448 1448 linknode = cl.node(mnfst.linkrev(n))
1449 1449 if linknode in has_cl_set:
1450 1450 has_mnfst_set[n] = 1
1451 1451 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1452 1452
1453 1453 # Use the information collected in collect_manifests_and_files to say
1454 1454 # which changenode any manifestnode belongs to.
1455 1455 def lookup_manifest_link(mnfstnode):
1456 1456 return msng_mnfst_set[mnfstnode]
1457 1457
1458 1458 # A function generating function that sets up the initial environment
1459 1459 # the inner function.
1460 1460 def filenode_collector(changedfiles):
1461 1461 next_rev = [0]
1462 1462 # This gathers information from each manifestnode included in the
1463 1463 # changegroup about which filenodes the manifest node references
1464 1464 # so we can include those in the changegroup too.
1465 1465 #
1466 1466 # It also remembers which changenode each filenode belongs to. It
1467 1467 # does this by assuming the a filenode belongs to the changenode
1468 1468 # the first manifest that references it belongs to.
1469 1469 def collect_msng_filenodes(mnfstnode):
1470 1470 r = mnfst.rev(mnfstnode)
1471 1471 if r == next_rev[0]:
1472 1472 # If the last rev we looked at was the one just previous,
1473 1473 # we only need to see a diff.
1474 1474 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1475 1475 # For each line in the delta
1476 1476 for dline in delta.splitlines():
1477 1477 # get the filename and filenode for that line
1478 1478 f, fnode = dline.split('\0')
1479 1479 fnode = bin(fnode[:40])
1480 1480 f = changedfiles.get(f, None)
1481 1481 # And if the file is in the list of files we care
1482 1482 # about.
1483 1483 if f is not None:
1484 1484 # Get the changenode this manifest belongs to
1485 1485 clnode = msng_mnfst_set[mnfstnode]
1486 1486 # Create the set of filenodes for the file if
1487 1487 # there isn't one already.
1488 1488 ndset = msng_filenode_set.setdefault(f, {})
1489 1489 # And set the filenode's changelog node to the
1490 1490 # manifest's if it hasn't been set already.
1491 1491 ndset.setdefault(fnode, clnode)
1492 1492 else:
1493 1493 # Otherwise we need a full manifest.
1494 1494 m = mnfst.read(mnfstnode)
1495 1495 # For every file in we care about.
1496 1496 for f in changedfiles:
1497 1497 fnode = m.get(f, None)
1498 1498 # If it's in the manifest
1499 1499 if fnode is not None:
1500 1500 # See comments above.
1501 1501 clnode = msng_mnfst_set[mnfstnode]
1502 1502 ndset = msng_filenode_set.setdefault(f, {})
1503 1503 ndset.setdefault(fnode, clnode)
1504 1504 # Remember the revision we hope to see next.
1505 1505 next_rev[0] = r + 1
1506 1506 return collect_msng_filenodes
1507 1507
1508 1508 # We have a list of filenodes we think we need for a file, lets remove
1509 1509 # all those we now the recipient must have.
1510 1510 def prune_filenodes(f, filerevlog):
1511 1511 msngset = msng_filenode_set[f]
1512 1512 hasset = {}
1513 1513 # If a 'missing' filenode thinks it belongs to a changenode we
1514 1514 # assume the recipient must have, then the recipient must have
1515 1515 # that filenode.
1516 1516 for n in msngset:
1517 1517 clnode = cl.node(filerevlog.linkrev(n))
1518 1518 if clnode in has_cl_set:
1519 1519 hasset[n] = 1
1520 1520 prune_parents(filerevlog, hasset, msngset)
1521 1521
1522 1522 # A function generator function that sets up the a context for the
1523 1523 # inner function.
1524 1524 def lookup_filenode_link_func(fname):
1525 1525 msngset = msng_filenode_set[fname]
1526 1526 # Lookup the changenode the filenode belongs to.
1527 1527 def lookup_filenode_link(fnode):
1528 1528 return msngset[fnode]
1529 1529 return lookup_filenode_link
1530 1530
1531 1531 # Now that we have all theses utility functions to help out and
1532 1532 # logically divide up the task, generate the group.
1533 1533 def gengroup():
1534 1534 # The set of changed files starts empty.
1535 1535 changedfiles = {}
1536 1536 # Create a changenode group generator that will call our functions
1537 1537 # back to lookup the owning changenode and collect information.
1538 1538 group = cl.group(msng_cl_lst, identity,
1539 1539 manifest_and_file_collector(changedfiles))
1540 1540 for chnk in group:
1541 1541 yield chnk
1542 1542
1543 1543 # The list of manifests has been collected by the generator
1544 1544 # calling our functions back.
1545 1545 prune_manifests()
1546 1546 msng_mnfst_lst = msng_mnfst_set.keys()
1547 1547 # Sort the manifestnodes by revision number.
1548 1548 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1549 1549 # Create a generator for the manifestnodes that calls our lookup
1550 1550 # and data collection functions back.
1551 1551 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1552 1552 filenode_collector(changedfiles))
1553 1553 for chnk in group:
1554 1554 yield chnk
1555 1555
1556 1556 # These are no longer needed, dereference and toss the memory for
1557 1557 # them.
1558 1558 msng_mnfst_lst = None
1559 1559 msng_mnfst_set.clear()
1560 1560
1561 1561 changedfiles = changedfiles.keys()
1562 1562 changedfiles.sort()
1563 1563 # Go through all our files in order sorted by name.
1564 1564 for fname in changedfiles:
1565 1565 filerevlog = self.file(fname)
1566 1566 # Toss out the filenodes that the recipient isn't really
1567 1567 # missing.
1568 1568 if msng_filenode_set.has_key(fname):
1569 1569 prune_filenodes(fname, filerevlog)
1570 1570 msng_filenode_lst = msng_filenode_set[fname].keys()
1571 1571 else:
1572 1572 msng_filenode_lst = []
1573 1573 # If any filenodes are left, generate the group for them,
1574 1574 # otherwise don't bother.
1575 1575 if len(msng_filenode_lst) > 0:
1576 1576 yield changegroup.genchunk(fname)
1577 1577 # Sort the filenodes by their revision #
1578 1578 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1579 1579 # Create a group generator and only pass in a changenode
1580 1580 # lookup function as we need to collect no information
1581 1581 # from filenodes.
1582 1582 group = filerevlog.group(msng_filenode_lst,
1583 1583 lookup_filenode_link_func(fname))
1584 1584 for chnk in group:
1585 1585 yield chnk
1586 1586 if msng_filenode_set.has_key(fname):
1587 1587 # Don't need this anymore, toss it to free memory.
1588 1588 del msng_filenode_set[fname]
1589 1589 # Signal that no more groups are left.
1590 1590 yield changegroup.closechunk()
1591 1591
1592 1592 if msng_cl_lst:
1593 1593 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1594 1594
1595 1595 return util.chunkbuffer(gengroup())
1596 1596
1597 1597 def changegroup(self, basenodes, source):
1598 1598 """Generate a changegroup of all nodes that we have that a recipient
1599 1599 doesn't.
1600 1600
1601 1601 This is much easier than the previous function as we can assume that
1602 1602 the recipient has any changenode we aren't sending them."""
1603 1603
1604 1604 self.hook('preoutgoing', throw=True, source=source)
1605 1605
1606 1606 cl = self.changelog
1607 1607 nodes = cl.nodesbetween(basenodes, None)[0]
1608 1608 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1609 1609
1610 1610 def identity(x):
1611 1611 return x
1612 1612
1613 1613 def gennodelst(revlog):
1614 1614 for r in xrange(0, revlog.count()):
1615 1615 n = revlog.node(r)
1616 1616 if revlog.linkrev(n) in revset:
1617 1617 yield n
1618 1618
1619 1619 def changed_file_collector(changedfileset):
1620 1620 def collect_changed_files(clnode):
1621 1621 c = cl.read(clnode)
1622 1622 for fname in c[3]:
1623 1623 changedfileset[fname] = 1
1624 1624 return collect_changed_files
1625 1625
1626 1626 def lookuprevlink_func(revlog):
1627 1627 def lookuprevlink(n):
1628 1628 return cl.node(revlog.linkrev(n))
1629 1629 return lookuprevlink
1630 1630
1631 1631 def gengroup():
1632 1632 # construct a list of all changed files
1633 1633 changedfiles = {}
1634 1634
1635 1635 for chnk in cl.group(nodes, identity,
1636 1636 changed_file_collector(changedfiles)):
1637 1637 yield chnk
1638 1638 changedfiles = changedfiles.keys()
1639 1639 changedfiles.sort()
1640 1640
1641 1641 mnfst = self.manifest
1642 1642 nodeiter = gennodelst(mnfst)
1643 1643 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1644 1644 yield chnk
1645 1645
1646 1646 for fname in changedfiles:
1647 1647 filerevlog = self.file(fname)
1648 1648 nodeiter = gennodelst(filerevlog)
1649 1649 nodeiter = list(nodeiter)
1650 1650 if nodeiter:
1651 1651 yield changegroup.genchunk(fname)
1652 1652 lookup = lookuprevlink_func(filerevlog)
1653 1653 for chnk in filerevlog.group(nodeiter, lookup):
1654 1654 yield chnk
1655 1655
1656 1656 yield changegroup.closechunk()
1657 1657
1658 1658 if nodes:
1659 1659 self.hook('outgoing', node=hex(nodes[0]), source=source)
1660 1660
1661 1661 return util.chunkbuffer(gengroup())
1662 1662
1663 1663 def addchangegroup(self, source, srctype, url):
1664 1664 """add changegroup to repo.
1665 1665 returns number of heads modified or added + 1."""
1666 1666
1667 1667 def csmap(x):
1668 1668 self.ui.debug(_("add changeset %s\n") % short(x))
1669 1669 return cl.count()
1670 1670
1671 1671 def revmap(x):
1672 1672 return cl.rev(x)
1673 1673
1674 1674 if not source:
1675 1675 return 0
1676 1676
1677 1677 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1678 1678
1679 1679 changesets = files = revisions = 0
1680 1680
1681 1681 tr = self.transaction()
1682 1682
1683 1683 # write changelog data to temp files so concurrent readers will not see
1684 1684 # inconsistent view
1685 1685 cl = None
1686 1686 try:
1687 1687 cl = appendfile.appendchangelog(self.opener, self.changelog.version)
1688 1688
1689 1689 oldheads = len(cl.heads())
1690 1690
1691 1691 # pull off the changeset group
1692 1692 self.ui.status(_("adding changesets\n"))
1693 1693 cor = cl.count() - 1
1694 1694 chunkiter = changegroup.chunkiter(source)
1695 1695 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1696 1696 raise util.Abort(_("received changelog group is empty"))
1697 1697 cnr = cl.count() - 1
1698 1698 changesets = cnr - cor
1699 1699
1700 1700 # pull off the manifest group
1701 1701 self.ui.status(_("adding manifests\n"))
1702 1702 chunkiter = changegroup.chunkiter(source)
1703 1703 # no need to check for empty manifest group here:
1704 1704 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1705 1705 # no new manifest will be created and the manifest group will
1706 1706 # be empty during the pull
1707 1707 self.manifest.addgroup(chunkiter, revmap, tr)
1708 1708
1709 1709 # process the files
1710 1710 self.ui.status(_("adding file changes\n"))
1711 1711 while 1:
1712 1712 f = changegroup.getchunk(source)
1713 1713 if not f:
1714 1714 break
1715 1715 self.ui.debug(_("adding %s revisions\n") % f)
1716 1716 fl = self.file(f)
1717 1717 o = fl.count()
1718 1718 chunkiter = changegroup.chunkiter(source)
1719 1719 if fl.addgroup(chunkiter, revmap, tr) is None:
1720 1720 raise util.Abort(_("received file revlog group is empty"))
1721 1721 revisions += fl.count() - o
1722 1722 files += 1
1723 1723
1724 1724 cl.writedata()
1725 1725 finally:
1726 1726 if cl:
1727 1727 cl.cleanup()
1728 1728
1729 1729 # make changelog see real files again
1730 1730 self.changelog = changelog.changelog(self.opener, self.changelog.version)
1731 1731 self.changelog.checkinlinesize(tr)
1732 1732
1733 1733 newheads = len(self.changelog.heads())
1734 1734 heads = ""
1735 1735 if oldheads and newheads != oldheads:
1736 1736 heads = _(" (%+d heads)") % (newheads - oldheads)
1737 1737
1738 1738 self.ui.status(_("added %d changesets"
1739 1739 " with %d changes to %d files%s\n")
1740 1740 % (changesets, revisions, files, heads))
1741 1741
1742 1742 if changesets > 0:
1743 1743 self.hook('pretxnchangegroup', throw=True,
1744 1744 node=hex(self.changelog.node(cor+1)), source=srctype,
1745 1745 url=url)
1746 1746
1747 1747 tr.close()
1748 1748
1749 1749 if changesets > 0:
1750 1750 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1751 1751 source=srctype, url=url)
1752 1752
1753 for i in range(cor + 1, cnr + 1):
1753 for i in xrange(cor + 1, cnr + 1):
1754 1754 self.hook("incoming", node=hex(self.changelog.node(i)),
1755 1755 source=srctype, url=url)
1756 1756
1757 1757 return newheads - oldheads + 1
1758 1758
1759 1759
1760 1760 def stream_in(self, remote):
1761 1761 fp = remote.stream_out()
1762 1762 resp = int(fp.readline())
1763 1763 if resp != 0:
1764 1764 raise util.Abort(_('operation forbidden by server'))
1765 1765 self.ui.status(_('streaming all changes\n'))
1766 1766 total_files, total_bytes = map(int, fp.readline().split(' ', 1))
1767 1767 self.ui.status(_('%d files to transfer, %s of data\n') %
1768 1768 (total_files, util.bytecount(total_bytes)))
1769 1769 start = time.time()
1770 1770 for i in xrange(total_files):
1771 1771 name, size = fp.readline().split('\0', 1)
1772 1772 size = int(size)
1773 1773 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1774 1774 ofp = self.opener(name, 'w')
1775 1775 for chunk in util.filechunkiter(fp, limit=size):
1776 1776 ofp.write(chunk)
1777 1777 ofp.close()
1778 1778 elapsed = time.time() - start
1779 1779 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1780 1780 (util.bytecount(total_bytes), elapsed,
1781 1781 util.bytecount(total_bytes / elapsed)))
1782 1782 self.reload()
1783 1783 return len(self.heads()) + 1
1784 1784
1785 1785 def clone(self, remote, heads=[], stream=False):
1786 1786 '''clone remote repository.
1787 1787
1788 1788 keyword arguments:
1789 1789 heads: list of revs to clone (forces use of pull)
1790 1790 stream: use streaming clone if possible'''
1791 1791
1792 1792 # now, all clients that can request uncompressed clones can
1793 1793 # read repo formats supported by all servers that can serve
1794 1794 # them.
1795 1795
1796 1796 # if revlog format changes, client will have to check version
1797 1797 # and format flags on "stream" capability, and use
1798 1798 # uncompressed only if compatible.
1799 1799
1800 1800 if stream and not heads and remote.capable('stream'):
1801 1801 return self.stream_in(remote)
1802 1802 return self.pull(remote, heads)
1803 1803
1804 1804 # used to avoid circular references so destructors work
1805 1805 def aftertrans(base):
1806 1806 p = base
1807 1807 def a():
1808 1808 util.rename(os.path.join(p, "journal"), os.path.join(p, "undo"))
1809 1809 util.rename(os.path.join(p, "journal.dirstate"),
1810 1810 os.path.join(p, "undo.dirstate"))
1811 1811 return a
1812 1812
1813 1813 def instance(ui, path, create):
1814 1814 return localrepository(ui, util.drop_scheme('file', path), create)
1815 1815
1816 1816 def islocal(path):
1817 1817 return True
@@ -1,657 +1,657 b''
1 1 # patch.py - patch file parsing routines
2 2 #
3 3 # Copyright 2006 Brendan Cully <brendan@kublai.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from demandload import demandload
9 9 from i18n import gettext as _
10 10 from node import *
11 11 demandload(globals(), "base85 cmdutil mdiff util")
12 12 demandload(globals(), "cStringIO email.Parser errno os popen2 re shutil sha")
13 13 demandload(globals(), "sys tempfile zlib")
14 14
15 15 # helper functions
16 16
17 17 def copyfile(src, dst, basedir=None):
18 18 if not basedir:
19 19 basedir = os.getcwd()
20 20
21 21 abssrc, absdst = [os.path.join(basedir, n) for n in (src, dst)]
22 22 if os.path.exists(absdst):
23 23 raise util.Abort(_("cannot create %s: destination already exists") %
24 24 dst)
25 25
26 26 targetdir = os.path.dirname(absdst)
27 27 if not os.path.isdir(targetdir):
28 28 os.makedirs(targetdir)
29 29 try:
30 30 shutil.copyfile(abssrc, absdst)
31 31 shutil.copymode(abssrc, absdst)
32 32 except shutil.Error, inst:
33 33 raise util.Abort(str(inst))
34 34
35 35 # public functions
36 36
37 37 def extract(ui, fileobj):
38 38 '''extract patch from data read from fileobj.
39 39
40 40 patch can be normal patch or contained in email message.
41 41
42 42 return tuple (filename, message, user, date). any item in returned
43 43 tuple can be None. if filename is None, fileobj did not contain
44 44 patch. caller must unlink filename when done.'''
45 45
46 46 # attempt to detect the start of a patch
47 47 # (this heuristic is borrowed from quilt)
48 48 diffre = re.compile(r'^(?:Index:[ \t]|diff[ \t]|RCS file: |' +
49 49 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
50 50 '(---|\*\*\*)[ \t])', re.MULTILINE)
51 51
52 52 fd, tmpname = tempfile.mkstemp(prefix='hg-patch-')
53 53 tmpfp = os.fdopen(fd, 'w')
54 54 try:
55 55 hgpatch = False
56 56
57 57 msg = email.Parser.Parser().parse(fileobj)
58 58
59 59 message = msg['Subject']
60 60 user = msg['From']
61 61 # should try to parse msg['Date']
62 62 date = None
63 63
64 64 if message:
65 65 message = message.replace('\n\t', ' ')
66 66 ui.debug('Subject: %s\n' % message)
67 67 if user:
68 68 ui.debug('From: %s\n' % user)
69 69 diffs_seen = 0
70 70 ok_types = ('text/plain', 'text/x-diff', 'text/x-patch')
71 71
72 72 for part in msg.walk():
73 73 content_type = part.get_content_type()
74 74 ui.debug('Content-Type: %s\n' % content_type)
75 75 if content_type not in ok_types:
76 76 continue
77 77 payload = part.get_payload(decode=True)
78 78 m = diffre.search(payload)
79 79 if m:
80 80 ui.debug(_('found patch at byte %d\n') % m.start(0))
81 81 diffs_seen += 1
82 82 cfp = cStringIO.StringIO()
83 83 if message:
84 84 cfp.write(message)
85 85 cfp.write('\n')
86 86 for line in payload[:m.start(0)].splitlines():
87 87 if line.startswith('# HG changeset patch'):
88 88 ui.debug(_('patch generated by hg export\n'))
89 89 hgpatch = True
90 90 # drop earlier commit message content
91 91 cfp.seek(0)
92 92 cfp.truncate()
93 93 elif hgpatch:
94 94 if line.startswith('# User '):
95 95 user = line[7:]
96 96 ui.debug('From: %s\n' % user)
97 97 elif line.startswith("# Date "):
98 98 date = line[7:]
99 99 if not line.startswith('# '):
100 100 cfp.write(line)
101 101 cfp.write('\n')
102 102 message = cfp.getvalue()
103 103 if tmpfp:
104 104 tmpfp.write(payload)
105 105 if not payload.endswith('\n'):
106 106 tmpfp.write('\n')
107 107 elif not diffs_seen and message and content_type == 'text/plain':
108 108 message += '\n' + payload
109 109 except:
110 110 tmpfp.close()
111 111 os.unlink(tmpname)
112 112 raise
113 113
114 114 tmpfp.close()
115 115 if not diffs_seen:
116 116 os.unlink(tmpname)
117 117 return None, message, user, date
118 118 return tmpname, message, user, date
119 119
120 120 def readgitpatch(patchname):
121 121 """extract git-style metadata about patches from <patchname>"""
122 122 class gitpatch:
123 123 "op is one of ADD, DELETE, RENAME, MODIFY or COPY"
124 124 def __init__(self, path):
125 125 self.path = path
126 126 self.oldpath = None
127 127 self.mode = None
128 128 self.op = 'MODIFY'
129 129 self.copymod = False
130 130 self.lineno = 0
131 131 self.binary = False
132 132
133 133 # Filter patch for git information
134 134 gitre = re.compile('diff --git a/(.*) b/(.*)')
135 135 pf = file(patchname)
136 136 gp = None
137 137 gitpatches = []
138 138 # Can have a git patch with only metadata, causing patch to complain
139 139 dopatch = False
140 140
141 141 lineno = 0
142 142 for line in pf:
143 143 lineno += 1
144 144 if line.startswith('diff --git'):
145 145 m = gitre.match(line)
146 146 if m:
147 147 if gp:
148 148 gitpatches.append(gp)
149 149 src, dst = m.group(1,2)
150 150 gp = gitpatch(dst)
151 151 gp.lineno = lineno
152 152 elif gp:
153 153 if line.startswith('--- '):
154 154 if gp.op in ('COPY', 'RENAME'):
155 155 gp.copymod = True
156 156 dopatch = 'filter'
157 157 gitpatches.append(gp)
158 158 gp = None
159 159 if not dopatch:
160 160 dopatch = True
161 161 continue
162 162 if line.startswith('rename from '):
163 163 gp.op = 'RENAME'
164 164 gp.oldpath = line[12:].rstrip()
165 165 elif line.startswith('rename to '):
166 166 gp.path = line[10:].rstrip()
167 167 elif line.startswith('copy from '):
168 168 gp.op = 'COPY'
169 169 gp.oldpath = line[10:].rstrip()
170 170 elif line.startswith('copy to '):
171 171 gp.path = line[8:].rstrip()
172 172 elif line.startswith('deleted file'):
173 173 gp.op = 'DELETE'
174 174 elif line.startswith('new file mode '):
175 175 gp.op = 'ADD'
176 176 gp.mode = int(line.rstrip()[-3:], 8)
177 177 elif line.startswith('new mode '):
178 178 gp.mode = int(line.rstrip()[-3:], 8)
179 179 elif line.startswith('GIT binary patch'):
180 180 if not dopatch:
181 181 dopatch = 'binary'
182 182 gp.binary = True
183 183 if gp:
184 184 gitpatches.append(gp)
185 185
186 186 if not gitpatches:
187 187 dopatch = True
188 188
189 189 return (dopatch, gitpatches)
190 190
191 191 def dogitpatch(patchname, gitpatches, cwd=None):
192 192 """Preprocess git patch so that vanilla patch can handle it"""
193 193 def extractbin(fp):
194 194 line = fp.readline().rstrip()
195 195 while line and not line.startswith('literal '):
196 196 line = fp.readline().rstrip()
197 197 if not line:
198 198 return
199 199 size = int(line[8:])
200 200 dec = []
201 201 line = fp.readline().rstrip()
202 202 while line:
203 203 l = line[0]
204 204 if l <= 'Z' and l >= 'A':
205 205 l = ord(l) - ord('A') + 1
206 206 else:
207 207 l = ord(l) - ord('a') + 27
208 208 dec.append(base85.b85decode(line[1:])[:l])
209 209 line = fp.readline().rstrip()
210 210 text = zlib.decompress(''.join(dec))
211 211 if len(text) != size:
212 212 raise util.Abort(_('binary patch is %d bytes, not %d') %
213 213 (len(text), size))
214 214 return text
215 215
216 216 pf = file(patchname)
217 217 pfline = 1
218 218
219 219 fd, patchname = tempfile.mkstemp(prefix='hg-patch-')
220 220 tmpfp = os.fdopen(fd, 'w')
221 221
222 222 try:
223 for i in range(len(gitpatches)):
223 for i in xrange(len(gitpatches)):
224 224 p = gitpatches[i]
225 225 if not p.copymod and not p.binary:
226 226 continue
227 227
228 228 # rewrite patch hunk
229 229 while pfline < p.lineno:
230 230 tmpfp.write(pf.readline())
231 231 pfline += 1
232 232
233 233 if p.binary:
234 234 text = extractbin(pf)
235 235 if not text:
236 236 raise util.Abort(_('binary patch extraction failed'))
237 237 if not cwd:
238 238 cwd = os.getcwd()
239 239 absdst = os.path.join(cwd, p.path)
240 240 basedir = os.path.dirname(absdst)
241 241 if not os.path.isdir(basedir):
242 242 os.makedirs(basedir)
243 243 out = file(absdst, 'wb')
244 244 out.write(text)
245 245 out.close()
246 246 elif p.copymod:
247 247 copyfile(p.oldpath, p.path, basedir=cwd)
248 248 tmpfp.write('diff --git a/%s b/%s\n' % (p.path, p.path))
249 249 line = pf.readline()
250 250 pfline += 1
251 251 while not line.startswith('--- a/'):
252 252 tmpfp.write(line)
253 253 line = pf.readline()
254 254 pfline += 1
255 255 tmpfp.write('--- a/%s\n' % p.path)
256 256
257 257 line = pf.readline()
258 258 while line:
259 259 tmpfp.write(line)
260 260 line = pf.readline()
261 261 except:
262 262 tmpfp.close()
263 263 os.unlink(patchname)
264 264 raise
265 265
266 266 tmpfp.close()
267 267 return patchname
268 268
269 269 def patch(patchname, ui, strip=1, cwd=None, files={}):
270 270 """apply the patch <patchname> to the working directory.
271 271 a list of patched files is returned"""
272 272
273 273 # helper function
274 274 def __patch(patchname):
275 275 """patch and updates the files and fuzz variables"""
276 276 fuzz = False
277 277
278 278 patcher = util.find_in_path('gpatch', os.environ.get('PATH', ''),
279 279 'patch')
280 280 args = []
281 281 if cwd:
282 282 args.append('-d %s' % util.shellquote(cwd))
283 283 fp = os.popen('%s %s -p%d < %s' % (patcher, ' '.join(args), strip,
284 284 util.shellquote(patchname)))
285 285
286 286 for line in fp:
287 287 line = line.rstrip()
288 288 ui.note(line + '\n')
289 289 if line.startswith('patching file '):
290 290 pf = util.parse_patch_output(line)
291 291 printed_file = False
292 292 files.setdefault(pf, (None, None))
293 293 elif line.find('with fuzz') >= 0:
294 294 fuzz = True
295 295 if not printed_file:
296 296 ui.warn(pf + '\n')
297 297 printed_file = True
298 298 ui.warn(line + '\n')
299 299 elif line.find('saving rejects to file') >= 0:
300 300 ui.warn(line + '\n')
301 301 elif line.find('FAILED') >= 0:
302 302 if not printed_file:
303 303 ui.warn(pf + '\n')
304 304 printed_file = True
305 305 ui.warn(line + '\n')
306 306 code = fp.close()
307 307 if code:
308 308 raise util.Abort(_("patch command failed: %s") %
309 309 util.explain_exit(code)[0])
310 310 return fuzz
311 311
312 312 (dopatch, gitpatches) = readgitpatch(patchname)
313 313 for gp in gitpatches:
314 314 files[gp.path] = (gp.op, gp)
315 315
316 316 fuzz = False
317 317 if dopatch:
318 318 if dopatch in ('filter', 'binary'):
319 319 patchname = dogitpatch(patchname, gitpatches, cwd=cwd)
320 320 try:
321 321 if dopatch != 'binary':
322 322 fuzz = __patch(patchname)
323 323 finally:
324 324 if dopatch == 'filter':
325 325 os.unlink(patchname)
326 326
327 327 return fuzz
328 328
329 329 def diffopts(ui, opts={}):
330 330 return mdiff.diffopts(
331 331 text=opts.get('text'),
332 332 git=(opts.get('git') or
333 333 ui.configbool('diff', 'git', None)),
334 334 nodates=(opts.get('nodates') or
335 335 ui.configbool('diff', 'nodates', None)),
336 336 showfunc=(opts.get('show_function') or
337 337 ui.configbool('diff', 'showfunc', None)),
338 338 ignorews=(opts.get('ignore_all_space') or
339 339 ui.configbool('diff', 'ignorews', None)),
340 340 ignorewsamount=(opts.get('ignore_space_change') or
341 341 ui.configbool('diff', 'ignorewsamount', None)),
342 342 ignoreblanklines=(opts.get('ignore_blank_lines') or
343 343 ui.configbool('diff', 'ignoreblanklines', None)))
344 344
345 345 def updatedir(ui, repo, patches, wlock=None):
346 346 '''Update dirstate after patch application according to metadata'''
347 347 if not patches:
348 348 return
349 349 copies = []
350 350 removes = []
351 351 cfiles = patches.keys()
352 352 cwd = repo.getcwd()
353 353 if cwd:
354 354 cfiles = [util.pathto(cwd, f) for f in patches.keys()]
355 355 for f in patches:
356 356 ctype, gp = patches[f]
357 357 if ctype == 'RENAME':
358 358 copies.append((gp.oldpath, gp.path, gp.copymod))
359 359 removes.append(gp.oldpath)
360 360 elif ctype == 'COPY':
361 361 copies.append((gp.oldpath, gp.path, gp.copymod))
362 362 elif ctype == 'DELETE':
363 363 removes.append(gp.path)
364 364 for src, dst, after in copies:
365 365 if not after:
366 366 copyfile(src, dst, repo.root)
367 367 repo.copy(src, dst, wlock=wlock)
368 368 if removes:
369 369 repo.remove(removes, True, wlock=wlock)
370 370 for f in patches:
371 371 ctype, gp = patches[f]
372 372 if gp and gp.mode:
373 373 x = gp.mode & 0100 != 0
374 374 dst = os.path.join(repo.root, gp.path)
375 375 util.set_exec(dst, x)
376 376 cmdutil.addremove(repo, cfiles, wlock=wlock)
377 377 files = patches.keys()
378 378 files.extend([r for r in removes if r not in files])
379 379 files.sort()
380 380
381 381 return files
382 382
383 383 def b85diff(fp, to, tn):
384 384 '''print base85-encoded binary diff'''
385 385 def gitindex(text):
386 386 if not text:
387 387 return '0' * 40
388 388 l = len(text)
389 389 s = sha.new('blob %d\0' % l)
390 390 s.update(text)
391 391 return s.hexdigest()
392 392
393 393 def fmtline(line):
394 394 l = len(line)
395 395 if l <= 26:
396 396 l = chr(ord('A') + l - 1)
397 397 else:
398 398 l = chr(l - 26 + ord('a') - 1)
399 399 return '%c%s\n' % (l, base85.b85encode(line, True))
400 400
401 401 def chunk(text, csize=52):
402 402 l = len(text)
403 403 i = 0
404 404 while i < l:
405 405 yield text[i:i+csize]
406 406 i += csize
407 407
408 408 # TODO: deltas
409 409 l = len(tn)
410 410 fp.write('index %s..%s\nGIT binary patch\nliteral %s\n' %
411 411 (gitindex(to), gitindex(tn), len(tn)))
412 412
413 413 tn = ''.join([fmtline(l) for l in chunk(zlib.compress(tn))])
414 414 fp.write(tn)
415 415 fp.write('\n')
416 416
417 417 def diff(repo, node1=None, node2=None, files=None, match=util.always,
418 418 fp=None, changes=None, opts=None):
419 419 '''print diff of changes to files between two nodes, or node and
420 420 working directory.
421 421
422 422 if node1 is None, use first dirstate parent instead.
423 423 if node2 is None, compare node1 with working directory.'''
424 424
425 425 if opts is None:
426 426 opts = mdiff.defaultopts
427 427 if fp is None:
428 428 fp = repo.ui
429 429
430 430 if not node1:
431 431 node1 = repo.dirstate.parents()[0]
432 432
433 433 clcache = {}
434 434 def getchangelog(n):
435 435 if n not in clcache:
436 436 clcache[n] = repo.changelog.read(n)
437 437 return clcache[n]
438 438 mcache = {}
439 439 def getmanifest(n):
440 440 if n not in mcache:
441 441 mcache[n] = repo.manifest.read(n)
442 442 return mcache[n]
443 443 fcache = {}
444 444 def getfile(f):
445 445 if f not in fcache:
446 446 fcache[f] = repo.file(f)
447 447 return fcache[f]
448 448
449 449 # reading the data for node1 early allows it to play nicely
450 450 # with repo.status and the revlog cache.
451 451 change = getchangelog(node1)
452 452 mmap = getmanifest(change[0])
453 453 date1 = util.datestr(change[2])
454 454
455 455 if not changes:
456 456 changes = repo.status(node1, node2, files, match=match)[:5]
457 457 modified, added, removed, deleted, unknown = changes
458 458 if files:
459 459 def filterfiles(filters):
460 460 l = [x for x in filters if x in files]
461 461
462 462 for t in files:
463 463 if not t.endswith("/"):
464 464 t += "/"
465 465 l += [x for x in filters if x.startswith(t)]
466 466 return l
467 467
468 468 modified, added, removed = map(filterfiles, (modified, added, removed))
469 469
470 470 if not modified and not added and not removed:
471 471 return
472 472
473 473 def renamedbetween(f, n1, n2):
474 474 r1, r2 = map(repo.changelog.rev, (n1, n2))
475 475 src = None
476 476 while r2 > r1:
477 477 cl = getchangelog(n2)[0]
478 478 m = getmanifest(cl)
479 479 try:
480 480 src = getfile(f).renamed(m[f])
481 481 except KeyError:
482 482 return None
483 483 if src:
484 484 f = src[0]
485 485 n2 = repo.changelog.parents(n2)[0]
486 486 r2 = repo.changelog.rev(n2)
487 487 return src
488 488
489 489 if node2:
490 490 change = getchangelog(node2)
491 491 mmap2 = getmanifest(change[0])
492 492 _date2 = util.datestr(change[2])
493 493 def date2(f):
494 494 return _date2
495 495 def read(f):
496 496 return getfile(f).read(mmap2[f])
497 497 def renamed(f):
498 498 return renamedbetween(f, node1, node2)
499 499 else:
500 500 tz = util.makedate()[1]
501 501 _date2 = util.datestr()
502 502 def date2(f):
503 503 try:
504 504 return util.datestr((os.lstat(repo.wjoin(f)).st_mtime, tz))
505 505 except OSError, err:
506 506 if err.errno != errno.ENOENT: raise
507 507 return _date2
508 508 def read(f):
509 509 return repo.wread(f)
510 510 def renamed(f):
511 511 src = repo.dirstate.copied(f)
512 512 parent = repo.dirstate.parents()[0]
513 513 if src:
514 514 f = src[0]
515 515 of = renamedbetween(f, node1, parent)
516 516 if of:
517 517 return of
518 518 elif src:
519 519 cl = getchangelog(parent)[0]
520 520 return (src, getmanifest(cl)[src])
521 521 else:
522 522 return None
523 523
524 524 if repo.ui.quiet:
525 525 r = None
526 526 else:
527 527 hexfunc = repo.ui.debugflag and hex or short
528 528 r = [hexfunc(node) for node in [node1, node2] if node]
529 529
530 530 if opts.git:
531 531 copied = {}
532 532 for f in added:
533 533 src = renamed(f)
534 534 if src:
535 535 copied[f] = src
536 536 srcs = [x[1][0] for x in copied.items()]
537 537
538 538 all = modified + added + removed
539 539 all.sort()
540 540 for f in all:
541 541 to = None
542 542 tn = None
543 543 dodiff = True
544 544 header = []
545 545 if f in mmap:
546 546 to = getfile(f).read(mmap[f])
547 547 if f not in removed:
548 548 tn = read(f)
549 549 if opts.git:
550 550 def gitmode(x):
551 551 return x and '100755' or '100644'
552 552 def addmodehdr(header, omode, nmode):
553 553 if omode != nmode:
554 554 header.append('old mode %s\n' % omode)
555 555 header.append('new mode %s\n' % nmode)
556 556
557 557 a, b = f, f
558 558 if f in added:
559 559 if node2:
560 560 mode = gitmode(mmap2.execf(f))
561 561 else:
562 562 mode = gitmode(util.is_exec(repo.wjoin(f), None))
563 563 if f in copied:
564 564 a, arev = copied[f]
565 565 omode = gitmode(mmap.execf(a))
566 566 addmodehdr(header, omode, mode)
567 567 op = a in removed and 'rename' or 'copy'
568 568 header.append('%s from %s\n' % (op, a))
569 569 header.append('%s to %s\n' % (op, f))
570 570 to = getfile(a).read(arev)
571 571 else:
572 572 header.append('new file mode %s\n' % mode)
573 573 if util.binary(tn):
574 574 dodiff = 'binary'
575 575 elif f in removed:
576 576 if f in srcs:
577 577 dodiff = False
578 578 else:
579 579 mode = gitmode(mmap.execf(f))
580 580 header.append('deleted file mode %s\n' % mode)
581 581 else:
582 582 omode = gitmode(mmap.execf(f))
583 583 if node2:
584 584 nmode = gitmode(mmap2.execf(f))
585 585 else:
586 586 nmode = gitmode(util.is_exec(repo.wjoin(f), mmap.execf(f)))
587 587 addmodehdr(header, omode, nmode)
588 588 if util.binary(to) or util.binary(tn):
589 589 dodiff = 'binary'
590 590 r = None
591 591 header.insert(0, 'diff --git a/%s b/%s\n' % (a, b))
592 592 if dodiff == 'binary':
593 593 fp.write(''.join(header))
594 594 b85diff(fp, to, tn)
595 595 elif dodiff:
596 596 text = mdiff.unidiff(to, date1, tn, date2(f), f, r, opts=opts)
597 597 if text or len(header) > 1:
598 598 fp.write(''.join(header))
599 599 fp.write(text)
600 600
601 601 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
602 602 opts=None):
603 603 '''export changesets as hg patches.'''
604 604
605 605 total = len(revs)
606 606 revwidth = max(map(len, revs))
607 607
608 608 def single(node, seqno, fp):
609 609 parents = [p for p in repo.changelog.parents(node) if p != nullid]
610 610 if switch_parent:
611 611 parents.reverse()
612 612 prev = (parents and parents[0]) or nullid
613 613 change = repo.changelog.read(node)
614 614
615 615 if not fp:
616 616 fp = cmdutil.make_file(repo, template, node, total=total,
617 617 seqno=seqno, revwidth=revwidth)
618 618 if fp not in (sys.stdout, repo.ui):
619 619 repo.ui.note("%s\n" % fp.name)
620 620
621 621 fp.write("# HG changeset patch\n")
622 622 fp.write("# User %s\n" % change[1])
623 623 fp.write("# Date %d %d\n" % change[2])
624 624 fp.write("# Node ID %s\n" % hex(node))
625 625 fp.write("# Parent %s\n" % hex(prev))
626 626 if len(parents) > 1:
627 627 fp.write("# Parent %s\n" % hex(parents[1]))
628 628 fp.write(change[4].rstrip())
629 629 fp.write("\n\n")
630 630
631 631 diff(repo, prev, node, fp=fp, opts=opts)
632 632 if fp not in (sys.stdout, repo.ui):
633 633 fp.close()
634 634
635 635 for seqno, cset in enumerate(revs):
636 636 single(cset, seqno, fp)
637 637
638 638 def diffstat(patchlines):
639 639 fd, name = tempfile.mkstemp(prefix="hg-patchbomb-", suffix=".txt")
640 640 try:
641 641 p = popen2.Popen3('diffstat -p1 -w79 2>/dev/null > ' + name)
642 642 try:
643 643 for line in patchlines: print >> p.tochild, line
644 644 p.tochild.close()
645 645 if p.wait(): return
646 646 fp = os.fdopen(fd, 'r')
647 647 stat = []
648 648 for line in fp: stat.append(line.lstrip())
649 649 last = stat.pop()
650 650 stat.insert(0, last)
651 651 stat = ''.join(stat)
652 652 if stat.startswith('0 files'): raise ValueError
653 653 return stat
654 654 except: raise
655 655 finally:
656 656 try: os.unlink(name)
657 657 except: pass
@@ -1,194 +1,194 b''
1 1 # verify.py - repository integrity checking for Mercurial
2 2 #
3 3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from node import *
9 9 from i18n import gettext as _
10 10 import revlog, mdiff
11 11
12 12 def verify(repo):
13 13 filelinkrevs = {}
14 14 filenodes = {}
15 15 changesets = revisions = files = 0
16 16 errors = [0]
17 17 warnings = [0]
18 18 neededmanifests = {}
19 19
20 20 def err(msg):
21 21 repo.ui.warn(msg + "\n")
22 22 errors[0] += 1
23 23
24 24 def warn(msg):
25 25 repo.ui.warn(msg + "\n")
26 26 warnings[0] += 1
27 27
28 28 def checksize(obj, name):
29 29 d = obj.checksize()
30 30 if d[0]:
31 31 err(_("%s data length off by %d bytes") % (name, d[0]))
32 32 if d[1]:
33 33 err(_("%s index contains %d extra bytes") % (name, d[1]))
34 34
35 35 def checkversion(obj, name):
36 36 if obj.version != revlog.REVLOGV0:
37 37 if not revlogv1:
38 38 warn(_("warning: `%s' uses revlog format 1") % name)
39 39 elif revlogv1:
40 40 warn(_("warning: `%s' uses revlog format 0") % name)
41 41
42 42 revlogv1 = repo.revlogversion != revlog.REVLOGV0
43 43 if repo.ui.verbose or revlogv1 != repo.revlogv1:
44 44 repo.ui.status(_("repository uses revlog format %d\n") %
45 45 (revlogv1 and 1 or 0))
46 46
47 47 seen = {}
48 48 repo.ui.status(_("checking changesets\n"))
49 49 checksize(repo.changelog, "changelog")
50 50
51 for i in range(repo.changelog.count()):
51 for i in xrange(repo.changelog.count()):
52 52 changesets += 1
53 53 n = repo.changelog.node(i)
54 54 l = repo.changelog.linkrev(n)
55 55 if l != i:
56 56 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
57 57 if n in seen:
58 58 err(_("duplicate changeset at revision %d") % i)
59 59 seen[n] = 1
60 60
61 61 for p in repo.changelog.parents(n):
62 62 if p not in repo.changelog.nodemap:
63 63 err(_("changeset %s has unknown parent %s") %
64 64 (short(n), short(p)))
65 65 try:
66 66 changes = repo.changelog.read(n)
67 67 except KeyboardInterrupt:
68 68 repo.ui.warn(_("interrupted"))
69 69 raise
70 70 except Exception, inst:
71 71 err(_("unpacking changeset %s: %s") % (short(n), inst))
72 72 continue
73 73
74 74 neededmanifests[changes[0]] = n
75 75
76 76 for f in changes[3]:
77 77 filelinkrevs.setdefault(f, []).append(i)
78 78
79 79 seen = {}
80 80 repo.ui.status(_("checking manifests\n"))
81 81 checkversion(repo.manifest, "manifest")
82 82 checksize(repo.manifest, "manifest")
83 83
84 for i in range(repo.manifest.count()):
84 for i in xrange(repo.manifest.count()):
85 85 n = repo.manifest.node(i)
86 86 l = repo.manifest.linkrev(n)
87 87
88 88 if l < 0 or l >= repo.changelog.count():
89 89 err(_("bad manifest link (%d) at revision %d") % (l, i))
90 90
91 91 if n in neededmanifests:
92 92 del neededmanifests[n]
93 93
94 94 if n in seen:
95 95 err(_("duplicate manifest at revision %d") % i)
96 96
97 97 seen[n] = 1
98 98
99 99 for p in repo.manifest.parents(n):
100 100 if p not in repo.manifest.nodemap:
101 101 err(_("manifest %s has unknown parent %s") %
102 102 (short(n), short(p)))
103 103
104 104 try:
105 105 for f, fn in repo.manifest.readdelta(n).iteritems():
106 106 filenodes.setdefault(f, {})[fn] = 1
107 107 except KeyboardInterrupt:
108 108 repo.ui.warn(_("interrupted"))
109 109 raise
110 110 except Exception, inst:
111 111 err(_("reading delta for manifest %s: %s") % (short(n), inst))
112 112 continue
113 113
114 114 repo.ui.status(_("crosschecking files in changesets and manifests\n"))
115 115
116 116 for m, c in neededmanifests.items():
117 117 err(_("Changeset %s refers to unknown manifest %s") %
118 118 (short(m), short(c)))
119 119 del neededmanifests
120 120
121 121 for f in filenodes:
122 122 if f not in filelinkrevs:
123 123 err(_("file %s in manifest but not in changesets") % f)
124 124
125 125 for f in filelinkrevs:
126 126 if f not in filenodes:
127 127 err(_("file %s in changeset but not in manifest") % f)
128 128
129 129 repo.ui.status(_("checking files\n"))
130 130 ff = filenodes.keys()
131 131 ff.sort()
132 132 for f in ff:
133 133 if f == "/dev/null":
134 134 continue
135 135 files += 1
136 136 if not f:
137 137 err(_("file without name in manifest %s") % short(n))
138 138 continue
139 139 fl = repo.file(f)
140 140 checkversion(fl, f)
141 141 checksize(fl, f)
142 142
143 143 nodes = {nullid: 1}
144 144 seen = {}
145 for i in range(fl.count()):
145 for i in xrange(fl.count()):
146 146 revisions += 1
147 147 n = fl.node(i)
148 148
149 149 if n in seen:
150 150 err(_("%s: duplicate revision %d") % (f, i))
151 151 if n not in filenodes[f]:
152 152 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
153 153 else:
154 154 del filenodes[f][n]
155 155
156 156 flr = fl.linkrev(n)
157 157 if flr not in filelinkrevs.get(f, []):
158 158 err(_("%s:%s points to unexpected changeset %d")
159 159 % (f, short(n), flr))
160 160 else:
161 161 filelinkrevs[f].remove(flr)
162 162
163 163 # verify contents
164 164 try:
165 165 t = fl.read(n)
166 166 except KeyboardInterrupt:
167 167 repo.ui.warn(_("interrupted"))
168 168 raise
169 169 except Exception, inst:
170 170 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
171 171
172 172 # verify parents
173 173 (p1, p2) = fl.parents(n)
174 174 if p1 not in nodes:
175 175 err(_("file %s:%s unknown parent 1 %s") %
176 176 (f, short(n), short(p1)))
177 177 if p2 not in nodes:
178 178 err(_("file %s:%s unknown parent 2 %s") %
179 179 (f, short(n), short(p1)))
180 180 nodes[n] = 1
181 181
182 182 # cross-check
183 183 for node in filenodes[f]:
184 184 err(_("node %s in manifests not in %s") % (hex(node), f))
185 185
186 186 repo.ui.status(_("%d files, %d changesets, %d total revisions\n") %
187 187 (files, changesets, revisions))
188 188
189 189 if warnings[0]:
190 190 repo.ui.warn(_("%d warnings encountered!\n") % warnings[0])
191 191 if errors[0]:
192 192 repo.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
193 193 return 1
194 194
General Comments 0
You need to be logged in to leave comments. Login now