##// END OF EJS Templates
Merge with crew
Thomas Arendsen Hein -
r2100:2b8f887b merge default
parent child Browse files
Show More
@@ -1,289 +1,289 b''
1 1 #!/usr/bin/env python
2 2 #
3 3 # This is a generalized framework for converting between SCM
4 4 # repository formats.
5 5 #
6 6 # In its current form, it's hardcoded to convert incrementally between
7 7 # git and Mercurial.
8 8 #
9 9 # To use, you must first import the first git version into Mercurial,
10 10 # and establish a mapping between the git commit hash and the hash in
11 11 # Mercurial for that version. This mapping is kept in a simple text
12 12 # file with lines like so:
13 13 #
14 14 # <git hash> <mercurial hash>
15 15 #
16 16 # To convert the rest of the repo, run:
17 17 #
18 18 # convert-repo <git-dir> <hg-dir> <mapfile>
19 19 #
20 20 # This updates the mapfile on each commit copied, so it can be
21 21 # interrupted and can be run repeatedly to copy new commits.
22 22
23 23 import sys, os, zlib, sha, time
24 24 from mercurial import hg, ui, util
25 25
26 26 class convert_git:
27 27 def __init__(self, path):
28 28 self.path = path
29 29
30 30 def getheads(self):
31 31 return [file(self.path + "/HEAD").read()[:-1]]
32 32
33 33 def catfile(self, rev, type):
34 34 if rev == "0" * 40: raise IOError()
35 35 fh = os.popen("GIT_DIR=%s git-cat-file %s %s 2>/dev/null" % (self.path, type, rev))
36 36 return fh.read()
37 37
38 38 def getfile(self, name, rev):
39 39 return self.catfile(rev, "blob")
40 40
41 41 def getchanges(self, version):
42 42 fh = os.popen("GIT_DIR=%s git-diff-tree --root -m -r %s" % (self.path, version))
43 43 changes = []
44 44 for l in fh:
45 45 if "\t" not in l: continue
46 46 m, f = l[:-1].split("\t")
47 47 m = m.split()
48 48 h = m[3]
49 49 p = (m[1] == "100755")
50 50 changes.append((f, h, p))
51 51 return changes
52 52
53 53 def getcommit(self, version):
54 54 c = self.catfile(version, "commit") # read the commit hash
55 55 end = c.find("\n\n")
56 56 message = c[end+2:]
57 57 l = c[:end].splitlines()
58 58 manifest = l[0].split()[1]
59 59 parents = []
60 60 for e in l[1:]:
61 61 n,v = e.split(" ", 1)
62 62 if n == "author":
63 63 p = v.split()
64 64 tm, tz = p[-2:]
65 65 author = " ".join(p[:-2])
66 66 if author[0] == "<": author = author[1:-1]
67 67 if n == "committer":
68 68 p = v.split()
69 69 tm, tz = p[-2:]
70 70 committer = " ".join(p[:-2])
71 71 if committer[0] == "<": committer = committer[1:-1]
72 72 message += "\ncommitter: %s\n" % v
73 73 if n == "parent": parents.append(v)
74 74
75 75 tzs, tzh, tzm = tz[-5:-4] + "1", tz[-4:-2], tz[-2:]
76 tz = int(tzs) * (int(tzh) * 3600 + int(tzm))
76 tz = -int(tzs) * (int(tzh) * 3600 + int(tzm))
77 77 date = tm + " " + str(tz)
78 78 return (parents, author, date, message)
79 79
80 80 def gettags(self):
81 81 tags = {}
82 82 for f in os.listdir(self.path + "/refs/tags"):
83 83 try:
84 84 h = file(self.path + "/refs/tags/" + f).read().strip()
85 85 c = self.catfile(h, "tag") # read the commit hash
86 86 h = c.splitlines()[0].split()[1]
87 87 tags[f] = h
88 88 except:
89 89 pass
90 90 return tags
91 91
92 92 class convert_mercurial:
93 93 def __init__(self, path):
94 94 self.path = path
95 95 u = ui.ui()
96 96 self.repo = hg.repository(u, path)
97 97
98 98 def getheads(self):
99 99 h = self.repo.changelog.heads()
100 100 return [ hg.hex(x) for x in h ]
101 101
102 102 def putfile(self, f, e, data):
103 103 self.repo.wfile(f, "w").write(data)
104 104 if self.repo.dirstate.state(f) == '?':
105 105 self.repo.dirstate.update([f], "a")
106 106
107 107 util.set_exec(self.repo.wjoin(f), e)
108 108
109 109 def delfile(self, f):
110 110 try:
111 111 os.unlink(self.repo.wjoin(f))
112 112 #self.repo.remove([f])
113 113 except:
114 114 pass
115 115
116 116 def putcommit(self, files, parents, author, dest, text):
117 117 seen = {}
118 118 pl = []
119 119 for p in parents:
120 120 if p not in seen:
121 121 pl.append(p)
122 122 seen[p] = 1
123 123 parents = pl
124 124
125 125 if len(parents) < 2: parents.append("0" * 40)
126 126 if len(parents) < 2: parents.append("0" * 40)
127 127 p2 = parents.pop(0)
128 128
129 129 while parents:
130 130 p1 = p2
131 131 p2 = parents.pop(0)
132 132 self.repo.rawcommit(files, text, author, dest,
133 133 hg.bin(p1), hg.bin(p2))
134 134 text = "(octopus merge fixup)\n"
135 135 p2 = hg.hex(self.repo.changelog.tip())
136 136
137 137 return p2
138 138
139 139 def puttags(self, tags):
140 140 try:
141 141 old = self.repo.wfile(".hgtags").read()
142 142 oldlines = old.splitlines(1)
143 143 oldlines.sort()
144 144 except:
145 145 oldlines = []
146 146
147 147 k = tags.keys()
148 148 k.sort()
149 149 newlines = []
150 150 for tag in k:
151 151 newlines.append("%s %s\n" % (tags[tag], tag))
152 152
153 153 newlines.sort()
154 154
155 155 if newlines != oldlines:
156 156 #print "updating tags"
157 157 f = self.repo.wfile(".hgtags", "w")
158 158 f.write("".join(newlines))
159 159 f.close()
160 160 if not oldlines: self.repo.add([".hgtags"])
161 161 date = "%s 0" % int(time.mktime(time.gmtime()))
162 162 self.repo.rawcommit([".hgtags"], "update tags", "convert-repo",
163 163 date, self.repo.changelog.tip(), hg.nullid)
164 164 return hg.hex(self.repo.changelog.tip())
165 165
166 166 class convert:
167 167 def __init__(self, source, dest, mapfile):
168 168 self.source = source
169 169 self.dest = dest
170 170 self.mapfile = mapfile
171 171 self.commitcache = {}
172 172
173 173 self.map = {}
174 174 try:
175 175 for l in file(self.mapfile):
176 176 sv, dv = l[:-1].split()
177 177 self.map[sv] = dv
178 178 except IOError:
179 179 pass
180 180
181 181 def walktree(self, heads):
182 182 visit = heads
183 183 known = {}
184 184 parents = {}
185 185 while visit:
186 186 n = visit.pop(0)
187 187 if n in known or n in self.map: continue
188 188 known[n] = 1
189 189 self.commitcache[n] = self.source.getcommit(n)
190 190 cp = self.commitcache[n][0]
191 191 for p in cp:
192 192 parents.setdefault(n, []).append(p)
193 193 visit.append(p)
194 194
195 195 return parents
196 196
197 197 def toposort(self, parents):
198 198 visit = parents.keys()
199 199 seen = {}
200 200 children = {}
201 201
202 202 while visit:
203 203 n = visit.pop(0)
204 204 if n in seen: continue
205 205 seen[n] = 1
206 206 pc = 0
207 207 if n in parents:
208 208 for p in parents[n]:
209 209 if p not in self.map: pc += 1
210 210 visit.append(p)
211 211 children.setdefault(p, []).append(n)
212 212 if not pc: root = n
213 213
214 214 s = []
215 215 removed = {}
216 216 visit = children.keys()
217 217 while visit:
218 218 n = visit.pop(0)
219 219 if n in removed: continue
220 220 dep = 0
221 221 if n in parents:
222 222 for p in parents[n]:
223 223 if p in self.map: continue
224 224 if p not in removed:
225 225 # we're still dependent
226 226 visit.append(n)
227 227 dep = 1
228 228 break
229 229
230 230 if not dep:
231 231 # all n's parents are in the list
232 232 removed[n] = 1
233 233 s.append(n)
234 234 if n in children:
235 235 for c in children[n]:
236 236 visit.insert(0, c)
237 237
238 238 return s
239 239
240 240 def copy(self, rev):
241 241 p, a, d, t = self.commitcache[rev]
242 242 files = self.source.getchanges(rev)
243 243
244 244 for f,v,e in files:
245 245 try:
246 246 data = self.source.getfile(f, v)
247 247 except IOError, inst:
248 248 self.dest.delfile(f)
249 249 else:
250 250 self.dest.putfile(f, e, data)
251 251
252 252 r = [self.map[v] for v in p]
253 253 f = [f for f,v,e in files]
254 254 self.map[rev] = self.dest.putcommit(f, r, a, d, t)
255 255 file(self.mapfile, "a").write("%s %s\n" % (rev, self.map[rev]))
256 256
257 257 def convert(self):
258 258 heads = self.source.getheads()
259 259 parents = self.walktree(heads)
260 260 t = self.toposort(parents)
261 261 t = [n for n in t if n not in self.map]
262 262 num = len(t)
263 263 c = None
264 264
265 265 for c in t:
266 266 num -= 1
267 267 desc = self.commitcache[c][3].splitlines()[0]
268 268 #print num, desc
269 269 self.copy(c)
270 270
271 271 tags = self.source.gettags()
272 272 ctags = {}
273 273 for k in tags:
274 274 v = tags[k]
275 275 if v in self.map:
276 276 ctags[k] = self.map[v]
277 277
278 278 if c and ctags:
279 279 nrev = self.dest.puttags(ctags)
280 280 # write another hash correspondence to override the previous
281 281 # one so we don't end up with extra tag heads
282 282 file(self.mapfile, "a").write("%s %s\n" % (c, nrev))
283 283
284 284 gitpath, hgpath, mapfile = sys.argv[1:]
285 285 if os.path.isdir(gitpath + "/.git"):
286 286 gitpath += "/.git"
287 287
288 288 c = convert(convert_git(gitpath), convert_mercurial(hgpath), mapfile)
289 289 c.convert()
@@ -1,1310 +1,1311 b''
1 1 # queue.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005 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(), "os sys re struct traceback errno bz2")
10 10 from mercurial.i18n import gettext as _
11 11 from mercurial import ui, hg, revlog, commands, util
12 12
13 13 versionstr = "0.45"
14 14
15 15 repomap = {}
16 16
17 17 commands.norepo += " qversion"
18 18 class queue:
19 19 def __init__(self, ui, path, patchdir=None):
20 20 self.basepath = path
21 21 if patchdir:
22 22 self.path = patchdir
23 23 else:
24 24 self.path = os.path.join(path, "patches")
25 25 self.opener = util.opener(self.path)
26 26 self.ui = ui
27 27 self.applied = []
28 28 self.full_series = []
29 29 self.applied_dirty = 0
30 30 self.series_dirty = 0
31 31 self.series_path = "series"
32 32 self.status_path = "status"
33 33
34 34 if os.path.exists(os.path.join(self.path, self.series_path)):
35 35 self.full_series = self.opener(self.series_path).read().splitlines()
36 36 self.read_series(self.full_series)
37 37
38 38 if os.path.exists(os.path.join(self.path, self.status_path)):
39 39 self.applied = self.opener(self.status_path).read().splitlines()
40 40
41 41 def find_series(self, patch):
42 42 pre = re.compile("(\s*)([^#]+)")
43 43 index = 0
44 44 for l in self.full_series:
45 45 m = pre.match(l)
46 46 if m:
47 47 s = m.group(2)
48 48 s = s.rstrip()
49 49 if s == patch:
50 50 return index
51 51 index += 1
52 52 return None
53 53
54 54 def read_series(self, list):
55 55 def matcher(list):
56 56 pre = re.compile("(\s*)([^#]+)")
57 57 for l in list:
58 58 m = pre.match(l)
59 59 if m:
60 60 s = m.group(2)
61 61 s = s.rstrip()
62 62 if len(s) > 0:
63 63 yield s
64 64 self.series = []
65 65 self.series = [ x for x in matcher(list) ]
66 66
67 67 def save_dirty(self):
68 68 if self.applied_dirty:
69 69 if len(self.applied) > 0:
70 70 nl = "\n"
71 71 else:
72 72 nl = ""
73 73 f = self.opener(self.status_path, "w")
74 74 f.write("\n".join(self.applied) + nl)
75 75 if self.series_dirty:
76 76 if len(self.full_series) > 0:
77 77 nl = "\n"
78 78 else:
79 79 nl = ""
80 80 f = self.opener(self.series_path, "w")
81 81 f.write("\n".join(self.full_series) + nl)
82 82
83 83 def readheaders(self, patch):
84 84 def eatdiff(lines):
85 85 while lines:
86 86 l = lines[-1]
87 87 if (l.startswith("diff -") or
88 88 l.startswith("Index:") or
89 89 l.startswith("===========")):
90 90 del lines[-1]
91 91 else:
92 92 break
93 93 def eatempty(lines):
94 94 while lines:
95 95 l = lines[-1]
96 96 if re.match('\s*$', l):
97 97 del lines[-1]
98 98 else:
99 99 break
100 100
101 101 pf = os.path.join(self.path, patch)
102 102 message = []
103 103 comments = []
104 104 user = None
105 105 format = None
106 106 subject = None
107 107 diffstart = 0
108 108
109 109 for line in file(pf):
110 110 line = line.rstrip()
111 111 if diffstart:
112 112 if line.startswith('+++ '):
113 113 diffstart = 2
114 114 break
115 115 if line.startswith("--- "):
116 116 diffstart = 1
117 117 continue
118 118 elif format == "hgpatch":
119 119 # parse values when importing the result of an hg export
120 120 if line.startswith("# User "):
121 121 user = line[7:]
122 122 elif not line.startswith("# ") and line:
123 123 message.append(line)
124 124 format = None
125 125 elif line == '# HG changeset patch':
126 126 format = "hgpatch"
127 127 elif (format != "tagdone" and (line.startswith("Subject: ") or
128 128 line.startswith("subject: "))):
129 129 subject = line[9:]
130 130 format = "tag"
131 131 elif (format != "tagdone" and (line.startswith("From: ") or
132 132 line.startswith("from: "))):
133 133 user = line[6:]
134 134 format = "tag"
135 135 elif format == "tag" and line == "":
136 136 # when looking for tags (subject: from: etc) they
137 137 # end once you find a blank line in the source
138 138 format = "tagdone"
139 139 else:
140 140 message.append(line)
141 141 comments.append(line)
142 142
143 143 eatdiff(message)
144 144 eatdiff(comments)
145 145 eatempty(message)
146 146 eatempty(comments)
147 147
148 148 # make sure message isn't empty
149 149 if format and format.startswith("tag") and subject:
150 150 message.insert(0, "")
151 151 message.insert(0, subject)
152 152 return (message, comments, user, diffstart > 1)
153 153
154 154 def mergeone(self, repo, mergeq, head, patch, rev, wlock):
155 155 # first try just applying the patch
156 156 (err, n) = self.apply(repo, [ patch ], update_status=False,
157 157 strict=True, merge=rev, wlock=wlock)
158 158
159 159 if err == 0:
160 160 return (err, n)
161 161
162 162 if n is None:
163 163 self.ui.warn("apply failed for patch %s\n" % patch)
164 164 sys.exit(1)
165 165
166 166 self.ui.warn("patch didn't work out, merging %s\n" % patch)
167 167
168 168 # apply failed, strip away that rev and merge.
169 169 repo.update(head, allow=False, force=True, wlock=wlock)
170 170 self.strip(repo, n, update=False, backup='strip', wlock=wlock)
171 171
172 172 c = repo.changelog.read(rev)
173 173 ret = repo.update(rev, allow=True, wlock=wlock)
174 174 if ret:
175 175 self.ui.warn("update returned %d\n" % ret)
176 176 sys.exit(1)
177 177 n = repo.commit(None, c[4], c[1], force=1, wlock=wlock)
178 178 if n == None:
179 179 self.ui.warn("repo commit failed\n")
180 180 sys.exit(1)
181 181 try:
182 182 message, comments, user, patchfound = mergeq.readheaders(patch)
183 183 except:
184 184 self.ui.warn("Unable to read %s\n" % patch)
185 185 sys.exit(1)
186 186
187 187 patchf = self.opener(patch, "w")
188 188 if comments:
189 189 comments = "\n".join(comments) + '\n\n'
190 190 patchf.write(comments)
191 191 commands.dodiff(patchf, self.ui, repo, head, n)
192 192 patchf.close()
193 193 return (0, n)
194 194
195 195 def qparents(self, repo, rev=None):
196 196 if rev is None:
197 197 (p1, p2) = repo.dirstate.parents()
198 198 if p2 == revlog.nullid:
199 199 return p1
200 200 if len(self.applied) == 0:
201 201 return None
202 202 (top, patch) = self.applied[-1].split(':')
203 203 top = revlog.bin(top)
204 204 return top
205 205 pp = repo.changelog.parents(rev)
206 206 if pp[1] != revlog.nullid:
207 207 arevs = [ x.split(':')[0] for x in self.applied ]
208 208 p0 = revlog.hex(pp[0])
209 209 p1 = revlog.hex(pp[1])
210 210 if p0 in arevs:
211 211 return pp[0]
212 212 if p1 in arevs:
213 213 return pp[1]
214 214 return None
215 215 return pp[0]
216 216
217 217 def mergepatch(self, repo, mergeq, series, wlock):
218 218 if len(self.applied) == 0:
219 219 # each of the patches merged in will have two parents. This
220 220 # can confuse the qrefresh, qdiff, and strip code because it
221 221 # needs to know which parent is actually in the patch queue.
222 222 # so, we insert a merge marker with only one parent. This way
223 223 # the first patch in the queue is never a merge patch
224 224 #
225 225 pname = ".hg.patches.merge.marker"
226 226 n = repo.commit(None, '[mq]: merge marker', user=None, force=1,
227 227 wlock=wlock)
228 228 self.applied.append(revlog.hex(n) + ":" + pname)
229 229 self.applied_dirty = 1
230 230
231 231 head = self.qparents(repo)
232 232
233 233 for patch in series:
234 234 patch = mergeq.lookup(patch)
235 235 if not patch:
236 236 self.ui.warn("patch %s does not exist\n" % patch)
237 237 return (1, None)
238 238
239 239 info = mergeq.isapplied(patch)
240 240 if not info:
241 241 self.ui.warn("patch %s is not applied\n" % patch)
242 242 return (1, None)
243 243 rev = revlog.bin(info[1])
244 244 (err, head) = self.mergeone(repo, mergeq, head, patch, rev, wlock)
245 245 if head:
246 246 self.applied.append(revlog.hex(head) + ":" + patch)
247 247 self.applied_dirty = 1
248 248 if err:
249 249 return (err, head)
250 250 return (0, head)
251 251
252 252 def apply(self, repo, series, list=False, update_status=True,
253 253 strict=False, patchdir=None, merge=None, wlock=None):
254 254 # TODO unify with commands.py
255 255 if not patchdir:
256 256 patchdir = self.path
257 257 pwd = os.getcwd()
258 258 os.chdir(repo.root)
259 259 err = 0
260 260 if not wlock:
261 261 wlock = repo.wlock()
262 262 lock = repo.lock()
263 263 tr = repo.transaction()
264 264 n = None
265 265 for patch in series:
266 266 self.ui.warn("applying %s\n" % patch)
267 267 pf = os.path.join(patchdir, patch)
268 268
269 269 try:
270 270 message, comments, user, patchfound = self.readheaders(patch)
271 271 except:
272 272 self.ui.warn("Unable to read %s\n" % pf)
273 273 err = 1
274 274 break
275 275
276 276 if not message:
277 277 message = "imported patch %s\n" % patch
278 278 else:
279 279 if list:
280 280 message.append("\nimported patch %s" % patch)
281 281 message = '\n'.join(message)
282 282
283 283 try:
284 284 f = os.popen("patch -p1 --no-backup-if-mismatch < '%s'" % (pf))
285 285 except:
286 286 self.ui.warn("patch failed, unable to continue (try -v)\n")
287 287 err = 1
288 288 break
289 289 files = []
290 290 fuzz = False
291 291 for l in f:
292 292 l = l.rstrip('\r\n');
293 293 if self.ui.verbose:
294 294 self.ui.warn(l + "\n")
295 295 if l[:14] == 'patching file ':
296 296 pf = os.path.normpath(l[14:])
297 297 # when patch finds a space in the file name, it puts
298 298 # single quotes around the filename. strip them off
299 299 if pf[0] == "'" and pf[-1] == "'":
300 300 pf = pf[1:-1]
301 301 if pf not in files:
302 302 files.append(pf)
303 303 printed_file = False
304 304 file_str = l
305 305 elif l.find('with fuzz') >= 0:
306 306 if not printed_file:
307 307 self.ui.warn(file_str + '\n')
308 308 printed_file = True
309 309 self.ui.warn(l + '\n')
310 310 fuzz = True
311 311 elif l.find('saving rejects to file') >= 0:
312 312 self.ui.warn(l + '\n')
313 313 elif l.find('FAILED') >= 0:
314 314 if not printed_file:
315 315 self.ui.warn(file_str + '\n')
316 316 printed_file = True
317 317 self.ui.warn(l + '\n')
318 318 patcherr = f.close()
319 319
320 320 if merge and len(files) > 0:
321 321 # Mark as merged and update dirstate parent info
322 322 repo.dirstate.update(repo.dirstate.filterfiles(files), 'm')
323 323 p1, p2 = repo.dirstate.parents()
324 324 repo.dirstate.setparents(p1, merge)
325 325 if len(files) > 0:
326 326 commands.addremove_lock(self.ui, repo, files,
327 327 opts={}, wlock=wlock)
328 328 n = repo.commit(files, message, user, force=1, lock=lock,
329 329 wlock=wlock)
330 330
331 331 if n == None:
332 332 self.ui.warn("repo commit failed\n")
333 333 sys.exit(1)
334 334
335 335 if update_status:
336 336 self.applied.append(revlog.hex(n) + ":" + patch)
337 337
338 338 if patcherr:
339 339 if not patchfound:
340 340 self.ui.warn("patch %s is empty\n" % patch)
341 341 err = 0
342 342 else:
343 343 self.ui.warn("patch failed, rejects left in working dir\n")
344 344 err = 1
345 345 break
346 346
347 347 if fuzz and strict:
348 348 self.ui.warn("fuzz found when applying patch, stopping\n")
349 349 err = 1
350 350 break
351 351 tr.close()
352 352 os.chdir(pwd)
353 353 return (err, n)
354 354
355 355 def delete(self, repo, patch):
356 356 patch = self.lookup(patch)
357 357 info = self.isapplied(patch)
358 358 if info:
359 359 self.ui.warn("cannot delete applied patch %s\n" % patch)
360 360 sys.exit(1)
361 361 if patch not in self.series:
362 362 self.ui.warn("patch %s not in series file\n" % patch)
363 363 sys.exit(1)
364 364 i = self.find_series(patch)
365 365 del self.full_series[i]
366 366 self.read_series(self.full_series)
367 367 self.series_dirty = 1
368 368
369 369 def check_toppatch(self, repo):
370 370 if len(self.applied) > 0:
371 371 (top, patch) = self.applied[-1].split(':')
372 372 top = revlog.bin(top)
373 373 pp = repo.dirstate.parents()
374 374 if top not in pp:
375 375 self.ui.warn("queue top not at dirstate parents. top %s dirstate %s %s\n" %( revlog.short(top), revlog.short(pp[0]), revlog.short(pp[1])))
376 376 sys.exit(1)
377 377 return top
378 378 return None
379 379 def check_localchanges(self, repo):
380 380 (c, a, r, d, u) = repo.changes(None, None)
381 381 if c or a or d or r:
382 382 self.ui.write("Local changes found, refresh first\n")
383 383 sys.exit(1)
384 384 def new(self, repo, patch, msg=None, force=None):
385 385 if not force:
386 386 self.check_localchanges(repo)
387 387 self.check_toppatch(repo)
388 388 wlock = repo.wlock()
389 389 insert = self.series_end()
390 390 if msg:
391 391 n = repo.commit([], "[mq]: %s" % msg, force=True, wlock=wlock)
392 392 else:
393 393 n = repo.commit([],
394 394 "New patch: %s" % patch, force=True, wlock=wlock)
395 395 if n == None:
396 396 self.ui.warn("repo commit failed\n")
397 397 sys.exit(1)
398 398 self.full_series[insert:insert] = [patch]
399 399 self.applied.append(revlog.hex(n) + ":" + patch)
400 400 self.read_series(self.full_series)
401 401 self.series_dirty = 1
402 402 self.applied_dirty = 1
403 403 p = self.opener(patch, "w")
404 404 if msg:
405 405 msg = msg + "\n"
406 406 p.write(msg)
407 407 p.close()
408 408 wlock = None
409 409 r = self.qrepo()
410 410 if r: r.add([patch])
411 411
412 412 def strip(self, repo, rev, update=True, backup="all", wlock=None):
413 413 def limitheads(chlog, stop):
414 414 """return the list of all nodes that have no children"""
415 415 p = {}
416 416 h = []
417 417 stoprev = 0
418 418 if stop in chlog.nodemap:
419 419 stoprev = chlog.rev(stop)
420 420
421 421 for r in range(chlog.count() - 1, -1, -1):
422 422 n = chlog.node(r)
423 423 if n not in p:
424 424 h.append(n)
425 425 if n == stop:
426 426 break
427 427 if r < stoprev:
428 428 break
429 429 for pn in chlog.parents(n):
430 430 p[pn] = 1
431 431 return h
432 432
433 433 def bundle(cg):
434 434 backupdir = repo.join("strip-backup")
435 435 if not os.path.isdir(backupdir):
436 436 os.mkdir(backupdir)
437 437 name = os.path.join(backupdir, "%s" % revlog.short(rev))
438 438 name = savename(name)
439 439 self.ui.warn("saving bundle to %s\n" % name)
440 440 # TODO, exclusive open
441 441 f = open(name, "wb")
442 442 try:
443 443 f.write("HG10")
444 444 z = bz2.BZ2Compressor(9)
445 445 while 1:
446 446 chunk = cg.read(4096)
447 447 if not chunk:
448 448 break
449 449 f.write(z.compress(chunk))
450 450 f.write(z.flush())
451 451 except:
452 452 os.unlink(name)
453 453 raise
454 454 f.close()
455 455 return name
456 456
457 457 def stripall(rev, revnum):
458 458 cl = repo.changelog
459 459 c = cl.read(rev)
460 460 mm = repo.manifest.read(c[0])
461 461 seen = {}
462 462
463 463 for x in xrange(revnum, cl.count()):
464 464 c = cl.read(cl.node(x))
465 465 for f in c[3]:
466 466 if f in seen:
467 467 continue
468 468 seen[f] = 1
469 469 if f in mm:
470 470 filerev = mm[f]
471 471 else:
472 472 filerev = 0
473 473 seen[f] = filerev
474 474 # we go in two steps here so the strip loop happens in a
475 475 # sensible order. When stripping many files, this helps keep
476 476 # our disk access patterns under control.
477 477 list = seen.keys()
478 478 list.sort()
479 479 for f in list:
480 480 ff = repo.file(f)
481 481 filerev = seen[f]
482 482 if filerev != 0:
483 483 if filerev in ff.nodemap:
484 484 filerev = ff.rev(filerev)
485 485 else:
486 486 filerev = 0
487 487 ff.strip(filerev, revnum)
488 488
489 489 if not wlock:
490 490 wlock = repo.wlock()
491 491 lock = repo.lock()
492 492 chlog = repo.changelog
493 493 # TODO delete the undo files, and handle undo of merge sets
494 494 pp = chlog.parents(rev)
495 495 revnum = chlog.rev(rev)
496 496
497 497 if update:
498 498 urev = self.qparents(repo, rev)
499 499 repo.update(urev, allow=False, force=True, wlock=wlock)
500 500 repo.dirstate.write()
501 501
502 502 # save is a list of all the branches we are truncating away
503 503 # that we actually want to keep. changegroup will be used
504 504 # to preserve them and add them back after the truncate
505 505 saveheads = []
506 506 savebases = {}
507 507
508 508 tip = chlog.tip()
509 509 heads = limitheads(chlog, rev)
510 510 seen = {}
511 511
512 512 # search through all the heads, finding those where the revision
513 513 # we want to strip away is an ancestor. Also look for merges
514 514 # that might be turned into new heads by the strip.
515 515 while heads:
516 516 h = heads.pop()
517 517 n = h
518 518 while True:
519 519 seen[n] = 1
520 520 pp = chlog.parents(n)
521 521 if pp[1] != revlog.nullid and chlog.rev(pp[1]) > revnum:
522 522 if pp[1] not in seen:
523 523 heads.append(pp[1])
524 524 if pp[0] == revlog.nullid:
525 525 break
526 526 if chlog.rev(pp[0]) < revnum:
527 527 break
528 528 n = pp[0]
529 529 if n == rev:
530 530 break
531 531 r = chlog.reachable(h, rev)
532 532 if rev not in r:
533 533 saveheads.append(h)
534 534 for x in r:
535 535 if chlog.rev(x) > revnum:
536 536 savebases[x] = 1
537 537
538 538 # create a changegroup for all the branches we need to keep
539 539 if backup is "all":
540 540 backupch = repo.changegroupsubset([rev], chlog.heads(), 'strip')
541 541 bundle(backupch)
542 542 if saveheads:
543 543 backupch = repo.changegroupsubset(savebases.keys(), saveheads, 'strip')
544 544 chgrpfile = bundle(backupch)
545 545
546 546 stripall(rev, revnum)
547 547
548 548 change = chlog.read(rev)
549 549 repo.manifest.strip(repo.manifest.rev(change[0]), revnum)
550 550 chlog.strip(revnum, revnum)
551 551 if saveheads:
552 552 self.ui.status("adding branch\n")
553 553 commands.unbundle(self.ui, repo, chgrpfile, update=False)
554 554 if backup is not "strip":
555 555 os.unlink(chgrpfile)
556 556
557 557 def isapplied(self, patch):
558 558 """returns (index, rev, patch)"""
559 559 for i in xrange(len(self.applied)):
560 560 p = self.applied[i]
561 561 a = p.split(':')
562 562 if a[1] == patch:
563 563 return (i, a[0], a[1])
564 564 return None
565 565
566 566 def lookup(self, patch):
567 567 if patch == None:
568 568 return None
569 569 if patch in self.series:
570 570 return patch
571 571 if not os.path.isfile(os.path.join(self.path, patch)):
572 572 try:
573 573 sno = int(patch)
574 574 except(ValueError, OverflowError):
575 575 self.ui.warn("patch %s not in series\n" % patch)
576 576 sys.exit(1)
577 577 if sno >= len(self.series):
578 578 self.ui.warn("patch number %d is out of range\n" % sno)
579 579 sys.exit(1)
580 580 patch = self.series[sno]
581 581 else:
582 582 self.ui.warn("patch %s not in series\n" % patch)
583 583 sys.exit(1)
584 584 return patch
585 585
586 586 def push(self, repo, patch=None, force=False, list=False,
587 587 mergeq=None, wlock=None):
588 588 if not wlock:
589 589 wlock = repo.wlock()
590 590 patch = self.lookup(patch)
591 591 if patch and self.isapplied(patch):
592 592 self.ui.warn("patch %s is already applied\n" % patch)
593 593 sys.exit(1)
594 594 if self.series_end() == len(self.series):
595 595 self.ui.warn("File series fully applied\n")
596 596 sys.exit(1)
597 597 if not force:
598 598 self.check_localchanges(repo)
599 599
600 600 self.applied_dirty = 1;
601 601 start = self.series_end()
602 602 if start > 0:
603 603 self.check_toppatch(repo)
604 604 if not patch:
605 605 patch = self.series[start]
606 606 end = start + 1
607 607 else:
608 608 end = self.series.index(patch, start) + 1
609 609 s = self.series[start:end]
610 610 if mergeq:
611 611 ret = self.mergepatch(repo, mergeq, s, wlock)
612 612 else:
613 613 ret = self.apply(repo, s, list, wlock=wlock)
614 614 top = self.applied[-1].split(':')[1]
615 615 if ret[0]:
616 616 self.ui.write("Errors during apply, please fix and refresh %s\n" %
617 617 top)
618 618 else:
619 619 self.ui.write("Now at: %s\n" % top)
620 620 return ret[0]
621 621
622 622 def pop(self, repo, patch=None, force=False, update=True, wlock=None):
623 623 def getfile(f, rev):
624 624 t = repo.file(f).read(rev)
625 625 try:
626 626 repo.wfile(f, "w").write(t)
627 627 except IOError:
628 628 try:
629 629 os.makedirs(os.path.dirname(repo.wjoin(f)))
630 630 except OSError, err:
631 631 if err.errno != errno.EEXIST: raise
632 632 repo.wfile(f, "w").write(t)
633 633
634 634 if not wlock:
635 635 wlock = repo.wlock()
636 636 if patch:
637 637 # index, rev, patch
638 638 info = self.isapplied(patch)
639 639 if not info:
640 640 patch = self.lookup(patch)
641 641 info = self.isapplied(patch)
642 642 if not info:
643 643 self.ui.warn("patch %s is not applied\n" % patch)
644 644 sys.exit(1)
645 645 if len(self.applied) == 0:
646 646 self.ui.warn("No patches applied\n")
647 647 sys.exit(1)
648 648
649 649 if not update:
650 650 parents = repo.dirstate.parents()
651 651 rr = [ revlog.bin(x.split(':')[0]) for x in self.applied ]
652 652 for p in parents:
653 653 if p in rr:
654 654 self.ui.warn("qpop: forcing dirstate update\n")
655 655 update = True
656 656
657 657 if not force and update:
658 658 self.check_localchanges(repo)
659 659
660 660 self.applied_dirty = 1;
661 661 end = len(self.applied)
662 662 if not patch:
663 663 info = [len(self.applied) - 1] + self.applied[-1].split(':')
664 664 start = info[0]
665 665 rev = revlog.bin(info[1])
666 666
667 667 # we know there are no local changes, so we can make a simplified
668 668 # form of hg.update.
669 669 if update:
670 670 top = self.check_toppatch(repo)
671 671 qp = self.qparents(repo, rev)
672 672 changes = repo.changelog.read(qp)
673 673 mf1 = repo.manifest.readflags(changes[0])
674 674 mmap = repo.manifest.read(changes[0])
675 675 (c, a, r, d, u) = repo.changes(qp, top)
676 676 if d:
677 677 raise util.Abort("deletions found between repo revs")
678 678 for f in c:
679 679 getfile(f, mmap[f])
680 680 for f in r:
681 681 getfile(f, mmap[f])
682 682 util.set_exec(repo.wjoin(f), mf1[f])
683 683 repo.dirstate.update(c + r, 'n')
684 684 for f in a:
685 685 try: os.unlink(repo.wjoin(f))
686 686 except: raise
687 687 try: os.removedirs(os.path.dirname(repo.wjoin(f)))
688 688 except: pass
689 689 if a:
690 690 repo.dirstate.forget(a)
691 691 repo.dirstate.setparents(qp, revlog.nullid)
692 692 self.strip(repo, rev, update=False, backup='strip', wlock=wlock)
693 693 del self.applied[start:end]
694 694 if len(self.applied):
695 695 self.ui.write("Now at: %s\n" % self.applied[-1].split(':')[1])
696 696 else:
697 697 self.ui.write("Patch queue now empty\n")
698 698
699 699 def diff(self, repo, files):
700 700 top = self.check_toppatch(repo)
701 701 if not top:
702 702 self.ui.write("No patches applied\n")
703 703 return
704 704 qp = self.qparents(repo, top)
705 705 commands.dodiff(sys.stdout, self.ui, repo, qp, None, files)
706 706
707 707 def refresh(self, repo, short=False):
708 708 if len(self.applied) == 0:
709 709 self.ui.write("No patches applied\n")
710 710 return
711 711 wlock = repo.wlock()
712 712 self.check_toppatch(repo)
713 713 qp = self.qparents(repo)
714 714 (top, patch) = self.applied[-1].split(':')
715 715 top = revlog.bin(top)
716 716 cparents = repo.changelog.parents(top)
717 717 patchparent = self.qparents(repo, top)
718 718 message, comments, user, patchfound = self.readheaders(patch)
719 719
720 720 patchf = self.opener(patch, "w")
721 721 if comments:
722 722 comments = "\n".join(comments) + '\n\n'
723 723 patchf.write(comments)
724 724
725 725 tip = repo.changelog.tip()
726 726 if top == tip:
727 727 # if the top of our patch queue is also the tip, there is an
728 728 # optimization here. We update the dirstate in place and strip
729 729 # off the tip commit. Then just commit the current directory
730 730 # tree. We can also send repo.commit the list of files
731 731 # changed to speed up the diff
732 732 #
733 733 # in short mode, we only diff the files included in the
734 734 # patch already
735 735 #
736 736 # this should really read:
737 737 #(cc, dd, aa, aa2, uu) = repo.changes(tip, patchparent)
738 738 # but we do it backwards to take advantage of manifest/chlog
739 739 # caching against the next repo.changes call
740 740 #
741 741 (cc, aa, dd, aa2, uu) = repo.changes(patchparent, tip)
742 742 if short:
743 743 filelist = cc + aa + dd
744 744 else:
745 745 filelist = None
746 746 (c, a, r, d, u) = repo.changes(None, None, filelist)
747 747
748 748 # we might end up with files that were added between tip and
749 749 # the dirstate parent, but then changed in the local dirstate.
750 750 # in this case, we want them to only show up in the added section
751 751 for x in c:
752 752 if x not in aa:
753 753 cc.append(x)
754 754 # we might end up with files added by the local dirstate that
755 755 # were deleted by the patch. In this case, they should only
756 756 # show up in the changed section.
757 757 for x in a:
758 758 if x in dd:
759 759 del dd[dd.index(x)]
760 760 cc.append(x)
761 761 else:
762 762 aa.append(x)
763 763 # make sure any files deleted in the local dirstate
764 764 # are not in the add or change column of the patch
765 765 forget = []
766 766 for x in d + r:
767 767 if x in aa:
768 768 del aa[aa.index(x)]
769 769 forget.append(x)
770 770 continue
771 771 elif x in cc:
772 772 del cc[cc.index(x)]
773 773 dd.append(x)
774 774
775 775 c = list(util.unique(cc))
776 776 r = list(util.unique(dd))
777 777 a = list(util.unique(aa))
778 778 filelist = list(util.unique(c + r + a ))
779 779 commands.dodiff(patchf, self.ui, repo, patchparent, None,
780 780 filelist, changes=(c, a, r, [], u))
781 781 patchf.close()
782 782
783 783 changes = repo.changelog.read(tip)
784 784 repo.dirstate.setparents(*cparents)
785 785 repo.dirstate.update(a, 'a')
786 786 repo.dirstate.update(r, 'r')
787 787 repo.dirstate.update(c, 'n')
788 788 repo.dirstate.forget(forget)
789 789
790 790 if not message:
791 791 message = "patch queue: %s\n" % patch
792 792 else:
793 793 message = "\n".join(message)
794 794 self.strip(repo, top, update=False, backup='strip', wlock=wlock)
795 795 n = repo.commit(filelist, message, changes[1], force=1, wlock=wlock)
796 796 self.applied[-1] = revlog.hex(n) + ':' + patch
797 797 self.applied_dirty = 1
798 798 else:
799 799 commands.dodiff(patchf, self.ui, repo, patchparent, None)
800 800 patchf.close()
801 801 self.pop(repo, force=True, wlock=wlock)
802 802 self.push(repo, force=True, wlock=wlock)
803 803
804 804 def init(self, repo, create=False):
805 805 if os.path.isdir(self.path):
806 806 raise util.Abort("patch queue directory already exists")
807 807 os.mkdir(self.path)
808 808 if create:
809 809 return self.qrepo(create=True)
810 810
811 811 def unapplied(self, repo, patch=None):
812 812 if patch and patch not in self.series:
813 813 self.ui.warn("%s not in the series file\n" % patch)
814 814 sys.exit(1)
815 815 if not patch:
816 816 start = self.series_end()
817 817 else:
818 818 start = self.series.index(patch) + 1
819 819 for p in self.series[start:]:
820 820 self.ui.write("%s\n" % p)
821 821
822 822 def qseries(self, repo, missing=None):
823 823 start = self.series_end()
824 824 if not missing:
825 825 for p in self.series[:start]:
826 826 if self.ui.verbose:
827 827 self.ui.write("%d A " % self.series.index(p))
828 828 self.ui.write("%s\n" % p)
829 829 for p in self.series[start:]:
830 830 if self.ui.verbose:
831 831 self.ui.write("%d U " % self.series.index(p))
832 832 self.ui.write("%s\n" % p)
833 833 else:
834 834 list = []
835 835 for root, dirs, files in os.walk(self.path):
836 836 d = root[len(self.path) + 1:]
837 837 for f in files:
838 838 fl = os.path.join(d, f)
839 839 if (fl not in self.series and
840 840 fl not in (self.status_path, self.series_path)
841 841 and not fl.startswith('.')):
842 842 list.append(fl)
843 843 list.sort()
844 844 if list:
845 845 for x in list:
846 846 if self.ui.verbose:
847 847 self.ui.write("D ")
848 848 self.ui.write("%s\n" % x)
849 849
850 850 def issaveline(self, l):
851 851 name = l.split(':')[1]
852 852 if name == '.hg.patches.save.line':
853 853 return True
854 854
855 855 def qrepo(self, create=False):
856 856 if create or os.path.isdir(os.path.join(self.path, ".hg")):
857 857 return hg.repository(self.ui, path=self.path, create=create)
858 858
859 859 def restore(self, repo, rev, delete=None, qupdate=None):
860 860 c = repo.changelog.read(rev)
861 861 desc = c[4].strip()
862 862 lines = desc.splitlines()
863 863 i = 0
864 864 datastart = None
865 865 series = []
866 866 applied = []
867 867 qpp = None
868 868 for i in xrange(0, len(lines)):
869 869 if lines[i] == 'Patch Data:':
870 870 datastart = i + 1
871 871 elif lines[i].startswith('Dirstate:'):
872 872 l = lines[i].rstrip()
873 873 l = l[10:].split(' ')
874 874 qpp = [ hg.bin(x) for x in l ]
875 875 elif datastart != None:
876 876 l = lines[i].rstrip()
877 877 index = l.index(':')
878 878 id = l[:index]
879 879 file = l[index + 1:]
880 880 if id:
881 881 applied.append(l)
882 882 series.append(file)
883 883 if datastart == None:
884 884 self.ui.warn("No saved patch data found\n")
885 885 return 1
886 886 self.ui.warn("restoring status: %s\n" % lines[0])
887 887 self.full_series = series
888 888 self.applied = applied
889 889 self.read_series(self.full_series)
890 890 self.series_dirty = 1
891 891 self.applied_dirty = 1
892 892 heads = repo.changelog.heads()
893 893 if delete:
894 894 if rev not in heads:
895 895 self.ui.warn("save entry has children, leaving it alone\n")
896 896 else:
897 897 self.ui.warn("removing save entry %s\n" % hg.short(rev))
898 898 pp = repo.dirstate.parents()
899 899 if rev in pp:
900 900 update = True
901 901 else:
902 902 update = False
903 903 self.strip(repo, rev, update=update, backup='strip')
904 904 if qpp:
905 905 self.ui.warn("saved queue repository parents: %s %s\n" %
906 906 (hg.short(qpp[0]), hg.short(qpp[1])))
907 907 if qupdate:
908 908 print "queue directory updating"
909 909 r = self.qrepo()
910 910 if not r:
911 911 self.ui.warn("Unable to load queue repository\n")
912 912 return 1
913 913 r.update(qpp[0], allow=False, force=True)
914 914
915 915 def save(self, repo, msg=None):
916 916 if len(self.applied) == 0:
917 917 self.ui.warn("save: no patches applied, exiting\n")
918 918 return 1
919 919 if self.issaveline(self.applied[-1]):
920 920 self.ui.warn("status is already saved\n")
921 921 return 1
922 922
923 923 ar = [ ':' + x for x in self.full_series ]
924 924 if not msg:
925 925 msg = "hg patches saved state"
926 926 else:
927 927 msg = "hg patches: " + msg.rstrip('\r\n')
928 928 r = self.qrepo()
929 929 if r:
930 930 pp = r.dirstate.parents()
931 931 msg += "\nDirstate: %s %s" % (hg.hex(pp[0]), hg.hex(pp[1]))
932 932 msg += "\n\nPatch Data:\n"
933 933 text = msg + "\n".join(self.applied) + '\n' + (ar and "\n".join(ar)
934 934 + '\n' or "")
935 935 n = repo.commit(None, text, user=None, force=1)
936 936 if not n:
937 937 self.ui.warn("repo commit failed\n")
938 938 return 1
939 939 self.applied.append(revlog.hex(n) + ":" + '.hg.patches.save.line')
940 940 self.applied_dirty = 1
941 941
942 942 def series_end(self):
943 943 end = 0
944 944 if len(self.applied) > 0:
945 945 (top, p) = self.applied[-1].split(':')
946 946 try:
947 947 end = self.series.index(p)
948 948 except ValueError:
949 949 return 0
950 950 return end + 1
951 951 return end
952 952
953 953 def qapplied(self, repo, patch=None):
954 954 if patch and patch not in self.series:
955 955 self.ui.warn("%s not in the series file\n" % patch)
956 956 sys.exit(1)
957 957 if not patch:
958 958 end = len(self.applied)
959 959 else:
960 960 end = self.series.index(patch) + 1
961 961 for x in xrange(end):
962 962 p = self.appliedname(x)
963 963 self.ui.write("%s\n" % p)
964 964
965 965 def appliedname(self, index):
966 966 p = self.applied[index]
967 967 if not self.ui.verbose:
968 968 p = p.split(':')[1]
969 969 return p
970 970
971 971 def top(self, repo):
972 972 if len(self.applied):
973 973 p = self.appliedname(-1)
974 974 self.ui.write(p + '\n')
975 975 else:
976 976 self.ui.write("No patches applied\n")
977 977
978 978 def next(self, repo):
979 979 end = self.series_end()
980 980 if end == len(self.series):
981 981 self.ui.write("All patches applied\n")
982 982 else:
983 983 self.ui.write(self.series[end] + '\n')
984 984
985 985 def prev(self, repo):
986 986 if len(self.applied) > 1:
987 987 p = self.appliedname(-2)
988 988 self.ui.write(p + '\n')
989 989 elif len(self.applied) == 1:
990 990 self.ui.write("Only one patch applied\n")
991 991 else:
992 992 self.ui.write("No patches applied\n")
993 993
994 994 def qimport(self, repo, files, patch=None, existing=None, force=None):
995 995 if len(files) > 1 and patch:
996 996 self.ui.warn("-n option not valid when importing multiple files\n")
997 997 sys.exit(1)
998 998 i = 0
999 999 for filename in files:
1000 1000 if existing:
1001 1001 if not patch:
1002 1002 patch = filename
1003 1003 if not os.path.isfile(os.path.join(self.path, patch)):
1004 1004 self.ui.warn("patch %s does not exist\n" % patch)
1005 1005 sys.exit(1)
1006 1006 else:
1007 1007 try:
1008 1008 text = file(filename).read()
1009 1009 except IOError:
1010 1010 self.ui.warn("Unable to read %s\n" % patch)
1011 1011 sys.exit(1)
1012 1012 if not patch:
1013 1013 patch = os.path.split(filename)[1]
1014 1014 if not force and os.path.isfile(os.path.join(self.path, patch)):
1015 1015 self.ui.warn("patch %s already exists\n" % patch)
1016 1016 sys.exit(1)
1017 1017 patchf = self.opener(patch, "w")
1018 1018 patchf.write(text)
1019 1019 if patch in self.series:
1020 1020 self.ui.warn("patch %s is already in the series file\n" % patch)
1021 1021 sys.exit(1)
1022 1022 index = self.series_end() + i
1023 1023 self.full_series[index:index] = [patch]
1024 1024 self.read_series(self.full_series)
1025 1025 self.ui.warn("adding %s to series file\n" % patch)
1026 1026 i += 1
1027 1027 patch = None
1028 1028 self.series_dirty = 1
1029 1029
1030 1030 def delete(ui, repo, patch, **opts):
1031 1031 """remove a patch from the series file"""
1032 1032 q = repomap[repo]
1033 1033 q.delete(repo, patch)
1034 1034 q.save_dirty()
1035 1035 return 0
1036 1036
1037 1037 def applied(ui, repo, patch=None, **opts):
1038 1038 """print the patches already applied"""
1039 1039 repomap[repo].qapplied(repo, patch)
1040 1040 return 0
1041 1041
1042 1042 def unapplied(ui, repo, patch=None, **opts):
1043 1043 """print the patches not yet applied"""
1044 1044 repomap[repo].unapplied(repo, patch)
1045 1045 return 0
1046 1046
1047 1047 def qimport(ui, repo, *filename, **opts):
1048 1048 """import a patch"""
1049 1049 q = repomap[repo]
1050 1050 q.qimport(repo, filename, patch=opts['name'],
1051 1051 existing=opts['existing'], force=opts['force'])
1052 1052 q.save_dirty()
1053 1053 return 0
1054 1054
1055 1055 def init(ui, repo, **opts):
1056 1056 """init a new queue repository"""
1057 1057 q = repomap[repo]
1058 1058 r = q.init(repo, create=opts['create_repo'])
1059 1059 q.save_dirty()
1060 1060 if r:
1061 1061 fp = r.wopener('.hgignore', 'w')
1062 1062 print >> fp, 'syntax: glob'
1063 1063 print >> fp, 'status'
1064 1064 fp.close()
1065 1065 r.wopener('series', 'w').close()
1066 1066 r.add(['.hgignore', 'series'])
1067 1067 return 0
1068 1068
1069 1069 def commit(ui, repo, *pats, **opts):
1070 1070 q = repomap[repo]
1071 1071 r = q.qrepo()
1072 1072 if not r: raise util.Abort('no queue repository')
1073 1073 commands.commit(r.ui, r, *pats, **opts)
1074 1074
1075 1075 def series(ui, repo, **opts):
1076 1076 """print the entire series file"""
1077 1077 repomap[repo].qseries(repo, missing=opts['missing'])
1078 1078 return 0
1079 1079
1080 1080 def top(ui, repo, **opts):
1081 1081 """print the name of the current patch"""
1082 1082 repomap[repo].top(repo)
1083 1083 return 0
1084 1084
1085 1085 def next(ui, repo, **opts):
1086 1086 """print the name of the next patch"""
1087 1087 repomap[repo].next(repo)
1088 1088 return 0
1089 1089
1090 1090 def prev(ui, repo, **opts):
1091 1091 """print the name of the previous patch"""
1092 1092 repomap[repo].prev(repo)
1093 1093 return 0
1094 1094
1095 1095 def new(ui, repo, patch, **opts):
1096 1096 """create a new patch"""
1097 1097 q = repomap[repo]
1098 1098 q.new(repo, patch, msg=opts['message'], force=opts['force'])
1099 1099 q.save_dirty()
1100 1100 return 0
1101 1101
1102 1102 def refresh(ui, repo, **opts):
1103 1103 """update the current patch"""
1104 1104 q = repomap[repo]
1105 1105 q.refresh(repo, short=opts['short'])
1106 1106 q.save_dirty()
1107 1107 return 0
1108 1108
1109 1109 def diff(ui, repo, *files, **opts):
1110 1110 """diff of the current patch"""
1111 repomap[repo].diff(repo, files)
1111 # deep in the dirstate code, the walkhelper method wants a list, not a tuple
1112 repomap[repo].diff(repo, list(files))
1112 1113 return 0
1113 1114
1114 1115 def lastsavename(path):
1115 1116 (dir, base) = os.path.split(path)
1116 1117 names = os.listdir(dir)
1117 1118 namere = re.compile("%s.([0-9]+)" % base)
1118 1119 max = None
1119 1120 maxname = None
1120 1121 for f in names:
1121 1122 m = namere.match(f)
1122 1123 if m:
1123 1124 index = int(m.group(1))
1124 1125 if max == None or index > max:
1125 1126 max = index
1126 1127 maxname = f
1127 1128 if maxname:
1128 1129 return (os.path.join(dir, maxname), max)
1129 1130 return (None, None)
1130 1131
1131 1132 def savename(path):
1132 1133 (last, index) = lastsavename(path)
1133 1134 if last is None:
1134 1135 index = 0
1135 1136 newpath = path + ".%d" % (index + 1)
1136 1137 return newpath
1137 1138
1138 1139 def push(ui, repo, patch=None, **opts):
1139 1140 """push the next patch onto the stack"""
1140 1141 q = repomap[repo]
1141 1142 mergeq = None
1142 1143
1143 1144 if opts['all']:
1144 1145 patch = q.series[-1]
1145 1146 if opts['merge']:
1146 1147 if opts['name']:
1147 1148 newpath = opts['name']
1148 1149 else:
1149 1150 newpath, i = lastsavename(q.path)
1150 1151 if not newpath:
1151 1152 ui.warn("no saved queues found, please use -n\n")
1152 1153 return 1
1153 1154 mergeq = queue(ui, repo.join(""), newpath)
1154 1155 ui.warn("merging with queue at: %s\n" % mergeq.path)
1155 1156 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
1156 1157 mergeq=mergeq)
1157 1158 q.save_dirty()
1158 1159 return ret
1159 1160
1160 1161 def pop(ui, repo, patch=None, **opts):
1161 1162 """pop the current patch off the stack"""
1162 1163 localupdate = True
1163 1164 if opts['name']:
1164 1165 q = queue(ui, repo.join(""), repo.join(opts['name']))
1165 1166 ui.warn('using patch queue: %s\n' % q.path)
1166 1167 localupdate = False
1167 1168 else:
1168 1169 q = repomap[repo]
1169 1170 if opts['all'] and len(q.applied) > 0:
1170 1171 patch = q.applied[0].split(':')[1]
1171 1172 q.pop(repo, patch, force=opts['force'], update=localupdate)
1172 1173 q.save_dirty()
1173 1174 return 0
1174 1175
1175 1176 def restore(ui, repo, rev, **opts):
1176 1177 """restore the queue state saved by a rev"""
1177 1178 rev = repo.lookup(rev)
1178 1179 q = repomap[repo]
1179 1180 q.restore(repo, rev, delete=opts['delete'],
1180 1181 qupdate=opts['update'])
1181 1182 q.save_dirty()
1182 1183 return 0
1183 1184
1184 1185 def save(ui, repo, **opts):
1185 1186 """save current queue state"""
1186 1187 q = repomap[repo]
1187 1188 ret = q.save(repo, msg=opts['message'])
1188 1189 if ret:
1189 1190 return ret
1190 1191 q.save_dirty()
1191 1192 if opts['copy']:
1192 1193 path = q.path
1193 1194 if opts['name']:
1194 1195 newpath = os.path.join(q.basepath, opts['name'])
1195 1196 if os.path.exists(newpath):
1196 1197 if not os.path.isdir(newpath):
1197 1198 ui.warn("destination %s exists and is not a directory\n" %
1198 1199 newpath)
1199 1200 sys.exit(1)
1200 1201 if not opts['force']:
1201 1202 ui.warn("destination %s exists, use -f to force\n" %
1202 1203 newpath)
1203 1204 sys.exit(1)
1204 1205 else:
1205 1206 newpath = savename(path)
1206 1207 ui.warn("copy %s to %s\n" % (path, newpath))
1207 1208 util.copyfiles(path, newpath)
1208 1209 if opts['empty']:
1209 1210 try:
1210 1211 os.unlink(os.path.join(q.path, q.status_path))
1211 1212 except:
1212 1213 pass
1213 1214 return 0
1214 1215
1215 1216 def strip(ui, repo, rev, **opts):
1216 1217 """strip a revision and all later revs on the same branch"""
1217 1218 rev = repo.lookup(rev)
1218 1219 backup = 'all'
1219 1220 if opts['backup']:
1220 1221 backup = 'strip'
1221 1222 elif opts['nobackup']:
1222 1223 backup = 'none'
1223 1224 repomap[repo].strip(repo, rev, backup=backup)
1224 1225 return 0
1225 1226
1226 1227 def version(ui, q=None):
1227 1228 """print the version number"""
1228 1229 ui.write("mq version %s\n" % versionstr)
1229 1230 return 0
1230 1231
1231 1232 def reposetup(ui, repo):
1232 1233 repomap[repo] = queue(ui, repo.join(""))
1233 1234
1234 1235 cmdtable = {
1235 1236 "qapplied": (applied, [], 'hg qapplied [patch]'),
1236 1237 "qcommit|qci":
1237 1238 (commit,
1238 1239 [('A', 'addremove', None, _('run addremove during commit')),
1239 1240 ('I', 'include', [], _('include names matching the given patterns')),
1240 1241 ('X', 'exclude', [], _('exclude names matching the given patterns')),
1241 1242 ('m', 'message', '', _('use <text> as commit message')),
1242 1243 ('l', 'logfile', '', _('read the commit message from <file>')),
1243 1244 ('d', 'date', '', _('record datecode as commit date')),
1244 1245 ('u', 'user', '', _('record user as commiter'))],
1245 1246 'hg qcommit [options] [files]'),
1246 1247 "^qdiff": (diff, [], 'hg qdiff [files]'),
1247 1248 "qdelete": (delete, [], 'hg qdelete [patch]'),
1248 1249 "^qimport":
1249 1250 (qimport,
1250 1251 [('e', 'existing', None, 'import file in patch dir'),
1251 1252 ('n', 'name', '', 'patch file name'),
1252 1253 ('f', 'force', None, 'overwrite existing files')],
1253 1254 'hg qimport'),
1254 1255 "^qinit":
1255 1256 (init,
1256 1257 [('c', 'create-repo', None, 'create patch repository')],
1257 1258 'hg [-c] qinit'),
1258 1259 "qnew":
1259 1260 (new,
1260 1261 [('m', 'message', '', 'commit message'),
1261 1262 ('f', 'force', None, 'force')],
1262 1263 'hg qnew [-m message ] patch'),
1263 1264 "qnext": (next, [], 'hg qnext'),
1264 1265 "qprev": (prev, [], 'hg qprev'),
1265 1266 "^qpop":
1266 1267 (pop,
1267 1268 [('a', 'all', None, 'pop all patches'),
1268 1269 ('n', 'name', '', 'queue name to pop'),
1269 1270 ('f', 'force', None, 'forget any local changes')],
1270 1271 'hg qpop [options] [patch/index]'),
1271 1272 "^qpush":
1272 1273 (push,
1273 1274 [('f', 'force', None, 'apply if the patch has rejects'),
1274 1275 ('l', 'list', None, 'list patch name in commit text'),
1275 1276 ('a', 'all', None, 'apply all patches'),
1276 1277 ('m', 'merge', None, 'merge from another queue'),
1277 1278 ('n', 'name', '', 'merge queue name')],
1278 1279 'hg qpush [options] [patch/index]'),
1279 1280 "^qrefresh":
1280 1281 (refresh,
1281 1282 [('s', 'short', None, 'short refresh')],
1282 1283 'hg qrefresh'),
1283 1284 "qrestore":
1284 1285 (restore,
1285 1286 [('d', 'delete', None, 'delete save entry'),
1286 1287 ('u', 'update', None, 'update queue working dir')],
1287 1288 'hg qrestore rev'),
1288 1289 "qsave":
1289 1290 (save,
1290 1291 [('m', 'message', '', 'commit message'),
1291 1292 ('c', 'copy', None, 'copy patch directory'),
1292 1293 ('n', 'name', '', 'copy directory name'),
1293 1294 ('e', 'empty', None, 'clear queue status file'),
1294 1295 ('f', 'force', None, 'force copy')],
1295 1296 'hg qsave'),
1296 1297 "qseries":
1297 1298 (series,
1298 1299 [('m', 'missing', None, 'print patches not in series')],
1299 1300 'hg qseries'),
1300 1301 "^strip":
1301 1302 (strip,
1302 1303 [('f', 'force', None, 'force multi-head removal'),
1303 1304 ('b', 'backup', None, 'bundle unrelated changesets'),
1304 1305 ('n', 'nobackup', None, 'no backups')],
1305 1306 'hg strip rev'),
1306 1307 "qtop": (top, [], 'hg qtop'),
1307 1308 "qunapplied": (unapplied, [], 'hg qunapplied [patch]'),
1308 1309 "qversion": (version, [], 'hg qversion')
1309 1310 }
1310 1311
@@ -1,3459 +1,3457 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005 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 demandload import demandload
9 9 from node import *
10 10 from i18n import gettext as _
11 11 demandload(globals(), "os re sys signal shutil imp urllib pdb")
12 12 demandload(globals(), "fancyopts ui hg util lock revlog templater bundlerepo")
13 13 demandload(globals(), "fnmatch hgweb mdiff random signal tempfile time")
14 14 demandload(globals(), "traceback errno socket version struct atexit sets bz2")
15 15 demandload(globals(), "changegroup")
16 16
17 17 class UnknownCommand(Exception):
18 18 """Exception raised if command is not in the command table."""
19 19 class AmbiguousCommand(Exception):
20 20 """Exception raised if command shortcut matches more than one command."""
21 21
22 22 def filterfiles(filters, files):
23 23 l = [x for x in files if x in filters]
24 24
25 25 for t in filters:
26 26 if t and t[-1] != "/":
27 27 t += "/"
28 28 l += [x for x in files if x.startswith(t)]
29 29 return l
30 30
31 31 def relpath(repo, args):
32 32 cwd = repo.getcwd()
33 33 if cwd:
34 34 return [util.normpath(os.path.join(cwd, x)) for x in args]
35 35 return args
36 36
37 37 def matchpats(repo, pats=[], opts={}, head=''):
38 38 cwd = repo.getcwd()
39 39 if not pats and cwd:
40 40 opts['include'] = [os.path.join(cwd, i) for i in opts['include']]
41 41 opts['exclude'] = [os.path.join(cwd, x) for x in opts['exclude']]
42 42 cwd = ''
43 43 return util.cmdmatcher(repo.root, cwd, pats or ['.'], opts.get('include'),
44 44 opts.get('exclude'), head)
45 45
46 46 def makewalk(repo, pats, opts, node=None, head='', badmatch=None):
47 47 files, matchfn, anypats = matchpats(repo, pats, opts, head)
48 48 exact = dict(zip(files, files))
49 49 def walk():
50 50 for src, fn in repo.walk(node=node, files=files, match=matchfn,
51 51 badmatch=badmatch):
52 52 yield src, fn, util.pathto(repo.getcwd(), fn), fn in exact
53 53 return files, matchfn, walk()
54 54
55 55 def walk(repo, pats, opts, node=None, head='', badmatch=None):
56 56 files, matchfn, results = makewalk(repo, pats, opts, node, head, badmatch)
57 57 for r in results:
58 58 yield r
59 59
60 60 def walkchangerevs(ui, repo, pats, opts):
61 61 '''Iterate over files and the revs they changed in.
62 62
63 63 Callers most commonly need to iterate backwards over the history
64 64 it is interested in. Doing so has awful (quadratic-looking)
65 65 performance, so we use iterators in a "windowed" way.
66 66
67 67 We walk a window of revisions in the desired order. Within the
68 68 window, we first walk forwards to gather data, then in the desired
69 69 order (usually backwards) to display it.
70 70
71 71 This function returns an (iterator, getchange, matchfn) tuple. The
72 72 getchange function returns the changelog entry for a numeric
73 73 revision. The iterator yields 3-tuples. They will be of one of
74 74 the following forms:
75 75
76 76 "window", incrementing, lastrev: stepping through a window,
77 77 positive if walking forwards through revs, last rev in the
78 78 sequence iterated over - use to reset state for the current window
79 79
80 80 "add", rev, fns: out-of-order traversal of the given file names
81 81 fns, which changed during revision rev - use to gather data for
82 82 possible display
83 83
84 84 "iter", rev, None: in-order traversal of the revs earlier iterated
85 85 over with "add" - use to display data'''
86 86
87 87 def increasing_windows(start, end, windowsize=8, sizelimit=512):
88 88 if start < end:
89 89 while start < end:
90 90 yield start, min(windowsize, end-start)
91 91 start += windowsize
92 92 if windowsize < sizelimit:
93 93 windowsize *= 2
94 94 else:
95 95 while start > end:
96 96 yield start, min(windowsize, start-end-1)
97 97 start -= windowsize
98 98 if windowsize < sizelimit:
99 99 windowsize *= 2
100 100
101 101
102 102 files, matchfn, anypats = matchpats(repo, pats, opts)
103 103
104 104 if repo.changelog.count() == 0:
105 105 return [], False, matchfn
106 106
107 107 revs = map(int, revrange(ui, repo, opts['rev'] or ['tip:0']))
108 108 wanted = {}
109 109 slowpath = anypats
110 110 fncache = {}
111 111
112 112 chcache = {}
113 113 def getchange(rev):
114 114 ch = chcache.get(rev)
115 115 if ch is None:
116 116 chcache[rev] = ch = repo.changelog.read(repo.lookup(str(rev)))
117 117 return ch
118 118
119 119 if not slowpath and not files:
120 120 # No files, no patterns. Display all revs.
121 121 wanted = dict(zip(revs, revs))
122 122 if not slowpath:
123 123 # Only files, no patterns. Check the history of each file.
124 124 def filerevgen(filelog):
125 125 for i, window in increasing_windows(filelog.count()-1, -1):
126 126 revs = []
127 127 for j in xrange(i - window, i + 1):
128 128 revs.append(filelog.linkrev(filelog.node(j)))
129 129 revs.reverse()
130 130 for rev in revs:
131 131 yield rev
132 132
133 133 minrev, maxrev = min(revs), max(revs)
134 134 for file_ in files:
135 135 filelog = repo.file(file_)
136 136 # A zero count may be a directory or deleted file, so
137 137 # try to find matching entries on the slow path.
138 138 if filelog.count() == 0:
139 139 slowpath = True
140 140 break
141 141 for rev in filerevgen(filelog):
142 142 if rev <= maxrev:
143 143 if rev < minrev:
144 144 break
145 145 fncache.setdefault(rev, [])
146 146 fncache[rev].append(file_)
147 147 wanted[rev] = 1
148 148 if slowpath:
149 149 # The slow path checks files modified in every changeset.
150 150 def changerevgen():
151 151 for i, window in increasing_windows(repo.changelog.count()-1, -1):
152 152 for j in xrange(i - window, i + 1):
153 153 yield j, getchange(j)[3]
154 154
155 155 for rev, changefiles in changerevgen():
156 156 matches = filter(matchfn, changefiles)
157 157 if matches:
158 158 fncache[rev] = matches
159 159 wanted[rev] = 1
160 160
161 161 def iterate():
162 162 for i, window in increasing_windows(0, len(revs)):
163 163 yield 'window', revs[0] < revs[-1], revs[-1]
164 164 nrevs = [rev for rev in revs[i:i+window]
165 165 if rev in wanted]
166 166 srevs = list(nrevs)
167 167 srevs.sort()
168 168 for rev in srevs:
169 169 fns = fncache.get(rev) or filter(matchfn, getchange(rev)[3])
170 170 yield 'add', rev, fns
171 171 for rev in nrevs:
172 172 yield 'iter', rev, None
173 173 return iterate(), getchange, matchfn
174 174
175 175 revrangesep = ':'
176 176
177 177 def revrange(ui, repo, revs, revlog=None):
178 178 """Yield revision as strings from a list of revision specifications."""
179 179 if revlog is None:
180 180 revlog = repo.changelog
181 181 revcount = revlog.count()
182 182 def fix(val, defval):
183 183 if not val:
184 184 return defval
185 185 try:
186 186 num = int(val)
187 187 if str(num) != val:
188 188 raise ValueError
189 189 if num < 0:
190 190 num += revcount
191 191 if num < 0:
192 192 num = 0
193 193 elif num >= revcount:
194 194 raise ValueError
195 195 except ValueError:
196 196 try:
197 197 num = repo.changelog.rev(repo.lookup(val))
198 198 except KeyError:
199 199 try:
200 200 num = revlog.rev(revlog.lookup(val))
201 201 except KeyError:
202 202 raise util.Abort(_('invalid revision identifier %s'), val)
203 203 return num
204 204 seen = {}
205 205 for spec in revs:
206 206 if spec.find(revrangesep) >= 0:
207 207 start, end = spec.split(revrangesep, 1)
208 208 start = fix(start, 0)
209 209 end = fix(end, revcount - 1)
210 210 step = start > end and -1 or 1
211 211 for rev in xrange(start, end+step, step):
212 212 if rev in seen:
213 213 continue
214 214 seen[rev] = 1
215 215 yield str(rev)
216 216 else:
217 217 rev = fix(spec, None)
218 218 if rev in seen:
219 219 continue
220 220 seen[rev] = 1
221 221 yield str(rev)
222 222
223 223 def make_filename(repo, r, pat, node=None,
224 224 total=None, seqno=None, revwidth=None, pathname=None):
225 225 node_expander = {
226 226 'H': lambda: hex(node),
227 227 'R': lambda: str(r.rev(node)),
228 228 'h': lambda: short(node),
229 229 }
230 230 expander = {
231 231 '%': lambda: '%',
232 232 'b': lambda: os.path.basename(repo.root),
233 233 }
234 234
235 235 try:
236 236 if node:
237 237 expander.update(node_expander)
238 238 if node and revwidth is not None:
239 239 expander['r'] = lambda: str(r.rev(node)).zfill(revwidth)
240 240 if total is not None:
241 241 expander['N'] = lambda: str(total)
242 242 if seqno is not None:
243 243 expander['n'] = lambda: str(seqno)
244 244 if total is not None and seqno is not None:
245 245 expander['n'] = lambda:str(seqno).zfill(len(str(total)))
246 246 if pathname is not None:
247 247 expander['s'] = lambda: os.path.basename(pathname)
248 248 expander['d'] = lambda: os.path.dirname(pathname) or '.'
249 249 expander['p'] = lambda: pathname
250 250
251 251 newname = []
252 252 patlen = len(pat)
253 253 i = 0
254 254 while i < patlen:
255 255 c = pat[i]
256 256 if c == '%':
257 257 i += 1
258 258 c = pat[i]
259 259 c = expander[c]()
260 260 newname.append(c)
261 261 i += 1
262 262 return ''.join(newname)
263 263 except KeyError, inst:
264 264 raise util.Abort(_("invalid format spec '%%%s' in output file name"),
265 265 inst.args[0])
266 266
267 267 def make_file(repo, r, pat, node=None,
268 268 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
269 269 if not pat or pat == '-':
270 270 return 'w' in mode and sys.stdout or sys.stdin
271 271 if hasattr(pat, 'write') and 'w' in mode:
272 272 return pat
273 273 if hasattr(pat, 'read') and 'r' in mode:
274 274 return pat
275 275 return open(make_filename(repo, r, pat, node, total, seqno, revwidth,
276 276 pathname),
277 277 mode)
278 278
279 279 def write_bundle(cg, filename=None, compress=True):
280 280 """Write a bundle file and return its filename.
281 281
282 282 Existing files will not be overwritten.
283 283 If no filename is specified, a temporary file is created.
284 284 bz2 compression can be turned off.
285 285 The bundle file will be deleted in case of errors.
286 286 """
287 287 class nocompress(object):
288 288 def compress(self, x):
289 289 return x
290 290 def flush(self):
291 291 return ""
292 292
293 293 fh = None
294 294 cleanup = None
295 295 try:
296 296 if filename:
297 297 if os.path.exists(filename):
298 298 raise util.Abort(_("file '%s' already exists"), filename)
299 299 fh = open(filename, "wb")
300 300 else:
301 301 fd, filename = tempfile.mkstemp(suffix=".hg", prefix="hg-bundle-")
302 302 fh = os.fdopen(fd, "wb")
303 303 cleanup = filename
304 304
305 305 if compress:
306 306 fh.write("HG10")
307 307 z = bz2.BZ2Compressor(9)
308 308 else:
309 309 fh.write("HG10UN")
310 310 z = nocompress()
311 311 # parse the changegroup data, otherwise we will block
312 312 # in case of sshrepo because we don't know the end of the stream
313 313
314 314 # an empty chunkiter is the end of the changegroup
315 315 empty = False
316 316 while not empty:
317 317 empty = True
318 318 for chunk in changegroup.chunkiter(cg):
319 319 empty = False
320 320 fh.write(z.compress(changegroup.genchunk(chunk)))
321 321 fh.write(z.compress(changegroup.closechunk()))
322 322 fh.write(z.flush())
323 323 cleanup = None
324 324 return filename
325 325 finally:
326 326 if fh is not None:
327 327 fh.close()
328 328 if cleanup is not None:
329 329 os.unlink(cleanup)
330 330
331 331 def dodiff(fp, ui, repo, node1, node2, files=None, match=util.always,
332 332 changes=None, text=False, opts={}):
333 333 if not node1:
334 334 node1 = repo.dirstate.parents()[0]
335 335 # reading the data for node1 early allows it to play nicely
336 336 # with repo.changes and the revlog cache.
337 337 change = repo.changelog.read(node1)
338 338 mmap = repo.manifest.read(change[0])
339 339 date1 = util.datestr(change[2])
340 340
341 341 if not changes:
342 342 changes = repo.changes(node1, node2, files, match=match)
343 343 modified, added, removed, deleted, unknown = changes
344 344 if files:
345 345 modified, added, removed = map(lambda x: filterfiles(files, x),
346 346 (modified, added, removed))
347 347
348 348 if not modified and not added and not removed:
349 349 return
350 350
351 351 if node2:
352 352 change = repo.changelog.read(node2)
353 353 mmap2 = repo.manifest.read(change[0])
354 354 date2 = util.datestr(change[2])
355 355 def read(f):
356 356 return repo.file(f).read(mmap2[f])
357 357 else:
358 358 date2 = util.datestr()
359 359 def read(f):
360 360 return repo.wread(f)
361 361
362 362 if ui.quiet:
363 363 r = None
364 364 else:
365 365 hexfunc = ui.verbose and hex or short
366 366 r = [hexfunc(node) for node in [node1, node2] if node]
367 367
368 368 diffopts = ui.diffopts()
369 369 showfunc = opts.get('show_function') or diffopts['showfunc']
370 370 ignorews = opts.get('ignore_all_space') or diffopts['ignorews']
371 371 for f in modified:
372 372 to = None
373 373 if f in mmap:
374 374 to = repo.file(f).read(mmap[f])
375 375 tn = read(f)
376 376 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
377 377 showfunc=showfunc, ignorews=ignorews))
378 378 for f in added:
379 379 to = None
380 380 tn = read(f)
381 381 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
382 382 showfunc=showfunc, ignorews=ignorews))
383 383 for f in removed:
384 384 to = repo.file(f).read(mmap[f])
385 385 tn = None
386 386 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
387 387 showfunc=showfunc, ignorews=ignorews))
388 388
389 389 def trimuser(ui, name, rev, revcache):
390 390 """trim the name of the user who committed a change"""
391 391 user = revcache.get(rev)
392 392 if user is None:
393 393 user = revcache[rev] = ui.shortuser(name)
394 394 return user
395 395
396 396 class changeset_templater(object):
397 397 '''use templater module to format changeset information.'''
398 398
399 399 def __init__(self, ui, repo, mapfile):
400 400 self.t = templater.templater(mapfile, templater.common_filters,
401 401 cache={'parent': '{rev}:{node|short} ',
402 402 'manifest': '{rev}:{node|short}'})
403 403 self.ui = ui
404 404 self.repo = repo
405 405
406 406 def use_template(self, t):
407 407 '''set template string to use'''
408 408 self.t.cache['changeset'] = t
409 409
410 410 def write(self, thing, header=False):
411 411 '''write expanded template.
412 412 uses in-order recursive traverse of iterators.'''
413 413 for t in thing:
414 414 if hasattr(t, '__iter__'):
415 415 self.write(t, header=header)
416 416 elif header:
417 417 self.ui.write_header(t)
418 418 else:
419 419 self.ui.write(t)
420 420
421 421 def write_header(self, thing):
422 422 self.write(thing, header=True)
423 423
424 424 def show(self, rev=0, changenode=None, brinfo=None):
425 425 '''show a single changeset or file revision'''
426 426 log = self.repo.changelog
427 427 if changenode is None:
428 428 changenode = log.node(rev)
429 429 elif not rev:
430 430 rev = log.rev(changenode)
431 431
432 432 changes = log.read(changenode)
433 433
434 434 def showlist(name, values, plural=None, **args):
435 435 '''expand set of values.
436 436 name is name of key in template map.
437 437 values is list of strings or dicts.
438 438 plural is plural of name, if not simply name + 's'.
439 439
440 440 expansion works like this, given name 'foo'.
441 441
442 442 if values is empty, expand 'no_foos'.
443 443
444 444 if 'foo' not in template map, return values as a string,
445 445 joined by space.
446 446
447 447 expand 'start_foos'.
448 448
449 449 for each value, expand 'foo'. if 'last_foo' in template
450 450 map, expand it instead of 'foo' for last key.
451 451
452 452 expand 'end_foos'.
453 453 '''
454 454 if plural: names = plural
455 455 else: names = name + 's'
456 456 if not values:
457 457 noname = 'no_' + names
458 458 if noname in self.t:
459 459 yield self.t(noname, **args)
460 460 return
461 461 if name not in self.t:
462 462 if isinstance(values[0], str):
463 463 yield ' '.join(values)
464 464 else:
465 465 for v in values:
466 466 yield dict(v, **args)
467 467 return
468 468 startname = 'start_' + names
469 469 if startname in self.t:
470 470 yield self.t(startname, **args)
471 471 vargs = args.copy()
472 472 def one(v, tag=name):
473 473 try:
474 474 vargs.update(v)
475 475 except (AttributeError, ValueError):
476 476 try:
477 477 for a, b in v:
478 478 vargs[a] = b
479 479 except ValueError:
480 480 vargs[name] = v
481 481 return self.t(tag, **vargs)
482 482 lastname = 'last_' + name
483 483 if lastname in self.t:
484 484 last = values.pop()
485 485 else:
486 486 last = None
487 487 for v in values:
488 488 yield one(v)
489 489 if last is not None:
490 490 yield one(last, tag=lastname)
491 491 endname = 'end_' + names
492 492 if endname in self.t:
493 493 yield self.t(endname, **args)
494 494
495 495 if brinfo:
496 496 def showbranches(**args):
497 497 if changenode in brinfo:
498 498 for x in showlist('branch', brinfo[changenode],
499 499 plural='branches', **args):
500 500 yield x
501 501 else:
502 502 showbranches = ''
503 503
504 504 if self.ui.debugflag:
505 505 def showmanifest(**args):
506 506 args = args.copy()
507 507 args.update(dict(rev=self.repo.manifest.rev(changes[0]),
508 508 node=hex(changes[0])))
509 509 yield self.t('manifest', **args)
510 510 else:
511 511 showmanifest = ''
512 512
513 513 def showparents(**args):
514 514 parents = [[('rev', log.rev(p)), ('node', hex(p))]
515 515 for p in log.parents(changenode)
516 516 if self.ui.debugflag or p != nullid]
517 517 if (not self.ui.debugflag and len(parents) == 1 and
518 518 parents[0][0][1] == rev - 1):
519 519 return
520 520 for x in showlist('parent', parents, **args):
521 521 yield x
522 522
523 523 def showtags(**args):
524 524 for x in showlist('tag', self.repo.nodetags(changenode), **args):
525 525 yield x
526 526
527 527 if self.ui.debugflag:
528 528 files = self.repo.changes(log.parents(changenode)[0], changenode)
529 529 def showfiles(**args):
530 530 for x in showlist('file', files[0], **args): yield x
531 531 def showadds(**args):
532 532 for x in showlist('file_add', files[1], **args): yield x
533 533 def showdels(**args):
534 534 for x in showlist('file_del', files[2], **args): yield x
535 535 else:
536 536 def showfiles(**args):
537 537 for x in showlist('file', changes[3], **args): yield x
538 538 showadds = ''
539 539 showdels = ''
540 540
541 541 props = {
542 542 'author': changes[1],
543 543 'branches': showbranches,
544 544 'date': changes[2],
545 545 'desc': changes[4],
546 546 'file_adds': showadds,
547 547 'file_dels': showdels,
548 548 'files': showfiles,
549 549 'manifest': showmanifest,
550 550 'node': hex(changenode),
551 551 'parents': showparents,
552 552 'rev': rev,
553 553 'tags': showtags,
554 554 }
555 555
556 556 try:
557 557 if self.ui.debugflag and 'header_debug' in self.t:
558 558 key = 'header_debug'
559 559 elif self.ui.quiet and 'header_quiet' in self.t:
560 560 key = 'header_quiet'
561 561 elif self.ui.verbose and 'header_verbose' in self.t:
562 562 key = 'header_verbose'
563 563 elif 'header' in self.t:
564 564 key = 'header'
565 565 else:
566 566 key = ''
567 567 if key:
568 568 self.write_header(self.t(key, **props))
569 569 if self.ui.debugflag and 'changeset_debug' in self.t:
570 570 key = 'changeset_debug'
571 571 elif self.ui.quiet and 'changeset_quiet' in self.t:
572 572 key = 'changeset_quiet'
573 573 elif self.ui.verbose and 'changeset_verbose' in self.t:
574 574 key = 'changeset_verbose'
575 575 else:
576 576 key = 'changeset'
577 577 self.write(self.t(key, **props))
578 578 except KeyError, inst:
579 579 raise util.Abort(_("%s: no key named '%s'") % (self.t.mapfile,
580 580 inst.args[0]))
581 581 except SyntaxError, inst:
582 582 raise util.Abort(_('%s: %s') % (self.t.mapfile, inst.args[0]))
583 583
584 584 class changeset_printer(object):
585 585 '''show changeset information when templating not requested.'''
586 586
587 587 def __init__(self, ui, repo):
588 588 self.ui = ui
589 589 self.repo = repo
590 590
591 591 def show(self, rev=0, changenode=None, brinfo=None):
592 592 '''show a single changeset or file revision'''
593 593 log = self.repo.changelog
594 594 if changenode is None:
595 595 changenode = log.node(rev)
596 596 elif not rev:
597 597 rev = log.rev(changenode)
598 598
599 599 if self.ui.quiet:
600 600 self.ui.write("%d:%s\n" % (rev, short(changenode)))
601 601 return
602 602
603 603 changes = log.read(changenode)
604 604 date = util.datestr(changes[2])
605 605
606 606 parents = [(log.rev(p), self.ui.verbose and hex(p) or short(p))
607 607 for p in log.parents(changenode)
608 608 if self.ui.debugflag or p != nullid]
609 609 if (not self.ui.debugflag and len(parents) == 1 and
610 610 parents[0][0] == rev-1):
611 611 parents = []
612 612
613 613 if self.ui.verbose:
614 614 self.ui.write(_("changeset: %d:%s\n") % (rev, hex(changenode)))
615 615 else:
616 616 self.ui.write(_("changeset: %d:%s\n") % (rev, short(changenode)))
617 617
618 618 for tag in self.repo.nodetags(changenode):
619 619 self.ui.status(_("tag: %s\n") % tag)
620 620 for parent in parents:
621 621 self.ui.write(_("parent: %d:%s\n") % parent)
622 622
623 623 if brinfo and changenode in brinfo:
624 624 br = brinfo[changenode]
625 625 self.ui.write(_("branch: %s\n") % " ".join(br))
626 626
627 627 self.ui.debug(_("manifest: %d:%s\n") %
628 628 (self.repo.manifest.rev(changes[0]), hex(changes[0])))
629 629 self.ui.status(_("user: %s\n") % changes[1])
630 630 self.ui.status(_("date: %s\n") % date)
631 631
632 632 if self.ui.debugflag:
633 633 files = self.repo.changes(log.parents(changenode)[0], changenode)
634 634 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
635 635 files):
636 636 if value:
637 637 self.ui.note("%-12s %s\n" % (key, " ".join(value)))
638 638 else:
639 639 self.ui.note(_("files: %s\n") % " ".join(changes[3]))
640 640
641 641 description = changes[4].strip()
642 642 if description:
643 643 if self.ui.verbose:
644 644 self.ui.status(_("description:\n"))
645 645 self.ui.status(description)
646 646 self.ui.status("\n\n")
647 647 else:
648 648 self.ui.status(_("summary: %s\n") %
649 649 description.splitlines()[0])
650 650 self.ui.status("\n")
651 651
652 652 def show_changeset(ui, repo, opts):
653 653 '''show one changeset. uses template or regular display. caller
654 654 can pass in 'style' and 'template' options in opts.'''
655 655
656 656 tmpl = opts.get('template')
657 657 if tmpl:
658 658 tmpl = templater.parsestring(tmpl, quoted=False)
659 659 else:
660 660 tmpl = ui.config('ui', 'logtemplate')
661 661 if tmpl: tmpl = templater.parsestring(tmpl)
662 662 mapfile = opts.get('style') or ui.config('ui', 'style')
663 663 if tmpl or mapfile:
664 664 if mapfile:
665 665 if not os.path.isfile(mapfile):
666 666 mapname = templater.templatepath('map-cmdline.' + mapfile)
667 667 if not mapname: mapname = templater.templatepath(mapfile)
668 668 if mapname: mapfile = mapname
669 669 try:
670 670 t = changeset_templater(ui, repo, mapfile)
671 671 except SyntaxError, inst:
672 672 raise util.Abort(inst.args[0])
673 673 if tmpl: t.use_template(tmpl)
674 674 return t
675 675 return changeset_printer(ui, repo)
676 676
677 677 def show_version(ui):
678 678 """output version and copyright information"""
679 679 ui.write(_("Mercurial Distributed SCM (version %s)\n")
680 680 % version.get_version())
681 681 ui.status(_(
682 682 "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
683 683 "This is free software; see the source for copying conditions. "
684 684 "There is NO\nwarranty; "
685 685 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
686 686 ))
687 687
688 688 def help_(ui, cmd=None, with_version=False):
689 689 """show help for a given command or all commands"""
690 690 option_lists = []
691 691 if cmd and cmd != 'shortlist':
692 692 if with_version:
693 693 show_version(ui)
694 694 ui.write('\n')
695 695 aliases, i = find(cmd)
696 696 # synopsis
697 697 ui.write("%s\n\n" % i[2])
698 698
699 699 # description
700 700 doc = i[0].__doc__
701 701 if not doc:
702 702 doc = _("(No help text available)")
703 703 if ui.quiet:
704 704 doc = doc.splitlines(0)[0]
705 705 ui.write("%s\n" % doc.rstrip())
706 706
707 707 if not ui.quiet:
708 708 # aliases
709 709 if len(aliases) > 1:
710 710 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
711 711
712 712 # options
713 713 if i[1]:
714 714 option_lists.append(("options", i[1]))
715 715
716 716 else:
717 717 # program name
718 718 if ui.verbose or with_version:
719 719 show_version(ui)
720 720 else:
721 721 ui.status(_("Mercurial Distributed SCM\n"))
722 722 ui.status('\n')
723 723
724 724 # list of commands
725 725 if cmd == "shortlist":
726 726 ui.status(_('basic commands (use "hg help" '
727 727 'for the full list or option "-v" for details):\n\n'))
728 728 elif ui.verbose:
729 729 ui.status(_('list of commands:\n\n'))
730 730 else:
731 731 ui.status(_('list of commands (use "hg help -v" '
732 732 'to show aliases and global options):\n\n'))
733 733
734 734 h = {}
735 735 cmds = {}
736 736 for c, e in table.items():
737 737 f = c.split("|")[0]
738 738 if cmd == "shortlist" and not f.startswith("^"):
739 739 continue
740 740 f = f.lstrip("^")
741 741 if not ui.debugflag and f.startswith("debug"):
742 742 continue
743 743 doc = e[0].__doc__
744 744 if not doc:
745 745 doc = _("(No help text available)")
746 746 h[f] = doc.splitlines(0)[0].rstrip()
747 747 cmds[f] = c.lstrip("^")
748 748
749 749 fns = h.keys()
750 750 fns.sort()
751 751 m = max(map(len, fns))
752 752 for f in fns:
753 753 if ui.verbose:
754 754 commands = cmds[f].replace("|",", ")
755 755 ui.write(" %s:\n %s\n"%(commands, h[f]))
756 756 else:
757 757 ui.write(' %-*s %s\n' % (m, f, h[f]))
758 758
759 759 # global options
760 760 if ui.verbose:
761 761 option_lists.append(("global options", globalopts))
762 762
763 763 # list all option lists
764 764 opt_output = []
765 765 for title, options in option_lists:
766 766 opt_output.append(("\n%s:\n" % title, None))
767 767 for shortopt, longopt, default, desc in options:
768 768 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
769 769 longopt and " --%s" % longopt),
770 770 "%s%s" % (desc,
771 771 default
772 772 and _(" (default: %s)") % default
773 773 or "")))
774 774
775 775 if opt_output:
776 776 opts_len = max([len(line[0]) for line in opt_output if line[1]])
777 777 for first, second in opt_output:
778 778 if second:
779 779 ui.write(" %-*s %s\n" % (opts_len, first, second))
780 780 else:
781 781 ui.write("%s\n" % first)
782 782
783 783 # Commands start here, listed alphabetically
784 784
785 785 def add(ui, repo, *pats, **opts):
786 786 """add the specified files on the next commit
787 787
788 788 Schedule files to be version controlled and added to the repository.
789 789
790 790 The files will be added to the repository at the next commit.
791 791
792 792 If no names are given, add all files in the repository.
793 793 """
794 794
795 795 names = []
796 796 for src, abs, rel, exact in walk(repo, pats, opts):
797 797 if exact:
798 798 if ui.verbose:
799 799 ui.status(_('adding %s\n') % rel)
800 800 names.append(abs)
801 801 elif repo.dirstate.state(abs) == '?':
802 802 ui.status(_('adding %s\n') % rel)
803 803 names.append(abs)
804 804 repo.add(names)
805 805
806 806 def addremove(ui, repo, *pats, **opts):
807 807 """add all new files, delete all missing files
808 808
809 809 Add all new files and remove all missing files from the repository.
810 810
811 811 New files are ignored if they match any of the patterns in .hgignore. As
812 812 with add, these changes take effect at the next commit.
813 813 """
814 814 return addremove_lock(ui, repo, pats, opts)
815 815
816 816 def addremove_lock(ui, repo, pats, opts, wlock=None):
817 817 add, remove = [], []
818 818 for src, abs, rel, exact in walk(repo, pats, opts):
819 819 if src == 'f' and repo.dirstate.state(abs) == '?':
820 820 add.append(abs)
821 821 if ui.verbose or not exact:
822 822 ui.status(_('adding %s\n') % ((pats and rel) or abs))
823 823 if repo.dirstate.state(abs) != 'r' and not os.path.exists(rel):
824 824 remove.append(abs)
825 825 if ui.verbose or not exact:
826 826 ui.status(_('removing %s\n') % ((pats and rel) or abs))
827 827 repo.add(add, wlock=wlock)
828 828 repo.remove(remove, wlock=wlock)
829 829
830 830 def annotate(ui, repo, *pats, **opts):
831 831 """show changeset information per file line
832 832
833 833 List changes in files, showing the revision id responsible for each line
834 834
835 835 This command is useful to discover who did a change or when a change took
836 836 place.
837 837
838 838 Without the -a option, annotate will avoid processing files it
839 839 detects as binary. With -a, annotate will generate an annotation
840 840 anyway, probably with undesirable results.
841 841 """
842 842 def getnode(rev):
843 843 return short(repo.changelog.node(rev))
844 844
845 845 ucache = {}
846 846 def getname(rev):
847 847 cl = repo.changelog.read(repo.changelog.node(rev))
848 848 return trimuser(ui, cl[1], rev, ucache)
849 849
850 850 dcache = {}
851 851 def getdate(rev):
852 852 datestr = dcache.get(rev)
853 853 if datestr is None:
854 854 cl = repo.changelog.read(repo.changelog.node(rev))
855 855 datestr = dcache[rev] = util.datestr(cl[2])
856 856 return datestr
857 857
858 858 if not pats:
859 859 raise util.Abort(_('at least one file name or pattern required'))
860 860
861 861 opmap = [['user', getname], ['number', str], ['changeset', getnode],
862 862 ['date', getdate]]
863 863 if not opts['user'] and not opts['changeset'] and not opts['date']:
864 864 opts['number'] = 1
865 865
866 866 if opts['rev']:
867 867 node = repo.changelog.lookup(opts['rev'])
868 868 else:
869 869 node = repo.dirstate.parents()[0]
870 870 change = repo.changelog.read(node)
871 871 mmap = repo.manifest.read(change[0])
872 872
873 873 for src, abs, rel, exact in walk(repo, pats, opts, node=node):
874 874 f = repo.file(abs)
875 875 if not opts['text'] and util.binary(f.read(mmap[abs])):
876 876 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
877 877 continue
878 878
879 879 lines = f.annotate(mmap[abs])
880 880 pieces = []
881 881
882 882 for o, f in opmap:
883 883 if opts[o]:
884 884 l = [f(n) for n, dummy in lines]
885 885 if l:
886 886 m = max(map(len, l))
887 887 pieces.append(["%*s" % (m, x) for x in l])
888 888
889 889 if pieces:
890 890 for p, l in zip(zip(*pieces), lines):
891 891 ui.write("%s: %s" % (" ".join(p), l[1]))
892 892
893 893 def bundle(ui, repo, fname, dest="default-push", **opts):
894 894 """create a changegroup file
895 895
896 896 Generate a compressed changegroup file collecting all changesets
897 897 not found in the other repository.
898 898
899 899 This file can then be transferred using conventional means and
900 900 applied to another repository with the unbundle command. This is
901 901 useful when native push and pull are not available or when
902 902 exporting an entire repository is undesirable. The standard file
903 903 extension is ".hg".
904 904
905 905 Unlike import/export, this exactly preserves all changeset
906 906 contents including permissions, rename data, and revision history.
907 907 """
908 908 dest = ui.expandpath(dest)
909 909 other = hg.repository(ui, dest)
910 910 o = repo.findoutgoing(other, force=opts['force'])
911 911 cg = repo.changegroup(o, 'bundle')
912 912 write_bundle(cg, fname)
913 913
914 914 def cat(ui, repo, file1, *pats, **opts):
915 915 """output the latest or given revisions of files
916 916
917 917 Print the specified files as they were at the given revision.
918 918 If no revision is given then the tip is used.
919 919
920 920 Output may be to a file, in which case the name of the file is
921 921 given using a format string. The formatting rules are the same as
922 922 for the export command, with the following additions:
923 923
924 924 %s basename of file being printed
925 925 %d dirname of file being printed, or '.' if in repo root
926 926 %p root-relative path name of file being printed
927 927 """
928 928 mf = {}
929 929 rev = opts['rev']
930 930 if rev:
931 931 node = repo.lookup(rev)
932 932 else:
933 933 node = repo.changelog.tip()
934 934 change = repo.changelog.read(node)
935 935 mf = repo.manifest.read(change[0])
936 936 for src, abs, rel, exact in walk(repo, (file1,) + pats, opts, node):
937 937 r = repo.file(abs)
938 938 n = mf[abs]
939 939 fp = make_file(repo, r, opts['output'], node=n, pathname=abs)
940 940 fp.write(r.read(n))
941 941
942 942 def clone(ui, source, dest=None, **opts):
943 943 """make a copy of an existing repository
944 944
945 945 Create a copy of an existing repository in a new directory.
946 946
947 947 If no destination directory name is specified, it defaults to the
948 948 basename of the source.
949 949
950 950 The location of the source is added to the new repository's
951 951 .hg/hgrc file, as the default to be used for future pulls.
952 952
953 953 For efficiency, hardlinks are used for cloning whenever the source
954 954 and destination are on the same filesystem. Some filesystems,
955 955 such as AFS, implement hardlinking incorrectly, but do not report
956 956 errors. In these cases, use the --pull option to avoid
957 957 hardlinking.
958 958
959 959 See pull for valid source format details.
960 960 """
961 961 if dest is None:
962 962 dest = os.path.basename(os.path.normpath(source))
963 963
964 964 if os.path.exists(dest):
965 965 raise util.Abort(_("destination '%s' already exists"), dest)
966 966
967 967 dest = os.path.realpath(dest)
968 968
969 969 class Dircleanup(object):
970 970 def __init__(self, dir_):
971 971 self.rmtree = shutil.rmtree
972 972 self.dir_ = dir_
973 973 os.mkdir(dir_)
974 974 def close(self):
975 975 self.dir_ = None
976 976 def __del__(self):
977 977 if self.dir_:
978 978 self.rmtree(self.dir_, True)
979 979
980 980 if opts['ssh']:
981 981 ui.setconfig("ui", "ssh", opts['ssh'])
982 982 if opts['remotecmd']:
983 983 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
984 984
985 985 source = ui.expandpath(source)
986 986
987 987 d = Dircleanup(dest)
988 988 abspath = source
989 989 other = hg.repository(ui, source)
990 990
991 991 copy = False
992 992 if other.dev() != -1:
993 993 abspath = os.path.abspath(source)
994 994 if not opts['pull'] and not opts['rev']:
995 995 copy = True
996 996
997 997 if copy:
998 998 try:
999 999 # we use a lock here because if we race with commit, we
1000 1000 # can end up with extra data in the cloned revlogs that's
1001 1001 # not pointed to by changesets, thus causing verify to
1002 1002 # fail
1003 1003 l1 = other.lock()
1004 1004 except lock.LockException:
1005 1005 copy = False
1006 1006
1007 1007 if copy:
1008 1008 # we lock here to avoid premature writing to the target
1009 1009 os.mkdir(os.path.join(dest, ".hg"))
1010 1010 l2 = lock.lock(os.path.join(dest, ".hg", "lock"))
1011 1011
1012 1012 files = "data 00manifest.d 00manifest.i 00changelog.d 00changelog.i"
1013 1013 for f in files.split():
1014 1014 src = os.path.join(source, ".hg", f)
1015 1015 dst = os.path.join(dest, ".hg", f)
1016 1016 try:
1017 1017 util.copyfiles(src, dst)
1018 1018 except OSError, inst:
1019 1019 if inst.errno != errno.ENOENT:
1020 1020 raise
1021 1021
1022 1022 repo = hg.repository(ui, dest)
1023 1023
1024 1024 else:
1025 1025 revs = None
1026 1026 if opts['rev']:
1027 1027 if not other.local():
1028 1028 error = _("clone -r not supported yet for remote repositories.")
1029 1029 raise util.Abort(error)
1030 1030 else:
1031 1031 revs = [other.lookup(rev) for rev in opts['rev']]
1032 1032 repo = hg.repository(ui, dest, create=1)
1033 1033 repo.pull(other, heads = revs)
1034 1034
1035 1035 f = repo.opener("hgrc", "w", text=True)
1036 1036 f.write("[paths]\n")
1037 1037 f.write("default = %s\n" % abspath)
1038 1038 f.close()
1039 1039
1040 1040 if not opts['noupdate']:
1041 1041 update(repo.ui, repo)
1042 1042
1043 1043 d.close()
1044 1044
1045 1045 def commit(ui, repo, *pats, **opts):
1046 1046 """commit the specified files or all outstanding changes
1047 1047
1048 1048 Commit changes to the given files into the repository.
1049 1049
1050 1050 If a list of files is omitted, all changes reported by "hg status"
1051 1051 will be committed.
1052 1052
1053 1053 If no commit message is specified, the editor configured in your hgrc
1054 1054 or in the EDITOR environment variable is started to enter a message.
1055 1055 """
1056 1056 message = opts['message']
1057 1057 logfile = opts['logfile']
1058 1058
1059 1059 if message and logfile:
1060 1060 raise util.Abort(_('options --message and --logfile are mutually '
1061 1061 'exclusive'))
1062 1062 if not message and logfile:
1063 1063 try:
1064 1064 if logfile == '-':
1065 1065 message = sys.stdin.read()
1066 1066 else:
1067 1067 message = open(logfile).read()
1068 1068 except IOError, inst:
1069 1069 raise util.Abort(_("can't read commit message '%s': %s") %
1070 1070 (logfile, inst.strerror))
1071 1071
1072 1072 if opts['addremove']:
1073 1073 addremove(ui, repo, *pats, **opts)
1074 1074 fns, match, anypats = matchpats(repo, pats, opts)
1075 1075 if pats:
1076 1076 modified, added, removed, deleted, unknown = (
1077 1077 repo.changes(files=fns, match=match))
1078 1078 files = modified + added + removed
1079 1079 else:
1080 1080 files = []
1081 1081 try:
1082 1082 repo.commit(files, message, opts['user'], opts['date'], match)
1083 1083 except ValueError, inst:
1084 1084 raise util.Abort(str(inst))
1085 1085
1086 1086 def docopy(ui, repo, pats, opts, wlock):
1087 1087 # called with the repo lock held
1088 1088 cwd = repo.getcwd()
1089 1089 errors = 0
1090 1090 copied = []
1091 1091 targets = {}
1092 1092
1093 1093 def okaytocopy(abs, rel, exact):
1094 1094 reasons = {'?': _('is not managed'),
1095 1095 'a': _('has been marked for add'),
1096 1096 'r': _('has been marked for remove')}
1097 1097 state = repo.dirstate.state(abs)
1098 1098 reason = reasons.get(state)
1099 1099 if reason:
1100 1100 if state == 'a':
1101 1101 origsrc = repo.dirstate.copied(abs)
1102 1102 if origsrc is not None:
1103 1103 return origsrc
1104 1104 if exact:
1105 1105 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
1106 1106 else:
1107 1107 return abs
1108 1108
1109 1109 def copy(origsrc, abssrc, relsrc, target, exact):
1110 1110 abstarget = util.canonpath(repo.root, cwd, target)
1111 1111 reltarget = util.pathto(cwd, abstarget)
1112 1112 prevsrc = targets.get(abstarget)
1113 1113 if prevsrc is not None:
1114 1114 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1115 1115 (reltarget, abssrc, prevsrc))
1116 1116 return
1117 1117 if (not opts['after'] and os.path.exists(reltarget) or
1118 1118 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
1119 1119 if not opts['force']:
1120 1120 ui.warn(_('%s: not overwriting - file exists\n') %
1121 1121 reltarget)
1122 1122 return
1123 1123 if not opts['after']:
1124 1124 os.unlink(reltarget)
1125 1125 if opts['after']:
1126 1126 if not os.path.exists(reltarget):
1127 1127 return
1128 1128 else:
1129 1129 targetdir = os.path.dirname(reltarget) or '.'
1130 1130 if not os.path.isdir(targetdir):
1131 1131 os.makedirs(targetdir)
1132 1132 try:
1133 1133 restore = repo.dirstate.state(abstarget) == 'r'
1134 1134 if restore:
1135 1135 repo.undelete([abstarget], wlock)
1136 1136 try:
1137 1137 shutil.copyfile(relsrc, reltarget)
1138 1138 shutil.copymode(relsrc, reltarget)
1139 1139 restore = False
1140 1140 finally:
1141 1141 if restore:
1142 1142 repo.remove([abstarget], wlock)
1143 1143 except shutil.Error, inst:
1144 1144 raise util.Abort(str(inst))
1145 1145 except IOError, inst:
1146 1146 if inst.errno == errno.ENOENT:
1147 1147 ui.warn(_('%s: deleted in working copy\n') % relsrc)
1148 1148 else:
1149 1149 ui.warn(_('%s: cannot copy - %s\n') %
1150 1150 (relsrc, inst.strerror))
1151 1151 errors += 1
1152 1152 return
1153 1153 if ui.verbose or not exact:
1154 1154 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1155 1155 targets[abstarget] = abssrc
1156 1156 if abstarget != origsrc:
1157 1157 repo.copy(origsrc, abstarget, wlock)
1158 1158 copied.append((abssrc, relsrc, exact))
1159 1159
1160 1160 def targetpathfn(pat, dest, srcs):
1161 1161 if os.path.isdir(pat):
1162 1162 abspfx = util.canonpath(repo.root, cwd, pat)
1163 1163 if destdirexists:
1164 1164 striplen = len(os.path.split(abspfx)[0])
1165 1165 else:
1166 1166 striplen = len(abspfx)
1167 1167 if striplen:
1168 1168 striplen += len(os.sep)
1169 1169 res = lambda p: os.path.join(dest, p[striplen:])
1170 1170 elif destdirexists:
1171 1171 res = lambda p: os.path.join(dest, os.path.basename(p))
1172 1172 else:
1173 1173 res = lambda p: dest
1174 1174 return res
1175 1175
1176 1176 def targetpathafterfn(pat, dest, srcs):
1177 1177 if util.patkind(pat, None)[0]:
1178 1178 # a mercurial pattern
1179 1179 res = lambda p: os.path.join(dest, os.path.basename(p))
1180 1180 else:
1181 1181 abspfx = util.canonpath(repo.root, cwd, pat)
1182 1182 if len(abspfx) < len(srcs[0][0]):
1183 1183 # A directory. Either the target path contains the last
1184 1184 # component of the source path or it does not.
1185 1185 def evalpath(striplen):
1186 1186 score = 0
1187 1187 for s in srcs:
1188 1188 t = os.path.join(dest, s[0][striplen:])
1189 1189 if os.path.exists(t):
1190 1190 score += 1
1191 1191 return score
1192 1192
1193 1193 striplen = len(abspfx)
1194 1194 if striplen:
1195 1195 striplen += len(os.sep)
1196 1196 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1197 1197 score = evalpath(striplen)
1198 1198 striplen1 = len(os.path.split(abspfx)[0])
1199 1199 if striplen1:
1200 1200 striplen1 += len(os.sep)
1201 1201 if evalpath(striplen1) > score:
1202 1202 striplen = striplen1
1203 1203 res = lambda p: os.path.join(dest, p[striplen:])
1204 1204 else:
1205 1205 # a file
1206 1206 if destdirexists:
1207 1207 res = lambda p: os.path.join(dest, os.path.basename(p))
1208 1208 else:
1209 1209 res = lambda p: dest
1210 1210 return res
1211 1211
1212 1212
1213 1213 pats = list(pats)
1214 1214 if not pats:
1215 1215 raise util.Abort(_('no source or destination specified'))
1216 1216 if len(pats) == 1:
1217 1217 raise util.Abort(_('no destination specified'))
1218 1218 dest = pats.pop()
1219 1219 destdirexists = os.path.isdir(dest)
1220 1220 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
1221 1221 raise util.Abort(_('with multiple sources, destination must be an '
1222 1222 'existing directory'))
1223 1223 if opts['after']:
1224 1224 tfn = targetpathafterfn
1225 1225 else:
1226 1226 tfn = targetpathfn
1227 1227 copylist = []
1228 1228 for pat in pats:
1229 1229 srcs = []
1230 1230 for tag, abssrc, relsrc, exact in walk(repo, [pat], opts):
1231 1231 origsrc = okaytocopy(abssrc, relsrc, exact)
1232 1232 if origsrc:
1233 1233 srcs.append((origsrc, abssrc, relsrc, exact))
1234 1234 if not srcs:
1235 1235 continue
1236 1236 copylist.append((tfn(pat, dest, srcs), srcs))
1237 1237 if not copylist:
1238 1238 raise util.Abort(_('no files to copy'))
1239 1239
1240 1240 for targetpath, srcs in copylist:
1241 1241 for origsrc, abssrc, relsrc, exact in srcs:
1242 1242 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
1243 1243
1244 1244 if errors:
1245 1245 ui.warn(_('(consider using --after)\n'))
1246 1246 return errors, copied
1247 1247
1248 1248 def copy(ui, repo, *pats, **opts):
1249 1249 """mark files as copied for the next commit
1250 1250
1251 1251 Mark dest as having copies of source files. If dest is a
1252 1252 directory, copies are put in that directory. If dest is a file,
1253 1253 there can only be one source.
1254 1254
1255 1255 By default, this command copies the contents of files as they
1256 1256 stand in the working directory. If invoked with --after, the
1257 1257 operation is recorded, but no copying is performed.
1258 1258
1259 1259 This command takes effect in the next commit.
1260 1260
1261 1261 NOTE: This command should be treated as experimental. While it
1262 1262 should properly record copied files, this information is not yet
1263 1263 fully used by merge, nor fully reported by log.
1264 1264 """
1265 1265 wlock = repo.wlock(0)
1266 1266 errs, copied = docopy(ui, repo, pats, opts, wlock)
1267 1267 return errs
1268 1268
1269 1269 def debugancestor(ui, index, rev1, rev2):
1270 1270 """find the ancestor revision of two revisions in a given index"""
1271 1271 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "", 0)
1272 1272 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1273 1273 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1274 1274
1275 1275 def debugcomplete(ui, cmd='', **opts):
1276 1276 """returns the completion list associated with the given command"""
1277 1277
1278 1278 if opts['options']:
1279 1279 options = []
1280 1280 otables = [globalopts]
1281 1281 if cmd:
1282 1282 aliases, entry = find(cmd)
1283 1283 otables.append(entry[1])
1284 1284 for t in otables:
1285 1285 for o in t:
1286 1286 if o[0]:
1287 1287 options.append('-%s' % o[0])
1288 1288 options.append('--%s' % o[1])
1289 1289 ui.write("%s\n" % "\n".join(options))
1290 1290 return
1291 1291
1292 1292 clist = findpossible(cmd).keys()
1293 1293 clist.sort()
1294 1294 ui.write("%s\n" % "\n".join(clist))
1295 1295
1296 1296 def debugrebuildstate(ui, repo, rev=None):
1297 1297 """rebuild the dirstate as it would look like for the given revision"""
1298 1298 if not rev:
1299 1299 rev = repo.changelog.tip()
1300 1300 else:
1301 1301 rev = repo.lookup(rev)
1302 1302 change = repo.changelog.read(rev)
1303 1303 n = change[0]
1304 1304 files = repo.manifest.readflags(n)
1305 1305 wlock = repo.wlock()
1306 1306 repo.dirstate.rebuild(rev, files.iteritems())
1307 1307
1308 1308 def debugcheckstate(ui, repo):
1309 1309 """validate the correctness of the current dirstate"""
1310 1310 parent1, parent2 = repo.dirstate.parents()
1311 1311 repo.dirstate.read()
1312 1312 dc = repo.dirstate.map
1313 1313 keys = dc.keys()
1314 1314 keys.sort()
1315 1315 m1n = repo.changelog.read(parent1)[0]
1316 1316 m2n = repo.changelog.read(parent2)[0]
1317 1317 m1 = repo.manifest.read(m1n)
1318 1318 m2 = repo.manifest.read(m2n)
1319 1319 errors = 0
1320 1320 for f in dc:
1321 1321 state = repo.dirstate.state(f)
1322 1322 if state in "nr" and f not in m1:
1323 1323 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1324 1324 errors += 1
1325 1325 if state in "a" and f in m1:
1326 1326 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1327 1327 errors += 1
1328 1328 if state in "m" and f not in m1 and f not in m2:
1329 1329 ui.warn(_("%s in state %s, but not in either manifest\n") %
1330 1330 (f, state))
1331 1331 errors += 1
1332 1332 for f in m1:
1333 1333 state = repo.dirstate.state(f)
1334 1334 if state not in "nrm":
1335 1335 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1336 1336 errors += 1
1337 1337 if errors:
1338 1338 error = _(".hg/dirstate inconsistent with current parent's manifest")
1339 1339 raise util.Abort(error)
1340 1340
1341 1341 def debugconfig(ui, repo):
1342 1342 """show combined config settings from all hgrc files"""
1343 1343 for section, name, value in ui.walkconfig():
1344 1344 ui.write('%s.%s=%s\n' % (section, name, value))
1345 1345
1346 1346 def debugsetparents(ui, repo, rev1, rev2=None):
1347 1347 """manually set the parents of the current working directory
1348 1348
1349 1349 This is useful for writing repository conversion tools, but should
1350 1350 be used with care.
1351 1351 """
1352 1352
1353 1353 if not rev2:
1354 1354 rev2 = hex(nullid)
1355 1355
1356 1356 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1357 1357
1358 1358 def debugstate(ui, repo):
1359 1359 """show the contents of the current dirstate"""
1360 1360 repo.dirstate.read()
1361 1361 dc = repo.dirstate.map
1362 1362 keys = dc.keys()
1363 1363 keys.sort()
1364 1364 for file_ in keys:
1365 1365 ui.write("%c %3o %10d %s %s\n"
1366 1366 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1367 1367 time.strftime("%x %X",
1368 1368 time.localtime(dc[file_][3])), file_))
1369 1369 for f in repo.dirstate.copies:
1370 1370 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copies[f], f))
1371 1371
1372 1372 def debugdata(ui, file_, rev):
1373 1373 """dump the contents of an data file revision"""
1374 1374 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1375 1375 file_[:-2] + ".i", file_, 0)
1376 1376 try:
1377 1377 ui.write(r.revision(r.lookup(rev)))
1378 1378 except KeyError:
1379 1379 raise util.Abort(_('invalid revision identifier %s'), rev)
1380 1380
1381 1381 def debugindex(ui, file_):
1382 1382 """dump the contents of an index file"""
1383 1383 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1384 1384 ui.write(" rev offset length base linkrev" +
1385 1385 " nodeid p1 p2\n")
1386 1386 for i in range(r.count()):
1387 1387 node = r.node(i)
1388 1388 pp = r.parents(node)
1389 1389 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1390 1390 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
1391 1391 short(node), short(pp[0]), short(pp[1])))
1392 1392
1393 1393 def debugindexdot(ui, file_):
1394 1394 """dump an index DAG as a .dot file"""
1395 1395 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "", 0)
1396 1396 ui.write("digraph G {\n")
1397 1397 for i in range(r.count()):
1398 1398 e = r.index[i]
1399 1399 ui.write("\t%d -> %d\n" % (r.rev(e[4]), i))
1400 1400 if e[5] != nullid:
1401 1401 ui.write("\t%d -> %d\n" % (r.rev(e[5]), i))
1402 1402 ui.write("}\n")
1403 1403
1404 1404 def debugrename(ui, repo, file, rev=None):
1405 1405 """dump rename information"""
1406 1406 r = repo.file(relpath(repo, [file])[0])
1407 1407 if rev:
1408 1408 try:
1409 1409 # assume all revision numbers are for changesets
1410 1410 n = repo.lookup(rev)
1411 1411 change = repo.changelog.read(n)
1412 1412 m = repo.manifest.read(change[0])
1413 1413 n = m[relpath(repo, [file])[0]]
1414 1414 except (hg.RepoError, KeyError):
1415 1415 n = r.lookup(rev)
1416 1416 else:
1417 1417 n = r.tip()
1418 1418 m = r.renamed(n)
1419 1419 if m:
1420 1420 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1421 1421 else:
1422 1422 ui.write(_("not renamed\n"))
1423 1423
1424 1424 def debugwalk(ui, repo, *pats, **opts):
1425 1425 """show how files match on given patterns"""
1426 1426 items = list(walk(repo, pats, opts))
1427 1427 if not items:
1428 1428 return
1429 1429 fmt = '%%s %%-%ds %%-%ds %%s' % (
1430 1430 max([len(abs) for (src, abs, rel, exact) in items]),
1431 1431 max([len(rel) for (src, abs, rel, exact) in items]))
1432 1432 for src, abs, rel, exact in items:
1433 1433 line = fmt % (src, abs, rel, exact and 'exact' or '')
1434 1434 ui.write("%s\n" % line.rstrip())
1435 1435
1436 1436 def diff(ui, repo, *pats, **opts):
1437 1437 """diff repository (or selected files)
1438 1438
1439 1439 Show differences between revisions for the specified files.
1440 1440
1441 1441 Differences between files are shown using the unified diff format.
1442 1442
1443 1443 When two revision arguments are given, then changes are shown
1444 1444 between those revisions. If only one revision is specified then
1445 1445 that revision is compared to the working directory, and, when no
1446 1446 revisions are specified, the working directory files are compared
1447 1447 to its parent.
1448 1448
1449 1449 Without the -a option, diff will avoid generating diffs of files
1450 1450 it detects as binary. With -a, diff will generate a diff anyway,
1451 1451 probably with undesirable results.
1452 1452 """
1453 1453 node1, node2 = None, None
1454 1454 revs = [repo.lookup(x) for x in opts['rev']]
1455 1455
1456 1456 if len(revs) > 0:
1457 1457 node1 = revs[0]
1458 1458 if len(revs) > 1:
1459 1459 node2 = revs[1]
1460 1460 if len(revs) > 2:
1461 1461 raise util.Abort(_("too many revisions to diff"))
1462 1462
1463 1463 fns, matchfn, anypats = matchpats(repo, pats, opts)
1464 1464
1465 1465 dodiff(sys.stdout, ui, repo, node1, node2, fns, match=matchfn,
1466 1466 text=opts['text'], opts=opts)
1467 1467
1468 1468 def doexport(ui, repo, changeset, seqno, total, revwidth, opts):
1469 1469 node = repo.lookup(changeset)
1470 1470 parents = [p for p in repo.changelog.parents(node) if p != nullid]
1471 1471 if opts['switch_parent']:
1472 1472 parents.reverse()
1473 1473 prev = (parents and parents[0]) or nullid
1474 1474 change = repo.changelog.read(node)
1475 1475
1476 1476 fp = make_file(repo, repo.changelog, opts['output'],
1477 1477 node=node, total=total, seqno=seqno,
1478 1478 revwidth=revwidth)
1479 1479 if fp != sys.stdout:
1480 1480 ui.note("%s\n" % fp.name)
1481 1481
1482 1482 fp.write("# HG changeset patch\n")
1483 1483 fp.write("# User %s\n" % change[1])
1484 1484 fp.write("# Node ID %s\n" % hex(node))
1485 1485 fp.write("# Parent %s\n" % hex(prev))
1486 1486 if len(parents) > 1:
1487 1487 fp.write("# Parent %s\n" % hex(parents[1]))
1488 1488 fp.write(change[4].rstrip())
1489 1489 fp.write("\n\n")
1490 1490
1491 1491 dodiff(fp, ui, repo, prev, node, text=opts['text'])
1492 1492 if fp != sys.stdout:
1493 1493 fp.close()
1494 1494
1495 1495 def export(ui, repo, *changesets, **opts):
1496 1496 """dump the header and diffs for one or more changesets
1497 1497
1498 1498 Print the changeset header and diffs for one or more revisions.
1499 1499
1500 1500 The information shown in the changeset header is: author,
1501 1501 changeset hash, parent and commit comment.
1502 1502
1503 1503 Output may be to a file, in which case the name of the file is
1504 1504 given using a format string. The formatting rules are as follows:
1505 1505
1506 1506 %% literal "%" character
1507 1507 %H changeset hash (40 bytes of hexadecimal)
1508 1508 %N number of patches being generated
1509 1509 %R changeset revision number
1510 1510 %b basename of the exporting repository
1511 1511 %h short-form changeset hash (12 bytes of hexadecimal)
1512 1512 %n zero-padded sequence number, starting at 1
1513 1513 %r zero-padded changeset revision number
1514 1514
1515 1515 Without the -a option, export will avoid generating diffs of files
1516 1516 it detects as binary. With -a, export will generate a diff anyway,
1517 1517 probably with undesirable results.
1518 1518
1519 1519 With the --switch-parent option, the diff will be against the second
1520 1520 parent. It can be useful to review a merge.
1521 1521 """
1522 1522 if not changesets:
1523 1523 raise util.Abort(_("export requires at least one changeset"))
1524 1524 seqno = 0
1525 1525 revs = list(revrange(ui, repo, changesets))
1526 1526 total = len(revs)
1527 1527 revwidth = max(map(len, revs))
1528 1528 msg = len(revs) > 1 and _("Exporting patches:\n") or _("Exporting patch:\n")
1529 1529 ui.note(msg)
1530 1530 for cset in revs:
1531 1531 seqno += 1
1532 1532 doexport(ui, repo, cset, seqno, total, revwidth, opts)
1533 1533
1534 1534 def forget(ui, repo, *pats, **opts):
1535 1535 """don't add the specified files on the next commit
1536 1536
1537 1537 Undo an 'hg add' scheduled for the next commit.
1538 1538 """
1539 1539 forget = []
1540 1540 for src, abs, rel, exact in walk(repo, pats, opts):
1541 1541 if repo.dirstate.state(abs) == 'a':
1542 1542 forget.append(abs)
1543 1543 if ui.verbose or not exact:
1544 1544 ui.status(_('forgetting %s\n') % ((pats and rel) or abs))
1545 1545 repo.forget(forget)
1546 1546
1547 1547 def grep(ui, repo, pattern, *pats, **opts):
1548 1548 """search for a pattern in specified files and revisions
1549 1549
1550 1550 Search revisions of files for a regular expression.
1551 1551
1552 1552 This command behaves differently than Unix grep. It only accepts
1553 1553 Python/Perl regexps. It searches repository history, not the
1554 1554 working directory. It always prints the revision number in which
1555 1555 a match appears.
1556 1556
1557 1557 By default, grep only prints output for the first revision of a
1558 1558 file in which it finds a match. To get it to print every revision
1559 1559 that contains a change in match status ("-" for a match that
1560 1560 becomes a non-match, or "+" for a non-match that becomes a match),
1561 1561 use the --all flag.
1562 1562 """
1563 1563 reflags = 0
1564 1564 if opts['ignore_case']:
1565 1565 reflags |= re.I
1566 1566 regexp = re.compile(pattern, reflags)
1567 1567 sep, eol = ':', '\n'
1568 1568 if opts['print0']:
1569 1569 sep = eol = '\0'
1570 1570
1571 1571 fcache = {}
1572 1572 def getfile(fn):
1573 1573 if fn not in fcache:
1574 1574 fcache[fn] = repo.file(fn)
1575 1575 return fcache[fn]
1576 1576
1577 1577 def matchlines(body):
1578 1578 begin = 0
1579 1579 linenum = 0
1580 1580 while True:
1581 1581 match = regexp.search(body, begin)
1582 1582 if not match:
1583 1583 break
1584 1584 mstart, mend = match.span()
1585 1585 linenum += body.count('\n', begin, mstart) + 1
1586 1586 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1587 1587 lend = body.find('\n', mend)
1588 1588 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1589 1589 begin = lend + 1
1590 1590
1591 1591 class linestate(object):
1592 1592 def __init__(self, line, linenum, colstart, colend):
1593 1593 self.line = line
1594 1594 self.linenum = linenum
1595 1595 self.colstart = colstart
1596 1596 self.colend = colend
1597 1597 def __eq__(self, other):
1598 1598 return self.line == other.line
1599 1599 def __hash__(self):
1600 1600 return hash(self.line)
1601 1601
1602 1602 matches = {}
1603 1603 def grepbody(fn, rev, body):
1604 1604 matches[rev].setdefault(fn, {})
1605 1605 m = matches[rev][fn]
1606 1606 for lnum, cstart, cend, line in matchlines(body):
1607 1607 s = linestate(line, lnum, cstart, cend)
1608 1608 m[s] = s
1609 1609
1610 1610 # FIXME: prev isn't used, why ?
1611 1611 prev = {}
1612 1612 ucache = {}
1613 1613 def display(fn, rev, states, prevstates):
1614 1614 diff = list(sets.Set(states).symmetric_difference(sets.Set(prevstates)))
1615 1615 diff.sort(lambda x, y: cmp(x.linenum, y.linenum))
1616 1616 counts = {'-': 0, '+': 0}
1617 1617 filerevmatches = {}
1618 1618 for l in diff:
1619 1619 if incrementing or not opts['all']:
1620 1620 change = ((l in prevstates) and '-') or '+'
1621 1621 r = rev
1622 1622 else:
1623 1623 change = ((l in states) and '-') or '+'
1624 1624 r = prev[fn]
1625 1625 cols = [fn, str(rev)]
1626 1626 if opts['line_number']:
1627 1627 cols.append(str(l.linenum))
1628 1628 if opts['all']:
1629 1629 cols.append(change)
1630 1630 if opts['user']:
1631 1631 cols.append(trimuser(ui, getchange(rev)[1], rev,
1632 1632 ucache))
1633 1633 if opts['files_with_matches']:
1634 1634 c = (fn, rev)
1635 1635 if c in filerevmatches:
1636 1636 continue
1637 1637 filerevmatches[c] = 1
1638 1638 else:
1639 1639 cols.append(l.line)
1640 1640 ui.write(sep.join(cols), eol)
1641 1641 counts[change] += 1
1642 1642 return counts['+'], counts['-']
1643 1643
1644 1644 fstate = {}
1645 1645 skip = {}
1646 1646 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1647 1647 count = 0
1648 1648 incrementing = False
1649 1649 for st, rev, fns in changeiter:
1650 1650 if st == 'window':
1651 1651 incrementing = rev
1652 1652 matches.clear()
1653 1653 elif st == 'add':
1654 1654 change = repo.changelog.read(repo.lookup(str(rev)))
1655 1655 mf = repo.manifest.read(change[0])
1656 1656 matches[rev] = {}
1657 1657 for fn in fns:
1658 1658 if fn in skip:
1659 1659 continue
1660 1660 fstate.setdefault(fn, {})
1661 1661 try:
1662 1662 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1663 1663 except KeyError:
1664 1664 pass
1665 1665 elif st == 'iter':
1666 1666 states = matches[rev].items()
1667 1667 states.sort()
1668 1668 for fn, m in states:
1669 1669 if fn in skip:
1670 1670 continue
1671 1671 if incrementing or not opts['all'] or fstate[fn]:
1672 1672 pos, neg = display(fn, rev, m, fstate[fn])
1673 1673 count += pos + neg
1674 1674 if pos and not opts['all']:
1675 1675 skip[fn] = True
1676 1676 fstate[fn] = m
1677 1677 prev[fn] = rev
1678 1678
1679 1679 if not incrementing:
1680 1680 fstate = fstate.items()
1681 1681 fstate.sort()
1682 1682 for fn, state in fstate:
1683 1683 if fn in skip:
1684 1684 continue
1685 1685 display(fn, rev, {}, state)
1686 1686 return (count == 0 and 1) or 0
1687 1687
1688 1688 def heads(ui, repo, **opts):
1689 1689 """show current repository heads
1690 1690
1691 1691 Show all repository head changesets.
1692 1692
1693 1693 Repository "heads" are changesets that don't have children
1694 1694 changesets. They are where development generally takes place and
1695 1695 are the usual targets for update and merge operations.
1696 1696 """
1697 1697 if opts['rev']:
1698 1698 heads = repo.heads(repo.lookup(opts['rev']))
1699 1699 else:
1700 1700 heads = repo.heads()
1701 1701 br = None
1702 1702 if opts['branches']:
1703 1703 br = repo.branchlookup(heads)
1704 1704 displayer = show_changeset(ui, repo, opts)
1705 1705 for n in heads:
1706 1706 displayer.show(changenode=n, brinfo=br)
1707 1707
1708 1708 def identify(ui, repo):
1709 1709 """print information about the working copy
1710 1710
1711 1711 Print a short summary of the current state of the repo.
1712 1712
1713 1713 This summary identifies the repository state using one or two parent
1714 1714 hash identifiers, followed by a "+" if there are uncommitted changes
1715 1715 in the working directory, followed by a list of tags for this revision.
1716 1716 """
1717 1717 parents = [p for p in repo.dirstate.parents() if p != nullid]
1718 1718 if not parents:
1719 1719 ui.write(_("unknown\n"))
1720 1720 return
1721 1721
1722 1722 hexfunc = ui.verbose and hex or short
1723 1723 modified, added, removed, deleted, unknown = repo.changes()
1724 1724 output = ["%s%s" %
1725 1725 ('+'.join([hexfunc(parent) for parent in parents]),
1726 1726 (modified or added or removed or deleted) and "+" or "")]
1727 1727
1728 1728 if not ui.quiet:
1729 1729 # multiple tags for a single parent separated by '/'
1730 1730 parenttags = ['/'.join(tags)
1731 1731 for tags in map(repo.nodetags, parents) if tags]
1732 1732 # tags for multiple parents separated by ' + '
1733 1733 if parenttags:
1734 1734 output.append(' + '.join(parenttags))
1735 1735
1736 1736 ui.write("%s\n" % ' '.join(output))
1737 1737
1738 1738 def import_(ui, repo, patch1, *patches, **opts):
1739 1739 """import an ordered set of patches
1740 1740
1741 1741 Import a list of patches and commit them individually.
1742 1742
1743 1743 If there are outstanding changes in the working directory, import
1744 1744 will abort unless given the -f flag.
1745 1745
1746 1746 If a patch looks like a mail message (its first line starts with
1747 1747 "From " or looks like an RFC822 header), it will not be applied
1748 1748 unless the -f option is used. The importer neither parses nor
1749 1749 discards mail headers, so use -f only to override the "mailness"
1750 1750 safety check, not to import a real mail message.
1751 1751 """
1752 1752 patches = (patch1,) + patches
1753 1753
1754 1754 if not opts['force']:
1755 1755 modified, added, removed, deleted, unknown = repo.changes()
1756 1756 if modified or added or removed or deleted:
1757 1757 raise util.Abort(_("outstanding uncommitted changes"))
1758 1758
1759 1759 d = opts["base"]
1760 1760 strip = opts["strip"]
1761 1761
1762 1762 mailre = re.compile(r'(?:From |[\w-]+:)')
1763 1763
1764 1764 # attempt to detect the start of a patch
1765 1765 # (this heuristic is borrowed from quilt)
1766 1766 diffre = re.compile(r'(?:Index:[ \t]|diff[ \t]|RCS file: |' +
1767 1767 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
1768 1768 '(---|\*\*\*)[ \t])')
1769 1769
1770 1770 for patch in patches:
1771 1771 ui.status(_("applying %s\n") % patch)
1772 1772 pf = os.path.join(d, patch)
1773 1773
1774 1774 message = []
1775 1775 user = None
1776 1776 hgpatch = False
1777 1777 for line in file(pf):
1778 1778 line = line.rstrip()
1779 1779 if (not message and not hgpatch and
1780 1780 mailre.match(line) and not opts['force']):
1781 1781 if len(line) > 35:
1782 1782 line = line[:32] + '...'
1783 1783 raise util.Abort(_('first line looks like a '
1784 1784 'mail header: ') + line)
1785 1785 if diffre.match(line):
1786 1786 break
1787 1787 elif hgpatch:
1788 1788 # parse values when importing the result of an hg export
1789 1789 if line.startswith("# User "):
1790 1790 user = line[7:]
1791 1791 ui.debug(_('User: %s\n') % user)
1792 1792 elif not line.startswith("# ") and line:
1793 1793 message.append(line)
1794 1794 hgpatch = False
1795 1795 elif line == '# HG changeset patch':
1796 1796 hgpatch = True
1797 1797 message = [] # We may have collected garbage
1798 1798 else:
1799 1799 message.append(line)
1800 1800
1801 1801 # make sure message isn't empty
1802 1802 if not message:
1803 1803 message = _("imported patch %s\n") % patch
1804 1804 else:
1805 1805 message = "%s\n" % '\n'.join(message)
1806 1806 ui.debug(_('message:\n%s\n') % message)
1807 1807
1808 1808 files = util.patch(strip, pf, ui)
1809 1809
1810 1810 if len(files) > 0:
1811 1811 addremove(ui, repo, *files)
1812 1812 repo.commit(files, message, user)
1813 1813
1814 1814 def incoming(ui, repo, source="default", **opts):
1815 1815 """show new changesets found in source
1816 1816
1817 1817 Show new changesets found in the specified path/URL or the default
1818 1818 pull location. These are the changesets that would be pulled if a pull
1819 1819 was requested.
1820 1820
1821 1821 For remote repository, using --bundle avoids downloading the changesets
1822 1822 twice if the incoming is followed by a pull.
1823 1823
1824 1824 See pull for valid source format details.
1825 1825 """
1826 1826 source = ui.expandpath(source)
1827 1827 if opts['ssh']:
1828 1828 ui.setconfig("ui", "ssh", opts['ssh'])
1829 1829 if opts['remotecmd']:
1830 1830 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1831 1831
1832 1832 other = hg.repository(ui, source)
1833 1833 incoming = repo.findincoming(other, force=opts["force"])
1834 1834 if not incoming:
1835 1835 ui.status(_("no changes found\n"))
1836 1836 return
1837 1837
1838 1838 cleanup = None
1839 1839 try:
1840 1840 fname = opts["bundle"]
1841 1841 if fname or not other.local():
1842 1842 # create a bundle (uncompressed if other repo is not local)
1843 1843 cg = other.changegroup(incoming, "incoming")
1844 1844 fname = cleanup = write_bundle(cg, fname, compress=other.local())
1845 1845 # keep written bundle?
1846 1846 if opts["bundle"]:
1847 1847 cleanup = None
1848 1848 if not other.local():
1849 1849 # use the created uncompressed bundlerepo
1850 1850 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1851 1851
1852 1852 o = other.changelog.nodesbetween(incoming)[0]
1853 1853 if opts['newest_first']:
1854 1854 o.reverse()
1855 1855 displayer = show_changeset(ui, other, opts)
1856 1856 for n in o:
1857 1857 parents = [p for p in other.changelog.parents(n) if p != nullid]
1858 1858 if opts['no_merges'] and len(parents) == 2:
1859 1859 continue
1860 1860 displayer.show(changenode=n)
1861 1861 if opts['patch']:
1862 1862 prev = (parents and parents[0]) or nullid
1863 1863 dodiff(ui, ui, other, prev, n)
1864 1864 ui.write("\n")
1865 1865 finally:
1866 1866 if hasattr(other, 'close'):
1867 1867 other.close()
1868 1868 if cleanup:
1869 1869 os.unlink(cleanup)
1870 1870
1871 1871 def init(ui, dest="."):
1872 1872 """create a new repository in the given directory
1873 1873
1874 1874 Initialize a new repository in the given directory. If the given
1875 1875 directory does not exist, it is created.
1876 1876
1877 1877 If no directory is given, the current directory is used.
1878 1878 """
1879 1879 if not os.path.exists(dest):
1880 1880 os.mkdir(dest)
1881 1881 hg.repository(ui, dest, create=1)
1882 1882
1883 1883 def locate(ui, repo, *pats, **opts):
1884 1884 """locate files matching specific patterns
1885 1885
1886 1886 Print all files under Mercurial control whose names match the
1887 1887 given patterns.
1888 1888
1889 1889 This command searches the current directory and its
1890 1890 subdirectories. To search an entire repository, move to the root
1891 1891 of the repository.
1892 1892
1893 1893 If no patterns are given to match, this command prints all file
1894 1894 names.
1895 1895
1896 1896 If you want to feed the output of this command into the "xargs"
1897 1897 command, use the "-0" option to both this command and "xargs".
1898 1898 This will avoid the problem of "xargs" treating single filenames
1899 1899 that contain white space as multiple filenames.
1900 1900 """
1901 1901 end = opts['print0'] and '\0' or '\n'
1902 1902 rev = opts['rev']
1903 1903 if rev:
1904 1904 node = repo.lookup(rev)
1905 1905 else:
1906 1906 node = None
1907 1907
1908 1908 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
1909 1909 head='(?:.*/|)'):
1910 1910 if not node and repo.dirstate.state(abs) == '?':
1911 1911 continue
1912 1912 if opts['fullpath']:
1913 1913 ui.write(os.path.join(repo.root, abs), end)
1914 1914 else:
1915 1915 ui.write(((pats and rel) or abs), end)
1916 1916
1917 1917 def log(ui, repo, *pats, **opts):
1918 1918 """show revision history of entire repository or files
1919 1919
1920 1920 Print the revision history of the specified files or the entire project.
1921 1921
1922 1922 By default this command outputs: changeset id and hash, tags,
1923 1923 non-trivial parents, user, date and time, and a summary for each
1924 1924 commit. When the -v/--verbose switch is used, the list of changed
1925 1925 files and full commit message is shown.
1926 1926 """
1927 1927 class dui(object):
1928 1928 # Implement and delegate some ui protocol. Save hunks of
1929 1929 # output for later display in the desired order.
1930 1930 def __init__(self, ui):
1931 1931 self.ui = ui
1932 1932 self.hunk = {}
1933 1933 self.header = {}
1934 1934 def bump(self, rev):
1935 1935 self.rev = rev
1936 1936 self.hunk[rev] = []
1937 1937 self.header[rev] = []
1938 1938 def note(self, *args):
1939 1939 if self.verbose:
1940 1940 self.write(*args)
1941 1941 def status(self, *args):
1942 1942 if not self.quiet:
1943 1943 self.write(*args)
1944 1944 def write(self, *args):
1945 1945 self.hunk[self.rev].append(args)
1946 1946 def write_header(self, *args):
1947 1947 self.header[self.rev].append(args)
1948 1948 def debug(self, *args):
1949 1949 if self.debugflag:
1950 1950 self.write(*args)
1951 1951 def __getattr__(self, key):
1952 1952 return getattr(self.ui, key)
1953 1953
1954 1954 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1955 1955
1956 1956 if opts['limit']:
1957 1957 try:
1958 1958 limit = int(opts['limit'])
1959 1959 except ValueError:
1960 1960 raise util.Abort(_('limit must be a positive integer'))
1961 1961 if limit <= 0: raise util.Abort(_('limit must be positive'))
1962 1962 else:
1963 1963 limit = sys.maxint
1964 1964 count = 0
1965 1965
1966 1966 displayer = show_changeset(ui, repo, opts)
1967 1967 for st, rev, fns in changeiter:
1968 1968 if st == 'window':
1969 1969 du = dui(ui)
1970 1970 displayer.ui = du
1971 1971 elif st == 'add':
1972 1972 du.bump(rev)
1973 1973 changenode = repo.changelog.node(rev)
1974 1974 parents = [p for p in repo.changelog.parents(changenode)
1975 1975 if p != nullid]
1976 1976 if opts['no_merges'] and len(parents) == 2:
1977 1977 continue
1978 1978 if opts['only_merges'] and len(parents) != 2:
1979 1979 continue
1980 1980
1981 1981 if opts['keyword']:
1982 1982 changes = getchange(rev)
1983 1983 miss = 0
1984 1984 for k in [kw.lower() for kw in opts['keyword']]:
1985 1985 if not (k in changes[1].lower() or
1986 1986 k in changes[4].lower() or
1987 1987 k in " ".join(changes[3][:20]).lower()):
1988 1988 miss = 1
1989 1989 break
1990 1990 if miss:
1991 1991 continue
1992 1992
1993 1993 br = None
1994 1994 if opts['branches']:
1995 1995 br = repo.branchlookup([repo.changelog.node(rev)])
1996 1996
1997 1997 displayer.show(rev, brinfo=br)
1998 1998 if opts['patch']:
1999 1999 prev = (parents and parents[0]) or nullid
2000 2000 dodiff(du, du, repo, prev, changenode, match=matchfn)
2001 2001 du.write("\n\n")
2002 2002 elif st == 'iter':
2003 2003 if count == limit: break
2004 2004 if du.header[rev]:
2005 2005 for args in du.header[rev]:
2006 2006 ui.write_header(*args)
2007 2007 if du.hunk[rev]:
2008 2008 count += 1
2009 2009 for args in du.hunk[rev]:
2010 2010 ui.write(*args)
2011 2011
2012 2012 def manifest(ui, repo, rev=None):
2013 2013 """output the latest or given revision of the project manifest
2014 2014
2015 2015 Print a list of version controlled files for the given revision.
2016 2016
2017 2017 The manifest is the list of files being version controlled. If no revision
2018 2018 is given then the tip is used.
2019 2019 """
2020 2020 if rev:
2021 2021 try:
2022 2022 # assume all revision numbers are for changesets
2023 2023 n = repo.lookup(rev)
2024 2024 change = repo.changelog.read(n)
2025 2025 n = change[0]
2026 2026 except hg.RepoError:
2027 2027 n = repo.manifest.lookup(rev)
2028 2028 else:
2029 2029 n = repo.manifest.tip()
2030 2030 m = repo.manifest.read(n)
2031 2031 mf = repo.manifest.readflags(n)
2032 2032 files = m.keys()
2033 2033 files.sort()
2034 2034
2035 2035 for f in files:
2036 2036 ui.write("%40s %3s %s\n" % (hex(m[f]), mf[f] and "755" or "644", f))
2037 2037
2038 2038 def merge(ui, repo, node=None, **opts):
2039 2039 """Merge working directory with another revision
2040 2040
2041 2041 Merge the contents of the current working directory and the
2042 2042 requested revision. Files that changed between either parent are
2043 2043 marked as changed for the next commit and a commit must be
2044 2044 performed before any further updates are allowed.
2045 2045 """
2046 2046 return update(ui, repo, node=node, merge=True, **opts)
2047 2047
2048 2048 def outgoing(ui, repo, dest="default-push", **opts):
2049 2049 """show changesets not found in destination
2050 2050
2051 2051 Show changesets not found in the specified destination repository or
2052 2052 the default push location. These are the changesets that would be pushed
2053 2053 if a push was requested.
2054 2054
2055 2055 See pull for valid destination format details.
2056 2056 """
2057 2057 dest = ui.expandpath(dest)
2058 2058 if opts['ssh']:
2059 2059 ui.setconfig("ui", "ssh", opts['ssh'])
2060 2060 if opts['remotecmd']:
2061 2061 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
2062 2062
2063 2063 other = hg.repository(ui, dest)
2064 2064 o = repo.findoutgoing(other, force=opts['force'])
2065 2065 if not o:
2066 2066 ui.status(_("no changes found\n"))
2067 2067 return
2068 2068 o = repo.changelog.nodesbetween(o)[0]
2069 2069 if opts['newest_first']:
2070 2070 o.reverse()
2071 2071 displayer = show_changeset(ui, repo, opts)
2072 2072 for n in o:
2073 2073 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2074 2074 if opts['no_merges'] and len(parents) == 2:
2075 2075 continue
2076 2076 displayer.show(changenode=n)
2077 2077 if opts['patch']:
2078 2078 prev = (parents and parents[0]) or nullid
2079 2079 dodiff(ui, ui, repo, prev, n)
2080 2080 ui.write("\n")
2081 2081
2082 2082 def parents(ui, repo, rev=None, branches=None, **opts):
2083 2083 """show the parents of the working dir or revision
2084 2084
2085 2085 Print the working directory's parent revisions.
2086 2086 """
2087 2087 if rev:
2088 2088 p = repo.changelog.parents(repo.lookup(rev))
2089 2089 else:
2090 2090 p = repo.dirstate.parents()
2091 2091
2092 2092 br = None
2093 2093 if branches is not None:
2094 2094 br = repo.branchlookup(p)
2095 2095 displayer = show_changeset(ui, repo, opts)
2096 2096 for n in p:
2097 2097 if n != nullid:
2098 2098 displayer.show(changenode=n, brinfo=br)
2099 2099
2100 2100 def paths(ui, repo, search=None):
2101 2101 """show definition of symbolic path names
2102 2102
2103 2103 Show definition of symbolic path name NAME. If no name is given, show
2104 2104 definition of available names.
2105 2105
2106 2106 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2107 2107 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2108 2108 """
2109 2109 if search:
2110 2110 for name, path in ui.configitems("paths"):
2111 2111 if name == search:
2112 2112 ui.write("%s\n" % path)
2113 2113 return
2114 2114 ui.warn(_("not found!\n"))
2115 2115 return 1
2116 2116 else:
2117 2117 for name, path in ui.configitems("paths"):
2118 2118 ui.write("%s = %s\n" % (name, path))
2119 2119
2120 2120 def postincoming(ui, repo, modheads, optupdate):
2121 2121 if modheads == 0:
2122 2122 return
2123 2123 if optupdate:
2124 2124 if modheads == 1:
2125 2125 return update(ui, repo)
2126 2126 else:
2127 2127 ui.status(_("not updating, since new heads added\n"))
2128 2128 if modheads > 1:
2129 2129 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2130 2130 else:
2131 2131 ui.status(_("(run 'hg update' to get a working copy)\n"))
2132 2132
2133 2133 def pull(ui, repo, source="default", **opts):
2134 2134 """pull changes from the specified source
2135 2135
2136 2136 Pull changes from a remote repository to a local one.
2137 2137
2138 2138 This finds all changes from the repository at the specified path
2139 2139 or URL and adds them to the local repository. By default, this
2140 2140 does not update the copy of the project in the working directory.
2141 2141
2142 2142 Valid URLs are of the form:
2143 2143
2144 2144 local/filesystem/path
2145 2145 http://[user@]host[:port][/path]
2146 2146 https://[user@]host[:port][/path]
2147 2147 ssh://[user@]host[:port][/path]
2148 2148
2149 2149 Some notes about using SSH with Mercurial:
2150 2150 - SSH requires an accessible shell account on the destination machine
2151 2151 and a copy of hg in the remote path or specified with as remotecmd.
2152 2152 - /path is relative to the remote user's home directory by default.
2153 2153 Use two slashes at the start of a path to specify an absolute path.
2154 2154 - Mercurial doesn't use its own compression via SSH; the right thing
2155 2155 to do is to configure it in your ~/.ssh/ssh_config, e.g.:
2156 2156 Host *.mylocalnetwork.example.com
2157 2157 Compression off
2158 2158 Host *
2159 2159 Compression on
2160 2160 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2161 2161 with the --ssh command line option.
2162 2162 """
2163 2163 source = ui.expandpath(source)
2164 2164 ui.status(_('pulling from %s\n') % (source))
2165 2165
2166 2166 if opts['ssh']:
2167 2167 ui.setconfig("ui", "ssh", opts['ssh'])
2168 2168 if opts['remotecmd']:
2169 2169 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
2170 2170
2171 2171 other = hg.repository(ui, source)
2172 2172 revs = None
2173 2173 if opts['rev'] and not other.local():
2174 2174 raise util.Abort(_("pull -r doesn't work for remote repositories yet"))
2175 2175 elif opts['rev']:
2176 2176 revs = [other.lookup(rev) for rev in opts['rev']]
2177 2177 modheads = repo.pull(other, heads=revs, force=opts['force'])
2178 2178 return postincoming(ui, repo, modheads, opts['update'])
2179 2179
2180 2180 def push(ui, repo, dest="default-push", **opts):
2181 2181 """push changes to the specified destination
2182 2182
2183 2183 Push changes from the local repository to the given destination.
2184 2184
2185 2185 This is the symmetrical operation for pull. It helps to move
2186 2186 changes from the current repository to a different one. If the
2187 2187 destination is local this is identical to a pull in that directory
2188 2188 from the current one.
2189 2189
2190 2190 By default, push will refuse to run if it detects the result would
2191 2191 increase the number of remote heads. This generally indicates the
2192 2192 the client has forgotten to sync and merge before pushing.
2193 2193
2194 2194 Valid URLs are of the form:
2195 2195
2196 2196 local/filesystem/path
2197 2197 ssh://[user@]host[:port][/path]
2198 2198
2199 2199 Look at the help text for the pull command for important details
2200 2200 about ssh:// URLs.
2201 2201 """
2202 2202 dest = ui.expandpath(dest)
2203 2203 ui.status('pushing to %s\n' % (dest))
2204 2204
2205 2205 if opts['ssh']:
2206 2206 ui.setconfig("ui", "ssh", opts['ssh'])
2207 2207 if opts['remotecmd']:
2208 2208 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
2209 2209
2210 2210 other = hg.repository(ui, dest)
2211 2211 revs = None
2212 2212 if opts['rev']:
2213 2213 revs = [repo.lookup(rev) for rev in opts['rev']]
2214 2214 r = repo.push(other, opts['force'], revs=revs)
2215 2215 return r == 0
2216 2216
2217 2217 def rawcommit(ui, repo, *flist, **rc):
2218 2218 """raw commit interface (DEPRECATED)
2219 2219
2220 2220 (DEPRECATED)
2221 2221 Lowlevel commit, for use in helper scripts.
2222 2222
2223 2223 This command is not intended to be used by normal users, as it is
2224 2224 primarily useful for importing from other SCMs.
2225 2225
2226 2226 This command is now deprecated and will be removed in a future
2227 2227 release, please use debugsetparents and commit instead.
2228 2228 """
2229 2229
2230 2230 ui.warn(_("(the rawcommit command is deprecated)\n"))
2231 2231
2232 2232 message = rc['message']
2233 2233 if not message and rc['logfile']:
2234 2234 try:
2235 2235 message = open(rc['logfile']).read()
2236 2236 except IOError:
2237 2237 pass
2238 2238 if not message and not rc['logfile']:
2239 2239 raise util.Abort(_("missing commit message"))
2240 2240
2241 2241 files = relpath(repo, list(flist))
2242 2242 if rc['files']:
2243 2243 files += open(rc['files']).read().splitlines()
2244 2244
2245 2245 rc['parent'] = map(repo.lookup, rc['parent'])
2246 2246
2247 2247 try:
2248 2248 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
2249 2249 except ValueError, inst:
2250 2250 raise util.Abort(str(inst))
2251 2251
2252 2252 def recover(ui, repo):
2253 2253 """roll back an interrupted transaction
2254 2254
2255 2255 Recover from an interrupted commit or pull.
2256 2256
2257 2257 This command tries to fix the repository status after an interrupted
2258 2258 operation. It should only be necessary when Mercurial suggests it.
2259 2259 """
2260 2260 if repo.recover():
2261 2261 return repo.verify()
2262 2262 return 1
2263 2263
2264 2264 def remove(ui, repo, pat, *pats, **opts):
2265 2265 """remove the specified files on the next commit
2266 2266
2267 2267 Schedule the indicated files for removal from the repository.
2268 2268
2269 2269 This command schedules the files to be removed at the next commit.
2270 2270 This only removes files from the current branch, not from the
2271 2271 entire project history. If the files still exist in the working
2272 2272 directory, they will be deleted from it.
2273 2273 """
2274 2274 names = []
2275 2275 def okaytoremove(abs, rel, exact):
2276 2276 modified, added, removed, deleted, unknown = repo.changes(files=[abs])
2277 2277 reason = None
2278 2278 if modified and not opts['force']:
2279 2279 reason = _('is modified')
2280 2280 elif added:
2281 2281 reason = _('has been marked for add')
2282 2282 elif unknown:
2283 2283 reason = _('is not managed')
2284 2284 if reason:
2285 2285 if exact:
2286 2286 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2287 2287 else:
2288 2288 return True
2289 2289 for src, abs, rel, exact in walk(repo, (pat,) + pats, opts):
2290 2290 if okaytoremove(abs, rel, exact):
2291 2291 if ui.verbose or not exact:
2292 2292 ui.status(_('removing %s\n') % rel)
2293 2293 names.append(abs)
2294 2294 repo.remove(names, unlink=True)
2295 2295
2296 2296 def rename(ui, repo, *pats, **opts):
2297 2297 """rename files; equivalent of copy + remove
2298 2298
2299 2299 Mark dest as copies of sources; mark sources for deletion. If
2300 2300 dest is a directory, copies are put in that directory. If dest is
2301 2301 a file, there can only be one source.
2302 2302
2303 2303 By default, this command copies the contents of files as they
2304 2304 stand in the working directory. If invoked with --after, the
2305 2305 operation is recorded, but no copying is performed.
2306 2306
2307 2307 This command takes effect in the next commit.
2308 2308
2309 2309 NOTE: This command should be treated as experimental. While it
2310 2310 should properly record rename files, this information is not yet
2311 2311 fully used by merge, nor fully reported by log.
2312 2312 """
2313 2313 wlock = repo.wlock(0)
2314 2314 errs, copied = docopy(ui, repo, pats, opts, wlock)
2315 2315 names = []
2316 2316 for abs, rel, exact in copied:
2317 2317 if ui.verbose or not exact:
2318 2318 ui.status(_('removing %s\n') % rel)
2319 2319 names.append(abs)
2320 2320 repo.remove(names, True, wlock)
2321 2321 return errs
2322 2322
2323 2323 def revert(ui, repo, *pats, **opts):
2324 2324 """revert modified files or dirs back to their unmodified states
2325 2325
2326 2326 In its default mode, it reverts any uncommitted modifications made
2327 2327 to the named files or directories. This restores the contents of
2328 2328 the affected files to an unmodified state.
2329 2329
2330 2330 Modified files are saved with a .orig suffix before reverting.
2331 2331 To disable these backups, use --no-backup.
2332 2332
2333 2333 Using the -r option, it reverts the given files or directories to
2334 2334 their state as of an earlier revision. This can be helpful to "roll
2335 2335 back" some or all of a change that should not have been committed.
2336 2336
2337 2337 Revert modifies the working directory. It does not commit any
2338 2338 changes, or change the parent of the current working directory.
2339 2339
2340 2340 If a file has been deleted, it is recreated. If the executable
2341 2341 mode of a file was changed, it is reset.
2342 2342
2343 2343 If names are given, all files matching the names are reverted.
2344 2344
2345 2345 If no arguments are given, all files in the repository are reverted.
2346 2346 """
2347 2347 parent = repo.dirstate.parents()[0]
2348 2348 node = opts['rev'] and repo.lookup(opts['rev']) or parent
2349 2349 mf = repo.manifest.read(repo.changelog.read(node)[0])
2350 2350
2351 2351 wlock = repo.wlock()
2352 2352
2353 2353 # need all matching names in dirstate and manifest of target rev,
2354 2354 # so have to walk both. do not print errors if files exist in one
2355 2355 # but not other.
2356 2356
2357 2357 names = {}
2358 2358 target_only = {}
2359 2359
2360 2360 # walk dirstate.
2361 2361
2362 2362 for src, abs, rel, exact in walk(repo, pats, opts, badmatch=mf.has_key):
2363 2363 names[abs] = (rel, exact)
2364 2364 if src == 'b':
2365 2365 target_only[abs] = True
2366 2366
2367 2367 # walk target manifest.
2368 2368
2369 2369 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
2370 2370 badmatch=names.has_key):
2371 2371 if abs in names: continue
2372 2372 names[abs] = (rel, exact)
2373 2373 target_only[abs] = True
2374 2374
2375 2375 changes = repo.changes(match=names.has_key, wlock=wlock)
2376 2376 modified, added, removed, deleted, unknown = map(dict.fromkeys, changes)
2377 2377
2378 2378 revert = ([], _('reverting %s\n'))
2379 2379 add = ([], _('adding %s\n'))
2380 2380 remove = ([], _('removing %s\n'))
2381 2381 forget = ([], _('forgetting %s\n'))
2382 2382 undelete = ([], _('undeleting %s\n'))
2383 2383 update = {}
2384 2384
2385 2385 disptable = (
2386 2386 # dispatch table:
2387 2387 # file state
2388 2388 # action if in target manifest
2389 2389 # action if not in target manifest
2390 2390 # make backup if in target manifest
2391 2391 # make backup if not in target manifest
2392 2392 (modified, revert, remove, True, True),
2393 2393 (added, revert, forget, True, False),
2394 2394 (removed, undelete, None, False, False),
2395 2395 (deleted, revert, remove, False, False),
2396 2396 (unknown, add, None, True, False),
2397 2397 (target_only, add, None, False, False),
2398 2398 )
2399 2399
2400 2400 entries = names.items()
2401 2401 entries.sort()
2402 2402
2403 2403 for abs, (rel, exact) in entries:
2404 2404 in_mf = abs in mf
2405 2405 def handle(xlist, dobackup):
2406 2406 xlist[0].append(abs)
2407 2407 if dobackup and not opts['no_backup'] and os.path.exists(rel):
2408 2408 bakname = "%s.orig" % rel
2409 2409 ui.note(_('saving current version of %s as %s\n') %
2410 2410 (rel, bakname))
2411 2411 shutil.copyfile(rel, bakname)
2412 2412 shutil.copymode(rel, bakname)
2413 2413 if ui.verbose or not exact:
2414 2414 ui.status(xlist[1] % rel)
2415 2415 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2416 2416 if abs not in table: continue
2417 2417 # file has changed in dirstate
2418 2418 if in_mf:
2419 2419 handle(hitlist, backuphit)
2420 2420 elif misslist is not None:
2421 2421 handle(misslist, backupmiss)
2422 2422 else:
2423 2423 if exact: ui.warn(_('file not managed: %s\n' % rel))
2424 2424 break
2425 2425 else:
2426 2426 # file has not changed in dirstate
2427 2427 if node == parent:
2428 2428 if exact: ui.warn(_('no changes needed to %s\n' % rel))
2429 2429 continue
2430 2430 if not in_mf:
2431 2431 handle(remove, False)
2432 2432 update[abs] = True
2433 2433
2434 2434 repo.dirstate.forget(forget[0])
2435 2435 r = repo.update(node, False, True, update.has_key, False, wlock=wlock)
2436 2436 repo.dirstate.update(add[0], 'a')
2437 2437 repo.dirstate.update(undelete[0], 'n')
2438 2438 repo.dirstate.update(remove[0], 'r')
2439 2439 return r
2440 2440
2441 2441 def root(ui, repo):
2442 2442 """print the root (top) of the current working dir
2443 2443
2444 2444 Print the root directory of the current repository.
2445 2445 """
2446 2446 ui.write(repo.root + "\n")
2447 2447
2448 2448 def serve(ui, repo, **opts):
2449 2449 """export the repository via HTTP
2450 2450
2451 2451 Start a local HTTP repository browser and pull server.
2452 2452
2453 2453 By default, the server logs accesses to stdout and errors to
2454 2454 stderr. Use the "-A" and "-E" options to log to files.
2455 2455 """
2456 2456
2457 2457 if opts["stdio"]:
2458 2458 fin, fout = sys.stdin, sys.stdout
2459 2459 sys.stdout = sys.stderr
2460 2460
2461 2461 # Prevent insertion/deletion of CRs
2462 2462 util.set_binary(fin)
2463 2463 util.set_binary(fout)
2464 2464
2465 2465 def getarg():
2466 2466 argline = fin.readline()[:-1]
2467 2467 arg, l = argline.split()
2468 2468 val = fin.read(int(l))
2469 2469 return arg, val
2470 2470 def respond(v):
2471 2471 fout.write("%d\n" % len(v))
2472 2472 fout.write(v)
2473 2473 fout.flush()
2474 2474
2475 2475 lock = None
2476 2476
2477 2477 while 1:
2478 2478 cmd = fin.readline()[:-1]
2479 2479 if cmd == '':
2480 2480 return
2481 2481 if cmd == "heads":
2482 2482 h = repo.heads()
2483 2483 respond(" ".join(map(hex, h)) + "\n")
2484 2484 if cmd == "lock":
2485 2485 lock = repo.lock()
2486 2486 respond("")
2487 2487 if cmd == "unlock":
2488 2488 if lock:
2489 2489 lock.release()
2490 2490 lock = None
2491 2491 respond("")
2492 2492 elif cmd == "branches":
2493 2493 arg, nodes = getarg()
2494 2494 nodes = map(bin, nodes.split(" "))
2495 2495 r = []
2496 2496 for b in repo.branches(nodes):
2497 2497 r.append(" ".join(map(hex, b)) + "\n")
2498 2498 respond("".join(r))
2499 2499 elif cmd == "between":
2500 2500 arg, pairs = getarg()
2501 2501 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
2502 2502 r = []
2503 2503 for b in repo.between(pairs):
2504 2504 r.append(" ".join(map(hex, b)) + "\n")
2505 2505 respond("".join(r))
2506 2506 elif cmd == "changegroup":
2507 2507 nodes = []
2508 2508 arg, roots = getarg()
2509 2509 nodes = map(bin, roots.split(" "))
2510 2510
2511 2511 cg = repo.changegroup(nodes, 'serve')
2512 2512 while 1:
2513 2513 d = cg.read(4096)
2514 2514 if not d:
2515 2515 break
2516 2516 fout.write(d)
2517 2517
2518 2518 fout.flush()
2519 2519
2520 2520 elif cmd == "addchangegroup":
2521 2521 if not lock:
2522 2522 respond("not locked")
2523 2523 continue
2524 2524 respond("")
2525 2525
2526 2526 r = repo.addchangegroup(fin)
2527 2527 respond(str(r))
2528 2528
2529 2529 optlist = "name templates style address port ipv6 accesslog errorlog"
2530 2530 for o in optlist.split():
2531 2531 if opts[o]:
2532 2532 ui.setconfig("web", o, opts[o])
2533 2533
2534 2534 if opts['daemon'] and not opts['daemon_pipefds']:
2535 2535 rfd, wfd = os.pipe()
2536 2536 args = sys.argv[:]
2537 2537 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2538 2538 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2539 2539 args[0], args)
2540 2540 os.close(wfd)
2541 2541 os.read(rfd, 1)
2542 2542 os._exit(0)
2543 2543
2544 2544 try:
2545 2545 httpd = hgweb.create_server(repo)
2546 2546 except socket.error, inst:
2547 2547 raise util.Abort(_('cannot start server: ') + inst.args[1])
2548 2548
2549 2549 if ui.verbose:
2550 2550 addr, port = httpd.socket.getsockname()
2551 2551 if addr == '0.0.0.0':
2552 2552 addr = socket.gethostname()
2553 2553 else:
2554 2554 try:
2555 2555 addr = socket.gethostbyaddr(addr)[0]
2556 2556 except socket.error:
2557 2557 pass
2558 2558 if port != 80:
2559 2559 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2560 2560 else:
2561 2561 ui.status(_('listening at http://%s/\n') % addr)
2562 2562
2563 2563 if opts['pid_file']:
2564 2564 fp = open(opts['pid_file'], 'w')
2565 2565 fp.write(str(os.getpid()))
2566 2566 fp.close()
2567 2567
2568 2568 if opts['daemon_pipefds']:
2569 2569 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2570 2570 os.close(rfd)
2571 2571 os.write(wfd, 'y')
2572 2572 os.close(wfd)
2573 2573 sys.stdout.flush()
2574 2574 sys.stderr.flush()
2575 2575 fd = os.open(util.nulldev, os.O_RDWR)
2576 2576 if fd != 0: os.dup2(fd, 0)
2577 2577 if fd != 1: os.dup2(fd, 1)
2578 2578 if fd != 2: os.dup2(fd, 2)
2579 2579 if fd not in (0, 1, 2): os.close(fd)
2580 2580
2581 2581 httpd.serve_forever()
2582 2582
2583 2583 def status(ui, repo, *pats, **opts):
2584 2584 """show changed files in the working directory
2585 2585
2586 2586 Show changed files in the repository. If names are
2587 2587 given, only files that match are shown.
2588 2588
2589 2589 The codes used to show the status of files are:
2590 2590 M = modified
2591 2591 A = added
2592 2592 R = removed
2593 2593 ! = deleted, but still tracked
2594 2594 ? = not tracked
2595 2595 I = ignored (not shown by default)
2596 2596 """
2597 2597
2598 2598 show_ignored = opts['ignored'] and True or False
2599 2599 files, matchfn, anypats = matchpats(repo, pats, opts)
2600 2600 cwd = (pats and repo.getcwd()) or ''
2601 2601 modified, added, removed, deleted, unknown, ignored = [
2602 2602 [util.pathto(cwd, x) for x in n]
2603 2603 for n in repo.changes(files=files, match=matchfn,
2604 2604 show_ignored=show_ignored)]
2605 2605
2606 2606 changetypes = [('modified', 'M', modified),
2607 2607 ('added', 'A', added),
2608 2608 ('removed', 'R', removed),
2609 2609 ('deleted', '!', deleted),
2610 2610 ('unknown', '?', unknown),
2611 2611 ('ignored', 'I', ignored)]
2612 2612
2613 2613 end = opts['print0'] and '\0' or '\n'
2614 2614
2615 2615 for opt, char, changes in ([ct for ct in changetypes if opts[ct[0]]]
2616 2616 or changetypes):
2617 2617 if opts['no_status']:
2618 2618 format = "%%s%s" % end
2619 2619 else:
2620 2620 format = "%s %%s%s" % (char, end)
2621 2621
2622 2622 for f in changes:
2623 2623 ui.write(format % f)
2624 2624
2625 2625 def tag(ui, repo, name, rev_=None, **opts):
2626 2626 """add a tag for the current tip or a given revision
2627 2627
2628 2628 Name a particular revision using <name>.
2629 2629
2630 2630 Tags are used to name particular revisions of the repository and are
2631 2631 very useful to compare different revision, to go back to significant
2632 2632 earlier versions or to mark branch points as releases, etc.
2633 2633
2634 2634 If no revision is given, the tip is used.
2635 2635
2636 2636 To facilitate version control, distribution, and merging of tags,
2637 2637 they are stored as a file named ".hgtags" which is managed
2638 2638 similarly to other project files and can be hand-edited if
2639 2639 necessary. The file '.hg/localtags' is used for local tags (not
2640 2640 shared among repositories).
2641 2641 """
2642 2642 if name == "tip":
2643 2643 raise util.Abort(_("the name 'tip' is reserved"))
2644 2644 if rev_ is not None:
2645 2645 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2646 2646 "please use 'hg tag [-r REV] NAME' instead\n"))
2647 2647 if opts['rev']:
2648 2648 raise util.Abort(_("use only one form to specify the revision"))
2649 2649 if opts['rev']:
2650 2650 rev_ = opts['rev']
2651 2651 if rev_:
2652 2652 r = hex(repo.lookup(rev_))
2653 2653 else:
2654 2654 r = hex(repo.changelog.tip())
2655 2655
2656 2656 disallowed = (revrangesep, '\r', '\n')
2657 2657 for c in disallowed:
2658 2658 if name.find(c) >= 0:
2659 2659 raise util.Abort(_("%s cannot be used in a tag name") % repr(c))
2660 2660
2661 2661 repo.hook('pretag', throw=True, node=r, tag=name,
2662 2662 local=int(not not opts['local']))
2663 2663
2664 2664 if opts['local']:
2665 2665 repo.opener("localtags", "a").write("%s %s\n" % (r, name))
2666 2666 repo.hook('tag', node=r, tag=name, local=1)
2667 2667 return
2668 2668
2669 2669 for x in repo.changes():
2670 2670 if ".hgtags" in x:
2671 2671 raise util.Abort(_("working copy of .hgtags is changed "
2672 2672 "(please commit .hgtags manually)"))
2673 2673
2674 2674 repo.wfile(".hgtags", "ab").write("%s %s\n" % (r, name))
2675 2675 if repo.dirstate.state(".hgtags") == '?':
2676 2676 repo.add([".hgtags"])
2677 2677
2678 2678 message = (opts['message'] or
2679 2679 _("Added tag %s for changeset %s") % (name, r))
2680 2680 try:
2681 2681 repo.commit([".hgtags"], message, opts['user'], opts['date'])
2682 2682 repo.hook('tag', node=r, tag=name, local=0)
2683 2683 except ValueError, inst:
2684 2684 raise util.Abort(str(inst))
2685 2685
2686 2686 def tags(ui, repo):
2687 2687 """list repository tags
2688 2688
2689 2689 List the repository tags.
2690 2690
2691 2691 This lists both regular and local tags.
2692 2692 """
2693 2693
2694 2694 l = repo.tagslist()
2695 2695 l.reverse()
2696 2696 for t, n in l:
2697 2697 try:
2698 2698 r = "%5d:%s" % (repo.changelog.rev(n), hex(n))
2699 2699 except KeyError:
2700 2700 r = " ?:?"
2701 2701 if ui.quiet:
2702 2702 ui.write("%s\n" % t)
2703 2703 else:
2704 2704 ui.write("%-30s %s\n" % (t, r))
2705 2705
2706 2706 def tip(ui, repo, **opts):
2707 2707 """show the tip revision
2708 2708
2709 2709 Show the tip revision.
2710 2710 """
2711 2711 n = repo.changelog.tip()
2712 2712 br = None
2713 2713 if opts['branches']:
2714 2714 br = repo.branchlookup([n])
2715 2715 show_changeset(ui, repo, opts).show(changenode=n, brinfo=br)
2716 2716 if opts['patch']:
2717 2717 dodiff(ui, ui, repo, repo.changelog.parents(n)[0], n)
2718 2718
2719 2719 def unbundle(ui, repo, fname, **opts):
2720 2720 """apply a changegroup file
2721 2721
2722 2722 Apply a compressed changegroup file generated by the bundle
2723 2723 command.
2724 2724 """
2725 2725 f = urllib.urlopen(fname)
2726 2726
2727 2727 header = f.read(6)
2728 2728 if not header.startswith("HG"):
2729 2729 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2730 2730 elif not header.startswith("HG10"):
2731 2731 raise util.Abort(_("%s: unknown bundle version") % fname)
2732 2732 elif header == "HG10BZ":
2733 2733 def generator(f):
2734 2734 zd = bz2.BZ2Decompressor()
2735 2735 zd.decompress("BZ")
2736 2736 for chunk in f:
2737 2737 yield zd.decompress(chunk)
2738 2738 elif header == "HG10UN":
2739 2739 def generator(f):
2740 2740 for chunk in f:
2741 2741 yield chunk
2742 2742 else:
2743 2743 raise util.Abort(_("%s: unknown bundle compression type")
2744 2744 % fname)
2745 2745 gen = generator(util.filechunkiter(f, 4096))
2746 2746 modheads = repo.addchangegroup(util.chunkbuffer(gen))
2747 2747 return postincoming(ui, repo, modheads, opts['update'])
2748 2748
2749 2749 def undo(ui, repo):
2750 2750 """undo the last commit or pull
2751 2751
2752 2752 Roll back the last pull or commit transaction on the
2753 2753 repository, restoring the project to its earlier state.
2754 2754
2755 2755 This command should be used with care. There is only one level of
2756 2756 undo and there is no redo.
2757 2757
2758 2758 This command is not intended for use on public repositories. Once
2759 2759 a change is visible for pull by other users, undoing it locally is
2760 2760 ineffective. Furthemore a race is possible with readers of the
2761 2761 repository, for example an ongoing pull from the repository will
2762 2762 fail and rollback.
2763 2763 """
2764 2764 repo.undo()
2765 2765
2766 2766 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2767 2767 branch=None, **opts):
2768 2768 """update or merge working directory
2769 2769
2770 2770 Update the working directory to the specified revision.
2771 2771
2772 2772 If there are no outstanding changes in the working directory and
2773 2773 there is a linear relationship between the current version and the
2774 2774 requested version, the result is the requested version.
2775 2775
2776 2776 Otherwise the result is a merge between the contents of the
2777 2777 current working directory and the requested version. Files that
2778 2778 changed between either parent are marked as changed for the next
2779 2779 commit and a commit must be performed before any further updates
2780 2780 are allowed.
2781 2781
2782 2782 By default, update will refuse to run if doing so would require
2783 2783 merging or discarding local changes.
2784 2784 """
2785 2785 if branch:
2786 2786 br = repo.branchlookup(branch=branch)
2787 2787 found = []
2788 2788 for x in br:
2789 2789 if branch in br[x]:
2790 2790 found.append(x)
2791 2791 if len(found) > 1:
2792 2792 ui.warn(_("Found multiple heads for %s\n") % branch)
2793 2793 for x in found:
2794 2794 show_changeset(ui, repo, opts).show(changenode=x, brinfo=br)
2795 2795 return 1
2796 2796 if len(found) == 1:
2797 2797 node = found[0]
2798 2798 ui.warn(_("Using head %s for branch %s\n") % (short(node), branch))
2799 2799 else:
2800 2800 ui.warn(_("branch %s not found\n") % (branch))
2801 2801 return 1
2802 2802 else:
2803 2803 node = node and repo.lookup(node) or repo.changelog.tip()
2804 2804 return repo.update(node, allow=merge, force=clean, forcemerge=force)
2805 2805
2806 2806 def verify(ui, repo):
2807 2807 """verify the integrity of the repository
2808 2808
2809 2809 Verify the integrity of the current repository.
2810 2810
2811 2811 This will perform an extensive check of the repository's
2812 2812 integrity, validating the hashes and checksums of each entry in
2813 2813 the changelog, manifest, and tracked files, as well as the
2814 2814 integrity of their crosslinks and indices.
2815 2815 """
2816 2816 return repo.verify()
2817 2817
2818 2818 # Command options and aliases are listed here, alphabetically
2819 2819
2820 2820 table = {
2821 2821 "^add":
2822 2822 (add,
2823 2823 [('I', 'include', [], _('include names matching the given patterns')),
2824 2824 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2825 2825 _('hg add [OPTION]... [FILE]...')),
2826 2826 "addremove":
2827 2827 (addremove,
2828 2828 [('I', 'include', [], _('include names matching the given patterns')),
2829 2829 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2830 2830 _('hg addremove [OPTION]... [FILE]...')),
2831 2831 "^annotate":
2832 2832 (annotate,
2833 2833 [('r', 'rev', '', _('annotate the specified revision')),
2834 2834 ('a', 'text', None, _('treat all files as text')),
2835 2835 ('u', 'user', None, _('list the author')),
2836 2836 ('d', 'date', None, _('list the date')),
2837 2837 ('n', 'number', None, _('list the revision number (default)')),
2838 2838 ('c', 'changeset', None, _('list the changeset')),
2839 2839 ('I', 'include', [], _('include names matching the given patterns')),
2840 2840 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2841 2841 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2842 2842 "bundle":
2843 2843 (bundle,
2844 2844 [('f', 'force', None,
2845 2845 _('run even when remote repository is unrelated'))],
2846 2846 _('hg bundle FILE DEST')),
2847 2847 "cat":
2848 2848 (cat,
2849 2849 [('o', 'output', '', _('print output to file with formatted name')),
2850 2850 ('r', 'rev', '', _('print the given revision')),
2851 2851 ('I', 'include', [], _('include names matching the given patterns')),
2852 2852 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2853 2853 _('hg cat [OPTION]... FILE...')),
2854 2854 "^clone":
2855 2855 (clone,
2856 2856 [('U', 'noupdate', None, _('do not update the new working directory')),
2857 2857 ('r', 'rev', [],
2858 2858 _('a changeset you would like to have after cloning')),
2859 2859 ('', 'pull', None, _('use pull protocol to copy metadata')),
2860 2860 ('e', 'ssh', '', _('specify ssh command to use')),
2861 2861 ('', 'remotecmd', '',
2862 2862 _('specify hg command to run on the remote side'))],
2863 2863 _('hg clone [OPTION]... SOURCE [DEST]')),
2864 2864 "^commit|ci":
2865 2865 (commit,
2866 2866 [('A', 'addremove', None, _('run addremove during commit')),
2867 2867 ('m', 'message', '', _('use <text> as commit message')),
2868 2868 ('l', 'logfile', '', _('read the commit message from <file>')),
2869 2869 ('d', 'date', '', _('record datecode as commit date')),
2870 2870 ('u', 'user', '', _('record user as commiter')),
2871 2871 ('I', 'include', [], _('include names matching the given patterns')),
2872 2872 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2873 2873 _('hg commit [OPTION]... [FILE]...')),
2874 2874 "copy|cp":
2875 2875 (copy,
2876 2876 [('A', 'after', None, _('record a copy that has already occurred')),
2877 2877 ('f', 'force', None,
2878 2878 _('forcibly copy over an existing managed file')),
2879 2879 ('I', 'include', [], _('include names matching the given patterns')),
2880 2880 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2881 2881 _('hg copy [OPTION]... [SOURCE]... DEST')),
2882 2882 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2883 2883 "debugcomplete":
2884 2884 (debugcomplete,
2885 2885 [('o', 'options', None, _('show the command options'))],
2886 2886 _('debugcomplete [-o] CMD')),
2887 2887 "debugrebuildstate":
2888 2888 (debugrebuildstate,
2889 2889 [('r', 'rev', '', _('revision to rebuild to'))],
2890 2890 _('debugrebuildstate [-r REV] [REV]')),
2891 2891 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2892 2892 "debugconfig": (debugconfig, [], _('debugconfig')),
2893 2893 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2894 2894 "debugstate": (debugstate, [], _('debugstate')),
2895 2895 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2896 2896 "debugindex": (debugindex, [], _('debugindex FILE')),
2897 2897 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2898 2898 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2899 2899 "debugwalk":
2900 2900 (debugwalk,
2901 2901 [('I', 'include', [], _('include names matching the given patterns')),
2902 2902 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2903 2903 _('debugwalk [OPTION]... [FILE]...')),
2904 2904 "^diff":
2905 2905 (diff,
2906 2906 [('r', 'rev', [], _('revision')),
2907 2907 ('a', 'text', None, _('treat all files as text')),
2908 2908 ('p', 'show-function', None,
2909 2909 _('show which function each change is in')),
2910 2910 ('w', 'ignore-all-space', None,
2911 2911 _('ignore white space when comparing lines')),
2912 2912 ('I', 'include', [], _('include names matching the given patterns')),
2913 2913 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2914 2914 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2915 2915 "^export":
2916 2916 (export,
2917 2917 [('o', 'output', '', _('print output to file with formatted name')),
2918 2918 ('a', 'text', None, _('treat all files as text')),
2919 2919 ('', 'switch-parent', None, _('diff against the second parent'))],
2920 2920 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2921 2921 "forget":
2922 2922 (forget,
2923 2923 [('I', 'include', [], _('include names matching the given patterns')),
2924 2924 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2925 2925 _('hg forget [OPTION]... FILE...')),
2926 2926 "grep":
2927 2927 (grep,
2928 2928 [('0', 'print0', None, _('end fields with NUL')),
2929 2929 ('', 'all', None, _('print all revisions that match')),
2930 2930 ('i', 'ignore-case', None, _('ignore case when matching')),
2931 2931 ('l', 'files-with-matches', None,
2932 2932 _('print only filenames and revs that match')),
2933 2933 ('n', 'line-number', None, _('print matching line numbers')),
2934 2934 ('r', 'rev', [], _('search in given revision range')),
2935 2935 ('u', 'user', None, _('print user who committed change')),
2936 2936 ('I', 'include', [], _('include names matching the given patterns')),
2937 2937 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2938 2938 _('hg grep [OPTION]... PATTERN [FILE]...')),
2939 2939 "heads":
2940 2940 (heads,
2941 2941 [('b', 'branches', None, _('show branches')),
2942 2942 ('', 'style', '', _('display using template map file')),
2943 2943 ('r', 'rev', '', _('show only heads which are descendants of rev')),
2944 2944 ('', 'template', '', _('display with template'))],
2945 2945 _('hg heads [-b] [-r <rev>]')),
2946 2946 "help": (help_, [], _('hg help [COMMAND]')),
2947 2947 "identify|id": (identify, [], _('hg identify')),
2948 2948 "import|patch":
2949 2949 (import_,
2950 2950 [('p', 'strip', 1,
2951 2951 _('directory strip option for patch. This has the same\n') +
2952 2952 _('meaning as the corresponding patch option')),
2953 2953 ('b', 'base', '', _('base path')),
2954 2954 ('f', 'force', None,
2955 2955 _('skip check for outstanding uncommitted changes'))],
2956 2956 _('hg import [-p NUM] [-b BASE] [-f] PATCH...')),
2957 2957 "incoming|in": (incoming,
2958 2958 [('M', 'no-merges', None, _('do not show merges')),
2959 2959 ('f', 'force', None,
2960 2960 _('run even when remote repository is unrelated')),
2961 2961 ('', 'style', '', _('display using template map file')),
2962 2962 ('n', 'newest-first', None, _('show newest record first')),
2963 2963 ('', 'bundle', '', _('file to store the bundles into')),
2964 2964 ('p', 'patch', None, _('show patch')),
2965 2965 ('', 'template', '', _('display with template')),
2966 2966 ('e', 'ssh', '', _('specify ssh command to use')),
2967 2967 ('', 'remotecmd', '',
2968 2968 _('specify hg command to run on the remote side'))],
2969 2969 _('hg incoming [-p] [-n] [-M] [--bundle FILENAME] [SOURCE]')),
2970 2970 "^init": (init, [], _('hg init [DEST]')),
2971 2971 "locate":
2972 2972 (locate,
2973 2973 [('r', 'rev', '', _('search the repository as it stood at rev')),
2974 2974 ('0', 'print0', None,
2975 2975 _('end filenames with NUL, for use with xargs')),
2976 2976 ('f', 'fullpath', None,
2977 2977 _('print complete paths from the filesystem root')),
2978 2978 ('I', 'include', [], _('include names matching the given patterns')),
2979 2979 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2980 2980 _('hg locate [OPTION]... [PATTERN]...')),
2981 2981 "^log|history":
2982 2982 (log,
2983 2983 [('b', 'branches', None, _('show branches')),
2984 2984 ('k', 'keyword', [], _('search for a keyword')),
2985 2985 ('l', 'limit', '', _('limit number of changes displayed')),
2986 2986 ('r', 'rev', [], _('show the specified revision or range')),
2987 2987 ('M', 'no-merges', None, _('do not show merges')),
2988 2988 ('', 'style', '', _('display using template map file')),
2989 2989 ('m', 'only-merges', None, _('show only merges')),
2990 2990 ('p', 'patch', None, _('show patch')),
2991 2991 ('', 'template', '', _('display with template')),
2992 2992 ('I', 'include', [], _('include names matching the given patterns')),
2993 2993 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2994 2994 _('hg log [OPTION]... [FILE]')),
2995 2995 "manifest": (manifest, [], _('hg manifest [REV]')),
2996 2996 "merge":
2997 2997 (merge,
2998 2998 [('b', 'branch', '', _('merge with head of a specific branch')),
2999 2999 ('f', 'force', None, _('force a merge with outstanding changes'))],
3000 3000 _('hg merge [-b TAG] [-f] [REV]')),
3001 3001 "outgoing|out": (outgoing,
3002 3002 [('M', 'no-merges', None, _('do not show merges')),
3003 3003 ('f', 'force', None,
3004 3004 _('run even when remote repository is unrelated')),
3005 3005 ('p', 'patch', None, _('show patch')),
3006 3006 ('', 'style', '', _('display using template map file')),
3007 3007 ('n', 'newest-first', None, _('show newest record first')),
3008 3008 ('', 'template', '', _('display with template')),
3009 3009 ('e', 'ssh', '', _('specify ssh command to use')),
3010 3010 ('', 'remotecmd', '',
3011 3011 _('specify hg command to run on the remote side'))],
3012 3012 _('hg outgoing [-M] [-p] [-n] [DEST]')),
3013 3013 "^parents":
3014 3014 (parents,
3015 3015 [('b', 'branches', None, _('show branches')),
3016 3016 ('', 'style', '', _('display using template map file')),
3017 3017 ('', 'template', '', _('display with template'))],
3018 3018 _('hg parents [-b] [REV]')),
3019 3019 "paths": (paths, [], _('hg paths [NAME]')),
3020 3020 "^pull":
3021 3021 (pull,
3022 3022 [('u', 'update', None,
3023 3023 _('update the working directory to tip after pull')),
3024 3024 ('e', 'ssh', '', _('specify ssh command to use')),
3025 3025 ('f', 'force', None,
3026 3026 _('run even when remote repository is unrelated')),
3027 3027 ('r', 'rev', [], _('a specific revision you would like to pull')),
3028 3028 ('', 'remotecmd', '',
3029 3029 _('specify hg command to run on the remote side'))],
3030 3030 _('hg pull [-u] [-e FILE] [-r REV]... [--remotecmd FILE] [SOURCE]')),
3031 3031 "^push":
3032 3032 (push,
3033 3033 [('f', 'force', None, _('force push')),
3034 3034 ('e', 'ssh', '', _('specify ssh command to use')),
3035 3035 ('r', 'rev', [], _('a specific revision you would like to push')),
3036 3036 ('', 'remotecmd', '',
3037 3037 _('specify hg command to run on the remote side'))],
3038 3038 _('hg push [-f] [-e FILE] [-r REV]... [--remotecmd FILE] [DEST]')),
3039 3039 "debugrawcommit|rawcommit":
3040 3040 (rawcommit,
3041 3041 [('p', 'parent', [], _('parent')),
3042 3042 ('d', 'date', '', _('date code')),
3043 3043 ('u', 'user', '', _('user')),
3044 3044 ('F', 'files', '', _('file list')),
3045 3045 ('m', 'message', '', _('commit message')),
3046 3046 ('l', 'logfile', '', _('commit message file'))],
3047 3047 _('hg debugrawcommit [OPTION]... [FILE]...')),
3048 3048 "recover": (recover, [], _('hg recover')),
3049 3049 "^remove|rm":
3050 3050 (remove,
3051 3051 [('f', 'force', None, _('remove file even if modified')),
3052 3052 ('I', 'include', [], _('include names matching the given patterns')),
3053 3053 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
3054 3054 _('hg remove [OPTION]... FILE...')),
3055 3055 "rename|mv":
3056 3056 (rename,
3057 3057 [('A', 'after', None, _('record a rename that has already occurred')),
3058 3058 ('f', 'force', None,
3059 3059 _('forcibly copy over an existing managed file')),
3060 3060 ('I', 'include', [], _('include names matching the given patterns')),
3061 3061 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
3062 3062 _('hg rename [OPTION]... SOURCE... DEST')),
3063 3063 "^revert":
3064 3064 (revert,
3065 3065 [('r', 'rev', '', _('revision to revert to')),
3066 3066 ('', 'no-backup', None, _('do not save backup copies of files')),
3067 3067 ('I', 'include', [], _('include names matching given patterns')),
3068 3068 ('X', 'exclude', [], _('exclude names matching given patterns'))],
3069 3069 _('hg revert [-r REV] [NAME]...')),
3070 3070 "root": (root, [], _('hg root')),
3071 3071 "^serve":
3072 3072 (serve,
3073 3073 [('A', 'accesslog', '', _('name of access log file to write to')),
3074 3074 ('d', 'daemon', None, _('run server in background')),
3075 3075 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3076 3076 ('E', 'errorlog', '', _('name of error log file to write to')),
3077 3077 ('p', 'port', 0, _('port to use (default: 8000)')),
3078 3078 ('a', 'address', '', _('address to use')),
3079 3079 ('n', 'name', '',
3080 3080 _('name to show in web pages (default: working dir)')),
3081 3081 ('', 'pid-file', '', _('name of file to write process ID to')),
3082 3082 ('', 'stdio', None, _('for remote clients')),
3083 3083 ('t', 'templates', '', _('web templates to use')),
3084 3084 ('', 'style', '', _('template style to use')),
3085 3085 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
3086 3086 _('hg serve [OPTION]...')),
3087 3087 "^status|st":
3088 3088 (status,
3089 3089 [('m', 'modified', None, _('show only modified files')),
3090 3090 ('a', 'added', None, _('show only added files')),
3091 3091 ('r', 'removed', None, _('show only removed files')),
3092 3092 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3093 3093 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3094 3094 ('i', 'ignored', None, _('show ignored files')),
3095 3095 ('n', 'no-status', None, _('hide status prefix')),
3096 3096 ('0', 'print0', None,
3097 3097 _('end filenames with NUL, for use with xargs')),
3098 3098 ('I', 'include', [], _('include names matching the given patterns')),
3099 3099 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
3100 3100 _('hg status [OPTION]... [FILE]...')),
3101 3101 "tag":
3102 3102 (tag,
3103 3103 [('l', 'local', None, _('make the tag local')),
3104 3104 ('m', 'message', '', _('message for tag commit log entry')),
3105 3105 ('d', 'date', '', _('record datecode as commit date')),
3106 3106 ('u', 'user', '', _('record user as commiter')),
3107 3107 ('r', 'rev', '', _('revision to tag'))],
3108 3108 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3109 3109 "tags": (tags, [], _('hg tags')),
3110 3110 "tip":
3111 3111 (tip,
3112 3112 [('b', 'branches', None, _('show branches')),
3113 3113 ('', 'style', '', _('display using template map file')),
3114 3114 ('p', 'patch', None, _('show patch')),
3115 3115 ('', 'template', '', _('display with template'))],
3116 3116 _('hg tip [-b] [-p]')),
3117 3117 "unbundle":
3118 3118 (unbundle,
3119 3119 [('u', 'update', None,
3120 3120 _('update the working directory to tip after unbundle'))],
3121 3121 _('hg unbundle [-u] FILE')),
3122 3122 "undo": (undo, [], _('hg undo')),
3123 3123 "^update|up|checkout|co":
3124 3124 (update,
3125 3125 [('b', 'branch', '', _('checkout the head of a specific branch')),
3126 3126 ('m', 'merge', None, _('allow merging of branches')),
3127 3127 ('C', 'clean', None, _('overwrite locally modified files')),
3128 3128 ('f', 'force', None, _('force a merge with outstanding changes'))],
3129 3129 _('hg update [-b TAG] [-m] [-C] [-f] [REV]')),
3130 3130 "verify": (verify, [], _('hg verify')),
3131 3131 "version": (show_version, [], _('hg version')),
3132 3132 }
3133 3133
3134 3134 globalopts = [
3135 3135 ('R', 'repository', '',
3136 3136 _('repository root directory or symbolic path name')),
3137 3137 ('', 'cwd', '', _('change working directory')),
3138 3138 ('y', 'noninteractive', None,
3139 3139 _('do not prompt, assume \'yes\' for any required answers')),
3140 3140 ('q', 'quiet', None, _('suppress output')),
3141 3141 ('v', 'verbose', None, _('enable additional output')),
3142 3142 ('', 'debug', None, _('enable debugging output')),
3143 3143 ('', 'debugger', None, _('start debugger')),
3144 3144 ('', 'traceback', None, _('print traceback on exception')),
3145 3145 ('', 'time', None, _('time how long the command takes')),
3146 3146 ('', 'profile', None, _('print command execution profile')),
3147 3147 ('', 'version', None, _('output version information and exit')),
3148 3148 ('h', 'help', None, _('display help and exit')),
3149 3149 ]
3150 3150
3151 3151 norepo = ("clone init version help debugancestor debugcomplete debugdata"
3152 3152 " debugindex debugindexdot")
3153 3153 optionalrepo = ("paths debugconfig")
3154 3154
3155 3155 def findpossible(cmd):
3156 3156 """
3157 3157 Return cmd -> (aliases, command table entry)
3158 3158 for each matching command.
3159 3159 Return debug commands (or their aliases) only if no normal command matches.
3160 3160 """
3161 3161 choice = {}
3162 3162 debugchoice = {}
3163 3163 for e in table.keys():
3164 3164 aliases = e.lstrip("^").split("|")
3165 3165 found = None
3166 3166 if cmd in aliases:
3167 3167 found = cmd
3168 3168 else:
3169 3169 for a in aliases:
3170 3170 if a.startswith(cmd):
3171 3171 found = a
3172 3172 break
3173 3173 if found is not None:
3174 3174 if aliases[0].startswith("debug"):
3175 3175 debugchoice[found] = (aliases, table[e])
3176 3176 else:
3177 3177 choice[found] = (aliases, table[e])
3178 3178
3179 3179 if not choice and debugchoice:
3180 3180 choice = debugchoice
3181 3181
3182 3182 return choice
3183 3183
3184 3184 def find(cmd):
3185 3185 """Return (aliases, command table entry) for command string."""
3186 3186 choice = findpossible(cmd)
3187 3187
3188 3188 if choice.has_key(cmd):
3189 3189 return choice[cmd]
3190 3190
3191 3191 if len(choice) > 1:
3192 3192 clist = choice.keys()
3193 3193 clist.sort()
3194 3194 raise AmbiguousCommand(cmd, clist)
3195 3195
3196 3196 if choice:
3197 3197 return choice.values()[0]
3198 3198
3199 3199 raise UnknownCommand(cmd)
3200 3200
3201 3201 class SignalInterrupt(Exception):
3202 3202 """Exception raised on SIGTERM and SIGHUP."""
3203 3203
3204 3204 def catchterm(*args):
3205 3205 raise SignalInterrupt
3206 3206
3207 3207 def run():
3208 3208 sys.exit(dispatch(sys.argv[1:]))
3209 3209
3210 3210 class ParseError(Exception):
3211 3211 """Exception raised on errors in parsing the command line."""
3212 3212
3213 3213 def parse(ui, args):
3214 3214 options = {}
3215 3215 cmdoptions = {}
3216 3216
3217 3217 try:
3218 3218 args = fancyopts.fancyopts(args, globalopts, options)
3219 3219 except fancyopts.getopt.GetoptError, inst:
3220 3220 raise ParseError(None, inst)
3221 3221
3222 3222 if args:
3223 3223 cmd, args = args[0], args[1:]
3224 3224 aliases, i = find(cmd)
3225 3225 cmd = aliases[0]
3226 3226 defaults = ui.config("defaults", cmd)
3227 3227 if defaults:
3228 3228 args = defaults.split() + args
3229 3229 c = list(i[1])
3230 3230 else:
3231 3231 cmd = None
3232 3232 c = []
3233 3233
3234 3234 # combine global options into local
3235 3235 for o in globalopts:
3236 3236 c.append((o[0], o[1], options[o[1]], o[3]))
3237 3237
3238 3238 try:
3239 3239 args = fancyopts.fancyopts(args, c, cmdoptions)
3240 3240 except fancyopts.getopt.GetoptError, inst:
3241 3241 raise ParseError(cmd, inst)
3242 3242
3243 3243 # separate global options back out
3244 3244 for o in globalopts:
3245 3245 n = o[1]
3246 3246 options[n] = cmdoptions[n]
3247 3247 del cmdoptions[n]
3248 3248
3249 3249 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
3250 3250
3251 3251 def dispatch(args):
3252 signal.signal(signal.SIGTERM, catchterm)
3253 try:
3254 signal.signal(signal.SIGHUP, catchterm)
3255 except AttributeError:
3256 pass
3252 for name in 'SIGTERM', 'SIGHUP', 'SIGBREAK':
3253 num = getattr(signal, name, None)
3254 if num: signal.signal(num, catchterm)
3257 3255
3258 3256 try:
3259 3257 u = ui.ui()
3260 3258 except util.Abort, inst:
3261 3259 sys.stderr.write(_("abort: %s\n") % inst)
3262 3260 return -1
3263 3261
3264 3262 external = []
3265 3263 for x in u.extensions():
3266 3264 try:
3267 3265 if x[1]:
3268 3266 mod = imp.load_source(x[0], x[1])
3269 3267 else:
3270 3268 def importh(name):
3271 3269 mod = __import__(name)
3272 3270 components = name.split('.')
3273 3271 for comp in components[1:]:
3274 3272 mod = getattr(mod, comp)
3275 3273 return mod
3276 3274 try:
3277 3275 mod = importh("hgext." + x[0])
3278 3276 except ImportError:
3279 3277 mod = importh(x[0])
3280 3278 external.append(mod)
3281 3279 except Exception, inst:
3282 3280 u.warn(_("*** failed to import extension %s: %s\n") % (x[0], inst))
3283 3281 if "--traceback" in sys.argv[1:]:
3284 3282 traceback.print_exc()
3285 3283 return 1
3286 3284 continue
3287 3285
3288 3286 for x in external:
3289 3287 cmdtable = getattr(x, 'cmdtable', {})
3290 3288 for t in cmdtable:
3291 3289 if t in table:
3292 3290 u.warn(_("module %s overrides %s\n") % (x.__name__, t))
3293 3291 table.update(cmdtable)
3294 3292
3295 3293 try:
3296 3294 cmd, func, args, options, cmdoptions = parse(u, args)
3297 3295 if options["time"]:
3298 3296 def get_times():
3299 3297 t = os.times()
3300 3298 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
3301 3299 t = (t[0], t[1], t[2], t[3], time.clock())
3302 3300 return t
3303 3301 s = get_times()
3304 3302 def print_time():
3305 3303 t = get_times()
3306 3304 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
3307 3305 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
3308 3306 atexit.register(print_time)
3309 3307
3310 3308 u.updateopts(options["verbose"], options["debug"], options["quiet"],
3311 3309 not options["noninteractive"])
3312 3310
3313 3311 # enter the debugger before command execution
3314 3312 if options['debugger']:
3315 3313 pdb.set_trace()
3316 3314
3317 3315 try:
3318 3316 if options['cwd']:
3319 3317 try:
3320 3318 os.chdir(options['cwd'])
3321 3319 except OSError, inst:
3322 3320 raise util.Abort('%s: %s' %
3323 3321 (options['cwd'], inst.strerror))
3324 3322
3325 3323 path = u.expandpath(options["repository"]) or ""
3326 3324 repo = path and hg.repository(u, path=path) or None
3327 3325
3328 3326 if options['help']:
3329 3327 return help_(u, cmd, options['version'])
3330 3328 elif options['version']:
3331 3329 return show_version(u)
3332 3330 elif not cmd:
3333 3331 return help_(u, 'shortlist')
3334 3332
3335 3333 if cmd not in norepo.split():
3336 3334 try:
3337 3335 if not repo:
3338 3336 repo = hg.repository(u, path=path)
3339 3337 u = repo.ui
3340 3338 for x in external:
3341 3339 if hasattr(x, 'reposetup'):
3342 3340 x.reposetup(u, repo)
3343 3341 except hg.RepoError:
3344 3342 if cmd not in optionalrepo.split():
3345 3343 raise
3346 3344 d = lambda: func(u, repo, *args, **cmdoptions)
3347 3345 else:
3348 3346 d = lambda: func(u, *args, **cmdoptions)
3349 3347
3350 3348 try:
3351 3349 if options['profile']:
3352 3350 import hotshot, hotshot.stats
3353 3351 prof = hotshot.Profile("hg.prof")
3354 3352 try:
3355 3353 try:
3356 3354 return prof.runcall(d)
3357 3355 except:
3358 3356 try:
3359 3357 u.warn(_('exception raised - generating '
3360 3358 'profile anyway\n'))
3361 3359 except:
3362 3360 pass
3363 3361 raise
3364 3362 finally:
3365 3363 prof.close()
3366 3364 stats = hotshot.stats.load("hg.prof")
3367 3365 stats.strip_dirs()
3368 3366 stats.sort_stats('time', 'calls')
3369 3367 stats.print_stats(40)
3370 3368 else:
3371 3369 return d()
3372 3370 finally:
3373 3371 u.flush()
3374 3372 except:
3375 3373 # enter the debugger when we hit an exception
3376 3374 if options['debugger']:
3377 3375 pdb.post_mortem(sys.exc_info()[2])
3378 3376 if options['traceback']:
3379 3377 traceback.print_exc()
3380 3378 raise
3381 3379 except ParseError, inst:
3382 3380 if inst.args[0]:
3383 3381 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
3384 3382 help_(u, inst.args[0])
3385 3383 else:
3386 3384 u.warn(_("hg: %s\n") % inst.args[1])
3387 3385 help_(u, 'shortlist')
3388 3386 except AmbiguousCommand, inst:
3389 3387 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
3390 3388 (inst.args[0], " ".join(inst.args[1])))
3391 3389 except UnknownCommand, inst:
3392 3390 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
3393 3391 help_(u, 'shortlist')
3394 3392 except hg.RepoError, inst:
3395 3393 u.warn(_("abort: "), inst, "!\n")
3396 3394 except lock.LockHeld, inst:
3397 3395 if inst.errno == errno.ETIMEDOUT:
3398 3396 reason = _('timed out waiting for lock held by %s') % inst.locker
3399 3397 else:
3400 3398 reason = _('lock held by %s') % inst.locker
3401 3399 u.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
3402 3400 except lock.LockUnavailable, inst:
3403 3401 u.warn(_("abort: could not lock %s: %s\n") %
3404 3402 (inst.desc or inst.filename, inst.strerror))
3405 3403 except revlog.RevlogError, inst:
3406 3404 u.warn(_("abort: "), inst, "!\n")
3407 3405 except SignalInterrupt:
3408 3406 u.warn(_("killed!\n"))
3409 3407 except KeyboardInterrupt:
3410 3408 try:
3411 3409 u.warn(_("interrupted!\n"))
3412 3410 except IOError, inst:
3413 3411 if inst.errno == errno.EPIPE:
3414 3412 if u.debugflag:
3415 3413 u.warn(_("\nbroken pipe\n"))
3416 3414 else:
3417 3415 raise
3418 3416 except IOError, inst:
3419 3417 if hasattr(inst, "code"):
3420 3418 u.warn(_("abort: %s\n") % inst)
3421 3419 elif hasattr(inst, "reason"):
3422 3420 u.warn(_("abort: error: %s\n") % inst.reason[1])
3423 3421 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
3424 3422 if u.debugflag:
3425 3423 u.warn(_("broken pipe\n"))
3426 3424 elif getattr(inst, "strerror", None):
3427 3425 if getattr(inst, "filename", None):
3428 3426 u.warn(_("abort: %s - %s\n") % (inst.strerror, inst.filename))
3429 3427 else:
3430 3428 u.warn(_("abort: %s\n") % inst.strerror)
3431 3429 else:
3432 3430 raise
3433 3431 except OSError, inst:
3434 3432 if hasattr(inst, "filename"):
3435 3433 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
3436 3434 else:
3437 3435 u.warn(_("abort: %s\n") % inst.strerror)
3438 3436 except util.Abort, inst:
3439 3437 u.warn(_('abort: '), inst.args[0] % inst.args[1:], '\n')
3440 3438 except TypeError, inst:
3441 3439 # was this an argument error?
3442 3440 tb = traceback.extract_tb(sys.exc_info()[2])
3443 3441 if len(tb) > 2: # no
3444 3442 raise
3445 3443 u.debug(inst, "\n")
3446 3444 u.warn(_("%s: invalid arguments\n") % cmd)
3447 3445 help_(u, cmd)
3448 3446 except SystemExit, inst:
3449 3447 # Commands shouldn't sys.exit directly, but give a return code.
3450 3448 # Just in case catch this and and pass exit code to caller.
3451 3449 return inst.code
3452 3450 except:
3453 3451 u.warn(_("** unknown exception encountered, details follow\n"))
3454 3452 u.warn(_("** report bug details to mercurial@selenic.com\n"))
3455 3453 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
3456 3454 % version.get_version())
3457 3455 raise
3458 3456
3459 3457 return -1
@@ -1,1085 +1,1086 b''
1 1 # hgweb.py - web interface to a mercurial repository
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005 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, cgi, sys
10 10 import mimetypes
11 11 from demandload import demandload
12 12 demandload(globals(), "mdiff time re socket zlib errno ui hg ConfigParser")
13 13 demandload(globals(), "zipfile tempfile StringIO tarfile BaseHTTPServer util")
14 14 demandload(globals(), "mimetypes templater")
15 15 from node import *
16 16 from i18n import gettext as _
17 17
18 18 def up(p):
19 19 if p[0] != "/":
20 20 p = "/" + p
21 21 if p[-1] == "/":
22 22 p = p[:-1]
23 23 up = os.path.dirname(p)
24 24 if up == "/":
25 25 return "/"
26 26 return up + "/"
27 27
28 28 def get_mtime(repo_path):
29 29 hg_path = os.path.join(repo_path, ".hg")
30 30 cl_path = os.path.join(hg_path, "00changelog.i")
31 31 if os.path.exists(os.path.join(cl_path)):
32 32 return os.stat(cl_path).st_mtime
33 33 else:
34 34 return os.stat(hg_path).st_mtime
35 35
36 36 def staticfile(directory, fname):
37 37 """return a file inside directory with guessed content-type header
38 38
39 39 fname always uses '/' as directory separator and isn't allowed to
40 40 contain unusual path components.
41 41 Content-type is guessed using the mimetypes module.
42 42 Return an empty string if fname is illegal or file not found.
43 43
44 44 """
45 45 parts = fname.split('/')
46 46 path = directory
47 47 for part in parts:
48 48 if (part in ('', os.curdir, os.pardir) or
49 49 os.sep in part or os.altsep is not None and os.altsep in part):
50 50 return ""
51 51 path = os.path.join(path, part)
52 52 try:
53 53 os.stat(path)
54 54 ct = mimetypes.guess_type(path)[0] or "text/plain"
55 55 return "Content-type: %s\n\n%s" % (ct, file(path).read())
56 56 except (TypeError, OSError):
57 57 # illegal fname or unreadable file
58 58 return ""
59 59
60 60 class hgrequest(object):
61 61 def __init__(self, inp=None, out=None, env=None):
62 62 self.inp = inp or sys.stdin
63 63 self.out = out or sys.stdout
64 64 self.env = env or os.environ
65 65 self.form = cgi.parse(self.inp, self.env, keep_blank_values=1)
66 66
67 67 def write(self, *things):
68 68 for thing in things:
69 69 if hasattr(thing, "__iter__"):
70 70 for part in thing:
71 71 self.write(part)
72 72 else:
73 73 try:
74 74 self.out.write(str(thing))
75 75 except socket.error, inst:
76 76 if inst[0] != errno.ECONNRESET:
77 77 raise
78 78
79 79 def header(self, headers=[('Content-type','text/html')]):
80 80 for header in headers:
81 81 self.out.write("%s: %s\r\n" % header)
82 82 self.out.write("\r\n")
83 83
84 84 def httphdr(self, type, file="", size=0):
85 85
86 86 headers = [('Content-type', type)]
87 87 if file:
88 88 headers.append(('Content-disposition', 'attachment; filename=%s' % file))
89 89 if size > 0:
90 90 headers.append(('Content-length', str(size)))
91 91 self.header(headers)
92 92
93 93 class hgweb(object):
94 94 def __init__(self, repo, name=None):
95 95 if type(repo) == type(""):
96 96 self.repo = hg.repository(ui.ui(), repo)
97 97 else:
98 98 self.repo = repo
99 99
100 100 self.mtime = -1
101 101 self.reponame = name
102 102 self.archives = 'zip', 'gz', 'bz2'
103 103
104 104 def refresh(self):
105 105 mtime = get_mtime(self.repo.root)
106 106 if mtime != self.mtime:
107 107 self.mtime = mtime
108 108 self.repo = hg.repository(self.repo.ui, self.repo.root)
109 109 self.maxchanges = int(self.repo.ui.config("web", "maxchanges", 10))
110 110 self.maxfiles = int(self.repo.ui.config("web", "maxfiles", 10))
111 111 self.allowpull = self.repo.ui.configbool("web", "allowpull", True)
112 112
113 113 def archivelist(self, nodeid):
114 114 for i in self.archives:
115 115 if self.repo.ui.configbool("web", "allow" + i, False):
116 116 yield {"type" : i, "node" : nodeid}
117 117
118 118 def listfiles(self, files, mf):
119 119 for f in files[:self.maxfiles]:
120 120 yield self.t("filenodelink", node=hex(mf[f]), file=f)
121 121 if len(files) > self.maxfiles:
122 122 yield self.t("fileellipses")
123 123
124 124 def listfilediffs(self, files, changeset):
125 125 for f in files[:self.maxfiles]:
126 126 yield self.t("filedifflink", node=hex(changeset), file=f)
127 127 if len(files) > self.maxfiles:
128 128 yield self.t("fileellipses")
129 129
130 130 def siblings(self, siblings=[], rev=None, hiderev=None, **args):
131 131 if not rev:
132 132 rev = lambda x: ""
133 133 siblings = [s for s in siblings if s != nullid]
134 134 if len(siblings) == 1 and rev(siblings[0]) == hiderev:
135 135 return
136 136 for s in siblings:
137 137 yield dict(node=hex(s), rev=rev(s), **args)
138 138
139 139 def renamelink(self, fl, node):
140 140 r = fl.renamed(node)
141 141 if r:
142 142 return [dict(file=r[0], node=hex(r[1]))]
143 143 return []
144 144
145 145 def showtag(self, t1, node=nullid, **args):
146 146 for t in self.repo.nodetags(node):
147 147 yield self.t(t1, tag=t, **args)
148 148
149 149 def diff(self, node1, node2, files):
150 150 def filterfiles(filters, files):
151 151 l = [x for x in files if x in filters]
152 152
153 153 for t in filters:
154 154 if t and t[-1] != os.sep:
155 155 t += os.sep
156 156 l += [x for x in files if x.startswith(t)]
157 157 return l
158 158
159 159 parity = [0]
160 160 def diffblock(diff, f, fn):
161 161 yield self.t("diffblock",
162 162 lines=prettyprintlines(diff),
163 163 parity=parity[0],
164 164 file=f,
165 165 filenode=hex(fn or nullid))
166 166 parity[0] = 1 - parity[0]
167 167
168 168 def prettyprintlines(diff):
169 169 for l in diff.splitlines(1):
170 170 if l.startswith('+'):
171 171 yield self.t("difflineplus", line=l)
172 172 elif l.startswith('-'):
173 173 yield self.t("difflineminus", line=l)
174 174 elif l.startswith('@'):
175 175 yield self.t("difflineat", line=l)
176 176 else:
177 177 yield self.t("diffline", line=l)
178 178
179 179 r = self.repo
180 180 cl = r.changelog
181 181 mf = r.manifest
182 182 change1 = cl.read(node1)
183 183 change2 = cl.read(node2)
184 184 mmap1 = mf.read(change1[0])
185 185 mmap2 = mf.read(change2[0])
186 186 date1 = util.datestr(change1[2])
187 187 date2 = util.datestr(change2[2])
188 188
189 189 modified, added, removed, deleted, unknown = r.changes(node1, node2)
190 190 if files:
191 191 modified, added, removed = map(lambda x: filterfiles(files, x),
192 192 (modified, added, removed))
193 193
194 194 diffopts = self.repo.ui.diffopts()
195 195 showfunc = diffopts['showfunc']
196 196 ignorews = diffopts['ignorews']
197 197 for f in modified:
198 198 to = r.file(f).read(mmap1[f])
199 199 tn = r.file(f).read(mmap2[f])
200 200 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
201 201 showfunc=showfunc, ignorews=ignorews), f, tn)
202 202 for f in added:
203 203 to = None
204 204 tn = r.file(f).read(mmap2[f])
205 205 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
206 206 showfunc=showfunc, ignorews=ignorews), f, tn)
207 207 for f in removed:
208 208 to = r.file(f).read(mmap1[f])
209 209 tn = None
210 210 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
211 211 showfunc=showfunc, ignorews=ignorews), f, tn)
212 212
213 213 def changelog(self, pos):
214 214 def changenav(**map):
215 215 def seq(factor, maxchanges=None):
216 216 if maxchanges:
217 217 yield maxchanges
218 218 if maxchanges >= 20 and maxchanges <= 40:
219 219 yield 50
220 220 else:
221 221 yield 1 * factor
222 222 yield 3 * factor
223 223 for f in seq(factor * 10):
224 224 yield f
225 225
226 226 l = []
227 227 last = 0
228 228 for f in seq(1, self.maxchanges):
229 229 if f < self.maxchanges or f <= last:
230 230 continue
231 231 if f > count:
232 232 break
233 233 last = f
234 234 r = "%d" % f
235 235 if pos + f < count:
236 236 l.append(("+" + r, pos + f))
237 237 if pos - f >= 0:
238 238 l.insert(0, ("-" + r, pos - f))
239 239
240 240 yield {"rev": 0, "label": "(0)"}
241 241
242 242 for label, rev in l:
243 243 yield {"label": label, "rev": rev}
244 244
245 245 yield {"label": "tip", "rev": "tip"}
246 246
247 247 def changelist(**map):
248 248 parity = (start - end) & 1
249 249 cl = self.repo.changelog
250 250 l = [] # build a list in forward order for efficiency
251 251 for i in range(start, end):
252 252 n = cl.node(i)
253 253 changes = cl.read(n)
254 254 hn = hex(n)
255 255
256 256 l.insert(0, {"parity": parity,
257 257 "author": changes[1],
258 258 "parent": self.siblings(cl.parents(n), cl.rev,
259 259 cl.rev(n) - 1),
260 260 "child": self.siblings(cl.children(n), cl.rev,
261 261 cl.rev(n) + 1),
262 262 "changelogtag": self.showtag("changelogtag",n),
263 263 "manifest": hex(changes[0]),
264 264 "desc": changes[4],
265 265 "date": changes[2],
266 266 "files": self.listfilediffs(changes[3], n),
267 267 "rev": i,
268 268 "node": hn})
269 269 parity = 1 - parity
270 270
271 271 for e in l:
272 272 yield e
273 273
274 274 cl = self.repo.changelog
275 275 mf = cl.read(cl.tip())[0]
276 276 count = cl.count()
277 277 start = max(0, pos - self.maxchanges + 1)
278 278 end = min(count, start + self.maxchanges)
279 279 pos = end - 1
280 280
281 281 yield self.t('changelog',
282 282 changenav=changenav,
283 283 manifest=hex(mf),
284 284 rev=pos, changesets=count, entries=changelist)
285 285
286 286 def search(self, query):
287 287
288 288 def changelist(**map):
289 289 cl = self.repo.changelog
290 290 count = 0
291 291 qw = query.lower().split()
292 292
293 293 def revgen():
294 294 for i in range(cl.count() - 1, 0, -100):
295 295 l = []
296 296 for j in range(max(0, i - 100), i):
297 297 n = cl.node(j)
298 298 changes = cl.read(n)
299 299 l.append((n, j, changes))
300 300 l.reverse()
301 301 for e in l:
302 302 yield e
303 303
304 304 for n, i, changes in revgen():
305 305 miss = 0
306 306 for q in qw:
307 307 if not (q in changes[1].lower() or
308 308 q in changes[4].lower() or
309 309 q in " ".join(changes[3][:20]).lower()):
310 310 miss = 1
311 311 break
312 312 if miss:
313 313 continue
314 314
315 315 count += 1
316 316 hn = hex(n)
317 317
318 318 yield self.t('searchentry',
319 319 parity=count & 1,
320 320 author=changes[1],
321 321 parent=self.siblings(cl.parents(n), cl.rev),
322 322 child=self.siblings(cl.children(n), cl.rev),
323 323 changelogtag=self.showtag("changelogtag",n),
324 324 manifest=hex(changes[0]),
325 325 desc=changes[4],
326 326 date=changes[2],
327 327 files=self.listfilediffs(changes[3], n),
328 328 rev=i,
329 329 node=hn)
330 330
331 331 if count >= self.maxchanges:
332 332 break
333 333
334 334 cl = self.repo.changelog
335 335 mf = cl.read(cl.tip())[0]
336 336
337 337 yield self.t('search',
338 338 query=query,
339 339 manifest=hex(mf),
340 340 entries=changelist)
341 341
342 342 def changeset(self, nodeid):
343 343 cl = self.repo.changelog
344 344 n = self.repo.lookup(nodeid)
345 345 nodeid = hex(n)
346 346 changes = cl.read(n)
347 347 p1 = cl.parents(n)[0]
348 348
349 349 files = []
350 350 mf = self.repo.manifest.read(changes[0])
351 351 for f in changes[3]:
352 352 files.append(self.t("filenodelink",
353 353 filenode=hex(mf.get(f, nullid)), file=f))
354 354
355 355 def diff(**map):
356 356 yield self.diff(p1, n, None)
357 357
358 358 yield self.t('changeset',
359 359 diff=diff,
360 360 rev=cl.rev(n),
361 361 node=nodeid,
362 362 parent=self.siblings(cl.parents(n), cl.rev),
363 363 child=self.siblings(cl.children(n), cl.rev),
364 364 changesettag=self.showtag("changesettag",n),
365 365 manifest=hex(changes[0]),
366 366 author=changes[1],
367 367 desc=changes[4],
368 368 date=changes[2],
369 369 files=files,
370 370 archives=self.archivelist(nodeid))
371 371
372 372 def filelog(self, f, filenode):
373 373 cl = self.repo.changelog
374 374 fl = self.repo.file(f)
375 375 filenode = hex(fl.lookup(filenode))
376 376 count = fl.count()
377 377
378 378 def entries(**map):
379 379 l = []
380 380 parity = (count - 1) & 1
381 381
382 382 for i in range(count):
383 383 n = fl.node(i)
384 384 lr = fl.linkrev(n)
385 385 cn = cl.node(lr)
386 386 cs = cl.read(cl.node(lr))
387 387
388 388 l.insert(0, {"parity": parity,
389 389 "filenode": hex(n),
390 390 "filerev": i,
391 391 "file": f,
392 392 "node": hex(cn),
393 393 "author": cs[1],
394 394 "date": cs[2],
395 395 "rename": self.renamelink(fl, n),
396 396 "parent": self.siblings(fl.parents(n),
397 397 fl.rev, file=f),
398 398 "child": self.siblings(fl.children(n),
399 399 fl.rev, file=f),
400 400 "desc": cs[4]})
401 401 parity = 1 - parity
402 402
403 403 for e in l:
404 404 yield e
405 405
406 406 yield self.t("filelog", file=f, filenode=filenode, entries=entries)
407 407
408 408 def filerevision(self, f, node):
409 409 fl = self.repo.file(f)
410 410 n = fl.lookup(node)
411 411 node = hex(n)
412 412 text = fl.read(n)
413 413 changerev = fl.linkrev(n)
414 414 cl = self.repo.changelog
415 415 cn = cl.node(changerev)
416 416 cs = cl.read(cn)
417 417 mfn = cs[0]
418 418
419 419 mt = mimetypes.guess_type(f)[0]
420 420 rawtext = text
421 421 if util.binary(text):
422 text = "(binary:%s)" % mt
422 text = "(binary:%s)" % (mt or 'data')
423 mt = mt or 'text/plain'
423 424
424 425 def lines():
425 426 for l, t in enumerate(text.splitlines(1)):
426 427 yield {"line": t,
427 428 "linenumber": "% 6d" % (l + 1),
428 429 "parity": l & 1}
429 430
430 431 yield self.t("filerevision",
431 432 file=f,
432 433 filenode=node,
433 434 path=up(f),
434 435 text=lines(),
435 436 raw=rawtext,
436 437 mimetype=mt,
437 438 rev=changerev,
438 439 node=hex(cn),
439 440 manifest=hex(mfn),
440 441 author=cs[1],
441 442 date=cs[2],
442 443 parent=self.siblings(fl.parents(n), fl.rev, file=f),
443 444 child=self.siblings(fl.children(n), fl.rev, file=f),
444 445 rename=self.renamelink(fl, n),
445 446 permissions=self.repo.manifest.readflags(mfn)[f])
446 447
447 448 def fileannotate(self, f, node):
448 449 bcache = {}
449 450 ncache = {}
450 451 fl = self.repo.file(f)
451 452 n = fl.lookup(node)
452 453 node = hex(n)
453 454 changerev = fl.linkrev(n)
454 455
455 456 cl = self.repo.changelog
456 457 cn = cl.node(changerev)
457 458 cs = cl.read(cn)
458 459 mfn = cs[0]
459 460
460 461 def annotate(**map):
461 462 parity = 1
462 463 last = None
463 464 for r, l in fl.annotate(n):
464 465 try:
465 466 cnode = ncache[r]
466 467 except KeyError:
467 468 cnode = ncache[r] = self.repo.changelog.node(r)
468 469
469 470 try:
470 471 name = bcache[r]
471 472 except KeyError:
472 473 cl = self.repo.changelog.read(cnode)
473 474 bcache[r] = name = self.repo.ui.shortuser(cl[1])
474 475
475 476 if last != cnode:
476 477 parity = 1 - parity
477 478 last = cnode
478 479
479 480 yield {"parity": parity,
480 481 "node": hex(cnode),
481 482 "rev": r,
482 483 "author": name,
483 484 "file": f,
484 485 "line": l}
485 486
486 487 yield self.t("fileannotate",
487 488 file=f,
488 489 filenode=node,
489 490 annotate=annotate,
490 491 path=up(f),
491 492 rev=changerev,
492 493 node=hex(cn),
493 494 manifest=hex(mfn),
494 495 author=cs[1],
495 496 date=cs[2],
496 497 rename=self.renamelink(fl, n),
497 498 parent=self.siblings(fl.parents(n), fl.rev, file=f),
498 499 child=self.siblings(fl.children(n), fl.rev, file=f),
499 500 permissions=self.repo.manifest.readflags(mfn)[f])
500 501
501 502 def manifest(self, mnode, path):
502 503 man = self.repo.manifest
503 504 mn = man.lookup(mnode)
504 505 mnode = hex(mn)
505 506 mf = man.read(mn)
506 507 rev = man.rev(mn)
507 508 node = self.repo.changelog.node(rev)
508 509 mff = man.readflags(mn)
509 510
510 511 files = {}
511 512
512 513 p = path[1:]
513 514 if p and p[-1] != "/":
514 515 p += "/"
515 516 l = len(p)
516 517
517 518 for f,n in mf.items():
518 519 if f[:l] != p:
519 520 continue
520 521 remain = f[l:]
521 522 if "/" in remain:
522 523 short = remain[:remain.find("/") + 1] # bleah
523 524 files[short] = (f, None)
524 525 else:
525 526 short = os.path.basename(remain)
526 527 files[short] = (f, n)
527 528
528 529 def filelist(**map):
529 530 parity = 0
530 531 fl = files.keys()
531 532 fl.sort()
532 533 for f in fl:
533 534 full, fnode = files[f]
534 535 if not fnode:
535 536 continue
536 537
537 538 yield {"file": full,
538 539 "manifest": mnode,
539 540 "filenode": hex(fnode),
540 541 "parity": parity,
541 542 "basename": f,
542 543 "permissions": mff[full]}
543 544 parity = 1 - parity
544 545
545 546 def dirlist(**map):
546 547 parity = 0
547 548 fl = files.keys()
548 549 fl.sort()
549 550 for f in fl:
550 551 full, fnode = files[f]
551 552 if fnode:
552 553 continue
553 554
554 555 yield {"parity": parity,
555 556 "path": os.path.join(path, f),
556 557 "manifest": mnode,
557 558 "basename": f[:-1]}
558 559 parity = 1 - parity
559 560
560 561 yield self.t("manifest",
561 562 manifest=mnode,
562 563 rev=rev,
563 564 node=hex(node),
564 565 path=path,
565 566 up=up(path),
566 567 fentries=filelist,
567 568 dentries=dirlist,
568 569 archives=self.archivelist(hex(node)))
569 570
570 571 def tags(self):
571 572 cl = self.repo.changelog
572 573 mf = cl.read(cl.tip())[0]
573 574
574 575 i = self.repo.tagslist()
575 576 i.reverse()
576 577
577 578 def entries(notip=False, **map):
578 579 parity = 0
579 580 for k,n in i:
580 581 if notip and k == "tip": continue
581 582 yield {"parity": parity,
582 583 "tag": k,
583 584 "tagmanifest": hex(cl.read(n)[0]),
584 585 "date": cl.read(n)[2],
585 586 "node": hex(n)}
586 587 parity = 1 - parity
587 588
588 589 yield self.t("tags",
589 590 manifest=hex(mf),
590 591 entries=lambda **x: entries(False, **x),
591 592 entriesnotip=lambda **x: entries(True, **x))
592 593
593 594 def summary(self):
594 595 cl = self.repo.changelog
595 596 mf = cl.read(cl.tip())[0]
596 597
597 598 i = self.repo.tagslist()
598 599 i.reverse()
599 600
600 601 def tagentries(**map):
601 602 parity = 0
602 603 count = 0
603 604 for k,n in i:
604 605 if k == "tip": # skip tip
605 606 continue;
606 607
607 608 count += 1
608 609 if count > 10: # limit to 10 tags
609 610 break;
610 611
611 612 c = cl.read(n)
612 613 m = c[0]
613 614 t = c[2]
614 615
615 616 yield self.t("tagentry",
616 617 parity = parity,
617 618 tag = k,
618 619 node = hex(n),
619 620 date = t,
620 621 tagmanifest = hex(m))
621 622 parity = 1 - parity
622 623
623 624 def changelist(**map):
624 625 parity = 0
625 626 cl = self.repo.changelog
626 627 l = [] # build a list in forward order for efficiency
627 628 for i in range(start, end):
628 629 n = cl.node(i)
629 630 changes = cl.read(n)
630 631 hn = hex(n)
631 632 t = changes[2]
632 633
633 634 l.insert(0, self.t(
634 635 'shortlogentry',
635 636 parity = parity,
636 637 author = changes[1],
637 638 manifest = hex(changes[0]),
638 639 desc = changes[4],
639 640 date = t,
640 641 rev = i,
641 642 node = hn))
642 643 parity = 1 - parity
643 644
644 645 yield l
645 646
646 647 cl = self.repo.changelog
647 648 mf = cl.read(cl.tip())[0]
648 649 count = cl.count()
649 650 start = max(0, count - self.maxchanges)
650 651 end = min(count, start + self.maxchanges)
651 652 pos = end - 1
652 653
653 654 yield self.t("summary",
654 655 desc = self.repo.ui.config("web", "description", "unknown"),
655 656 owner = (self.repo.ui.config("ui", "username") or # preferred
656 657 self.repo.ui.config("web", "contact") or # deprecated
657 658 self.repo.ui.config("web", "author", "unknown")), # also
658 659 lastchange = (0, 0), # FIXME
659 660 manifest = hex(mf),
660 661 tags = tagentries,
661 662 shortlog = changelist)
662 663
663 664 def filediff(self, file, changeset):
664 665 cl = self.repo.changelog
665 666 n = self.repo.lookup(changeset)
666 667 changeset = hex(n)
667 668 p1 = cl.parents(n)[0]
668 669 cs = cl.read(n)
669 670 mf = self.repo.manifest.read(cs[0])
670 671
671 672 def diff(**map):
672 673 yield self.diff(p1, n, file)
673 674
674 675 yield self.t("filediff",
675 676 file=file,
676 677 filenode=hex(mf.get(file, nullid)),
677 678 node=changeset,
678 679 rev=self.repo.changelog.rev(n),
679 680 parent=self.siblings(cl.parents(n), cl.rev),
680 681 child=self.siblings(cl.children(n), cl.rev),
681 682 diff=diff)
682 683
683 684 def archive(self, req, cnode, type):
684 685 cs = self.repo.changelog.read(cnode)
685 686 mnode = cs[0]
686 687 mf = self.repo.manifest.read(mnode)
687 688 rev = self.repo.manifest.rev(mnode)
688 689 reponame = re.sub(r"\W+", "-", self.reponame)
689 690 name = "%s-%s/" % (reponame, short(cnode))
690 691
691 692 files = mf.keys()
692 693 files.sort()
693 694
694 695 if type == 'zip':
695 696 tmp = tempfile.mkstemp()[1]
696 697 try:
697 698 zf = zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED)
698 699
699 700 for f in files:
700 701 zf.writestr(name + f, self.repo.file(f).read(mf[f]))
701 702 zf.close()
702 703
703 704 f = open(tmp, 'r')
704 705 req.httphdr('application/zip', name[:-1] + '.zip',
705 706 os.path.getsize(tmp))
706 707 req.write(f.read())
707 708 f.close()
708 709 finally:
709 710 os.unlink(tmp)
710 711
711 712 else:
712 713 tf = tarfile.TarFile.open(mode='w|' + type, fileobj=req.out)
713 714 mff = self.repo.manifest.readflags(mnode)
714 715 mtime = int(time.time())
715 716
716 717 if type == "gz":
717 718 encoding = "gzip"
718 719 else:
719 720 encoding = "x-bzip2"
720 721 req.header([('Content-type', 'application/x-tar'),
721 722 ('Content-disposition', 'attachment; filename=%s%s%s' %
722 723 (name[:-1], '.tar.', type)),
723 724 ('Content-encoding', encoding)])
724 725 for fname in files:
725 726 rcont = self.repo.file(fname).read(mf[fname])
726 727 finfo = tarfile.TarInfo(name + fname)
727 728 finfo.mtime = mtime
728 729 finfo.size = len(rcont)
729 730 finfo.mode = mff[fname] and 0755 or 0644
730 731 tf.addfile(finfo, StringIO.StringIO(rcont))
731 732 tf.close()
732 733
733 734 # add tags to things
734 735 # tags -> list of changesets corresponding to tags
735 736 # find tag, changeset, file
736 737
737 738 def run(self, req=hgrequest()):
738 739 def clean(path):
739 740 p = util.normpath(path)
740 741 if p[:2] == "..":
741 742 raise "suspicious path"
742 743 return p
743 744
744 745 def header(**map):
745 746 yield self.t("header", **map)
746 747
747 748 def footer(**map):
748 749 yield self.t("footer", **map)
749 750
750 751 def expand_form(form):
751 752 shortcuts = {
752 753 'cl': [('cmd', ['changelog']), ('rev', None)],
753 754 'cs': [('cmd', ['changeset']), ('node', None)],
754 755 'f': [('cmd', ['file']), ('filenode', None)],
755 756 'fl': [('cmd', ['filelog']), ('filenode', None)],
756 757 'fd': [('cmd', ['filediff']), ('node', None)],
757 758 'fa': [('cmd', ['annotate']), ('filenode', None)],
758 759 'mf': [('cmd', ['manifest']), ('manifest', None)],
759 760 'ca': [('cmd', ['archive']), ('node', None)],
760 761 'tags': [('cmd', ['tags'])],
761 762 'tip': [('cmd', ['changeset']), ('node', ['tip'])],
762 763 'static': [('cmd', ['static']), ('file', None)]
763 764 }
764 765
765 766 for k in shortcuts.iterkeys():
766 767 if form.has_key(k):
767 768 for name, value in shortcuts[k]:
768 769 if value is None:
769 770 value = form[k]
770 771 form[name] = value
771 772 del form[k]
772 773
773 774 self.refresh()
774 775
775 776 expand_form(req.form)
776 777
777 778 t = self.repo.ui.config("web", "templates", templater.templatepath())
778 779 static = self.repo.ui.config("web", "static", os.path.join(t,"static"))
779 780 m = os.path.join(t, "map")
780 781 style = self.repo.ui.config("web", "style", "")
781 782 if req.form.has_key('style'):
782 783 style = req.form['style'][0]
783 784 if style:
784 785 b = os.path.basename("map-" + style)
785 786 p = os.path.join(t, b)
786 787 if os.path.isfile(p):
787 788 m = p
788 789
789 790 port = req.env["SERVER_PORT"]
790 791 port = port != "80" and (":" + port) or ""
791 792 uri = req.env["REQUEST_URI"]
792 793 if "?" in uri:
793 794 uri = uri.split("?")[0]
794 795 url = "http://%s%s%s" % (req.env["SERVER_NAME"], port, uri)
795 796 if not self.reponame:
796 797 self.reponame = (self.repo.ui.config("web", "name")
797 798 or uri.strip('/') or self.repo.root)
798 799
799 800 self.t = templater.templater(m, templater.common_filters,
800 801 defaults={"url": url,
801 802 "repo": self.reponame,
802 803 "header": header,
803 804 "footer": footer,
804 805 })
805 806
806 807 if not req.form.has_key('cmd'):
807 808 req.form['cmd'] = [self.t.cache['default'],]
808 809
809 810 if req.form['cmd'][0] == 'changelog':
810 811 c = self.repo.changelog.count() - 1
811 812 hi = c
812 813 if req.form.has_key('rev'):
813 814 hi = req.form['rev'][0]
814 815 try:
815 816 hi = self.repo.changelog.rev(self.repo.lookup(hi))
816 817 except hg.RepoError:
817 818 req.write(self.search(hi))
818 819 return
819 820
820 821 req.write(self.changelog(hi))
821 822
822 823 elif req.form['cmd'][0] == 'changeset':
823 824 req.write(self.changeset(req.form['node'][0]))
824 825
825 826 elif req.form['cmd'][0] == 'manifest':
826 827 req.write(self.manifest(req.form['manifest'][0],
827 828 clean(req.form['path'][0])))
828 829
829 830 elif req.form['cmd'][0] == 'tags':
830 831 req.write(self.tags())
831 832
832 833 elif req.form['cmd'][0] == 'summary':
833 834 req.write(self.summary())
834 835
835 836 elif req.form['cmd'][0] == 'filediff':
836 837 req.write(self.filediff(clean(req.form['file'][0]),
837 838 req.form['node'][0]))
838 839
839 840 elif req.form['cmd'][0] == 'file':
840 841 req.write(self.filerevision(clean(req.form['file'][0]),
841 842 req.form['filenode'][0]))
842 843
843 844 elif req.form['cmd'][0] == 'annotate':
844 845 req.write(self.fileannotate(clean(req.form['file'][0]),
845 846 req.form['filenode'][0]))
846 847
847 848 elif req.form['cmd'][0] == 'filelog':
848 849 req.write(self.filelog(clean(req.form['file'][0]),
849 850 req.form['filenode'][0]))
850 851
851 852 elif req.form['cmd'][0] == 'heads':
852 853 req.httphdr("application/mercurial-0.1")
853 854 h = self.repo.heads()
854 855 req.write(" ".join(map(hex, h)) + "\n")
855 856
856 857 elif req.form['cmd'][0] == 'branches':
857 858 req.httphdr("application/mercurial-0.1")
858 859 nodes = []
859 860 if req.form.has_key('nodes'):
860 861 nodes = map(bin, req.form['nodes'][0].split(" "))
861 862 for b in self.repo.branches(nodes):
862 863 req.write(" ".join(map(hex, b)) + "\n")
863 864
864 865 elif req.form['cmd'][0] == 'between':
865 866 req.httphdr("application/mercurial-0.1")
866 867 nodes = []
867 868 if req.form.has_key('pairs'):
868 869 pairs = [map(bin, p.split("-"))
869 870 for p in req.form['pairs'][0].split(" ")]
870 871 for b in self.repo.between(pairs):
871 872 req.write(" ".join(map(hex, b)) + "\n")
872 873
873 874 elif req.form['cmd'][0] == 'changegroup':
874 875 req.httphdr("application/mercurial-0.1")
875 876 nodes = []
876 877 if not self.allowpull:
877 878 return
878 879
879 880 if req.form.has_key('roots'):
880 881 nodes = map(bin, req.form['roots'][0].split(" "))
881 882
882 883 z = zlib.compressobj()
883 884 f = self.repo.changegroup(nodes, 'serve')
884 885 while 1:
885 886 chunk = f.read(4096)
886 887 if not chunk:
887 888 break
888 889 req.write(z.compress(chunk))
889 890
890 891 req.write(z.flush())
891 892
892 893 elif req.form['cmd'][0] == 'archive':
893 894 changeset = self.repo.lookup(req.form['node'][0])
894 895 type = req.form['type'][0]
895 896 if (type in self.archives and
896 897 self.repo.ui.configbool("web", "allow" + type, False)):
897 898 self.archive(req, changeset, type)
898 899 return
899 900
900 901 req.write(self.t("error"))
901 902
902 903 elif req.form['cmd'][0] == 'static':
903 904 fname = req.form['file'][0]
904 905 req.write(staticfile(static, fname)
905 906 or self.t("error", error="%r not found" % fname))
906 907
907 908 else:
908 909 req.write(self.t("error"))
909 910
910 911 def create_server(repo):
911 912
912 913 def openlog(opt, default):
913 914 if opt and opt != '-':
914 915 return open(opt, 'w')
915 916 return default
916 917
917 918 address = repo.ui.config("web", "address", "")
918 919 port = int(repo.ui.config("web", "port", 8000))
919 920 use_ipv6 = repo.ui.configbool("web", "ipv6")
920 921 accesslog = openlog(repo.ui.config("web", "accesslog", "-"), sys.stdout)
921 922 errorlog = openlog(repo.ui.config("web", "errorlog", "-"), sys.stderr)
922 923
923 924 class IPv6HTTPServer(BaseHTTPServer.HTTPServer):
924 925 address_family = getattr(socket, 'AF_INET6', None)
925 926
926 927 def __init__(self, *args, **kwargs):
927 928 if self.address_family is None:
928 929 raise hg.RepoError(_('IPv6 not available on this system'))
929 930 BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
930 931
931 932 class hgwebhandler(BaseHTTPServer.BaseHTTPRequestHandler):
932 933 def log_error(self, format, *args):
933 934 errorlog.write("%s - - [%s] %s\n" % (self.address_string(),
934 935 self.log_date_time_string(),
935 936 format % args))
936 937
937 938 def log_message(self, format, *args):
938 939 accesslog.write("%s - - [%s] %s\n" % (self.address_string(),
939 940 self.log_date_time_string(),
940 941 format % args))
941 942
942 943 def do_POST(self):
943 944 try:
944 945 self.do_hgweb()
945 946 except socket.error, inst:
946 947 if inst[0] != errno.EPIPE:
947 948 raise
948 949
949 950 def do_GET(self):
950 951 self.do_POST()
951 952
952 953 def do_hgweb(self):
953 954 query = ""
954 955 p = self.path.find("?")
955 956 if p:
956 957 query = self.path[p + 1:]
957 958 query = query.replace('+', ' ')
958 959
959 960 env = {}
960 961 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
961 962 env['REQUEST_METHOD'] = self.command
962 963 env['SERVER_NAME'] = self.server.server_name
963 964 env['SERVER_PORT'] = str(self.server.server_port)
964 965 env['REQUEST_URI'] = "/"
965 966 if query:
966 967 env['QUERY_STRING'] = query
967 968 host = self.address_string()
968 969 if host != self.client_address[0]:
969 970 env['REMOTE_HOST'] = host
970 971 env['REMOTE_ADDR'] = self.client_address[0]
971 972
972 973 if self.headers.typeheader is None:
973 974 env['CONTENT_TYPE'] = self.headers.type
974 975 else:
975 976 env['CONTENT_TYPE'] = self.headers.typeheader
976 977 length = self.headers.getheader('content-length')
977 978 if length:
978 979 env['CONTENT_LENGTH'] = length
979 980 accept = []
980 981 for line in self.headers.getallmatchingheaders('accept'):
981 982 if line[:1] in "\t\n\r ":
982 983 accept.append(line.strip())
983 984 else:
984 985 accept = accept + line[7:].split(',')
985 986 env['HTTP_ACCEPT'] = ','.join(accept)
986 987
987 988 req = hgrequest(self.rfile, self.wfile, env)
988 989 self.send_response(200, "Script output follows")
989 990 hg.run(req)
990 991
991 992 hg = hgweb(repo)
992 993 if use_ipv6:
993 994 return IPv6HTTPServer((address, port), hgwebhandler)
994 995 else:
995 996 return BaseHTTPServer.HTTPServer((address, port), hgwebhandler)
996 997
997 998 # This is a stopgap
998 999 class hgwebdir(object):
999 1000 def __init__(self, config):
1000 1001 def cleannames(items):
1001 1002 return [(name.strip(os.sep), path) for name, path in items]
1002 1003
1003 1004 if isinstance(config, (list, tuple)):
1004 1005 self.repos = cleannames(config)
1005 1006 elif isinstance(config, dict):
1006 1007 self.repos = cleannames(config.items())
1007 1008 self.repos.sort()
1008 1009 else:
1009 1010 cp = ConfigParser.SafeConfigParser()
1010 1011 cp.read(config)
1011 1012 self.repos = []
1012 1013 if cp.has_section('paths'):
1013 1014 self.repos.extend(cleannames(cp.items('paths')))
1014 1015 if cp.has_section('collections'):
1015 1016 for prefix, root in cp.items('collections'):
1016 1017 for path in util.walkrepos(root):
1017 1018 repo = os.path.normpath(path)
1018 1019 name = repo
1019 1020 if name.startswith(prefix):
1020 1021 name = name[len(prefix):]
1021 1022 self.repos.append((name.lstrip(os.sep), repo))
1022 1023 self.repos.sort()
1023 1024
1024 1025 def run(self, req=hgrequest()):
1025 1026 def header(**map):
1026 1027 yield tmpl("header", **map)
1027 1028
1028 1029 def footer(**map):
1029 1030 yield tmpl("footer", **map)
1030 1031
1031 1032 m = os.path.join(templater.templatepath(), "map")
1032 1033 tmpl = templater.templater(m, templater.common_filters,
1033 1034 defaults={"header": header,
1034 1035 "footer": footer})
1035 1036
1036 1037 def entries(**map):
1037 1038 parity = 0
1038 1039 for name, path in self.repos:
1039 1040 u = ui.ui()
1040 1041 try:
1041 1042 u.readconfig(os.path.join(path, '.hg', 'hgrc'))
1042 1043 except IOError:
1043 1044 pass
1044 1045 get = u.config
1045 1046
1046 1047 url = ('/'.join([req.env["REQUEST_URI"].split('?')[0], name])
1047 1048 .replace("//", "/"))
1048 1049
1049 1050 # update time with local timezone
1050 1051 try:
1051 1052 d = (get_mtime(path), util.makedate()[1])
1052 1053 except OSError:
1053 1054 continue
1054 1055
1055 1056 yield dict(contact=(get("ui", "username") or # preferred
1056 1057 get("web", "contact") or # deprecated
1057 1058 get("web", "author", "unknown")), # also
1058 1059 name=get("web", "name", name),
1059 1060 url=url,
1060 1061 parity=parity,
1061 1062 shortdesc=get("web", "description", "unknown"),
1062 1063 lastupdate=d)
1063 1064
1064 1065 parity = 1 - parity
1065 1066
1066 1067 virtual = req.env.get("PATH_INFO", "").strip('/')
1067 1068 if virtual:
1068 1069 real = dict(self.repos).get(virtual)
1069 1070 if real:
1070 1071 try:
1071 1072 hgweb(real).run(req)
1072 1073 except IOError, inst:
1073 1074 req.write(tmpl("error", error=inst.strerror))
1074 1075 except hg.RepoError, inst:
1075 1076 req.write(tmpl("error", error=str(inst)))
1076 1077 else:
1077 1078 req.write(tmpl("notfound", repo=virtual))
1078 1079 else:
1079 1080 if req.form.has_key('static'):
1080 1081 static = os.path.join(templater.templatepath(), "static")
1081 1082 fname = req.form['static'][0]
1082 1083 req.write(staticfile(static, fname)
1083 1084 or tmpl("error", error="%r not found" % fname))
1084 1085 else:
1085 1086 req.write(tmpl("index", entries=entries))
@@ -1,814 +1,818 b''
1 1 """
2 2 util.py - Mercurial utility functions and platform specfic implementations
3 3
4 4 Copyright 2005 K. Thananchayan <thananck@yahoo.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 This contains helper routines that are independent of the SCM core and hide
10 10 platform-specific details from the core.
11 11 """
12 12
13 13 import os, errno
14 14 from i18n import gettext as _
15 15 from demandload import *
16 16 demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
17 17 demandload(globals(), "threading time")
18 18
19 19 def pipefilter(s, cmd):
20 20 '''filter string S through command CMD, returning its output'''
21 21 (pout, pin) = popen2.popen2(cmd, -1, 'b')
22 22 def writer():
23 pin.write(s)
24 pin.close()
23 try:
24 pin.write(s)
25 pin.close()
26 except IOError, inst:
27 if inst.errno != errno.EPIPE:
28 raise
25 29
26 30 # we should use select instead on UNIX, but this will work on most
27 31 # systems, including Windows
28 32 w = threading.Thread(target=writer)
29 33 w.start()
30 34 f = pout.read()
31 35 pout.close()
32 36 w.join()
33 37 return f
34 38
35 39 def tempfilter(s, cmd):
36 40 '''filter string S through a pair of temporary files with CMD.
37 41 CMD is used as a template to create the real command to be run,
38 42 with the strings INFILE and OUTFILE replaced by the real names of
39 43 the temporary files generated.'''
40 44 inname, outname = None, None
41 45 try:
42 46 infd, inname = tempfile.mkstemp(prefix='hgfin')
43 47 fp = os.fdopen(infd, 'wb')
44 48 fp.write(s)
45 49 fp.close()
46 50 outfd, outname = tempfile.mkstemp(prefix='hgfout')
47 51 os.close(outfd)
48 52 cmd = cmd.replace('INFILE', inname)
49 53 cmd = cmd.replace('OUTFILE', outname)
50 54 code = os.system(cmd)
51 55 if code: raise Abort(_("command '%s' failed: %s") %
52 56 (cmd, explain_exit(code)))
53 57 return open(outname, 'rb').read()
54 58 finally:
55 59 try:
56 60 if inname: os.unlink(inname)
57 61 except: pass
58 62 try:
59 63 if outname: os.unlink(outname)
60 64 except: pass
61 65
62 66 filtertable = {
63 67 'tempfile:': tempfilter,
64 68 'pipe:': pipefilter,
65 69 }
66 70
67 71 def filter(s, cmd):
68 72 "filter a string through a command that transforms its input to its output"
69 73 for name, fn in filtertable.iteritems():
70 74 if cmd.startswith(name):
71 75 return fn(s, cmd[len(name):].lstrip())
72 76 return pipefilter(s, cmd)
73 77
74 78 def find_in_path(name, path, default=None):
75 79 '''find name in search path. path can be string (will be split
76 80 with os.pathsep), or iterable thing that returns strings. if name
77 81 found, return path to name. else return default.'''
78 82 if isinstance(path, str):
79 83 path = path.split(os.pathsep)
80 84 for p in path:
81 85 p_name = os.path.join(p, name)
82 86 if os.path.exists(p_name):
83 87 return p_name
84 88 return default
85 89
86 90 def patch(strip, patchname, ui):
87 91 """apply the patch <patchname> to the working directory.
88 92 a list of patched files is returned"""
89 93 patcher = find_in_path('gpatch', os.environ.get('PATH', ''), 'patch')
90 94 fp = os.popen('"%s" -p%d < "%s"' % (patcher, strip, patchname))
91 95 files = {}
92 96 for line in fp:
93 97 line = line.rstrip()
94 98 ui.status("%s\n" % line)
95 99 if line.startswith('patching file '):
96 100 pf = parse_patch_output(line)
97 101 files.setdefault(pf, 1)
98 102 code = fp.close()
99 103 if code:
100 104 raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
101 105 return files.keys()
102 106
103 107 def binary(s):
104 108 """return true if a string is binary data using diff's heuristic"""
105 109 if s and '\0' in s[:4096]:
106 110 return True
107 111 return False
108 112
109 113 def unique(g):
110 114 """return the uniq elements of iterable g"""
111 115 seen = {}
112 116 for f in g:
113 117 if f not in seen:
114 118 seen[f] = 1
115 119 yield f
116 120
117 121 class Abort(Exception):
118 122 """Raised if a command needs to print an error and exit."""
119 123
120 124 def always(fn): return True
121 125 def never(fn): return False
122 126
123 127 def patkind(name, dflt_pat='glob'):
124 128 """Split a string into an optional pattern kind prefix and the
125 129 actual pattern."""
126 130 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
127 131 if name.startswith(prefix + ':'): return name.split(':', 1)
128 132 return dflt_pat, name
129 133
130 134 def globre(pat, head='^', tail='$'):
131 135 "convert a glob pattern into a regexp"
132 136 i, n = 0, len(pat)
133 137 res = ''
134 138 group = False
135 139 def peek(): return i < n and pat[i]
136 140 while i < n:
137 141 c = pat[i]
138 142 i = i+1
139 143 if c == '*':
140 144 if peek() == '*':
141 145 i += 1
142 146 res += '.*'
143 147 else:
144 148 res += '[^/]*'
145 149 elif c == '?':
146 150 res += '.'
147 151 elif c == '[':
148 152 j = i
149 153 if j < n and pat[j] in '!]':
150 154 j += 1
151 155 while j < n and pat[j] != ']':
152 156 j += 1
153 157 if j >= n:
154 158 res += '\\['
155 159 else:
156 160 stuff = pat[i:j].replace('\\','\\\\')
157 161 i = j + 1
158 162 if stuff[0] == '!':
159 163 stuff = '^' + stuff[1:]
160 164 elif stuff[0] == '^':
161 165 stuff = '\\' + stuff
162 166 res = '%s[%s]' % (res, stuff)
163 167 elif c == '{':
164 168 group = True
165 169 res += '(?:'
166 170 elif c == '}' and group:
167 171 res += ')'
168 172 group = False
169 173 elif c == ',' and group:
170 174 res += '|'
171 175 elif c == '\\':
172 176 p = peek()
173 177 if p:
174 178 i += 1
175 179 res += re.escape(p)
176 180 else:
177 181 res += re.escape(c)
178 182 else:
179 183 res += re.escape(c)
180 184 return head + res + tail
181 185
182 186 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
183 187
184 188 def pathto(n1, n2):
185 189 '''return the relative path from one place to another.
186 190 this returns a path in the form used by the local filesystem, not hg.'''
187 191 if not n1: return localpath(n2)
188 192 a, b = n1.split('/'), n2.split('/')
189 193 a.reverse()
190 194 b.reverse()
191 195 while a and b and a[-1] == b[-1]:
192 196 a.pop()
193 197 b.pop()
194 198 b.reverse()
195 199 return os.sep.join((['..'] * len(a)) + b)
196 200
197 201 def canonpath(root, cwd, myname):
198 202 """return the canonical path of myname, given cwd and root"""
199 203 if root == os.sep:
200 204 rootsep = os.sep
201 205 else:
202 206 rootsep = root + os.sep
203 207 name = myname
204 208 if not os.path.isabs(name):
205 209 name = os.path.join(root, cwd, name)
206 210 name = os.path.normpath(name)
207 211 if name.startswith(rootsep):
208 212 name = name[len(rootsep):]
209 213 audit_path(name)
210 214 return pconvert(name)
211 215 elif name == root:
212 216 return ''
213 217 else:
214 218 raise Abort('%s not under root' % myname)
215 219
216 220 def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
217 221 return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
218 222
219 223 def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
220 224 if os.name == 'nt':
221 225 dflt_pat = 'glob'
222 226 else:
223 227 dflt_pat = 'relpath'
224 228 return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
225 229
226 230 def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
227 231 """build a function to match a set of file patterns
228 232
229 233 arguments:
230 234 canonroot - the canonical root of the tree you're matching against
231 235 cwd - the current working directory, if relevant
232 236 names - patterns to find
233 237 inc - patterns to include
234 238 exc - patterns to exclude
235 239 head - a regex to prepend to patterns to control whether a match is rooted
236 240
237 241 a pattern is one of:
238 242 'glob:<rooted glob>'
239 243 're:<rooted regexp>'
240 244 'path:<rooted path>'
241 245 'relglob:<relative glob>'
242 246 'relpath:<relative path>'
243 247 'relre:<relative regexp>'
244 248 '<rooted path or regexp>'
245 249
246 250 returns:
247 251 a 3-tuple containing
248 252 - list of explicit non-pattern names passed in
249 253 - a bool match(filename) function
250 254 - a bool indicating if any patterns were passed in
251 255
252 256 todo:
253 257 make head regex a rooted bool
254 258 """
255 259
256 260 def contains_glob(name):
257 261 for c in name:
258 262 if c in _globchars: return True
259 263 return False
260 264
261 265 def regex(kind, name, tail):
262 266 '''convert a pattern into a regular expression'''
263 267 if kind == 're':
264 268 return name
265 269 elif kind == 'path':
266 270 return '^' + re.escape(name) + '(?:/|$)'
267 271 elif kind == 'relglob':
268 272 return head + globre(name, '(?:|.*/)', tail)
269 273 elif kind == 'relpath':
270 274 return head + re.escape(name) + tail
271 275 elif kind == 'relre':
272 276 if name.startswith('^'):
273 277 return name
274 278 return '.*' + name
275 279 return head + globre(name, '', tail)
276 280
277 281 def matchfn(pats, tail):
278 282 """build a matching function from a set of patterns"""
279 283 if not pats:
280 284 return
281 285 matches = []
282 286 for k, p in pats:
283 287 try:
284 288 pat = '(?:%s)' % regex(k, p, tail)
285 289 matches.append(re.compile(pat).match)
286 290 except re.error:
287 291 if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
288 292 else: raise Abort("invalid pattern (%s): %s" % (k, p))
289 293
290 294 def buildfn(text):
291 295 for m in matches:
292 296 r = m(text)
293 297 if r:
294 298 return r
295 299
296 300 return buildfn
297 301
298 302 def globprefix(pat):
299 303 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
300 304 root = []
301 305 for p in pat.split(os.sep):
302 306 if contains_glob(p): break
303 307 root.append(p)
304 308 return '/'.join(root)
305 309
306 310 pats = []
307 311 files = []
308 312 roots = []
309 313 for kind, name in [patkind(p, dflt_pat) for p in names]:
310 314 if kind in ('glob', 'relpath'):
311 315 name = canonpath(canonroot, cwd, name)
312 316 if name == '':
313 317 kind, name = 'glob', '**'
314 318 if kind in ('glob', 'path', 're'):
315 319 pats.append((kind, name))
316 320 if kind == 'glob':
317 321 root = globprefix(name)
318 322 if root: roots.append(root)
319 323 elif kind == 'relpath':
320 324 files.append((kind, name))
321 325 roots.append(name)
322 326
323 327 patmatch = matchfn(pats, '$') or always
324 328 filematch = matchfn(files, '(?:/|$)') or always
325 329 incmatch = always
326 330 if inc:
327 331 incmatch = matchfn(map(patkind, inc), '(?:/|$)')
328 332 excmatch = lambda fn: False
329 333 if exc:
330 334 excmatch = matchfn(map(patkind, exc), '(?:/|$)')
331 335
332 336 return (roots,
333 337 lambda fn: (incmatch(fn) and not excmatch(fn) and
334 338 (fn.endswith('/') or
335 339 (not pats and not files) or
336 340 (pats and patmatch(fn)) or
337 341 (files and filematch(fn)))),
338 342 (inc or exc or (pats and pats != [('glob', '**')])) and True)
339 343
340 344 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
341 345 '''enhanced shell command execution.
342 346 run with environment maybe modified, maybe in different dir.
343 347
344 348 if command fails and onerr is None, return status. if ui object,
345 349 print error message and return status, else raise onerr object as
346 350 exception.'''
347 351 oldenv = {}
348 352 for k in environ:
349 353 oldenv[k] = os.environ.get(k)
350 354 if cwd is not None:
351 355 oldcwd = os.getcwd()
352 356 try:
353 357 for k, v in environ.iteritems():
354 358 os.environ[k] = str(v)
355 359 if cwd is not None and oldcwd != cwd:
356 360 os.chdir(cwd)
357 361 rc = os.system(cmd)
358 362 if rc and onerr:
359 363 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
360 364 explain_exit(rc)[0])
361 365 if errprefix:
362 366 errmsg = '%s: %s' % (errprefix, errmsg)
363 367 try:
364 368 onerr.warn(errmsg + '\n')
365 369 except AttributeError:
366 370 raise onerr(errmsg)
367 371 return rc
368 372 finally:
369 373 for k, v in oldenv.iteritems():
370 374 if v is None:
371 375 del os.environ[k]
372 376 else:
373 377 os.environ[k] = v
374 378 if cwd is not None and oldcwd != cwd:
375 379 os.chdir(oldcwd)
376 380
377 381 def rename(src, dst):
378 382 """forcibly rename a file"""
379 383 try:
380 384 os.rename(src, dst)
381 385 except:
382 386 os.unlink(dst)
383 387 os.rename(src, dst)
384 388
385 389 def unlink(f):
386 390 """unlink and remove the directory if it is empty"""
387 391 os.unlink(f)
388 392 # try removing directories that might now be empty
389 393 try:
390 394 os.removedirs(os.path.dirname(f))
391 395 except OSError:
392 396 pass
393 397
394 398 def copyfiles(src, dst, hardlink=None):
395 399 """Copy a directory tree using hardlinks if possible"""
396 400
397 401 if hardlink is None:
398 402 hardlink = (os.stat(src).st_dev ==
399 403 os.stat(os.path.dirname(dst)).st_dev)
400 404
401 405 if os.path.isdir(src):
402 406 os.mkdir(dst)
403 407 for name in os.listdir(src):
404 408 srcname = os.path.join(src, name)
405 409 dstname = os.path.join(dst, name)
406 410 copyfiles(srcname, dstname, hardlink)
407 411 else:
408 412 if hardlink:
409 413 try:
410 414 os_link(src, dst)
411 415 except (IOError, OSError):
412 416 hardlink = False
413 417 shutil.copy(src, dst)
414 418 else:
415 419 shutil.copy(src, dst)
416 420
417 421 def audit_path(path):
418 422 """Abort if path contains dangerous components"""
419 423 parts = os.path.normcase(path).split(os.sep)
420 424 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
421 425 or os.pardir in parts):
422 426 raise Abort(_("path contains illegal component: %s\n") % path)
423 427
424 428 def opener(base, audit=True):
425 429 """
426 430 return a function that opens files relative to base
427 431
428 432 this function is used to hide the details of COW semantics and
429 433 remote file access from higher level code.
430 434 """
431 435 p = base
432 436 audit_p = audit
433 437
434 438 def mktempcopy(name):
435 439 d, fn = os.path.split(name)
436 440 fd, temp = tempfile.mkstemp(prefix=fn, dir=d)
437 441 fp = os.fdopen(fd, "wb")
438 442 try:
439 443 fp.write(file(name, "rb").read())
440 444 except:
441 445 try: os.unlink(temp)
442 446 except: pass
443 447 raise
444 448 fp.close()
445 449 st = os.lstat(name)
446 450 os.chmod(temp, st.st_mode)
447 451 return temp
448 452
449 453 class atomictempfile(file):
450 454 """the file will only be copied when rename is called"""
451 455 def __init__(self, name, mode):
452 456 self.__name = name
453 457 self.temp = mktempcopy(name)
454 458 file.__init__(self, self.temp, mode)
455 459 def rename(self):
456 460 if not self.closed:
457 461 file.close(self)
458 462 rename(self.temp, self.__name)
459 463 def __del__(self):
460 464 if not self.closed:
461 465 try:
462 466 os.unlink(self.temp)
463 467 except: pass
464 468 file.close(self)
465 469
466 470 class atomicfile(atomictempfile):
467 471 """the file will only be copied on close"""
468 472 def __init__(self, name, mode):
469 473 atomictempfile.__init__(self, name, mode)
470 474 def close(self):
471 475 self.rename()
472 476 def __del__(self):
473 477 self.rename()
474 478
475 479 def o(path, mode="r", text=False, atomic=False, atomictemp=False):
476 480 if audit_p:
477 481 audit_path(path)
478 482 f = os.path.join(p, path)
479 483
480 484 if not text:
481 485 mode += "b" # for that other OS
482 486
483 487 if mode[0] != "r":
484 488 try:
485 489 nlink = nlinks(f)
486 490 except OSError:
487 491 d = os.path.dirname(f)
488 492 if not os.path.isdir(d):
489 493 os.makedirs(d)
490 494 else:
491 495 if atomic:
492 496 return atomicfile(f, mode)
493 497 elif atomictemp:
494 498 return atomictempfile(f, mode)
495 499 if nlink > 1:
496 500 rename(mktempcopy(f), f)
497 501 return file(f, mode)
498 502
499 503 return o
500 504
501 505 def _makelock_file(info, pathname):
502 506 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
503 507 os.write(ld, info)
504 508 os.close(ld)
505 509
506 510 def _readlock_file(pathname):
507 511 return file(pathname).read()
508 512
509 513 def nlinks(pathname):
510 514 """Return number of hardlinks for the given file."""
511 515 return os.stat(pathname).st_nlink
512 516
513 517 if hasattr(os, 'link'):
514 518 os_link = os.link
515 519 else:
516 520 def os_link(src, dst):
517 521 raise OSError(0, _("Hardlinks not supported"))
518 522
519 523 # Platform specific variants
520 524 if os.name == 'nt':
521 525 demandload(globals(), "msvcrt")
522 526 nulldev = 'NUL:'
523 527
524 528 class winstdout:
525 529 '''stdout on windows misbehaves if sent through a pipe'''
526 530
527 531 def __init__(self, fp):
528 532 self.fp = fp
529 533
530 534 def __getattr__(self, key):
531 535 return getattr(self.fp, key)
532 536
533 537 def close(self):
534 538 try:
535 539 self.fp.close()
536 540 except: pass
537 541
538 542 def write(self, s):
539 543 try:
540 544 return self.fp.write(s)
541 545 except IOError, inst:
542 546 if inst.errno != 0: raise
543 547 self.close()
544 548 raise IOError(errno.EPIPE, 'Broken pipe')
545 549
546 550 sys.stdout = winstdout(sys.stdout)
547 551
548 552 def system_rcpath():
549 553 return [r'c:\mercurial\mercurial.ini']
550 554
551 555 def os_rcpath():
552 556 '''return default os-specific hgrc search path'''
553 557 return system_rcpath() + [os.path.join(os.path.expanduser('~'),
554 558 'mercurial.ini')]
555 559
556 560 def parse_patch_output(output_line):
557 561 """parses the output produced by patch and returns the file name"""
558 562 pf = output_line[14:]
559 563 if pf[0] == '`':
560 564 pf = pf[1:-1] # Remove the quotes
561 565 return pf
562 566
563 567 def testpid(pid):
564 568 '''return False if pid dead, True if running or not known'''
565 569 return True
566 570
567 571 def is_exec(f, last):
568 572 return last
569 573
570 574 def set_exec(f, mode):
571 575 pass
572 576
573 577 def set_binary(fd):
574 578 msvcrt.setmode(fd.fileno(), os.O_BINARY)
575 579
576 580 def pconvert(path):
577 581 return path.replace("\\", "/")
578 582
579 583 def localpath(path):
580 584 return path.replace('/', '\\')
581 585
582 586 def normpath(path):
583 587 return pconvert(os.path.normpath(path))
584 588
585 589 makelock = _makelock_file
586 590 readlock = _readlock_file
587 591
588 592 def explain_exit(code):
589 593 return _("exited with status %d") % code, code
590 594
591 595 try:
592 596 # override functions with win32 versions if possible
593 597 from util_win32 import *
594 598 except ImportError:
595 599 pass
596 600
597 601 else:
598 602 nulldev = '/dev/null'
599 603
600 604 def rcfiles(path):
601 605 rcs = [os.path.join(path, 'hgrc')]
602 606 rcdir = os.path.join(path, 'hgrc.d')
603 607 try:
604 608 rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
605 609 if f.endswith(".rc")])
606 610 except OSError, inst: pass
607 611 return rcs
608 612
609 613 def os_rcpath():
610 614 '''return default os-specific hgrc search path'''
611 615 path = []
612 616 if len(sys.argv) > 0:
613 617 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
614 618 '/../etc/mercurial'))
615 619 path.extend(rcfiles('/etc/mercurial'))
616 620 path.append(os.path.expanduser('~/.hgrc'))
617 621 path = [os.path.normpath(f) for f in path]
618 622 return path
619 623
620 624 def parse_patch_output(output_line):
621 625 """parses the output produced by patch and returns the file name"""
622 626 pf = output_line[14:]
623 627 if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
624 628 pf = pf[1:-1] # Remove the quotes
625 629 return pf
626 630
627 631 def is_exec(f, last):
628 632 """check whether a file is executable"""
629 633 return (os.stat(f).st_mode & 0100 != 0)
630 634
631 635 def set_exec(f, mode):
632 636 s = os.stat(f).st_mode
633 637 if (s & 0100 != 0) == mode:
634 638 return
635 639 if mode:
636 640 # Turn on +x for every +r bit when making a file executable
637 641 # and obey umask.
638 642 umask = os.umask(0)
639 643 os.umask(umask)
640 644 os.chmod(f, s | (s & 0444) >> 2 & ~umask)
641 645 else:
642 646 os.chmod(f, s & 0666)
643 647
644 648 def set_binary(fd):
645 649 pass
646 650
647 651 def pconvert(path):
648 652 return path
649 653
650 654 def localpath(path):
651 655 return path
652 656
653 657 normpath = os.path.normpath
654 658
655 659 def makelock(info, pathname):
656 660 try:
657 661 os.symlink(info, pathname)
658 662 except OSError, why:
659 663 if why.errno == errno.EEXIST:
660 664 raise
661 665 else:
662 666 _makelock_file(info, pathname)
663 667
664 668 def readlock(pathname):
665 669 try:
666 670 return os.readlink(pathname)
667 671 except OSError, why:
668 672 if why.errno == errno.EINVAL:
669 673 return _readlock_file(pathname)
670 674 else:
671 675 raise
672 676
673 677 def testpid(pid):
674 678 '''return False if pid dead, True if running or not sure'''
675 679 try:
676 680 os.kill(pid, 0)
677 681 return True
678 682 except OSError, inst:
679 683 return inst.errno != errno.ESRCH
680 684
681 685 def explain_exit(code):
682 686 """return a 2-tuple (desc, code) describing a process's status"""
683 687 if os.WIFEXITED(code):
684 688 val = os.WEXITSTATUS(code)
685 689 return _("exited with status %d") % val, val
686 690 elif os.WIFSIGNALED(code):
687 691 val = os.WTERMSIG(code)
688 692 return _("killed by signal %d") % val, val
689 693 elif os.WIFSTOPPED(code):
690 694 val = os.WSTOPSIG(code)
691 695 return _("stopped by signal %d") % val, val
692 696 raise ValueError(_("invalid exit code"))
693 697
694 698 class chunkbuffer(object):
695 699 """Allow arbitrary sized chunks of data to be efficiently read from an
696 700 iterator over chunks of arbitrary size."""
697 701
698 702 def __init__(self, in_iter, targetsize = 2**16):
699 703 """in_iter is the iterator that's iterating over the input chunks.
700 704 targetsize is how big a buffer to try to maintain."""
701 705 self.in_iter = iter(in_iter)
702 706 self.buf = ''
703 707 self.targetsize = int(targetsize)
704 708 if self.targetsize <= 0:
705 709 raise ValueError(_("targetsize must be greater than 0, was %d") %
706 710 targetsize)
707 711 self.iterempty = False
708 712
709 713 def fillbuf(self):
710 714 """Ignore target size; read every chunk from iterator until empty."""
711 715 if not self.iterempty:
712 716 collector = cStringIO.StringIO()
713 717 collector.write(self.buf)
714 718 for ch in self.in_iter:
715 719 collector.write(ch)
716 720 self.buf = collector.getvalue()
717 721 self.iterempty = True
718 722
719 723 def read(self, l):
720 724 """Read L bytes of data from the iterator of chunks of data.
721 725 Returns less than L bytes if the iterator runs dry."""
722 726 if l > len(self.buf) and not self.iterempty:
723 727 # Clamp to a multiple of self.targetsize
724 728 targetsize = self.targetsize * ((l // self.targetsize) + 1)
725 729 collector = cStringIO.StringIO()
726 730 collector.write(self.buf)
727 731 collected = len(self.buf)
728 732 for chunk in self.in_iter:
729 733 collector.write(chunk)
730 734 collected += len(chunk)
731 735 if collected >= targetsize:
732 736 break
733 737 if collected < targetsize:
734 738 self.iterempty = True
735 739 self.buf = collector.getvalue()
736 740 s, self.buf = self.buf[:l], buffer(self.buf, l)
737 741 return s
738 742
739 743 def filechunkiter(f, size = 65536):
740 744 """Create a generator that produces all the data in the file size
741 745 (default 65536) bytes at a time. Chunks may be less than size
742 746 bytes if the chunk is the last chunk in the file, or the file is a
743 747 socket or some other type of file that sometimes reads less data
744 748 than is requested."""
745 749 s = f.read(size)
746 750 while len(s) > 0:
747 751 yield s
748 752 s = f.read(size)
749 753
750 754 def makedate():
751 755 lt = time.localtime()
752 756 if lt[8] == 1 and time.daylight:
753 757 tz = time.altzone
754 758 else:
755 759 tz = time.timezone
756 760 return time.mktime(lt), tz
757 761
758 762 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
759 763 """represent a (unixtime, offset) tuple as a localized time.
760 764 unixtime is seconds since the epoch, and offset is the time zone's
761 765 number of seconds away from UTC. if timezone is false, do not
762 766 append time zone to string."""
763 767 t, tz = date or makedate()
764 768 s = time.strftime(format, time.gmtime(float(t) - tz))
765 769 if timezone:
766 770 s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
767 771 return s
768 772
769 773 def shortuser(user):
770 774 """Return a short representation of a user name or email address."""
771 775 f = user.find('@')
772 776 if f >= 0:
773 777 user = user[:f]
774 778 f = user.find('<')
775 779 if f >= 0:
776 780 user = user[f+1:]
777 781 return user
778 782
779 783 def walkrepos(path):
780 784 '''yield every hg repository under path, recursively.'''
781 785 def errhandler(err):
782 786 if err.filename == path:
783 787 raise err
784 788
785 789 for root, dirs, files in os.walk(path, onerror=errhandler):
786 790 for d in dirs:
787 791 if d == '.hg':
788 792 yield root
789 793 dirs[:] = []
790 794 break
791 795
792 796 _rcpath = None
793 797
794 798 def rcpath():
795 799 '''return hgrc search path. if env var HGRCPATH is set, use it.
796 800 for each item in path, if directory, use files ending in .rc,
797 801 else use item.
798 802 make HGRCPATH empty to only look in .hg/hgrc of current repo.
799 803 if no HGRCPATH, use default os-specific path.'''
800 804 global _rcpath
801 805 if _rcpath is None:
802 806 if 'HGRCPATH' in os.environ:
803 807 _rcpath = []
804 808 for p in os.environ['HGRCPATH'].split(os.pathsep):
805 809 if not p: continue
806 810 if os.path.isdir(p):
807 811 for f in os.listdir(p):
808 812 if f.endswith('.rc'):
809 813 _rcpath.append(os.path.join(p, f))
810 814 else:
811 815 _rcpath.append(p)
812 816 else:
813 817 _rcpath = os_rcpath()
814 818 return _rcpath
@@ -1,16 +1,16 b''
1 1 header = header-raw.tmpl
2 2 footer = ''
3 3 changeset = changeset-raw.tmpl
4 4 difflineplus = '#line#'
5 5 difflineminus = '#line#'
6 6 difflineat = '#line#'
7 7 diffline = '#line#'
8 8 changesetparent = '# parent: #node#'
9 9 changesetchild = '# child: #node#'
10 10 filenodelink = ''
11 filerevision = filerevision-raw.tmpl
11 filerevision = 'Content-Type: #mimetype#\nContent-Disposition: filename=#file#\n\n#raw#'
12 12 fileline = '#line#'
13 13 diffblock = '#lines#'
14 14 filediff = filediff-raw.tmpl
15 15 fileannotate = fileannotate-raw.tmpl
16 16 annotateline = '#author#@#rev#: #line#'
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now