svn: don't call resolve_rev directly
[yap.git] / plugins / svn.py
blob26f1ae165a2c6795347b7710b960bea60a1cfcfc
2 from yap.yap import YapCore, YapError
3 from yap.util import get_output, takes_options, run_command, run_safely, short_help
5 import os
6 import tempfile
7 import glob
8 import pickle
9 import re
10 import bisect
11 import struct
13 class RepoBlob(object):
14 def __init__(self, keys):
15 self.keys = keys
17 self.uuid = None
18 self.branches = None
19 self.tags = None
20 self.metadata = {}
22 def add_metadata(self, branch):
23 assert branch not in self.metadata
24 gitdir = get_output("git rev-parse --git-dir")
25 assert gitdir
26 revmap = os.path.join(gitdir[0], "svn", "svn", branch, ".rev_map*")
27 revmap = glob.glob(revmap)
28 if not revmap:
29 return
30 uuid = revmap[0].split('.')[-1]
31 if self.uuid is None:
32 self.uuid = uuid
33 assert self.uuid == uuid
34 rev = get_output("git rev-parse refs/remotes/svn/%s" % branch)
35 data = file(revmap[0]).read()
36 self.metadata[branch] = rev[0], data
38 # Helper class for dealing with SVN metadata
39 class SVNRevMap(object):
40 RECORD_SZ = 24
41 def __init__(self, filename):
42 self.fd = file(filename, "rb")
43 size = os.stat(filename)[6]
44 self.nrecords = size / self.RECORD_SZ
46 def __getitem__(self, index):
47 if index >= self.nrecords:
48 raise IndexError
49 return self.get_record(index)[0]
51 def __len__(self):
52 return self.nrecords
54 def get_record(self, index):
55 self.fd.seek(index * self.RECORD_SZ)
56 record = self.fd.read(self.RECORD_SZ)
57 return self.parse_record(record)
59 def parse_record(self, record):
60 record = struct.unpack("!I20B", record)
61 rev = record[0]
62 hash = map(lambda x: "%02x" % x, record[1:])
63 hash = ''.join(hash)
64 return rev, hash
66 class SvnPlugin(YapCore):
67 "Allow yap to interoperate with Subversion repositories"
69 revpat = re.compile('^r(\d+)$')
71 def _get_root(self, url):
72 root = get_output("svn info %s 2>/dev/null | gawk '/Repository Root:/{print $3}'" % url)
73 if not root:
74 raise YapError("Not an SVN repo: %s" % url)
75 return root[0]
77 def _configure_repo(self, url, fetch=None):
78 root = self._get_root(url)
79 os.system("git config svn-remote.svn.url %s" % root)
80 if fetch is None:
81 trunk = url.replace(root, '').strip('/')
82 else:
83 trunk = fetch.split(':')[0]
84 os.system("git config svn-remote.svn.fetch %s:refs/remotes/svn/trunk"
85 % trunk)
87 branches = trunk.replace('trunk', 'branches')
88 if branches != trunk:
89 os.system("git config svn-remote.svn.branches %s/*:refs/remotes/svn/*" % branches)
90 tags = trunk.replace('trunk', 'tags')
91 if tags != trunk:
92 os.system("git config svn-remote.svn.tags %s/*:refs/tags/*" % tags)
93 self.cmd_repo("svn", url)
94 os.system("git config yap.svn.enabled 1")
96 def _create_tagged_blob(self):
97 keys = dict()
98 for i in get_output("git config --list | grep ^svn-remote.svn"):
99 k, v = i.split('=')
100 keys[k] = v
101 blob = RepoBlob(keys)
102 for b in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/svn/*'"):
103 b = b.replace('refs/remotes/svn/', '')
104 blob.add_metadata(b)
106 fd_w, fd_r = os.popen2("git hash-object -w --stdin")
107 pickle.dump(blob, fd_w)
108 fd_w.close()
109 hash = fd_r.readline().strip()
110 run_safely("git tag -f yap-svn %s" % hash)
112 def _cleanup_branches(self):
113 for b in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/svn/*@*'"):
114 head = b.replace('refs/remotes/svn/', '')
115 path = os.path.join(".git", "svn", "svn", head)
116 files = os.listdir(path)
117 for f in files:
118 os.unlink(os.path.join(path, f))
119 os.rmdir(path)
121 ref = get_output("git rev-parse %s" % b)
122 if ref:
123 run_safely("git update-ref -d %s %s" % (b, ref[0]))
125 def _clone_svn(self, url, directory=None, **flags):
126 url = url.rstrip('/')
127 if directory is None:
128 directory = url.rsplit('/')[-1]
129 directory = directory.replace('.git', '')
131 try:
132 os.mkdir(directory)
133 except OSError:
134 raise YapError("Directory exists: %s" % directory)
135 os.chdir(directory)
137 self.cmd_init()
138 self._configure_repo(url)
139 os.system("git svn fetch -r %s:HEAD" % flags.get('-r', '1'))
141 self._cleanup_branches()
142 self._create_tagged_blob()
144 def _push_svn(self, branch, **flags):
145 if '-d' in flags:
146 raise YapError("Deleting svn branches not supported")
147 print "Verifying branch is up-to-date"
148 run_safely("git svn fetch svn")
150 branch = branch.replace('refs/heads/', '')
151 rev = get_output("git rev-parse --verify refs/remotes/svn/%s" % branch)
153 # Create the branch if requested
154 if not rev:
155 if '-c' not in flags:
156 raise YapError("No matching branch on the repo. Use -c to create a new branch there.")
157 src = get_output("git svn info | gawk '/URL:/{print $2}'")[0]
158 brev = get_output("git svn info | gawk '/Revision:/{print $2}'")[0]
159 root = get_output("git config svn-remote.svn.url")[0]
160 branch_path = get_output("git config svn-remote.svn.branches")[0].split(':')[0]
161 branch_path = branch_path.rstrip('/*')
162 dst = '/'.join((root, branch_path, branch))
164 # Create the branch in svn
165 run_safely("svn cp -r%s %s %s -m 'create branch %s'"
166 % (brev, src, dst, branch))
167 run_safely("git svn fetch svn")
168 rev = get_output("git rev-parse refs/remotes/svn/%s 2>/dev/null" % branch)
169 base = get_output("git svn find-rev r%s" % brev)
171 # Apply our commits to the new branch
172 try:
173 fd, tmpfile = tempfile.mkstemp("yap")
174 os.close(fd)
175 os.system("git format-patch -k --stdout '%s' > %s"
176 % (base[0], tmpfile))
177 start = get_output("git rev-parse HEAD")
178 self.cmd_point("refs/remotes/svn/%s"
179 % branch, **{'-f': True})
181 stat = os.stat(tmpfile)
182 size = stat[6]
183 if size > 0:
184 rc = run_command("git am -3 %s" % tmpfile)
185 if (rc):
186 self.cmd_point(start[0], **{'-f': True})
187 raise YapError("Failed to port changes to new svn branch")
188 finally:
189 os.unlink(tmpfile)
191 base = get_output("git merge-base HEAD %s" % rev[0])
192 if base[0] != rev[0]:
193 raise YapError("Branch not up-to-date. Update first.")
194 current = get_output("git symbolic-ref HEAD")
195 if not current:
196 raise YapError("Not on a branch!")
197 current = current[0].replace('refs/heads/', '')
198 self._confirm_push(current, branch, "svn")
199 if run_command("git update-index --refresh"):
200 raise YapError("Can't push with uncommitted changes")
202 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
203 os.system("git svn dcommit")
204 run_safely("git svn rebase")
205 if not master:
206 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
207 if master:
208 run_safely("git update-ref -d refs/heads/master %s" % master[0])
210 def _fetch_svn(self):
211 os.system("git svn fetch svn")
212 self._create_tagged_blob()
213 self._cleanup_branches()
215 def _enabled(self):
216 enabled = get_output("git config yap.svn.enabled")
217 return bool(enabled)
219 def _applicable(self, args):
220 if not self._enabled():
221 return False
223 if args and args[0] == 'svn':
224 return True
226 if not args:
227 current = get_output("git symbolic-ref HEAD")
228 if not current:
229 raise YapError("Not on a branch!")
231 current = current[0].replace('refs/heads/', '')
232 remote, merge = self._get_tracking(current)
233 if remote == "svn":
234 return True
236 return False
238 # Ensure users don't accidentally kill our "svn" repo
239 def cmd_repo(self, *args, **flags):
240 if self._enabled():
241 if '-d' in flags and args and args[0] == "svn":
242 raise YapError("Refusing to delete special svn repository")
243 super(SvnPlugin, self).cmd_repo(*args, **flags)
245 @takes_options("r:")
246 def cmd_clone(self, *args, **flags):
247 handled = True
248 if not args:
249 handled = False
250 if (handled and not args[0].startswith("http")
251 and not args[0].startswith("svn")
252 and not args[0].startswith("file://")):
253 handled = False
254 if handled and run_command("svn info %s" % args[0]):
255 handled = False
257 if handled:
258 self._clone_svn(*args, **flags)
259 else:
260 super(SvnPlugin, self).cmd_clone(*args, **flags)
262 if self._enabled():
263 # nothing to do
264 return
266 run_safely("git fetch origin --tags")
267 hash = get_output("git rev-parse --verify refs/tags/yap-svn 2>/dev/null")
268 if not hash:
269 return
271 fd = os.popen("git cat-file blob %s" % hash[0])
272 blob = pickle.load(fd)
273 for k, v in blob.keys.items():
274 run_safely("git config %s %s" % (k, v))
276 self.cmd_repo("svn", blob.keys['svn-remote.svn.url'])
277 os.system("git config yap.svn.enabled 1")
278 run_safely("git fetch origin 'refs/remotes/svn/*:refs/remotes/svn/*'")
280 for b in blob.metadata.keys():
281 branch = os.path.join(".git", "svn", "svn", b)
282 os.makedirs(branch)
283 fd = file(os.path.join(branch, ".rev_map.%s" % blob.uuid), "w")
285 rev, metadata = blob.metadata[b]
286 fd.write(metadata)
287 run_command("git update-ref refs/remotes/svn/%s %s" % (b, rev))
289 def cmd_fetch(self, *args, **flags):
290 if self._applicable(args):
291 self._fetch_svn()
292 return
294 super(SvnPlugin, self).cmd_fetch(*args, **flags)
296 def cmd_push(self, *args, **flags):
297 if self._applicable(args):
298 if len (args) >= 2:
299 merge = args[1]
300 else:
301 current = get_output("git symbolic-ref HEAD")
302 if not current:
303 raise YapError("Not on a branch!")
305 current = current[0].replace('refs/heads/', '')
306 remote, merge = self._get_tracking(current)
307 if remote != "svn":
308 raise YapError("Need a branch name")
309 self._push_svn(merge, **flags)
310 return
311 super(SvnPlugin, self).cmd_push(*args, **flags)
313 @short_help("change options for the svn plugin")
314 def cmd_svn(self, subcmd):
315 "enable"
317 if subcmd not in ["enable"]:
318 raise TypeError
320 if "svn" in [x[0] for x in self._list_remotes()]:
321 raise YapError("A remote named 'svn' already exists")
324 if not run_command("git config svn-remote.svn.branches"):
325 raise YapError("Cannot currently enable in a repository with svn branches")
327 url = get_output("git config svn-remote.svn.url")
328 if not url:
329 raise YapError("Not a git-svn repository?")
330 fetch = get_output("git config svn-remote.svn.fetch")
331 assert fetch
332 lhs, rhs = fetch[0].split(':')
335 rev = get_output("git rev-parse %s" % rhs)
336 assert rev
337 run_safely("git update-ref refs/remotes/svn/trunk %s" % rev[0])
339 url = '/'.join((url[0], lhs))
340 self._configure_repo(url)
341 run_safely("git update-ref -d %s %s" % (rhs, rev[0]))
343 # We are intentionally overriding yap utility functions
344 def _filter_log(self, commit):
345 commit = super(SvnPlugin, self)._filter_log(commit)
346 if not self._enabled():
347 return commit
349 new = []
350 for line in commit:
351 if line.strip().startswith("git-svn-id:"):
352 while not new[-1].strip():
353 new = new[:-1]
355 urlrev = line.strip().split(' ')[1]
356 url, rev = urlrev.split('@')
357 hash = commit[0].split(' ')[1].strip()
358 if self._resolve_svn_rev(int(rev)) != hash:
359 continue
361 root = get_output("git config svn-remote.svn.url")
362 assert root
363 url = url.replace(root[0], '')
364 new.insert(1, "Subversion: r%s %s\n" % (rev, url))
366 continue
367 new.append(line)
368 return new
370 def _resolve_svn_rev(self, revnum):
371 rev = get_output("git svn find-rev r%d 2>/dev/null" % revnum)
373 if rev:
374 return rev[0]
376 gitdir = get_output("git rev-parse --git-dir")
377 assert gitdir
378 revmaps = os.path.join(gitdir[0], "svn", "svn",
379 "*", ".rev_map*")
380 revmaps = glob.glob(revmaps)
382 for f in revmaps:
383 rm = SVNRevMap(f)
384 idx = bisect.bisect_left(rm, revnum)
385 if idx >= len(rm) or rm[idx] != revnum:
386 continue
388 revnum, rev = rm.get_record(idx)
389 if hash == "0" * 40:
390 continue
391 break
392 return rev
394 def _resolve_rev(self, *args, **flags):
395 rev = None
396 if args:
397 m = self.revpat.match(args[0])
398 if m is not None:
399 revnum = int(m.group(1))
400 rev = self._resolve_svn_rev(revnum)
402 if not rev:
403 rev = super(SvnPlugin, self)._resolve_rev(*args, **flags)
404 return rev