2 from yap
.yap
import YapCore
, YapError
3 from yap
.util
import get_output
, takes_options
, run_command
, run_safely
, short_help
13 class RepoBlob(object):
14 def __init__(self
, keys
):
22 def add_metadata(self
, branch
):
23 assert branch
not in self
.metadata
24 gitdir
= get_output("git rev-parse --git-dir")
26 revmap
= os
.path
.join(gitdir
[0], "svn", "svn", branch
, ".rev_map*")
27 revmap
= glob
.glob(revmap
)
30 uuid
= revmap
[0].split('.')[-1]
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):
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
:
49 return self
.get_record(index
)[0]
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
)
62 hash = map(lambda x
: "%02x" % x
, record
[1:])
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
)
74 raise YapError("Not an SVN repo: %s" % url
)
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
)
81 trunk
= url
.replace(root
, '').strip('/')
83 trunk
= fetch
.split(':')[0]
84 os
.system("git config svn-remote.svn.fetch %s:refs/remotes/svn/trunk"
87 branches
= trunk
.replace('trunk', 'branches')
89 os
.system("git config svn-remote.svn.branches %s/*:refs/remotes/svn/*" % branches
)
90 tags
= trunk
.replace('trunk', 'tags')
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
):
98 for i
in get_output("git config --list | grep ^svn-remote.svn"):
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/', '')
106 fd_w
, fd_r
= os
.popen2("git hash-object -w --stdin")
107 pickle
.dump(blob
, fd_w
)
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
)
118 os
.unlink(os
.path
.join(path
, f
))
121 ref
= get_output("git rev-parse %s" % b
)
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', '')
134 raise YapError("Directory exists: %s" % directory
)
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
):
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
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
173 fd
, tmpfile
= tempfile
.mkstemp("yap")
176 os
.system("git format-patch -k --stdout '%s' > %s"
177 % (base
[0], tmpfile
))
178 start
= get_output("git rev-parse HEAD")
179 self
.cmd_point("refs/remotes/svn/%s"
180 % branch
, **{'-f': True})
182 stat
= os
.stat(tmpfile
)
185 rc
= run_command("git am -3 %s" % tmpfile
)
187 self
.cmd_point(start
[0], **{'-f': True})
188 raise YapError("Failed to port changes to new svn branch")
192 base
= get_output("git merge-base HEAD %s" % rev
[0])
193 if base
[0] != rev
[0]:
194 raise YapError("Branch not up-to-date. Update first.")
195 current
= get_output("git symbolic-ref HEAD")
197 raise YapError("Not on a branch!")
198 current
= current
[0].replace('refs/heads/', '')
199 self
._confirm
_push
(current
, branch
, "svn")
200 if run_command("git update-index --refresh"):
201 raise YapError("Can't push with uncommitted changes")
203 master
= get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
204 os
.system("git svn dcommit")
205 run_safely("git svn rebase")
207 master
= get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
209 run_safely("git update-ref -d refs/heads/master %s" % master
[0])
211 def _fetch_svn(self
):
212 os
.system("git svn fetch svn")
213 self
._create
_tagged
_blob
()
214 self
._cleanup
_branches
()
217 enabled
= get_output("git config yap.svn.enabled")
220 def _applicable(self
, args
):
221 if not self
._enabled
():
224 if args
and args
[0] == 'svn':
228 current
= get_output("git symbolic-ref HEAD")
230 raise YapError("Not on a branch!")
232 current
= current
[0].replace('refs/heads/', '')
233 remote
, merge
= self
._get
_tracking
(current
)
239 # Ensure users don't accidentally kill our "svn" repo
240 def cmd_repo(self
, *args
, **flags
):
242 if '-d' in flags
and args
and args
[0] == "svn":
243 raise YapError("Refusing to delete special svn repository")
244 super(SvnPlugin
, self
).cmd_repo(*args
, **flags
)
247 def cmd_clone(self
, *args
, **flags
):
251 if (handled
and not args
[0].startswith("http")
252 and not args
[0].startswith("svn")
253 and not args
[0].startswith("file://")):
255 if handled
and run_command("svn info %s" % args
[0]):
259 self
._clone
_svn
(*args
, **flags
)
261 super(SvnPlugin
, self
).cmd_clone(*args
, **flags
)
267 run_safely("git fetch origin --tags")
268 hash = get_output("git rev-parse --verify refs/tags/yap-svn 2>/dev/null")
272 fd
= os
.popen("git cat-file blob %s" % hash[0])
273 blob
= pickle
.load(fd
)
274 for k
, v
in blob
.keys
.items():
275 run_safely("git config %s %s" % (k
, v
))
277 self
.cmd_repo("svn", blob
.keys
['svn-remote.svn.url'])
278 os
.system("git config yap.svn.enabled 1")
279 run_safely("git fetch origin 'refs/remotes/svn/*:refs/remotes/svn/*'")
281 for b
in blob
.metadata
.keys():
282 branch
= os
.path
.join(".git", "svn", "svn", b
)
284 fd
= file(os
.path
.join(branch
, ".rev_map.%s" % blob
.uuid
), "w")
286 rev
, metadata
= blob
.metadata
[b
]
288 run_command("git update-ref refs/remotes/svn/%s %s" % (b
, rev
))
290 def cmd_fetch(self
, *args
, **flags
):
291 if self
._applicable
(args
):
295 super(SvnPlugin
, self
).cmd_fetch(*args
, **flags
)
297 def cmd_push(self
, *args
, **flags
):
298 if self
._applicable
(args
):
302 current
= get_output("git symbolic-ref HEAD")
304 raise YapError("Not on a branch!")
306 current
= current
[0].replace('refs/heads/', '')
307 remote
, merge
= self
._get
_tracking
(current
)
309 raise YapError("Need a branch name")
310 self
._push
_svn
(merge
, **flags
)
312 super(SvnPlugin
, self
).cmd_push(*args
, **flags
)
314 @short_help("change options for the svn plugin")
315 def cmd_svn(self
, subcmd
):
318 if subcmd
not in ["enable"]:
321 if "svn" in [x
[0] for x
in self
._list
_remotes
()]:
322 raise YapError("A remote named 'svn' already exists")
325 if not run_command("git config svn-remote.svn.branches"):
326 raise YapError("Cannot currently enable in a repository with svn branches")
328 url
= get_output("git config svn-remote.svn.url")
330 raise YapError("Not a git-svn repository?")
331 fetch
= get_output("git config svn-remote.svn.fetch")
333 lhs
, rhs
= fetch
[0].split(':')
336 rev
= get_output("git rev-parse %s" % rhs
)
338 run_safely("git update-ref refs/remotes/svn/trunk %s" % rev
[0])
340 url
= '/'.join((url
[0], lhs
))
341 self
._configure
_repo
(url
)
342 run_safely("git update-ref -d %s %s" % (rhs
, rev
[0]))
344 # We are intentionally overriding a yap utility function
345 def _resolve_rev(self
, *args
, **flags
):
348 m
= self
.revpat
.match(args
[0])
350 revnum
= int(m
.group(1))
351 rev
= get_output("git svn find-rev r%d 2>/dev/null" % revnum
)
354 gitdir
= get_output("git rev-parse --git-dir")
356 revmaps
= os
.path
.join(gitdir
[0], "svn", "svn",
359 revmaps
= glob
.glob(revmaps
)
363 idx
= bisect
.bisect_left(rm
, revnum
)
364 if idx
>= len(rm
) or rm
[idx
] != revnum
:
367 revnum
, rev
= rm
.get_record(idx
)
374 rev
= super(SvnPlugin
, self
)._resolve
_rev
(*args
, **flags
)