svn: create a tagged blob with vital repository information
[yap.git] / plugins / svn.py
blob17fd426232bf8d16a8457ac46ad58c0db8b7652a
2 from yap import YapPlugin, 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
10 class RepoBlob(object):
11 def __init__(self, url, fetch):
12 self.url = url
13 self.fetch = fetch
15 self.uuid = None
16 self.branches = None
17 self.tags = None
18 self.metadata = {}
20 def add_metadata(self, branch):
21 assert branch not in self.metadata
22 gitdir = get_output("git rev-parse --git-dir")
23 assert gitdir
24 revmap = os.path.join(gitdir[0], "svn", "svn", branch, ".rev_map*")
25 revmap = glob.glob(revmap)[0]
26 uuid = revmap.split('.')[-1]
27 if self.uuid is None:
28 self.uuid = uuid
29 assert self.uuid == uuid
30 data = file(revmap).read()
31 self.metadata[branch] = data
33 class SvnPlugin(YapPlugin):
34 def __init__(self, yap):
35 self.yap = yap
37 def _get_root(self, url):
38 root = get_output("svn info %s 2>/dev/null | gawk '/Repository Root:/{print $3}'" % url)
39 if not root:
40 raise YapError("Not an SVN repo: %s" % url)
41 return root[0]
43 def _configure_repo(self, url, fetch=None):
44 root = self._get_root(url)
45 os.system("git config svn-remote.svn.url %s" % root)
46 if fetch is None:
47 trunk = url.replace(root, '').strip('/')
48 else:
49 trunk = fetch.split(':')[0]
50 os.system("git config svn-remote.svn.fetch %s:refs/remotes/svn/trunk"
51 % trunk)
53 branches = trunk.replace('trunk', 'branches')
54 os.system("git config svn-remote.svn.branches %s/*:refs/remotes/svn/*"
55 % branches)
56 tags = trunk.replace('trunk', 'tags')
57 os.system("git config svn-remote.svn.tags %s/*:refs/tags/*" % tags)
58 self.yap.cmd_repo("svn", url)
59 os.system("git config yap.svn.enabled 1")
61 def _create_tagged_blob(self):
62 url = get_output("git config svn-remote.svn.url")[0]
63 fetch = get_output("git config svn-remote.svn.fetch")[0]
64 blob = RepoBlob(url, fetch)
65 for b in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/svn/*'"):
66 b = b.replace('refs/remotes/svn/', '')
67 blob.add_metadata(b)
69 fd_w, fd_r = os.popen2("git hash-object -w --stdin")
70 import __builtin__
71 __builtin__.RepoBlob = RepoBlob
72 pickle.dump(blob, fd_w)
73 fd_w.close()
74 hash = fd_r.readline().strip()
75 run_safely("git tag -f yap-svn %s" % hash)
77 def _clone_svn(self, url, directory=None, **flags):
78 url = url.rstrip('/')
79 if directory is None:
80 directory = url.rsplit('/')[-1]
81 directory = directory.replace('.git', '')
83 try:
84 os.mkdir(directory)
85 except OSError:
86 raise YapError("Directory exists: %s" % directory)
87 os.chdir(directory)
89 self.yap.cmd_init()
90 run_command("git config svn-remote.svn.noMetadata 1")
91 self._configure_repo(url)
92 os.system("git svn fetch -r %s:HEAD" % flags.get('-r', '1'))
93 self._create_tagged_blob()
95 def _push_svn(self, branch, **flags):
96 if '-d' in flags:
97 raise YapError("Deleting svn branches not supported")
98 print "Verifying branch is up-to-date"
99 run_safely("git svn fetch svn")
101 branch = branch.replace('refs/heads/', '')
102 rev = get_output("git rev-parse --verify refs/remotes/svn/%s" % branch)
104 # Create the branch if requested
105 if not rev:
106 if '-c' not in flags:
107 raise YapError("No matching branch on the repo. Use -c to create a new branch there.")
108 src = get_output("git svn info | gawk '/URL:/{print $2}'")[0]
109 brev = get_output("git svn info | gawk '/Revision:/{print $2}'")[0]
110 root = get_output("git config svn-remote.svn.url")[0]
111 branch_path = get_output("git config svn-remote.svn.branches")[0].split(':')[0]
112 branch_path = branch_path.rstrip('/*')
113 dst = '/'.join((root, branch_path, branch))
115 # Create the branch in svn
116 run_safely("svn cp -r%s %s %s -m 'create branch %s'"
117 % (brev, src, dst, branch))
118 run_safely("git svn fetch svn")
119 rev = get_output("git rev-parse refs/remotes/svn/%s 2>/dev/null" % branch)
120 base = get_output("git svn find-rev r%s" % brev)
122 # Apply our commits to the new branch
123 try:
124 fd, tmpfile = tempfile.mkstemp("yap")
125 os.close(fd)
126 print base[0]
127 os.system("git format-patch -k --stdout '%s' > %s"
128 % (base[0], tmpfile))
129 start = get_output("git rev-parse HEAD")
130 self.yap.cmd_point("refs/remotes/svn/%s"
131 % branch, **{'-f': True})
133 stat = os.stat(tmpfile)
134 size = stat[6]
135 if size > 0:
136 rc = run_command("git am -3 %s" % tmpfile)
137 if (rc):
138 self.yap.cmd_point(start[0], **{'-f': True})
139 raise YapError("Failed to port changes to new svn branch")
140 finally:
141 os.unlink(tmpfile)
143 base = get_output("git merge-base HEAD %s" % rev[0])
144 if base[0] != rev[0]:
145 raise YapError("Branch not up-to-date. Update first.")
146 current = get_output("git symbolic-ref HEAD")
147 if not current:
148 raise YapError("Not on a branch!")
149 current = current[0].replace('refs/heads/', '')
150 self.yap._confirm_push(current, branch, "svn")
151 if run_command("git update-index --refresh"):
152 raise YapError("Can't push with uncommitted changes")
154 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
155 os.system("git svn dcommit")
156 run_safely("git svn rebase")
157 if not master:
158 master = get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
159 if master:
160 run_safely("git update-ref -d refs/heads/master %s" % master[0])
162 def _enabled(self):
163 enabled = get_output("git config yap.svn.enabled")
164 return bool(enabled)
166 # Ensure users don't accidentally kill our "svn" repo
167 def pre_repo(self, *args, **flags):
168 if not self._enabled():
169 return
170 if '-d' in flags and args and args[0] == "svn":
171 raise YapError("Refusing to delete special svn repository")
173 @takes_options("r:")
174 def cmd_clone(self, *args, **flags):
175 if args and not run_command("svn info %s" % args[0]):
176 self._clone_svn(*args, **flags)
177 else:
178 self.yap._call_base("cmd_clone", *args, **flags)
180 def cmd_fetch(self, *args, **flags):
181 if self._enabled():
182 if args and args[0] == 'svn':
183 os.system("git svn fetch svn")
184 self._create_tagged_blob()
185 return
186 elif not args:
187 current = get_output("git symbolic-ref HEAD")
188 if not current:
189 raise YapError("Not on a branch!")
191 current = current[0].replace('refs/heads/', '')
192 remote, merge = self.yap._get_tracking(current)
193 if remote == "svn":
194 os.system("git svn fetch svn")
195 self._create_tagged_blob()
196 return
197 self.yap._call_base("cmd_fetch", *args, **flags)
199 def cmd_push(self, *args, **flags):
200 if self._enabled():
201 if args and args[0] == 'svn':
202 if len (args) < 2:
203 raise YapError("Need a branch name")
204 self._push_svn(args[1], **flags)
205 return
206 elif not args:
207 current = get_output("git symbolic-ref HEAD")
208 if not current:
209 raise YapError("Not on a branch!")
211 current = current[0].replace('refs/heads/', '')
212 remote, merge = self.yap._get_tracking(current)
213 if remote == "svn":
214 self._push_svn(merge, **flags)
215 return
217 self.yap._call_base("cmd_push", *args, **flags)
219 @short_help("change options for the svn plugin")
220 def cmd_svn(self, subcmd):
221 "enable"
223 if subcmd not in ["enable"]:
224 raise TypeError
226 if "svn" in [x[0] for x in self.yap._list_remotes()]:
227 raise YapError("A remote named 'svn' already exists")
230 if not run_command("git config svn-remote.svn.branches"):
231 raise YapError("Cannot currently enable in a repository with svn branches")
233 url = get_output("git config svn-remote.svn.url")
234 if not url:
235 raise YapError("Not a git-svn repository?")
236 fetch = get_output("git config svn-remote.svn.fetch")
237 assert fetch
238 lhs, rhs = fetch[0].split(':')
241 rev = get_output("git rev-parse %s" % rhs)
242 assert rev
243 run_safely("git update-ref refs/remotes/svn/trunk %s" % rev[0])
245 url = '/'.join((url[0], lhs))
246 self._configure_repo(url)
247 run_safely("git update-ref -d %s %s" % (rhs, rev[0]))