5 # Author: Simon Hausmann <hausmann@kde.org>
6 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
9 # - support integrations (at least p4i)
10 # - support p4 submit (hah!)
11 # - emulate p4's delete behavior: if a directory becomes empty delete it. continue
12 # with parent dir until non-empty dir is found.
14 import os
, string
, sys
, time
, os
.path
15 import marshal
, popen2
, getopt
, sha
22 createdBranches
= Set()
23 committedChanges
= Set()
24 branch
= "refs/heads/master"
25 globalPrefix
= previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
26 detectBranches
= False
28 if len(globalPrefix
) != 0:
29 globalPrefix
= globalPrefix
[:-1]
32 opts
, args
= getopt
.getopt(sys
.argv
[1:], "", [ "branch=", "detect-branches", "changesfile=", "silent", "known-branches=" ])
33 except getopt
.GetoptError
:
34 print "fixme, syntax error"
39 branch
= "refs/heads/" + a
40 elif o
== "--detect-branches":
42 elif o
== "--changesfile":
46 elif o
== "--known-branches":
47 for branch
in open(a
).readlines():
48 knownBranches
.add(branch
[:-1])
50 if len(args
) == 0 and len(globalPrefix
) != 0:
52 print "[using previously specified depot path %s]" % globalPrefix
54 print "usage: %s //depot/path[@revRange]" % sys
.argv
[0]
56 print " %s //depot/my/project/ -- to import the current head"
57 print " %s //depot/my/project/@all -- to import everything"
58 print " %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
60 print " (a ... is not needed in the path p4 specification, it's added implicitly)"
64 if len(globalPrefix
) != 0 and globalPrefix
!= args
[0]:
65 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (globalPrefix
, args
[0])
67 globalPrefix
= args
[0]
76 if globalPrefix
.find("@") != -1:
77 atIdx
= globalPrefix
.index("@")
78 changeRange
= globalPrefix
[atIdx
:]
79 if changeRange
== "@all":
81 elif changeRange
.find(",") == -1:
82 revision
= changeRange
84 globalPrefix
= globalPrefix
[0:atIdx
]
85 elif globalPrefix
.find("#") != -1:
86 hashIdx
= globalPrefix
.index("#")
87 revision
= globalPrefix
[hashIdx
:]
88 globalPrefix
= globalPrefix
[0:hashIdx
]
89 elif len(previousDepotPath
) == 0:
92 if globalPrefix
.endswith("..."):
93 globalPrefix
= globalPrefix
[:-3]
95 if not globalPrefix
.endswith("/"):
98 def p4File(depotPath
):
99 cacheKey
= "/tmp/p4cache/data-" + sha
.new(depotPath
).hexdigest()
105 data
= open(cacheKey
, "rb").read()
107 data
= os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
109 open(cacheKey
, "wb").write(data
)
114 fullCmd
= "p4 -G %s" % cmd
;
116 cacheKey
= sha
.new(fullCmd
).hexdigest()
117 cacheKey
= "/tmp/p4cache/cmd-" + cacheKey
124 pipe
= open(cacheKey
, "rb")
127 pipe
= os
.popen(fullCmd
, "rb")
132 entry
= marshal
.load(pipe
)
138 if not cached
and cacheDebug
:
139 pipe
= open(cacheKey
, "wb")
141 marshal
.dump(r
, pipe
)
147 list = p4CmdList(cmd
)
153 def extractFilesFromCommit(commit
):
156 while commit
.has_key("depotFile%s" % fnum
):
157 path
= commit
["depotFile%s" % fnum
]
158 if not path
.startswith(globalPrefix
):
160 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, globalPrefix, change)
166 file["rev"] = commit
["rev%s" % fnum
]
167 file["action"] = commit
["action%s" % fnum
]
168 file["type"] = commit
["type%s" % fnum
]
173 def isSubPathOf(first
, second
):
174 if not first
.startswith(second
):
178 return first
[len(second
)] == "/"
180 def branchesForCommit(files
):
185 relativePath
= file["path"][len(globalPrefix
):]
186 # strip off the filename
187 relativePath
= relativePath
[0:relativePath
.rfind("/")]
189 # if len(branches) == 0:
190 # branches.add(relativePath)
191 # knownBranches.add(relativePath)
194 ###### this needs more testing :)
196 for branch
in branches
:
197 if relativePath
== branch
:
200 # if relativePath.startswith(branch):
201 if isSubPathOf(relativePath
, branch
):
204 # if branch.startswith(relativePath):
205 if isSubPathOf(branch
, relativePath
):
206 branches
.remove(branch
)
212 for branch
in knownBranches
:
213 #if relativePath.startswith(branch):
214 if isSubPathOf(relativePath
, branch
):
215 if len(branches
) == 0:
216 relativePath
= branch
224 branches
.add(relativePath
)
225 knownBranches
.add(relativePath
)
229 def findBranchParent(branchPrefix
, files
):
232 if not path
.startswith(branchPrefix
):
234 action
= file["action"]
235 if action
!= "integrate" and action
!= "branch":
238 depotPath
= path
+ "#" + rev
240 log
= p4CmdList("filelog \"%s\"" % depotPath
)
242 print "eek! I got confused by the filelog of %s" % depotPath
246 if log
["action0"] != action
:
247 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
250 branchAction
= log
["how0,0"]
251 # if branchAction == "branch into" or branchAction == "ignored":
252 # continue # ignore for branching
254 if not branchAction
.endswith(" from"):
255 continue # ignore for branching
256 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
259 source
= log
["file0,0"]
260 if source
.startswith(branchPrefix
):
263 lastSourceRev
= log
["erev0,0"]
265 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
266 if len(sourceLog
) != 1:
267 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
269 sourceLog
= sourceLog
[0]
271 relPath
= source
[len(globalPrefix
):]
272 # strip off the filename
273 relPath
= relPath
[0:relPath
.rfind("/")]
275 for branch
in knownBranches
:
276 if isSubPathOf(relPath
, branch
):
277 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
278 return "refs/heads/%s" % branch
280 # print "%s is not a subpath of branch %s" % (relPath, branch)
284 def commit(details
, files
, branch
, branchPrefix
, parent
):
287 global committedChanges
289 epoch
= details
["time"]
290 author
= details
["user"]
292 gitStream
.write("commit %s\n" % branch
)
293 gitStream
.write("mark :%s\n" % details
["change"])
294 committedChanges
.add(int(details
["change"]))
297 committer
= "%s %s %s" % (users
[author
], epoch
, tz
)
299 committer
= "%s <a@b> %s %s" % (author
, epoch
, tz
)
301 gitStream
.write("committer %s\n" % committer
)
303 gitStream
.write("data <<EOT\n")
304 gitStream
.write(details
["desc"])
305 gitStream
.write("\n[ imported from %s; change %s ]\n" % (branchPrefix
, details
["change"]))
306 gitStream
.write("EOT\n\n")
309 gitStream
.write("from %s\n" % parent
)
313 if not path
.startswith(branchPrefix
):
315 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
318 depotPath
= path
+ "#" + rev
319 relPath
= path
[len(branchPrefix
):]
320 action
= file["action"]
322 if action
== "delete":
323 gitStream
.write("D %s\n" % relPath
)
326 if file["type"].startswith("x"):
329 data
= p4File(depotPath
)
331 gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
332 gitStream
.write("data %s\n" % len(data
))
333 gitStream
.write(data
)
334 gitStream
.write("\n")
336 gitStream
.write("\n")
338 lastChange
= int(details
["change"])
343 for output
in p4CmdList("users"):
344 if not output
.has_key("User"):
346 users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
351 if len(changeRange
) == 0:
353 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % branch
)
355 if output
.endswith("\n"):
357 tagIdx
= output
.index(" tags/p4/")
358 caretIdx
= output
.find("^")
362 rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
363 changeRange
= "@%s,#head" % rev
364 initialParent
= os
.popen("git-rev-parse %s" % branch
).read()[:-1]
365 initialTag
= "p4/%s" % (int(rev
) - 1)
369 tz
= - time
.timezone
/ 36
370 tzsign
= ("%s" % tz
)[0]
371 if tzsign
!= '+' and tzsign
!= '-':
372 tz
= "+" + ("%s" % tz
)
374 gitOutput
, gitStream
, gitError
= popen2
.popen3("git-fast-import")
376 if len(revision
) > 0:
377 print "Doing initial import of %s from revision %s" % (globalPrefix
, revision
)
379 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
380 details
["desc"] = "Initial import of %s from the state at revision %s" % (globalPrefix
, revision
)
381 details
["change"] = revision
385 for info
in p4CmdList("files %s...%s" % (globalPrefix
, revision
)):
386 change
= int(info
["change"])
387 if change
> newestRevision
:
388 newestRevision
= change
390 if info
["action"] == "delete":
393 for prop
in [ "depotFile", "rev", "action", "type" ]:
394 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
396 fileCnt
= fileCnt
+ 1
398 details
["change"] = newestRevision
401 commit(details
, extractFilesFromCommit(details
), branch
, globalPrefix
)
403 print gitError
.read()
408 if len(changesFile
) > 0:
409 output
= open(changesFile
).readlines()
412 changeSet
.add(int(line
))
414 for change
in changeSet
:
415 changes
.append(change
)
419 output
= os
.popen("p4 changes %s...%s" % (globalPrefix
, changeRange
)).readlines()
422 changeNum
= line
.split(" ")[1]
423 changes
.append(changeNum
)
427 if len(changes
) == 0:
429 print "no changes to import!"
433 for change
in changes
:
434 description
= p4Cmd("describe %s" % change
)
437 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
442 files
= extractFilesFromCommit(description
)
444 for branch
in branchesForCommit(files
):
445 knownBranches
.add(branch
)
446 branchPrefix
= globalPrefix
+ branch
+ "/"
449 ########### remove cnt!!!
450 if branch
not in createdBranches
and cnt
> 2:
451 createdBranches
.add(branch
)
452 parent
= findBranchParent(branchPrefix
, files
)
455 # elif len(parent) > 0:
456 # print "%s branched off of %s" % (branch, parent)
458 branch
= "refs/heads/" + branch
459 commit(description
, files
, branch
, branchPrefix
, parent
)
461 commit(description
, files
, branch
, globalPrefix
, initialParent
)
464 # print gitError.read()
470 gitStream
.write("reset refs/tags/p4/%s\n" % lastChange
)
471 gitStream
.write("from %s\n\n" % branch
);
478 os
.popen("git-repo-config p4.depotpath %s" % globalPrefix
).read()
479 if len(initialTag
) > 0:
480 os
.popen("git tag -d %s" % initialTag
).read()