workdir: add usage and a completion message
[yap.git] / plugins / svn.py
blobed0fdaf822088ef4fc76a9795a9ec301e3bdfa72
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 __init__(self, *args, **flags):
72 super(SvnPlugin, self).__init__(*args, **flags)
73 self._svn_next_rev = None
75 def _get_root(self, url):
76 root = get_output("svn info %s 2>/dev/null | gawk '/Repository Root:/{print $3}'" % url)
77 if not root:
78 raise YapError("Not an SVN repo: %s" % url)
79 return root[0]
81 def _configure_repo(self, url, fetch=None):
82 root = self._get_root(url)
83 os.system("git config svn-remote.svn.url %s" % root)
84 if fetch is None:
85 trunk = url.replace(root, '').strip('/')
86 else:
87 trunk = fetch.split(':')[0]
88 os.system("git config svn-remote.svn.fetch %s:refs/remotes/svn/trunk"
89 % trunk)
91 branches = trunk.replace('trunk', 'branches')
92 if branches != trunk:
93 os.system("git config svn-remote.svn.branches %s/*:refs/remotes/svn/*" % branches)
94 tags = trunk.replace('trunk', 'tags')
95 if tags != trunk:
96 os.system("git config svn-remote.svn.tags %s/*:refs/tags/*" % tags)
97 self.cmd_repo("svn", url)
98 os.system("git config yap.svn.enabled 1")
100 def _create_tagged_blob(self):
101 keys = dict()
102 for i in get_output("git config --list | grep ^svn-remote."):
103 k, v = i.split('=')
104 keys[k] = v
105 blob = RepoBlob(keys)
106 for b in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/svn/*'"):
107 b = b.replace('refs/remotes/svn/', '')
108 blob.add_metadata(b)
110 fd_w, fd_r = os.popen2("git hash-object -w --stdin")
111 pickle.dump(blob, fd_w)
112 fd_w.close()
113 hash = fd_r.readline().strip()
114 run_safely("git tag -f yap-svn %s" % hash)
116 def _cleanup_branches(self):
117 for b in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/svn/*@*'"):
118 head = b.replace('refs/remotes/svn/', '')
119 path = os.path.join(".git", "svn", "svn", head)
120 files = os.listdir(path)
121 for f in files:
122 os.unlink(os.path.join(path, f))
123 os.rmdir(path)
125 ref = get_output("git rev-parse %s" % b)
126 if ref:
127 run_safely("git update-ref -d %s %s" % (b, ref[0]))
129 def _clone_svn(self, url, directory=None, **flags):
130 url = url.rstrip('/')
131 if directory is None:
132 directory = url.rsplit('/')[-1]
133 directory = directory.replace('.git', '')
135 try:
136 os.mkdir(directory)
137 except OSError:
138 raise YapError("Directory exists: %s" % directory)
139 os.chdir(directory)
141 self.cmd_init()
142 self._configure_repo(url)
143 os.system("git svn fetch -r %s:HEAD" % flags.get('-r', '1'))
145 self._cleanup_branches()
146 self._create_tagged_blob()
148 def _push_svn(self, branch, **flags):
149 if '-d' in flags:
150 raise YapError("Deleting svn branches not supported")
151 print "Verifying branch is up-to-date"
152 run_safely("git svn fetch svn")
154 branch = branch.replace('refs/heads/', '')
155 rev = get_output("git rev-parse --verify refs/remotes/svn/%s" % branch)
157 # Create the branch if requested
158 if not rev:
159 if '-c' not in flags:
160 raise YapError("No matching branch on the repo. Use -c to create a new branch there.")
161 src = get_output("git svn info | gawk '/URL:/{print $2}'")[0]
162 brev = get_output("git svn info | gawk '/Revision:/{print $2}'")[0]
163 root = get_output("git config svn-remote.svn.url")[0]
164 branch_path = get_output("git config svn-remote.svn.branches")[0].split(':')[0]
165 branch_path = branch_path.rstrip('/*')
166 dst = '/'.join((root, branch_path, branch))
168 # Create the branch in svn
169 run_safely("svn cp -r%s %s %s -m 'create branch %s'"
170 % (brev, src, dst, branch))
171 run_safely("git svn fetch svn")
172 rev = get_output("git rev-parse refs/remotes/svn/%s 2>/dev/null" % branch)
173 base = get_output("git svn find-rev r%s" % brev)
175 # Apply our commits to the new branch
176 try:
177 fd, tmpfile = tempfile.mkstemp("yap")
178 os.close(fd)
179 os.system("git format-patch -k --stdout '%s' > %s"
180 % (base[0], tmpfile))
181 start = get_output("git rev-parse HEAD")
182 self.cmd_point("refs/remotes/svn/%s"
183 % branch, **{'-f': True})
185 stat = os.stat(tmpfile)
186 size = stat[6]
187 if size > 0:
188 rc = run_command("git am -3 %s" % tmpfile)
189 if (rc):
190 self.cmd_point(start[0], **{'-f': True})
191 raise YapError("Failed to port changes to new svn branch")
192 finally:
193 os.unlink(tmpfile)
195 base = get_output("git merge-base HEAD %s" % rev[0])
196 if base[0] != rev[0]:
197 raise YapError("Branch not up-to-date. Update first.")
198 current = get_output("git symbolic-ref HEAD")
199 if not current:
200 raise YapError("Not on a branch!")
201 current = current[0].replace('refs/heads/', '')
202 self._confirm_push(current, branch, "svn")
203 if run_command("git update-index --refresh"):
204 raise YapError("Can't push with uncommitted changes")
206 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
207 os.system("git svn dcommit")
208 run_safely("git svn rebase")
209 if not master:
210 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
211 if master:
212 run_safely("git update-ref -d refs/heads/master %s" % master[0])
214 def _fetch_svn(self):
215 os.system("git svn fetch svn")
216 self._create_tagged_blob()
217 self._cleanup_branches()
219 def _enabled(self):
220 enabled = get_output("git config yap.svn.enabled")
221 return bool(enabled)
223 def _applicable(self, args):
224 if not self._enabled():
225 return False
227 if args and args[0] == 'svn':
228 return True
230 if not args:
231 current = get_output("git symbolic-ref HEAD")
232 if not current:
233 raise YapError("Not on a branch!")
235 current = current[0].replace('refs/heads/', '')
236 remote, merge = self._get_tracking(current)
237 if remote == "svn":
238 return True
240 return False
242 # Ensure users don't accidentally kill our "svn" repo
243 def cmd_repo(self, *args, **flags):
244 if self._enabled():
245 if '-d' in flags and args and args[0] == "svn":
246 raise YapError("Refusing to delete special svn repository")
247 super(SvnPlugin, self).cmd_repo(*args, **flags)
249 @takes_options("r:")
250 def cmd_clone(self, *args, **flags):
251 handled = True
252 if not args:
253 handled = False
254 if (handled and not args[0].startswith("http")
255 and not args[0].startswith("svn")
256 and not args[0].startswith("file://")):
257 handled = False
258 if handled and run_command("svn info %s" % args[0]):
259 handled = False
261 if handled:
262 self._clone_svn(*args, **flags)
263 else:
264 super(SvnPlugin, self).cmd_clone(*args, **flags)
266 if self._enabled():
267 # nothing to do
268 return
270 run_safely("git fetch origin --tags")
271 hash = get_output("git rev-parse --verify refs/tags/yap-svn 2>/dev/null")
272 if not hash:
273 return
275 fd = os.popen("git cat-file blob %s" % hash[0])
276 blob = pickle.load(fd)
277 for k, v in blob.keys.items():
278 run_safely("git config %s %s" % (k, v))
280 self.cmd_repo("svn", blob.keys['svn-remote.svn.url'])
281 os.system("git config yap.svn.enabled 1")
282 run_safely("git fetch origin 'refs/remotes/svn/*:refs/remotes/svn/*'")
284 for b in blob.metadata.keys():
285 branch = os.path.join(".git", "svn", "svn", b)
286 os.makedirs(branch)
287 fd = file(os.path.join(branch, ".rev_map.%s" % blob.uuid), "w")
289 rev, metadata = blob.metadata[b]
290 fd.write(metadata)
291 run_command("git update-ref refs/remotes/svn/%s %s" % (b, rev))
293 def cmd_fetch(self, *args, **flags):
294 if self._applicable(args):
295 self._fetch_svn()
296 return
298 super(SvnPlugin, self).cmd_fetch(*args, **flags)
300 def cmd_push(self, *args, **flags):
301 if self._applicable(args):
302 if len (args) >= 2:
303 merge = args[1]
304 else:
305 current = get_output("git symbolic-ref HEAD")
306 if not current:
307 raise YapError("Not on a branch!")
309 current = current[0].replace('refs/heads/', '')
310 remote, merge = self._get_tracking(current)
311 if remote != "svn":
312 raise YapError("Need a branch name")
313 self._push_svn(merge, **flags)
314 return
315 super(SvnPlugin, self).cmd_push(*args, **flags)
317 @short_help("change options for the svn plugin")
318 def cmd_svn(self, subcmd):
319 "enable"
321 if subcmd not in ["enable"]:
322 raise TypeError
324 if "svn" in [x[0] for x in self._list_remotes()]:
325 raise YapError("A remote named 'svn' already exists")
328 if not run_command("git config svn-remote.svn.branches"):
329 raise YapError("Cannot currently enable in a repository with svn branches")
331 url = get_output("git config svn-remote.svn.url")
332 if not url:
333 raise YapError("Not a git-svn repository?")
334 fetch = get_output("git config svn-remote.svn.fetch")
335 assert fetch
336 lhs, rhs = fetch[0].split(':')
339 rev = get_output("git rev-parse %s" % rhs)
340 assert rev
341 run_safely("git update-ref refs/remotes/svn/trunk %s" % rev[0])
343 url = '/'.join((url[0], lhs))
344 self._configure_repo(url)
345 run_safely("git update-ref -d %s %s" % (rhs, rev[0]))
347 # We are intentionally overriding yap utility functions
348 def _filter_log(self, commit):
349 commit = super(SvnPlugin, self)._filter_log(commit)
350 if not self._enabled():
351 return commit
353 new = []
354 for line in commit:
355 if line.strip().startswith("git-svn-id:"):
356 while not new[-1].strip():
357 new = new[:-1]
359 urlrev = line.strip().split(' ')[1]
360 url, rev = urlrev.split('@')
361 hash = commit[0].split(' ')[1].strip()
362 if self._svn_next_rev != hash:
363 h2 = self._resolve_svn_rev(int(rev))
364 if h2 != hash:
365 continue
367 next_hash = get_output("git rev-parse --verify %s^" % hash)
368 if next_hash:
369 self._svn_next_rev = next_hash[0]
370 else:
371 self._svn_next_rev = None
372 root = get_output("git config svn-remote.svn.url")
373 assert root
374 url = url.replace(root[0], '')
375 new.insert(1, "Subversion: r%s %s\n" % (rev, url))
377 continue
378 new.append(line)
379 return new
381 def _resolve_svn_rev(self, revnum):
382 rev = None
383 gitdir = get_output("git rev-parse --git-dir")
384 assert gitdir
385 revmaps = os.path.join(gitdir[0], "svn", "svn",
386 "*", ".rev_map*")
387 revmaps = glob.glob(revmaps)
389 for f in revmaps:
390 rm = SVNRevMap(f)
391 idx = bisect.bisect_left(rm, revnum)
392 if idx >= len(rm) or rm[idx] != revnum:
393 continue
395 revnum, rev = rm.get_record(idx)
396 if hash == "0" * 40:
397 continue
398 break
400 if not rev:
401 rev = get_output("git svn find-rev r%d 2>/dev/null" % revnum)
402 if not rev:
403 rev = None
404 return rev
406 def _resolve_rev(self, *args, **flags):
407 rev = None
408 if args:
409 m = self.revpat.match(args[0])
410 if m is not None:
411 revnum = int(m.group(1))
412 rev = self._resolve_svn_rev(revnum)
414 if not rev:
415 rev = super(SvnPlugin, self)._resolve_rev(*args, **flags)
416 return rev