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: * implement git-p4 rollback <perforce change number> for debugging
11 # to roll back all p4 remote branches to a commit older or equal to
12 # the specified change.
13 # * for git-p4 submit --direct it would be nice to still create a
14 # git commit without updating HEAD before submitting to perforce.
15 # With the commit sha1 printed (or recoded in a .git/foo file?)
16 # it's possible to recover if anything goes wrong instead of potentially
17 # loosing a change entirely because it was never comitted to git and
18 # the p4 submit failed (or resulted in lots of conflicts, etc.)
19 # * Consider making --with-origin the default, assuming that the git
20 # protocol is always more efficient. (needs manual testing first :)
23 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
24 import tempfile
, getopt
, sha
, os
.path
, time
, platform
27 gitdir
= os
.environ
.get("GIT_DIR", "")
30 return os
.popen(command
, "rb");
33 cmd
= "p4 -G %s" % cmd
34 pipe
= os
.popen(cmd
, "rb")
39 entry
= marshal
.load(pipe
)
54 def p4Where(depotPath
):
55 if not depotPath
.endswith("/"):
57 output
= p4Cmd("where %s..." % depotPath
)
58 if output
["code"] == "error":
62 clientPath
= output
.get("path")
63 elif "data" in output
:
64 data
= output
.get("data")
65 lastSpace
= data
.rfind(" ")
66 clientPath
= data
[lastSpace
+ 1:]
68 if clientPath
.endswith("..."):
69 clientPath
= clientPath
[:-3]
73 sys
.stderr
.write(msg
+ "\n")
76 def currentGitBranch():
77 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
79 def isValidGitDir(path
):
80 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
84 def parseRevision(ref
):
85 return mypopen("git rev-parse %s" % ref
).read()[:-1]
88 if os
.system(cmd
) != 0:
89 die("command failed: %s" % cmd
)
91 def extractLogMessageFromGitCommit(commit
):
94 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
103 def extractDepotPathAndChangeFromGitLog(log
):
105 for line
in log
.split("\n"):
107 if line
.startswith("[git-p4:") and line
.endswith("]"):
108 line
= line
[8:-1].strip()
109 for assignment
in line
.split(":"):
110 variable
= assignment
.strip()
112 equalPos
= assignment
.find("=")
114 variable
= assignment
[:equalPos
].strip()
115 value
= assignment
[equalPos
+ 1:].strip()
116 if value
.startswith("\"") and value
.endswith("\""):
118 values
[variable
] = value
120 return values
.get("depot-path"), values
.get("change")
122 def gitBranchExists(branch
):
123 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
124 return proc
.wait() == 0;
128 self
.usage
= "usage: %prog [options]"
131 class P4Debug(Command
):
133 Command
.__init
__(self
)
136 self
.description
= "A tool to debug the output of p4 -G."
137 self
.needsGit
= False
140 for output
in p4CmdList(" ".join(args
)):
144 class P4Submit(Command
):
146 Command
.__init
__(self
)
148 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
149 optparse
.make_option("--origin", dest
="origin"),
150 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
151 optparse
.make_option("--log-substitutions", dest
="substFile"),
152 optparse
.make_option("--noninteractive", action
="store_false"),
153 optparse
.make_option("--dry-run", action
="store_true"),
154 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
156 self
.description
= "Submit changes from git to the perforce depot."
157 self
.usage
+= " [name of git branch to submit into perforce depot]"
158 self
.firstTime
= True
160 self
.interactive
= True
163 self
.firstTime
= True
165 self
.directSubmit
= False
167 self
.logSubstitutions
= {}
168 self
.logSubstitutions
["<enter description here>"] = "%log%"
169 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
172 if len(p4CmdList("opened ...")) > 0:
173 die("You have files opened with perforce! Close them before starting the sync.")
176 if len(self
.config
) > 0 and not self
.reset
:
177 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
)
180 if self
.directSubmit
:
183 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
184 commits
.append(line
[:-1])
187 self
.config
["commits"] = commits
189 def prepareLogMessage(self
, template
, message
):
192 for line
in template
.split("\n"):
193 if line
.startswith("#"):
194 result
+= line
+ "\n"
198 for key
in self
.logSubstitutions
.keys():
199 if line
.find(key
) != -1:
200 value
= self
.logSubstitutions
[key
]
201 value
= value
.replace("%log%", message
)
202 if value
!= "@remove@":
203 result
+= line
.replace(key
, value
) + "\n"
208 result
+= line
+ "\n"
213 if self
.directSubmit
:
214 print "Applying local change in working directory/index"
215 diff
= self
.diffStatus
217 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
218 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
220 filesToDelete
= set()
224 path
= line
[1:].strip()
226 system("p4 edit \"%s\"" % path
)
227 editedFiles
.add(path
)
228 elif modifier
== "A":
230 if path
in filesToDelete
:
231 filesToDelete
.remove(path
)
232 elif modifier
== "D":
233 filesToDelete
.add(path
)
234 if path
in filesToAdd
:
235 filesToAdd
.remove(path
)
237 die("unknown modifier %s for %s" % (modifier
, path
))
239 if self
.directSubmit
:
240 diffcmd
= "cat \"%s\"" % self
.diffFile
242 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
243 patchcmd
= diffcmd
+ " | git apply "
244 tryPatchCmd
= patchcmd
+ "--check -"
245 applyPatchCmd
= patchcmd
+ "--check --apply -"
247 if os
.system(tryPatchCmd
) != 0:
248 print "Unfortunately applying the change failed!"
249 print "What do you want to do?"
251 while response
!= "s" and response
!= "a" and response
!= "w":
252 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) ")
254 print "Skipping! Good luck with the next patches..."
256 elif response
== "a":
257 os
.system(applyPatchCmd
)
258 if len(filesToAdd
) > 0:
259 print "You may also want to call p4 add on the following files:"
260 print " ".join(filesToAdd
)
261 if len(filesToDelete
):
262 print "The following files should be scheduled for deletion with p4 delete:"
263 print " ".join(filesToDelete
)
264 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
265 elif response
== "w":
266 system(diffcmd
+ " > patch.txt")
267 print "Patch saved to patch.txt in %s !" % self
.clientPath
268 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
270 system(applyPatchCmd
)
273 system("p4 add %s" % f
)
274 for f
in filesToDelete
:
275 system("p4 revert %s" % f
)
276 system("p4 delete %s" % f
)
279 if not self
.directSubmit
:
280 logMessage
= extractLogMessageFromGitCommit(id)
281 logMessage
= logMessage
.replace("\n", "\n\t")
282 logMessage
= logMessage
[:-1]
284 template
= mypopen("p4 change -o").read()
287 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
288 diff
= mypopen("p4 diff -du ...").read()
290 for newFile
in filesToAdd
:
291 diff
+= "==== new file ====\n"
292 diff
+= "--- /dev/null\n"
293 diff
+= "+++ %s\n" % newFile
294 f
= open(newFile
, "r")
295 for line
in f
.readlines():
299 separatorLine
= "######## everything below this line is just the diff #######"
300 if platform
.system() == "Windows":
301 separatorLine
+= "\r"
302 separatorLine
+= "\n"
305 firstIteration
= True
306 while response
== "e":
307 if not firstIteration
:
308 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
309 firstIteration
= False
311 [handle
, fileName
] = tempfile
.mkstemp()
312 tmpFile
= os
.fdopen(handle
, "w+")
313 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
316 if platform
.system() == "Windows":
317 defaultEditor
= "notepad"
318 editor
= os
.environ
.get("EDITOR", defaultEditor
);
319 system(editor
+ " " + fileName
)
320 tmpFile
= open(fileName
, "rb")
321 message
= tmpFile
.read()
324 submitTemplate
= message
[:message
.index(separatorLine
)]
326 if response
== "y" or response
== "yes":
329 raw_input("Press return to continue...")
331 pipe
= os
.popen("p4 submit -i", "wb")
332 pipe
.write(submitTemplate
)
334 elif response
== "s":
335 for f
in editedFiles
:
336 system("p4 revert \"%s\"" % f
);
338 system("p4 revert \"%s\"" % f
);
340 for f
in filesToDelete
:
341 system("p4 delete \"%s\"" % f
);
344 print "Not submitting!"
345 self
.interactive
= False
347 fileName
= "submit.txt"
348 file = open(fileName
, "w+")
349 file.write(self
.prepareLogMessage(template
, logMessage
))
351 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
355 # make gitdir absolute so we can cd out into the perforce checkout
356 gitdir
= os
.path
.abspath(gitdir
)
357 os
.environ
["GIT_DIR"] = gitdir
360 self
.master
= currentGitBranch()
361 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
362 die("Detecting current git branch failed!")
364 self
.master
= args
[0]
369 if gitBranchExists("p4"):
370 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
371 if len(depotPath
) == 0 and gitBranchExists("origin"):
372 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
374 if len(depotPath
) == 0:
375 print "Internal error: cannot locate perforce depot path from existing branches"
378 self
.clientPath
= p4Where(depotPath
)
380 if len(self
.clientPath
) == 0:
381 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
384 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
385 oldWorkingDirectory
= os
.getcwd()
387 if self
.directSubmit
:
388 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
389 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
390 self
.diffFile
= gitdir
+ "/p4-git-diff"
391 f
= open(self
.diffFile
, "wb")
395 os
.chdir(self
.clientPath
)
396 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
397 if response
== "y" or response
== "yes":
398 system("p4 sync ...")
400 if len(self
.origin
) == 0:
401 if gitBranchExists("p4"):
404 self
.origin
= "origin"
407 self
.firstTime
= True
409 if len(self
.substFile
) > 0:
410 for line
in open(self
.substFile
, "r").readlines():
411 tokens
= line
[:-1].split("=")
412 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
415 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
416 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
421 commits
= self
.config
.get("commits", [])
423 while len(commits
) > 0:
424 self
.firstTime
= False
426 commits
= commits
[1:]
427 self
.config
["commits"] = commits
429 if not self
.interactive
:
434 if self
.directSubmit
:
435 os
.remove(self
.diffFile
)
437 if len(commits
) == 0:
439 print "No changes found to apply between %s and current HEAD" % self
.origin
441 print "All changes applied!"
443 os
.chdir(oldWorkingDirectory
)
445 if self
.directSubmit
:
446 response
= raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
447 if response
== "y" or response
== "yes":
448 system("git reset --hard")
450 if len(response
) == 0:
451 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
452 if response
== "y" or response
== "yes":
455 os
.remove(self
.configFile
)
459 class P4Sync(Command
):
461 Command
.__init
__(self
)
463 optparse
.make_option("--branch", dest
="branch"),
464 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
465 optparse
.make_option("--changesfile", dest
="changesFile"),
466 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
467 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
468 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
469 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
471 self
.description
= """Imports from Perforce into a git repository.\n
473 //depot/my/project/ -- to import the current head
474 //depot/my/project/@all -- to import everything
475 //depot/my/project/@1,6 -- to import only from revision 1 to 6
477 (a ... is not needed in the path p4 specification, it's added implicitly)"""
479 self
.usage
+= " //depot/path[@revRange]"
482 self
.createdBranches
= Set()
483 self
.committedChanges
= Set()
485 self
.detectBranches
= False
486 self
.detectLabels
= False
487 self
.changesFile
= ""
488 self
.syncWithOrigin
= False
491 def p4File(self
, depotPath
):
492 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
494 def extractFilesFromCommit(self
, commit
):
497 while commit
.has_key("depotFile%s" % fnum
):
498 path
= commit
["depotFile%s" % fnum
]
499 if not path
.startswith(self
.depotPath
):
500 # if not self.silent:
501 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
507 file["rev"] = commit
["rev%s" % fnum
]
508 file["action"] = commit
["action%s" % fnum
]
509 file["type"] = commit
["type%s" % fnum
]
514 def splitFilesIntoBranches(self
, commit
):
518 while commit
.has_key("depotFile%s" % fnum
):
519 path
= commit
["depotFile%s" % fnum
]
520 if not path
.startswith(self
.depotPath
):
521 # if not self.silent:
522 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
528 file["rev"] = commit
["rev%s" % fnum
]
529 file["action"] = commit
["action%s" % fnum
]
530 file["type"] = commit
["type%s" % fnum
]
533 relPath
= path
[len(self
.depotPath
):]
535 for branch
in self
.knownBranches
.keys():
536 if relPath
.startswith(branch
):
537 if branch
not in branches
:
538 branches
[branch
] = []
539 branches
[branch
].append(file)
543 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
544 epoch
= details
["time"]
545 author
= details
["user"]
548 print "commit into %s" % branch
550 self
.gitStream
.write("commit %s\n" % branch
)
551 # gitStream.write("mark :%s\n" % details["change"])
552 self
.committedChanges
.add(int(details
["change"]))
554 if author
not in self
.users
:
555 self
.getUserMapFromPerforceServer()
556 if author
in self
.users
:
557 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
559 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
561 self
.gitStream
.write("committer %s\n" % committer
)
563 self
.gitStream
.write("data <<EOT\n")
564 self
.gitStream
.write(details
["desc"])
565 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
566 self
.gitStream
.write("EOT\n\n")
570 print "parent %s" % parent
571 self
.gitStream
.write("from %s\n" % parent
)
575 if not path
.startswith(branchPrefix
):
577 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
580 depotPath
= path
+ "#" + rev
581 relPath
= path
[len(branchPrefix
):]
582 action
= file["action"]
584 if file["type"] == "apple":
585 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
588 if action
== "delete":
589 self
.gitStream
.write("D %s\n" % relPath
)
592 if file["type"].startswith("x"):
595 data
= self
.p4File(depotPath
)
597 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
598 self
.gitStream
.write("data %s\n" % len(data
))
599 self
.gitStream
.write(data
)
600 self
.gitStream
.write("\n")
602 self
.gitStream
.write("\n")
604 change
= int(details
["change"])
606 if self
.labels
.has_key(change
):
607 label
= self
.labels
[change
]
608 labelDetails
= label
[0]
609 labelRevisions
= label
[1]
611 print "Change %s is labelled %s" % (change
, labelDetails
)
613 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
615 if len(files
) == len(labelRevisions
):
619 if info
["action"] == "delete":
621 cleanedFiles
[info
["depotFile"]] = info
["rev"]
623 if cleanedFiles
== labelRevisions
:
624 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
625 self
.gitStream
.write("from %s\n" % branch
)
627 owner
= labelDetails
["Owner"]
629 if author
in self
.users
:
630 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
632 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
633 self
.gitStream
.write("tagger %s\n" % tagger
)
634 self
.gitStream
.write("data <<EOT\n")
635 self
.gitStream
.write(labelDetails
["Description"])
636 self
.gitStream
.write("EOT\n\n")
640 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
644 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
646 def getUserMapFromPerforceServer(self
):
649 for output
in p4CmdList("users"):
650 if not output
.has_key("User"):
652 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
654 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
655 for user
in self
.users
.keys():
656 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
659 def loadUserMapFromCache(self
):
662 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
663 lines
= cache
.readlines()
666 entry
= line
[:-1].split("\t")
667 self
.users
[entry
[0]] = entry
[1]
669 self
.getUserMapFromPerforceServer()
674 l
= p4CmdList("labels %s..." % self
.depotPath
)
675 if len(l
) > 0 and not self
.silent
:
676 print "Finding files belonging to labels in %s" % self
.depotPath
679 label
= output
["label"]
683 print "Querying files for label %s" % label
684 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
685 revisions
[file["depotFile"]] = file["rev"]
686 change
= int(file["change"])
687 if change
> newestChange
:
688 newestChange
= change
690 self
.labels
[newestChange
] = [output
, revisions
]
693 print "Label changes: %s" % self
.labels
.keys()
695 def getBranchMapping(self
):
696 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
698 for info
in p4CmdList("branches"):
699 details
= p4Cmd("branch -o %s" % info
["branch"])
701 while details
.has_key("View%s" % viewIdx
):
702 paths
= details
["View%s" % viewIdx
].split(" ")
703 viewIdx
= viewIdx
+ 1
704 # require standard //depot/foo/... //depot/bar/... mapping
705 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
708 destination
= paths
[1]
709 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
710 source
= source
[len(self
.depotPath
):-4]
711 destination
= destination
[len(self
.depotPath
):-4]
712 if destination
not in self
.knownBranches
:
713 self
.knownBranches
[destination
] = source
714 if source
not in self
.knownBranches
:
715 self
.knownBranches
[source
] = source
717 def listExistingP4GitBranches(self
):
718 self
.p4BranchesInGit
= []
720 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
721 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
723 self
.p4BranchesInGit
.append(branch
)
724 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
728 self
.changeRange
= ""
729 self
.initialParent
= ""
730 self
.previousDepotPath
= ""
731 # map from branch depot path to parent branch
732 self
.knownBranches
= {}
733 self
.initialParents
= {}
735 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
736 ### needs to be ported to multi branch import
738 print "Syncing with origin first as requested by calling git fetch origin"
739 system("git fetch origin")
740 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
741 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
742 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
743 if originPreviousDepotPath
== p4PreviousDepotPath
:
744 originP4Change
= int(originP4Change
)
745 p4Change
= int(p4Change
)
746 if originP4Change
> p4Change
:
747 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
748 system("git update-ref refs/remotes/p4/master origin");
750 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
752 if len(self
.branch
) == 0:
753 self
.branch
= "refs/remotes/p4/master"
754 if gitBranchExists("refs/heads/p4"):
755 system("git update-ref %s refs/heads/p4" % self
.branch
)
756 system("git branch -D p4");
757 if not gitBranchExists("refs/remotes/p4/HEAD"):
758 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
760 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
761 self
.listExistingP4GitBranches()
762 if len(self
.p4BranchesInGit
) > 1 and not self
.silent
:
763 print "Importing from/into multiple branches"
764 self
.detectBranches
= True
767 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
768 ### needs to be ported to multi branch import
770 print "Creating %s branch in git repository based on origin" % self
.branch
772 if not branch
.startswith("refs"):
773 branch
= "refs/heads/" + branch
774 system("git update-ref %s origin" % branch
)
777 print "branches: %s" % self
.p4BranchesInGit
780 for branch
in self
.p4BranchesInGit
:
781 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
784 print "path %s change %s" % (depotPath
, change
)
786 if len(depotPath
) > 0 and len(change
) > 0:
787 change
= int(change
) + 1
788 p4Change
= max(p4Change
, change
)
790 if len(self
.previousDepotPath
) == 0:
791 self
.previousDepotPath
= depotPath
794 l
= min(len(self
.previousDepotPath
), len(depotPath
))
795 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
797 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
800 self
.depotPath
= self
.previousDepotPath
801 self
.changeRange
= "@%s,#head" % p4Change
802 self
.initialParent
= parseRevision(self
.branch
)
803 if not self
.silent
and not self
.detectBranches
:
804 print "Performing incremental import into %s git branch" % self
.branch
806 if not self
.branch
.startswith("refs/"):
807 self
.branch
= "refs/heads/" + self
.branch
809 if len(self
.depotPath
) != 0:
810 self
.depotPath
= self
.depotPath
[:-1]
812 if len(args
) == 0 and len(self
.depotPath
) != 0:
814 print "Depot path: %s" % self
.depotPath
818 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
819 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
821 self
.depotPath
= args
[0]
826 if self
.depotPath
.find("@") != -1:
827 atIdx
= self
.depotPath
.index("@")
828 self
.changeRange
= self
.depotPath
[atIdx
:]
829 if self
.changeRange
== "@all":
830 self
.changeRange
= ""
831 elif self
.changeRange
.find(",") == -1:
832 self
.revision
= self
.changeRange
833 self
.changeRange
= ""
834 self
.depotPath
= self
.depotPath
[0:atIdx
]
835 elif self
.depotPath
.find("#") != -1:
836 hashIdx
= self
.depotPath
.index("#")
837 self
.revision
= self
.depotPath
[hashIdx
:]
838 self
.depotPath
= self
.depotPath
[0:hashIdx
]
839 elif len(self
.previousDepotPath
) == 0:
840 self
.revision
= "#head"
842 if self
.depotPath
.endswith("..."):
843 self
.depotPath
= self
.depotPath
[:-3]
845 if not self
.depotPath
.endswith("/"):
846 self
.depotPath
+= "/"
848 self
.loadUserMapFromCache()
850 if self
.detectLabels
:
853 if self
.detectBranches
:
854 self
.getBranchMapping();
856 print "p4-git branches: %s" % self
.p4BranchesInGit
857 print "initial parents: %s" % self
.initialParents
858 for b
in self
.p4BranchesInGit
:
860 b
= b
[len(self
.projectName
):]
861 self
.createdBranches
.add(b
)
863 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
865 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
866 self
.gitOutput
= importProcess
.stdout
867 self
.gitStream
= importProcess
.stdin
868 self
.gitError
= importProcess
.stderr
870 if len(self
.revision
) > 0:
871 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
873 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
874 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
875 details
["change"] = self
.revision
879 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
880 change
= int(info
["change"])
881 if change
> newestRevision
:
882 newestRevision
= change
884 if info
["action"] == "delete":
885 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
886 #fileCnt = fileCnt + 1
889 for prop
in [ "depotFile", "rev", "action", "type" ]:
890 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
892 fileCnt
= fileCnt
+ 1
894 details
["change"] = newestRevision
897 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
899 print "IO error with git fast-import. Is your git version recent enough?"
900 print self
.gitError
.read()
905 if len(self
.changesFile
) > 0:
906 output
= open(self
.changesFile
).readlines()
909 changeSet
.add(int(line
))
911 for change
in changeSet
:
912 changes
.append(change
)
917 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
918 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
921 changeNum
= line
.split(" ")[1]
922 changes
.append(changeNum
)
926 if len(changes
) == 0:
928 print "No changes to import!"
931 self
.updatedBranches
= set()
934 for change
in changes
:
935 description
= p4Cmd("describe %s" % change
)
938 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
943 if self
.detectBranches
:
944 branches
= self
.splitFilesIntoBranches(description
)
945 for branch
in branches
.keys():
946 branchPrefix
= self
.depotPath
+ branch
+ "/"
950 filesForCommit
= branches
[branch
]
953 print "branch is %s" % branch
955 self
.updatedBranches
.add(branch
)
957 if branch
not in self
.createdBranches
:
958 self
.createdBranches
.add(branch
)
959 parent
= self
.knownBranches
[branch
]
963 print "parent determined through known branches: %s" % parent
965 # main branch? use master
969 branch
= self
.projectName
+ branch
973 elif len(parent
) > 0:
974 parent
= self
.projectName
+ parent
976 branch
= "refs/remotes/p4/" + branch
978 parent
= "refs/remotes/p4/" + parent
981 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
983 if len(parent
) == 0 and branch
in self
.initialParents
:
984 parent
= self
.initialParents
[branch
]
985 del self
.initialParents
[branch
]
987 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
989 files
= self
.extractFilesFromCommit(description
)
990 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
991 self
.initialParent
= ""
993 print self
.gitError
.read()
998 if len(self
.updatedBranches
) > 0:
999 sys
.stdout
.write("Updated branches: ")
1000 for b
in self
.updatedBranches
:
1001 sys
.stdout
.write("%s " % b
)
1002 sys
.stdout
.write("\n")
1005 self
.gitStream
.close()
1006 if importProcess
.wait() != 0:
1007 die("fast-import failed: %s" % self
.gitError
.read())
1008 self
.gitOutput
.close()
1009 self
.gitError
.close()
1013 class P4Rebase(Command
):
1015 Command
.__init
__(self
)
1016 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
1017 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1018 self
.syncWithOrigin
= False
1020 def run(self
, args
):
1022 sync
.syncWithOrigin
= self
.syncWithOrigin
1024 print "Rebasing the current branch"
1025 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1026 system("git rebase p4")
1027 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1030 class P4Clone(P4Sync
):
1032 P4Sync
.__init
__(self
)
1033 self
.description
= "Creates a new git repository and imports from Perforce into it"
1034 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1035 self
.needsGit
= False
1037 def run(self
, args
):
1049 if not depotPath
.startswith("//"):
1054 atPos
= dir.rfind("@")
1057 hashPos
= dir.rfind("#")
1059 dir = dir[0:hashPos
]
1061 if dir.endswith("..."):
1064 if dir.endswith("/"):
1067 slashPos
= dir.rfind("/")
1069 dir = dir[slashPos
+ 1:]
1071 print "Importing from %s into %s" % (depotPath
, dir)
1075 gitdir
= os
.getcwd() + "/.git"
1076 if not P4Sync
.run(self
, [depotPath
]):
1078 if self
.branch
!= "master":
1079 if gitBranchExists("refs/remotes/p4/master"):
1080 system("git branch master refs/remotes/p4/master")
1081 system("git checkout -f")
1083 print "Could not detect main branch. No checkout/master branch created."
1086 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1088 optparse
.IndentedHelpFormatter
.__init
__(self
)
1090 def format_description(self
, description
):
1092 return description
+ "\n"
1096 def printUsage(commands
):
1097 print "usage: %s <command> [options]" % sys
.argv
[0]
1099 print "valid commands: %s" % ", ".join(commands
)
1101 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1105 "debug" : P4Debug(),
1106 "submit" : P4Submit(),
1108 "rebase" : P4Rebase(),
1112 if len(sys
.argv
[1:]) == 0:
1113 printUsage(commands
.keys())
1117 cmdName
= sys
.argv
[1]
1119 cmd
= commands
[cmdName
]
1121 print "unknown command %s" % cmdName
1123 printUsage(commands
.keys())
1126 options
= cmd
.options
1131 if len(options
) > 0:
1132 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1134 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1136 description
= cmd
.description
,
1137 formatter
= HelpFormatter())
1139 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1143 if len(gitdir
) == 0:
1145 if not isValidGitDir(gitdir
):
1146 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1147 if os
.path
.exists(gitdir
):
1148 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1152 if not isValidGitDir(gitdir
):
1153 if isValidGitDir(gitdir
+ "/.git"):
1156 die("fatal: cannot locate git repository at %s" % gitdir
)
1158 os
.environ
["GIT_DIR"] = gitdir
1160 if not cmd
.run(args
):