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
23 createdBranches
= Set()
24 committedChanges
= Set()
25 branch
= "refs/heads/master"
26 globalPrefix
= previousDepotPath
= os
.popen("git-repo-config --get p4.depotpath").read()
27 detectBranches
= False
29 if len(globalPrefix
) != 0:
30 globalPrefix
= globalPrefix
[:-1]
33 opts
, args
= getopt
.getopt(sys
.argv
[1:], "", [ "branch=", "detect-branches", "changesfile=", "silent", "known-branches=",
34 "cache", "command-cache" ])
35 except getopt
.GetoptError
:
36 print "fixme, syntax error"
41 branch
= "refs/heads/" + a
42 elif o
== "--detect-branches":
44 elif o
== "--changesfile":
48 elif o
== "--known-branches":
49 for branch
in open(a
).readlines():
50 knownBranches
.add(branch
[:-1])
54 elif o
== "--command-cache":
57 if len(args
) == 0 and len(globalPrefix
) != 0:
59 print "[using previously specified depot path %s]" % globalPrefix
61 print "usage: %s //depot/path[@revRange]" % sys
.argv
[0]
63 print " %s //depot/my/project/ -- to import the current head"
64 print " %s //depot/my/project/@all -- to import everything"
65 print " %s //depot/my/project/@1,6 -- to import only from revision 1 to 6"
67 print " (a ... is not needed in the path p4 specification, it's added implicitly)"
71 if len(globalPrefix
) != 0 and globalPrefix
!= args
[0]:
72 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (globalPrefix
, args
[0])
74 globalPrefix
= args
[0]
83 if globalPrefix
.find("@") != -1:
84 atIdx
= globalPrefix
.index("@")
85 changeRange
= globalPrefix
[atIdx
:]
86 if changeRange
== "@all":
88 elif changeRange
.find(",") == -1:
89 revision
= changeRange
91 globalPrefix
= globalPrefix
[0:atIdx
]
92 elif globalPrefix
.find("#") != -1:
93 hashIdx
= globalPrefix
.index("#")
94 revision
= globalPrefix
[hashIdx
:]
95 globalPrefix
= globalPrefix
[0:hashIdx
]
96 elif len(previousDepotPath
) == 0:
99 if globalPrefix
.endswith("..."):
100 globalPrefix
= globalPrefix
[:-3]
102 if not globalPrefix
.endswith("/"):
105 def p4File(depotPath
):
106 cacheKey
= "/tmp/p4cache/data-" + sha
.new(depotPath
).hexdigest()
112 data
= open(cacheKey
, "rb").read()
114 data
= os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
116 open(cacheKey
, "wb").write(data
)
121 fullCmd
= "p4 -G %s" % cmd
;
123 cacheKey
= sha
.new(fullCmd
).hexdigest()
124 cacheKey
= "/tmp/p4cache/cmd-" + cacheKey
131 pipe
= open(cacheKey
, "rb")
134 pipe
= os
.popen(fullCmd
, "rb")
139 entry
= marshal
.load(pipe
)
145 if not cached
and commandCache
:
146 pipe
= open(cacheKey
, "wb")
148 marshal
.dump(r
, pipe
)
154 list = p4CmdList(cmd
)
160 def extractFilesFromCommit(commit
):
163 while commit
.has_key("depotFile%s" % fnum
):
164 path
= commit
["depotFile%s" % fnum
]
165 if not path
.startswith(globalPrefix
):
167 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, globalPrefix, change)
173 file["rev"] = commit
["rev%s" % fnum
]
174 file["action"] = commit
["action%s" % fnum
]
175 file["type"] = commit
["type%s" % fnum
]
180 def isSubPathOf(first
, second
):
181 if not first
.startswith(second
):
185 return first
[len(second
)] == "/"
187 def branchesForCommit(files
):
192 relativePath
= file["path"][len(globalPrefix
):]
193 # strip off the filename
194 relativePath
= relativePath
[0:relativePath
.rfind("/")]
196 # if len(branches) == 0:
197 # branches.add(relativePath)
198 # knownBranches.add(relativePath)
201 ###### this needs more testing :)
203 for branch
in branches
:
204 if relativePath
== branch
:
207 # if relativePath.startswith(branch):
208 if isSubPathOf(relativePath
, branch
):
211 # if branch.startswith(relativePath):
212 if isSubPathOf(branch
, relativePath
):
213 branches
.remove(branch
)
219 for branch
in knownBranches
:
220 #if relativePath.startswith(branch):
221 if isSubPathOf(relativePath
, branch
):
222 if len(branches
) == 0:
223 relativePath
= branch
231 branches
.add(relativePath
)
232 knownBranches
.add(relativePath
)
236 def findBranchParent(branchPrefix
, files
):
239 if not path
.startswith(branchPrefix
):
241 action
= file["action"]
242 if action
!= "integrate" and action
!= "branch":
245 depotPath
= path
+ "#" + rev
247 log
= p4CmdList("filelog \"%s\"" % depotPath
)
249 print "eek! I got confused by the filelog of %s" % depotPath
253 if log
["action0"] != action
:
254 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
257 branchAction
= log
["how0,0"]
258 # if branchAction == "branch into" or branchAction == "ignored":
259 # continue # ignore for branching
261 if not branchAction
.endswith(" from"):
262 continue # ignore for branching
263 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
266 source
= log
["file0,0"]
267 if source
.startswith(branchPrefix
):
270 lastSourceRev
= log
["erev0,0"]
272 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
273 if len(sourceLog
) != 1:
274 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
276 sourceLog
= sourceLog
[0]
278 relPath
= source
[len(globalPrefix
):]
279 # strip off the filename
280 relPath
= relPath
[0:relPath
.rfind("/")]
282 for branch
in knownBranches
:
283 if isSubPathOf(relPath
, branch
):
284 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
287 # print "%s is not a subpath of branch %s" % (relPath, branch)
291 def commit(details
, files
, branch
, branchPrefix
, parent
, merged
= ""):
294 global committedChanges
296 epoch
= details
["time"]
297 author
= details
["user"]
299 gitStream
.write("commit %s\n" % branch
)
300 # gitStream.write("mark :%s\n" % details["change"])
301 committedChanges
.add(int(details
["change"]))
304 committer
= "%s %s %s" % (users
[author
], epoch
, tz
)
306 committer
= "%s <a@b> %s %s" % (author
, epoch
, tz
)
308 gitStream
.write("committer %s\n" % committer
)
310 gitStream
.write("data <<EOT\n")
311 gitStream
.write(details
["desc"])
312 gitStream
.write("\n[ imported from %s; change %s ]\n" % (branchPrefix
, details
["change"]))
313 gitStream
.write("EOT\n\n")
316 gitStream
.write("from %s\n" % parent
)
319 gitStream
.write("merge %s\n" % merged
)
323 if not path
.startswith(branchPrefix
):
325 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
328 depotPath
= path
+ "#" + rev
329 relPath
= path
[len(branchPrefix
):]
330 action
= file["action"]
332 if file["type"] == "apple":
333 print "\nfile %s is a strange apple file that forks. Ignoring!" %s path
336 if action
== "delete":
337 gitStream
.write("D %s\n" % relPath
)
340 if file["type"].startswith("x"):
343 data
= p4File(depotPath
)
345 gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
346 gitStream
.write("data %s\n" % len(data
))
347 gitStream
.write(data
)
348 gitStream
.write("\n")
350 gitStream
.write("\n")
352 lastChange
= int(details
["change"])
354 def extractFilesInCommitToBranch(files
, branchPrefix
):
359 if path
.startswith(branchPrefix
):
360 newFiles
.append(file)
364 def findBranchSourceHeuristic(files
, branch
, branchPrefix
):
366 action
= file["action"]
367 if action
!= "integrate" and action
!= "branch":
371 depotPath
= path
+ "#" + rev
373 log
= p4CmdList("filelog \"%s\"" % depotPath
)
375 print "eek! I got confused by the filelog of %s" % depotPath
379 if log
["action0"] != action
:
380 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath
, log
["action0"], action
)
383 branchAction
= log
["how0,0"]
385 if not branchAction
.endswith(" from"):
386 continue # ignore for branching
387 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
390 source
= log
["file0,0"]
391 if source
.startswith(branchPrefix
):
394 lastSourceRev
= log
["erev0,0"]
396 sourceLog
= p4CmdList("filelog -m 1 \"%s%s\"" % (source
, lastSourceRev
))
397 if len(sourceLog
) != 1:
398 print "eek! I got confused by the source filelog of %s%s" % (source
, lastSourceRev
)
400 sourceLog
= sourceLog
[0]
402 relPath
= source
[len(globalPrefix
):]
403 # strip off the filename
404 relPath
= relPath
[0:relPath
.rfind("/")]
406 for candidate
in knownBranches
:
407 if isSubPathOf(relPath
, candidate
) and candidate
!= branch
:
412 def changeIsBranchMerge(sourceBranch
, destinationBranch
, change
):
414 for file in p4CmdList("files %s...@%s" % (globalPrefix
+ sourceBranch
+ "/", change
)):
415 if file["action"] == "delete":
417 sourceFiles
[file["depotFile"]] = file
419 destinationFiles
= {}
420 for file in p4CmdList("files %s...@%s" % (globalPrefix
+ destinationBranch
+ "/", change
)):
421 destinationFiles
[file["depotFile"]] = file
423 for fileName
in sourceFiles
.keys():
427 for integration
in p4CmdList("integrated \"%s\"" % fileName
):
428 toFile
= integration
["fromFile"] # yes, it's true, it's fromFile
429 if not toFile
in destinationFiles
:
431 destFile
= destinationFiles
[toFile
]
432 if destFile
["action"] == "delete":
433 # print "file %s has been deleted in %s" % (fileName, toFile)
436 integrationCount
+= 1
437 if integration
["how"] == "branch from":
440 if int(integration
["change"]) == change
:
441 integrations
.append(integration
)
443 if int(integration
["change"]) > change
:
446 destRev
= int(destFile
["rev"])
448 startRev
= integration
["startFromRev"][1:]
449 if startRev
== "none":
452 startRev
= int(startRev
)
454 endRev
= integration
["endFromRev"][1:]
460 initialBranch
= (destRev
== 1 and integration
["how"] != "branch into")
461 inRange
= (destRev
>= startRev
and destRev
<= endRev
)
462 newer
= (destRev
> startRev
and destRev
> endRev
)
464 if initialBranch
or inRange
or newer
:
465 integrations
.append(integration
)
470 if len(integrations
) == 0 and integrationCount
> 1:
471 print "file %s was not integrated from %s into %s" % (fileName
, sourceBranch
, destinationBranch
)
479 for output
in p4CmdList("users"):
480 if not output
.has_key("User"):
482 users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
487 if len(changeRange
) == 0:
489 sout
, sin
, serr
= popen2
.popen3("git-name-rev --tags `git-rev-parse %s`" % branch
)
491 if output
.endswith("\n"):
493 tagIdx
= output
.index(" tags/p4/")
494 caretIdx
= output
.find("^")
498 rev
= int(output
[tagIdx
+ 9 : endPos
]) + 1
499 changeRange
= "@%s,#head" % rev
500 initialParent
= os
.popen("git-rev-parse %s" % branch
).read()[:-1]
501 initialTag
= "p4/%s" % (int(rev
) - 1)
505 tz
= - time
.timezone
/ 36
506 tzsign
= ("%s" % tz
)[0]
507 if tzsign
!= '+' and tzsign
!= '-':
508 tz
= "+" + ("%s" % tz
)
510 gitOutput
, gitStream
, gitError
= popen2
.popen3("git-fast-import")
512 if len(revision
) > 0:
513 print "Doing initial import of %s from revision %s" % (globalPrefix
, revision
)
515 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
516 details
["desc"] = "Initial import of %s from the state at revision %s" % (globalPrefix
, revision
)
517 details
["change"] = revision
521 for info
in p4CmdList("files %s...%s" % (globalPrefix
, revision
)):
522 change
= int(info
["change"])
523 if change
> newestRevision
:
524 newestRevision
= change
526 if info
["action"] == "delete":
529 for prop
in [ "depotFile", "rev", "action", "type" ]:
530 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
532 fileCnt
= fileCnt
+ 1
534 details
["change"] = newestRevision
537 commit(details
, extractFilesFromCommit(details
), branch
, globalPrefix
)
539 print gitError
.read()
544 if len(changesFile
) > 0:
545 output
= open(changesFile
).readlines()
548 changeSet
.add(int(line
))
550 for change
in changeSet
:
551 changes
.append(change
)
555 output
= os
.popen("p4 changes %s...%s" % (globalPrefix
, changeRange
)).readlines()
558 changeNum
= line
.split(" ")[1]
559 changes
.append(changeNum
)
563 if len(changes
) == 0:
565 print "no changes to import!"
569 for change
in changes
:
570 description
= p4Cmd("describe %s" % change
)
573 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
578 files
= extractFilesFromCommit(description
)
580 for branch
in branchesForCommit(files
):
581 knownBranches
.add(branch
)
582 branchPrefix
= globalPrefix
+ branch
+ "/"
584 filesForCommit
= extractFilesInCommitToBranch(files
, branchPrefix
)
588 ########### remove cnt!!!
589 if branch
not in createdBranches
and cnt
> 2:
590 createdBranches
.add(branch
)
591 parent
= findBranchParent(branchPrefix
, files
)
594 # elif len(parent) > 0:
595 # print "%s branched off of %s" % (branch, parent)
598 merged
= findBranchSourceHeuristic(filesForCommit
, branch
, branchPrefix
)
600 print "change %s could be a merge from %s into %s" % (description
["change"], merged
, branch
)
601 if not changeIsBranchMerge(merged
, branch
, int(description
["change"])):
604 branch
= "refs/heads/" + branch
606 parent
= "refs/heads/" + parent
608 merged
= "refs/heads/" + merged
609 commit(description
, files
, branch
, branchPrefix
, parent
, merged
)
611 commit(description
, filesForCommit
, branch
, globalPrefix
, initialParent
)
614 print gitError
.read()
620 gitStream
.write("reset refs/tags/p4/%s\n" % lastChange
)
621 gitStream
.write("from %s\n\n" % branch
);
628 os
.popen("git-repo-config p4.depotpath %s" % globalPrefix
).read()
629 if len(initialTag
) > 0:
630 os
.popen("git tag -d %s" % initialTag
).read()