3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
10 # TODO: * Consider making --with-origin the default, assuming that the git
11 # protocol is always more efficient. (needs manual testing first :)
14 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
15 import tempfile
, getopt
, sha
, os
.path
, time
, platform
18 gitdir
= os
.environ
.get("GIT_DIR", "")
21 return os
.popen(command
, "rb");
24 cmd
= "p4 -G %s" % cmd
25 pipe
= os
.popen(cmd
, "rb")
30 entry
= marshal
.load(pipe
)
45 def p4Where(depotPath
):
46 if not depotPath
.endswith("/"):
48 output
= p4Cmd("where %s..." % depotPath
)
49 if output
["code"] == "error":
53 clientPath
= output
.get("path")
54 elif "data" in output
:
55 data
= output
.get("data")
56 lastSpace
= data
.rfind(" ")
57 clientPath
= data
[lastSpace
+ 1:]
59 if clientPath
.endswith("..."):
60 clientPath
= clientPath
[:-3]
64 sys
.stderr
.write(msg
+ "\n")
67 def currentGitBranch():
68 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
70 def isValidGitDir(path
):
71 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
75 def parseRevision(ref
):
76 return mypopen("git rev-parse %s" % ref
).read()[:-1]
79 if os
.system(cmd
) != 0:
80 die("command failed: %s" % cmd
)
82 def extractLogMessageFromGitCommit(commit
):
85 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
94 def extractDepotPathAndChangeFromGitLog(log
):
96 for line
in log
.split("\n"):
98 if line
.startswith("[git-p4:") and line
.endswith("]"):
99 line
= line
[8:-1].strip()
100 for assignment
in line
.split(":"):
101 variable
= assignment
.strip()
103 equalPos
= assignment
.find("=")
105 variable
= assignment
[:equalPos
].strip()
106 value
= assignment
[equalPos
+ 1:].strip()
107 if value
.startswith("\"") and value
.endswith("\""):
109 values
[variable
] = value
111 return values
.get("depot-path"), values
.get("change")
113 def gitBranchExists(branch
):
114 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
115 return proc
.wait() == 0;
119 self
.usage
= "usage: %prog [options]"
122 class P4Debug(Command
):
124 Command
.__init
__(self
)
127 self
.description
= "A tool to debug the output of p4 -G."
128 self
.needsGit
= False
131 for output
in p4CmdList(" ".join(args
)):
135 class P4RollBack(Command
):
137 Command
.__init
__(self
)
140 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
145 maxChange
= int(args
[0])
146 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
147 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
148 ref
= "refs/remotes/" + line
[:-1]
149 log
= extractLogMessageFromGitCommit(ref
)
150 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
152 while len(change
) > 0 and int(change
) > maxChange
:
154 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
155 system("git update-ref %s \"%s^\"" % (ref
, ref
))
156 log
= extractLogMessageFromGitCommit(ref
)
157 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
160 print "%s is at %s" % (ref
, change
)
164 class P4Submit(Command
):
166 Command
.__init
__(self
)
168 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
169 optparse
.make_option("--origin", dest
="origin"),
170 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
171 optparse
.make_option("--log-substitutions", dest
="substFile"),
172 optparse
.make_option("--noninteractive", action
="store_false"),
173 optparse
.make_option("--dry-run", action
="store_true"),
174 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
176 self
.description
= "Submit changes from git to the perforce depot."
177 self
.usage
+= " [name of git branch to submit into perforce depot]"
178 self
.firstTime
= True
180 self
.interactive
= True
183 self
.firstTime
= True
185 self
.directSubmit
= False
187 self
.logSubstitutions
= {}
188 self
.logSubstitutions
["<enter description here>"] = "%log%"
189 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
192 if len(p4CmdList("opened ...")) > 0:
193 die("You have files opened with perforce! Close them before starting the sync.")
196 if len(self
.config
) > 0 and not self
.reset
:
197 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self
.configFile
)
200 if self
.directSubmit
:
203 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
204 commits
.append(line
[:-1])
207 self
.config
["commits"] = commits
209 def prepareLogMessage(self
, template
, message
):
212 for line
in template
.split("\n"):
213 if line
.startswith("#"):
214 result
+= line
+ "\n"
218 for key
in self
.logSubstitutions
.keys():
219 if line
.find(key
) != -1:
220 value
= self
.logSubstitutions
[key
]
221 value
= value
.replace("%log%", message
)
222 if value
!= "@remove@":
223 result
+= line
.replace(key
, value
) + "\n"
228 result
+= line
+ "\n"
233 if self
.directSubmit
:
234 print "Applying local change in working directory/index"
235 diff
= self
.diffStatus
237 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
238 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
240 filesToDelete
= set()
244 path
= line
[1:].strip()
246 system("p4 edit \"%s\"" % path
)
247 editedFiles
.add(path
)
248 elif modifier
== "A":
250 if path
in filesToDelete
:
251 filesToDelete
.remove(path
)
252 elif modifier
== "D":
253 filesToDelete
.add(path
)
254 if path
in filesToAdd
:
255 filesToAdd
.remove(path
)
257 die("unknown modifier %s for %s" % (modifier
, path
))
259 if self
.directSubmit
:
260 diffcmd
= "cat \"%s\"" % self
.diffFile
262 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
263 patchcmd
= diffcmd
+ " | git apply "
264 tryPatchCmd
= patchcmd
+ "--check -"
265 applyPatchCmd
= patchcmd
+ "--check --apply -"
267 if os
.system(tryPatchCmd
) != 0:
268 print "Unfortunately applying the change failed!"
269 print "What do you want to do?"
271 while response
!= "s" and response
!= "a" and response
!= "w":
272 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
274 print "Skipping! Good luck with the next patches..."
276 elif response
== "a":
277 os
.system(applyPatchCmd
)
278 if len(filesToAdd
) > 0:
279 print "You may also want to call p4 add on the following files:"
280 print " ".join(filesToAdd
)
281 if len(filesToDelete
):
282 print "The following files should be scheduled for deletion with p4 delete:"
283 print " ".join(filesToDelete
)
284 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
285 elif response
== "w":
286 system(diffcmd
+ " > patch.txt")
287 print "Patch saved to patch.txt in %s !" % self
.clientPath
288 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
290 system(applyPatchCmd
)
293 system("p4 add %s" % f
)
294 for f
in filesToDelete
:
295 system("p4 revert %s" % f
)
296 system("p4 delete %s" % f
)
299 if not self
.directSubmit
:
300 logMessage
= extractLogMessageFromGitCommit(id)
301 logMessage
= logMessage
.replace("\n", "\n\t")
302 logMessage
= logMessage
[:-1]
304 template
= mypopen("p4 change -o").read()
307 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
308 diff
= mypopen("p4 diff -du ...").read()
310 for newFile
in filesToAdd
:
311 diff
+= "==== new file ====\n"
312 diff
+= "--- /dev/null\n"
313 diff
+= "+++ %s\n" % newFile
314 f
= open(newFile
, "r")
315 for line
in f
.readlines():
319 separatorLine
= "######## everything below this line is just the diff #######"
320 if platform
.system() == "Windows":
321 separatorLine
+= "\r"
322 separatorLine
+= "\n"
325 firstIteration
= True
326 while response
== "e":
327 if not firstIteration
:
328 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
329 firstIteration
= False
331 [handle
, fileName
] = tempfile
.mkstemp()
332 tmpFile
= os
.fdopen(handle
, "w+")
333 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
336 if platform
.system() == "Windows":
337 defaultEditor
= "notepad"
338 editor
= os
.environ
.get("EDITOR", defaultEditor
);
339 system(editor
+ " " + fileName
)
340 tmpFile
= open(fileName
, "rb")
341 message
= tmpFile
.read()
344 submitTemplate
= message
[:message
.index(separatorLine
)]
346 if response
== "y" or response
== "yes":
349 raw_input("Press return to continue...")
351 if self
.directSubmit
:
352 print "Submitting to git first"
353 os
.chdir(self
.oldWorkingDirectory
)
354 pipe
= os
.popen("git commit -a -F -", "wb")
355 pipe
.write(submitTemplate
)
357 os
.chdir(self
.clientPath
)
359 pipe
= os
.popen("p4 submit -i", "wb")
360 pipe
.write(submitTemplate
)
362 elif response
== "s":
363 for f
in editedFiles
:
364 system("p4 revert \"%s\"" % f
);
366 system("p4 revert \"%s\"" % f
);
368 for f
in filesToDelete
:
369 system("p4 delete \"%s\"" % f
);
372 print "Not submitting!"
373 self
.interactive
= False
375 fileName
= "submit.txt"
376 file = open(fileName
, "w+")
377 file.write(self
.prepareLogMessage(template
, logMessage
))
379 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
383 # make gitdir absolute so we can cd out into the perforce checkout
384 gitdir
= os
.path
.abspath(gitdir
)
385 os
.environ
["GIT_DIR"] = gitdir
388 self
.master
= currentGitBranch()
389 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
390 die("Detecting current git branch failed!")
392 self
.master
= args
[0]
397 if gitBranchExists("p4"):
398 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
399 if len(depotPath
) == 0 and gitBranchExists("origin"):
400 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
402 if len(depotPath
) == 0:
403 print "Internal error: cannot locate perforce depot path from existing branches"
406 self
.clientPath
= p4Where(depotPath
)
408 if len(self
.clientPath
) == 0:
409 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
412 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
413 self
.oldWorkingDirectory
= os
.getcwd()
415 if self
.directSubmit
:
416 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
417 if len(self
.diffStatus
) == 0:
418 print "No changes in working directory to submit."
420 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
421 self
.diffFile
= gitdir
+ "/p4-git-diff"
422 f
= open(self
.diffFile
, "wb")
426 os
.chdir(self
.clientPath
)
427 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
428 if response
== "y" or response
== "yes":
429 system("p4 sync ...")
431 if len(self
.origin
) == 0:
432 if gitBranchExists("p4"):
435 self
.origin
= "origin"
438 self
.firstTime
= True
440 if len(self
.substFile
) > 0:
441 for line
in open(self
.substFile
, "r").readlines():
442 tokens
= line
[:-1].split("=")
443 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
446 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
447 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
452 commits
= self
.config
.get("commits", [])
454 while len(commits
) > 0:
455 self
.firstTime
= False
457 commits
= commits
[1:]
458 self
.config
["commits"] = commits
460 if not self
.interactive
:
465 if self
.directSubmit
:
466 os
.remove(self
.diffFile
)
468 if len(commits
) == 0:
470 print "No changes found to apply between %s and current HEAD" % self
.origin
472 print "All changes applied!"
473 os
.chdir(self
.oldWorkingDirectory
)
474 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
475 if response
== "y" or response
== "yes":
478 os
.remove(self
.configFile
)
482 class P4Sync(Command
):
484 Command
.__init
__(self
)
486 optparse
.make_option("--branch", dest
="branch"),
487 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
488 optparse
.make_option("--changesfile", dest
="changesFile"),
489 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
490 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
491 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
492 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
494 self
.description
= """Imports from Perforce into a git repository.\n
496 //depot/my/project/ -- to import the current head
497 //depot/my/project/@all -- to import everything
498 //depot/my/project/@1,6 -- to import only from revision 1 to 6
500 (a ... is not needed in the path p4 specification, it's added implicitly)"""
502 self
.usage
+= " //depot/path[@revRange]"
505 self
.createdBranches
= Set()
506 self
.committedChanges
= Set()
508 self
.detectBranches
= False
509 self
.detectLabels
= False
510 self
.changesFile
= ""
511 self
.syncWithOrigin
= False
514 def p4File(self
, depotPath
):
515 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
517 def extractFilesFromCommit(self
, commit
):
520 while commit
.has_key("depotFile%s" % fnum
):
521 path
= commit
["depotFile%s" % fnum
]
522 if not path
.startswith(self
.depotPath
):
523 # if not self.silent:
524 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
530 file["rev"] = commit
["rev%s" % fnum
]
531 file["action"] = commit
["action%s" % fnum
]
532 file["type"] = commit
["type%s" % fnum
]
537 def splitFilesIntoBranches(self
, commit
):
541 while commit
.has_key("depotFile%s" % fnum
):
542 path
= commit
["depotFile%s" % fnum
]
543 if not path
.startswith(self
.depotPath
):
544 # if not self.silent:
545 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
551 file["rev"] = commit
["rev%s" % fnum
]
552 file["action"] = commit
["action%s" % fnum
]
553 file["type"] = commit
["type%s" % fnum
]
556 relPath
= path
[len(self
.depotPath
):]
558 for branch
in self
.knownBranches
.keys():
559 if relPath
.startswith(branch
):
560 if branch
not in branches
:
561 branches
[branch
] = []
562 branches
[branch
].append(file)
566 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
567 epoch
= details
["time"]
568 author
= details
["user"]
571 print "commit into %s" % branch
573 self
.gitStream
.write("commit %s\n" % branch
)
574 # gitStream.write("mark :%s\n" % details["change"])
575 self
.committedChanges
.add(int(details
["change"]))
577 if author
not in self
.users
:
578 self
.getUserMapFromPerforceServer()
579 if author
in self
.users
:
580 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
582 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
584 self
.gitStream
.write("committer %s\n" % committer
)
586 self
.gitStream
.write("data <<EOT\n")
587 self
.gitStream
.write(details
["desc"])
588 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
589 self
.gitStream
.write("EOT\n\n")
593 print "parent %s" % parent
594 self
.gitStream
.write("from %s\n" % parent
)
598 if not path
.startswith(branchPrefix
):
600 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
603 depotPath
= path
+ "#" + rev
604 relPath
= path
[len(branchPrefix
):]
605 action
= file["action"]
607 if file["type"] == "apple":
608 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
611 if action
== "delete":
612 self
.gitStream
.write("D %s\n" % relPath
)
615 if file["type"].startswith("x"):
618 data
= self
.p4File(depotPath
)
620 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
621 self
.gitStream
.write("data %s\n" % len(data
))
622 self
.gitStream
.write(data
)
623 self
.gitStream
.write("\n")
625 self
.gitStream
.write("\n")
627 change
= int(details
["change"])
629 if self
.labels
.has_key(change
):
630 label
= self
.labels
[change
]
631 labelDetails
= label
[0]
632 labelRevisions
= label
[1]
634 print "Change %s is labelled %s" % (change
, labelDetails
)
636 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
638 if len(files
) == len(labelRevisions
):
642 if info
["action"] == "delete":
644 cleanedFiles
[info
["depotFile"]] = info
["rev"]
646 if cleanedFiles
== labelRevisions
:
647 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
648 self
.gitStream
.write("from %s\n" % branch
)
650 owner
= labelDetails
["Owner"]
652 if author
in self
.users
:
653 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
655 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
656 self
.gitStream
.write("tagger %s\n" % tagger
)
657 self
.gitStream
.write("data <<EOT\n")
658 self
.gitStream
.write(labelDetails
["Description"])
659 self
.gitStream
.write("EOT\n\n")
663 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
667 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
669 def getUserMapFromPerforceServer(self
):
672 for output
in p4CmdList("users"):
673 if not output
.has_key("User"):
675 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
677 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
678 for user
in self
.users
.keys():
679 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
682 def loadUserMapFromCache(self
):
685 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
686 lines
= cache
.readlines()
689 entry
= line
[:-1].split("\t")
690 self
.users
[entry
[0]] = entry
[1]
692 self
.getUserMapFromPerforceServer()
697 l
= p4CmdList("labels %s..." % self
.depotPath
)
698 if len(l
) > 0 and not self
.silent
:
699 print "Finding files belonging to labels in %s" % self
.depotPath
702 label
= output
["label"]
706 print "Querying files for label %s" % label
707 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
708 revisions
[file["depotFile"]] = file["rev"]
709 change
= int(file["change"])
710 if change
> newestChange
:
711 newestChange
= change
713 self
.labels
[newestChange
] = [output
, revisions
]
716 print "Label changes: %s" % self
.labels
.keys()
718 def getBranchMapping(self
):
719 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
721 for info
in p4CmdList("branches"):
722 details
= p4Cmd("branch -o %s" % info
["branch"])
724 while details
.has_key("View%s" % viewIdx
):
725 paths
= details
["View%s" % viewIdx
].split(" ")
726 viewIdx
= viewIdx
+ 1
727 # require standard //depot/foo/... //depot/bar/... mapping
728 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
731 destination
= paths
[1]
732 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
733 source
= source
[len(self
.depotPath
):-4]
734 destination
= destination
[len(self
.depotPath
):-4]
735 if destination
not in self
.knownBranches
:
736 self
.knownBranches
[destination
] = source
737 if source
not in self
.knownBranches
:
738 self
.knownBranches
[source
] = source
740 def listExistingP4GitBranches(self
):
741 self
.p4BranchesInGit
= []
743 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
744 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
746 self
.p4BranchesInGit
.append(branch
)
747 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
751 self
.changeRange
= ""
752 self
.initialParent
= ""
753 self
.previousDepotPath
= ""
754 # map from branch depot path to parent branch
755 self
.knownBranches
= {}
756 self
.initialParents
= {}
758 createP4HeadRef
= False;
760 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
761 ### needs to be ported to multi branch import
763 print "Syncing with origin first as requested by calling git fetch origin"
764 system("git fetch origin")
765 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
766 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
767 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
768 if originPreviousDepotPath
== p4PreviousDepotPath
:
769 originP4Change
= int(originP4Change
)
770 p4Change
= int(p4Change
)
771 if originP4Change
> p4Change
:
772 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
773 system("git update-ref refs/remotes/p4/master origin");
775 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
777 if len(self
.branch
) == 0:
778 self
.branch
= "refs/remotes/p4/master"
779 if gitBranchExists("refs/heads/p4"):
780 system("git update-ref %s refs/heads/p4" % self
.branch
)
781 system("git branch -D p4");
782 # create it /after/ importing, when master exists
783 if not gitBranchExists("refs/remotes/p4/HEAD"):
784 createP4HeadRef
= True
786 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
787 self
.listExistingP4GitBranches()
788 if len(self
.p4BranchesInGit
) > 1 and not self
.silent
:
789 print "Importing from/into multiple branches"
790 self
.detectBranches
= True
793 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
794 ### needs to be ported to multi branch import
796 print "Creating %s branch in git repository based on origin" % self
.branch
798 if not branch
.startswith("refs"):
799 branch
= "refs/heads/" + branch
800 system("git update-ref %s origin" % branch
)
803 print "branches: %s" % self
.p4BranchesInGit
806 for branch
in self
.p4BranchesInGit
:
807 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
810 print "path %s change %s" % (depotPath
, change
)
812 if len(depotPath
) > 0 and len(change
) > 0:
813 change
= int(change
) + 1
814 p4Change
= max(p4Change
, change
)
816 if len(self
.previousDepotPath
) == 0:
817 self
.previousDepotPath
= depotPath
820 l
= min(len(self
.previousDepotPath
), len(depotPath
))
821 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
823 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
826 self
.depotPath
= self
.previousDepotPath
827 self
.changeRange
= "@%s,#head" % p4Change
828 self
.initialParent
= parseRevision(self
.branch
)
829 if not self
.silent
and not self
.detectBranches
:
830 print "Performing incremental import into %s git branch" % self
.branch
832 if not self
.branch
.startswith("refs/"):
833 self
.branch
= "refs/heads/" + self
.branch
835 if len(self
.depotPath
) != 0:
836 self
.depotPath
= self
.depotPath
[:-1]
838 if len(args
) == 0 and len(self
.depotPath
) != 0:
840 print "Depot path: %s" % self
.depotPath
844 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
845 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
847 self
.depotPath
= args
[0]
852 if self
.depotPath
.find("@") != -1:
853 atIdx
= self
.depotPath
.index("@")
854 self
.changeRange
= self
.depotPath
[atIdx
:]
855 if self
.changeRange
== "@all":
856 self
.changeRange
= ""
857 elif self
.changeRange
.find(",") == -1:
858 self
.revision
= self
.changeRange
859 self
.changeRange
= ""
860 self
.depotPath
= self
.depotPath
[0:atIdx
]
861 elif self
.depotPath
.find("#") != -1:
862 hashIdx
= self
.depotPath
.index("#")
863 self
.revision
= self
.depotPath
[hashIdx
:]
864 self
.depotPath
= self
.depotPath
[0:hashIdx
]
865 elif len(self
.previousDepotPath
) == 0:
866 self
.revision
= "#head"
868 if self
.depotPath
.endswith("..."):
869 self
.depotPath
= self
.depotPath
[:-3]
871 if not self
.depotPath
.endswith("/"):
872 self
.depotPath
+= "/"
874 self
.loadUserMapFromCache()
876 if self
.detectLabels
:
879 if self
.detectBranches
:
880 self
.getBranchMapping();
882 print "p4-git branches: %s" % self
.p4BranchesInGit
883 print "initial parents: %s" % self
.initialParents
884 for b
in self
.p4BranchesInGit
:
886 b
= b
[len(self
.projectName
):]
887 self
.createdBranches
.add(b
)
889 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
891 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
892 self
.gitOutput
= importProcess
.stdout
893 self
.gitStream
= importProcess
.stdin
894 self
.gitError
= importProcess
.stderr
896 if len(self
.revision
) > 0:
897 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
899 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
900 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
901 details
["change"] = self
.revision
905 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
906 change
= int(info
["change"])
907 if change
> newestRevision
:
908 newestRevision
= change
910 if info
["action"] == "delete":
911 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
912 #fileCnt = fileCnt + 1
915 for prop
in [ "depotFile", "rev", "action", "type" ]:
916 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
918 fileCnt
= fileCnt
+ 1
920 details
["change"] = newestRevision
923 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
925 print "IO error with git fast-import. Is your git version recent enough?"
926 print self
.gitError
.read()
931 if len(self
.changesFile
) > 0:
932 output
= open(self
.changesFile
).readlines()
935 changeSet
.add(int(line
))
937 for change
in changeSet
:
938 changes
.append(change
)
943 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
944 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
947 changeNum
= line
.split(" ")[1]
948 changes
.append(changeNum
)
952 if len(changes
) == 0:
954 print "No changes to import!"
957 self
.updatedBranches
= set()
960 for change
in changes
:
961 description
= p4Cmd("describe %s" % change
)
964 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
969 if self
.detectBranches
:
970 branches
= self
.splitFilesIntoBranches(description
)
971 for branch
in branches
.keys():
972 branchPrefix
= self
.depotPath
+ branch
+ "/"
976 filesForCommit
= branches
[branch
]
979 print "branch is %s" % branch
981 self
.updatedBranches
.add(branch
)
983 if branch
not in self
.createdBranches
:
984 self
.createdBranches
.add(branch
)
985 parent
= self
.knownBranches
[branch
]
989 print "parent determined through known branches: %s" % parent
991 # main branch? use master
995 branch
= self
.projectName
+ branch
999 elif len(parent
) > 0:
1000 parent
= self
.projectName
+ parent
1002 branch
= "refs/remotes/p4/" + branch
1004 parent
= "refs/remotes/p4/" + parent
1007 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1009 if len(parent
) == 0 and branch
in self
.initialParents
:
1010 parent
= self
.initialParents
[branch
]
1011 del self
.initialParents
[branch
]
1013 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1015 files
= self
.extractFilesFromCommit(description
)
1016 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1017 self
.initialParent
= ""
1019 print self
.gitError
.read()
1024 if len(self
.updatedBranches
) > 0:
1025 sys
.stdout
.write("Updated branches: ")
1026 for b
in self
.updatedBranches
:
1027 sys
.stdout
.write("%s " % b
)
1028 sys
.stdout
.write("\n")
1031 self
.gitStream
.close()
1032 if importProcess
.wait() != 0:
1033 die("fast-import failed: %s" % self
.gitError
.read())
1034 self
.gitOutput
.close()
1035 self
.gitError
.close()
1038 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
1042 class P4Rebase(Command
):
1044 Command
.__init
__(self
)
1045 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
1046 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1047 self
.syncWithOrigin
= False
1049 def run(self
, args
):
1051 sync
.syncWithOrigin
= self
.syncWithOrigin
1053 print "Rebasing the current branch"
1054 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1055 system("git rebase p4")
1056 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1059 class P4Clone(P4Sync
):
1061 P4Sync
.__init
__(self
)
1062 self
.description
= "Creates a new git repository and imports from Perforce into it"
1063 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1064 self
.needsGit
= False
1066 def run(self
, args
):
1078 if not depotPath
.startswith("//"):
1083 atPos
= dir.rfind("@")
1086 hashPos
= dir.rfind("#")
1088 dir = dir[0:hashPos
]
1090 if dir.endswith("..."):
1093 if dir.endswith("/"):
1096 slashPos
= dir.rfind("/")
1098 dir = dir[slashPos
+ 1:]
1100 print "Importing from %s into %s" % (depotPath
, dir)
1104 gitdir
= os
.getcwd() + "/.git"
1105 if not P4Sync
.run(self
, [depotPath
]):
1107 if self
.branch
!= "master":
1108 if gitBranchExists("refs/remotes/p4/master"):
1109 system("git branch master refs/remotes/p4/master")
1110 system("git checkout -f")
1112 print "Could not detect main branch. No checkout/master branch created."
1115 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1117 optparse
.IndentedHelpFormatter
.__init
__(self
)
1119 def format_description(self
, description
):
1121 return description
+ "\n"
1125 def printUsage(commands
):
1126 print "usage: %s <command> [options]" % sys
.argv
[0]
1128 print "valid commands: %s" % ", ".join(commands
)
1130 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1134 "debug" : P4Debug(),
1135 "submit" : P4Submit(),
1137 "rebase" : P4Rebase(),
1138 "clone" : P4Clone(),
1139 "rollback" : P4RollBack()
1142 if len(sys
.argv
[1:]) == 0:
1143 printUsage(commands
.keys())
1147 cmdName
= sys
.argv
[1]
1149 cmd
= commands
[cmdName
]
1151 print "unknown command %s" % cmdName
1153 printUsage(commands
.keys())
1156 options
= cmd
.options
1161 if len(options
) > 0:
1162 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1164 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1166 description
= cmd
.description
,
1167 formatter
= HelpFormatter())
1169 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1173 if len(gitdir
) == 0:
1175 if not isValidGitDir(gitdir
):
1176 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1177 if os
.path
.exists(gitdir
):
1178 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1182 if not isValidGitDir(gitdir
):
1183 if isValidGitDir(gitdir
+ "/.git"):
1186 die("fatal: cannot locate git repository at %s" % gitdir
)
1188 os
.environ
["GIT_DIR"] = gitdir
1190 if not cmd
.run(args
):