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")
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
)
184 rc
= run_command("git am -3 %s" % tmpfile
)
186 self
.cmd_point(start
[0], **{'-f': True})
187 raise YapError("Failed to port changes to new svn branch")
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")
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")
206 master
= get_output("git rev-parse --verify refs/heads/master 2>/dev/null")
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
()
216 enabled
= get_output("git config yap.svn.enabled")
219 def _applicable(self
, args
):
220 if not self
._enabled
():
223 if args
and args
[0] == 'svn':
227 current
= get_output("git symbolic-ref HEAD")
229 raise YapError("Not on a branch!")
231 current
= current
[0].replace('refs/heads/', '')
232 remote
, merge
= self
._get
_tracking
(current
)
238 # Ensure users don't accidentally kill our "svn" repo
239 def cmd_repo(self
, *args
, **flags
):
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
)
246 def cmd_clone(self
, *args
, **flags
):
250 if (handled
and not args
[0].startswith("http")
251 and not args
[0].startswith("svn")
252 and not args
[0].startswith("file://")):
254 if handled
and run_command("svn info %s" % args
[0]):
258 self
._clone
_svn
(*args
, **flags
)
260 super(SvnPlugin
, self
).cmd_clone(*args
, **flags
)
266 run_safely("git fetch origin --tags")
267 hash = get_output("git rev-parse --verify refs/tags/yap-svn 2>/dev/null")
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
)
283 fd
= file(os
.path
.join(branch
, ".rev_map.%s" % blob
.uuid
), "w")
285 rev
, metadata
= blob
.metadata
[b
]
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
):
294 super(SvnPlugin
, self
).cmd_fetch(*args
, **flags
)
296 def cmd_push(self
, *args
, **flags
):
297 if self
._applicable
(args
):
301 current
= get_output("git symbolic-ref HEAD")
303 raise YapError("Not on a branch!")
305 current
= current
[0].replace('refs/heads/', '')
306 remote
, merge
= self
._get
_tracking
(current
)
308 raise YapError("Need a branch name")
309 self
._push
_svn
(merge
, **flags
)
311 super(SvnPlugin
, self
).cmd_push(*args
, **flags
)
313 @short_help("change options for the svn plugin")
314 def cmd_svn(self
, subcmd
):
317 if subcmd
not in ["enable"]:
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")
329 raise YapError("Not a git-svn repository?")
330 fetch
= get_output("git config svn-remote.svn.fetch")
332 lhs
, rhs
= fetch
[0].split(':')
335 rev
= get_output("git rev-parse %s" % rhs
)
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
():
351 if line
.strip().startswith("git-svn-id:"):
352 while not new
[-1].strip():
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:
361 root
= get_output("git config svn-remote.svn.url")
363 url
= url
.replace(root
[0], '')
364 new
.insert(1, "Subversion: r%s %s\n" % (rev
, url
))
370 def _resolve_svn_rev(self
, revnum
):
371 rev
= get_output("git svn find-rev r%d 2>/dev/null" % revnum
)
376 gitdir
= get_output("git rev-parse --git-dir")
378 revmaps
= os
.path
.join(gitdir
[0], "svn", "svn",
380 revmaps
= glob
.glob(revmaps
)
384 idx
= bisect
.bisect_left(rm
, revnum
)
385 if idx
>= len(rm
) or rm
[idx
] != revnum
:
388 revnum
, rev
= rm
.get_record(idx
)
394 def _resolve_rev(self
, *args
, **flags
):
397 m
= self
.revpat
.match(args
[0])
399 revnum
= int(m
.group(1))
400 rev
= self
._resolve
_svn
_rev
(revnum
)
403 rev
= super(SvnPlugin
, self
)._resolve
_rev
(*args
, **flags
)