3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
, platform
16 gitdir
= os
.environ
.get("GIT_DIR", "")
19 return os
.popen(command
, "rb");
22 cmd
= "p4 -G %s" % cmd
23 pipe
= os
.popen(cmd
, "rb")
28 entry
= marshal
.load(pipe
)
32 exitCode
= pipe
.close()
35 entry
["p4ExitCode"] = exitCode
47 def p4Where(depotPath
):
48 if not depotPath
.endswith("/"):
50 output
= p4Cmd("where %s..." % depotPath
)
51 if output
["code"] == "error":
55 clientPath
= output
.get("path")
56 elif "data" in output
:
57 data
= output
.get("data")
58 lastSpace
= data
.rfind(" ")
59 clientPath
= data
[lastSpace
+ 1:]
61 if clientPath
.endswith("..."):
62 clientPath
= clientPath
[:-3]
66 sys
.stderr
.write(msg
+ "\n")
69 def currentGitBranch():
70 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
72 def isValidGitDir(path
):
73 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
77 def parseRevision(ref
):
78 return mypopen("git rev-parse %s" % ref
).read()[:-1]
81 if os
.system(cmd
) != 0:
82 die("command failed: %s" % cmd
)
84 def extractLogMessageFromGitCommit(commit
):
87 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
96 def extractDepotPathAndChangeFromGitLog(log
):
98 for line
in log
.split("\n"):
100 if line
.startswith("[git-p4:") and line
.endswith("]"):
101 line
= line
[8:-1].strip()
102 for assignment
in line
.split(":"):
103 variable
= assignment
.strip()
105 equalPos
= assignment
.find("=")
107 variable
= assignment
[:equalPos
].strip()
108 value
= assignment
[equalPos
+ 1:].strip()
109 if value
.startswith("\"") and value
.endswith("\""):
111 values
[variable
] = value
113 return values
.get("depot-path"), values
.get("change")
115 def gitBranchExists(branch
):
116 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
117 return proc
.wait() == 0;
120 return mypopen("git config %s" % key
).read()[:-1]
124 self
.usage
= "usage: %prog [options]"
127 class P4Debug(Command
):
129 Command
.__init
__(self
)
132 self
.description
= "A tool to debug the output of p4 -G."
133 self
.needsGit
= False
136 for output
in p4CmdList(" ".join(args
)):
140 class P4RollBack(Command
):
142 Command
.__init
__(self
)
144 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
145 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
147 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
149 self
.rollbackLocalBranches
= False
154 maxChange
= int(args
[0])
156 if "p4ExitCode" in p4Cmd("changes -m 1"):
157 die("Problems executing p4");
159 if self
.rollbackLocalBranches
:
160 refPrefix
= "refs/heads/"
161 lines
= mypopen("git rev-parse --symbolic --branches").readlines()
163 refPrefix
= "refs/remotes/"
164 lines
= mypopen("git rev-parse --symbolic --remotes").readlines()
167 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
168 ref
= refPrefix
+ line
[:-1]
169 log
= extractLogMessageFromGitCommit(ref
)
170 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
173 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
174 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
175 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
178 while len(change
) > 0 and int(change
) > maxChange
:
181 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
182 system("git update-ref %s \"%s^\"" % (ref
, ref
))
183 log
= extractLogMessageFromGitCommit(ref
)
184 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
187 print "%s rewound to %s" % (ref
, change
)
191 class P4Submit(Command
):
193 Command
.__init
__(self
)
195 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
196 optparse
.make_option("--origin", dest
="origin"),
197 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
198 optparse
.make_option("--log-substitutions", dest
="substFile"),
199 optparse
.make_option("--dry-run", action
="store_true"),
200 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
201 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
203 self
.description
= "Submit changes from git to the perforce depot."
204 self
.usage
+= " [name of git branch to submit into perforce depot]"
205 self
.firstTime
= True
207 self
.interactive
= True
210 self
.firstTime
= True
212 self
.directSubmit
= False
213 self
.trustMeLikeAFool
= False
215 self
.logSubstitutions
= {}
216 self
.logSubstitutions
["<enter description here>"] = "%log%"
217 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
220 if len(p4CmdList("opened ...")) > 0:
221 die("You have files opened with perforce! Close them before starting the sync.")
224 if len(self
.config
) > 0 and not self
.reset
:
225 die("Cannot start sync. Previous sync config found at %s\n"
226 "If you want to start submitting again from scratch "
227 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
230 if self
.directSubmit
:
233 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
234 commits
.append(line
[:-1])
237 self
.config
["commits"] = commits
239 def prepareLogMessage(self
, template
, message
):
242 for line
in template
.split("\n"):
243 if line
.startswith("#"):
244 result
+= line
+ "\n"
248 for key
in self
.logSubstitutions
.keys():
249 if line
.find(key
) != -1:
250 value
= self
.logSubstitutions
[key
]
251 value
= value
.replace("%log%", message
)
252 if value
!= "@remove@":
253 result
+= line
.replace(key
, value
) + "\n"
258 result
+= line
+ "\n"
262 def applyCommit(self
, id):
263 if self
.directSubmit
:
264 print "Applying local change in working directory/index"
265 diff
= self
.diffStatus
267 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
268 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
270 filesToDelete
= set()
274 path
= line
[1:].strip()
276 system("p4 edit \"%s\"" % path
)
277 editedFiles
.add(path
)
278 elif modifier
== "A":
280 if path
in filesToDelete
:
281 filesToDelete
.remove(path
)
282 elif modifier
== "D":
283 filesToDelete
.add(path
)
284 if path
in filesToAdd
:
285 filesToAdd
.remove(path
)
287 die("unknown modifier %s for %s" % (modifier
, path
))
289 if self
.directSubmit
:
290 diffcmd
= "cat \"%s\"" % self
.diffFile
292 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
293 patchcmd
= diffcmd
+ " | git apply "
294 tryPatchCmd
= patchcmd
+ "--check -"
295 applyPatchCmd
= patchcmd
+ "--check --apply -"
297 if os
.system(tryPatchCmd
) != 0:
298 print "Unfortunately applying the change failed!"
299 print "What do you want to do?"
301 while response
!= "s" and response
!= "a" and response
!= "w":
302 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
303 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
305 print "Skipping! Good luck with the next patches..."
307 elif response
== "a":
308 os
.system(applyPatchCmd
)
309 if len(filesToAdd
) > 0:
310 print "You may also want to call p4 add on the following files:"
311 print " ".join(filesToAdd
)
312 if len(filesToDelete
):
313 print "The following files should be scheduled for deletion with p4 delete:"
314 print " ".join(filesToDelete
)
315 die("Please resolve and submit the conflict manually and "
316 + "continue afterwards with git-p4 submit --continue")
317 elif response
== "w":
318 system(diffcmd
+ " > patch.txt")
319 print "Patch saved to patch.txt in %s !" % self
.clientPath
320 die("Please resolve and submit the conflict manually and "
321 "continue afterwards with git-p4 submit --continue")
323 system(applyPatchCmd
)
326 system("p4 add %s" % f
)
327 for f
in filesToDelete
:
328 system("p4 revert %s" % f
)
329 system("p4 delete %s" % f
)
332 if not self
.directSubmit
:
333 logMessage
= extractLogMessageFromGitCommit(id)
334 logMessage
= logMessage
.replace("\n", "\n\t")
335 logMessage
= logMessage
[:-1]
337 template
= mypopen("p4 change -o").read()
340 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
341 diff
= mypopen("p4 diff -du ...").read()
343 for newFile
in filesToAdd
:
344 diff
+= "==== new file ====\n"
345 diff
+= "--- /dev/null\n"
346 diff
+= "+++ %s\n" % newFile
347 f
= open(newFile
, "r")
348 for line
in f
.readlines():
352 separatorLine
= "######## everything below this line is just the diff #######"
353 if platform
.system() == "Windows":
354 separatorLine
+= "\r"
355 separatorLine
+= "\n"
358 if self
.trustMeLikeAFool
:
361 firstIteration
= True
362 while response
== "e":
363 if not firstIteration
:
364 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
365 firstIteration
= False
367 [handle
, fileName
] = tempfile
.mkstemp()
368 tmpFile
= os
.fdopen(handle
, "w+")
369 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
372 if platform
.system() == "Windows":
373 defaultEditor
= "notepad"
374 editor
= os
.environ
.get("EDITOR", defaultEditor
);
375 system(editor
+ " " + fileName
)
376 tmpFile
= open(fileName
, "rb")
377 message
= tmpFile
.read()
380 submitTemplate
= message
[:message
.index(separatorLine
)]
382 if response
== "y" or response
== "yes":
385 raw_input("Press return to continue...")
387 if self
.directSubmit
:
388 print "Submitting to git first"
389 os
.chdir(self
.oldWorkingDirectory
)
390 pipe
= os
.popen("git commit -a -F -", "wb")
391 pipe
.write(submitTemplate
)
393 os
.chdir(self
.clientPath
)
395 pipe
= os
.popen("p4 submit -i", "wb")
396 pipe
.write(submitTemplate
)
398 elif response
== "s":
399 for f
in editedFiles
:
400 system("p4 revert \"%s\"" % f
);
402 system("p4 revert \"%s\"" % f
);
404 for f
in filesToDelete
:
405 system("p4 delete \"%s\"" % f
);
408 print "Not submitting!"
409 self
.interactive
= False
411 fileName
= "submit.txt"
412 file = open(fileName
, "w+")
413 file.write(self
.prepareLogMessage(template
, logMessage
))
415 print ("Perforce submit template written as %s. "
416 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
417 % (fileName
, fileName
))
421 # make gitdir absolute so we can cd out into the perforce checkout
422 gitdir
= os
.path
.abspath(gitdir
)
423 os
.environ
["GIT_DIR"] = gitdir
426 self
.master
= currentGitBranch()
427 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
428 die("Detecting current git branch failed!")
430 self
.master
= args
[0]
435 if gitBranchExists("p4"):
436 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
437 if len(depotPath
) == 0 and gitBranchExists("origin"):
438 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
440 if len(depotPath
) == 0:
441 print "Internal error: cannot locate perforce depot path from existing branches"
444 self
.clientPath
= p4Where(depotPath
)
446 if len(self
.clientPath
) == 0:
447 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
450 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
451 self
.oldWorkingDirectory
= os
.getcwd()
453 if self
.directSubmit
:
454 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
455 if len(self
.diffStatus
) == 0:
456 print "No changes in working directory to submit."
458 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
459 self
.diffFile
= gitdir
+ "/p4-git-diff"
460 f
= open(self
.diffFile
, "wb")
464 os
.chdir(self
.clientPath
)
465 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
466 if response
== "y" or response
== "yes":
467 system("p4 sync ...")
469 if len(self
.origin
) == 0:
470 if gitBranchExists("p4"):
473 self
.origin
= "origin"
476 self
.firstTime
= True
478 if len(self
.substFile
) > 0:
479 for line
in open(self
.substFile
, "r").readlines():
480 tokens
= line
[:-1].split("=")
481 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
484 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
485 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
490 commits
= self
.config
.get("commits", [])
492 while len(commits
) > 0:
493 self
.firstTime
= False
495 commits
= commits
[1:]
496 self
.config
["commits"] = commits
497 self
.applyCommit(commit
)
498 if not self
.interactive
:
503 if self
.directSubmit
:
504 os
.remove(self
.diffFile
)
506 if len(commits
) == 0:
508 print "No changes found to apply between %s and current HEAD" % self
.origin
510 print "All changes applied!"
511 os
.chdir(self
.oldWorkingDirectory
)
512 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
513 if response
== "y" or response
== "yes":
516 os
.remove(self
.configFile
)
520 class P4Sync(Command
):
522 Command
.__init
__(self
)
524 optparse
.make_option("--branch", dest
="branch"),
525 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
526 optparse
.make_option("--changesfile", dest
="changesFile"),
527 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
528 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
529 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
530 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
531 optparse
.make_option("--max-changes", dest
="maxChanges")
533 self
.description
= """Imports from Perforce into a git repository.\n
535 //depot/my/project/ -- to import the current head
536 //depot/my/project/@all -- to import everything
537 //depot/my/project/@1,6 -- to import only from revision 1 to 6
539 (a ... is not needed in the path p4 specification, it's added implicitly)"""
541 self
.usage
+= " //depot/path[@revRange]"
544 self
.createdBranches
= Set()
545 self
.committedChanges
= Set()
547 self
.detectBranches
= False
548 self
.detectLabels
= False
549 self
.changesFile
= ""
550 self
.syncWithOrigin
= True
552 self
.importIntoRemotes
= True
554 self
.isWindows
= (platform
.system() == "Windows")
556 if gitConfig("git-p4.syncFromOrigin") == "false":
557 self
.syncWithOrigin
= False
559 def p4File(self
, depotPath
):
560 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
562 def extractFilesFromCommit(self
, commit
):
565 while commit
.has_key("depotFile%s" % fnum
):
566 path
= commit
["depotFile%s" % fnum
]
567 if not path
.startswith(self
.depotPath
):
568 # if not self.silent:
569 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
575 file["rev"] = commit
["rev%s" % fnum
]
576 file["action"] = commit
["action%s" % fnum
]
577 file["type"] = commit
["type%s" % fnum
]
582 def splitFilesIntoBranches(self
, commit
):
586 while commit
.has_key("depotFile%s" % fnum
):
587 path
= commit
["depotFile%s" % fnum
]
588 if not path
.startswith(self
.depotPath
):
589 # if not self.silent:
590 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
596 file["rev"] = commit
["rev%s" % fnum
]
597 file["action"] = commit
["action%s" % fnum
]
598 file["type"] = commit
["type%s" % fnum
]
601 relPath
= path
[len(self
.depotPath
):]
603 for branch
in self
.knownBranches
.keys():
604 if relPath
.startswith(branch
+ "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
605 if branch
not in branches
:
606 branches
[branch
] = []
607 branches
[branch
].append(file)
611 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
612 epoch
= details
["time"]
613 author
= details
["user"]
616 print "commit into %s" % branch
618 self
.gitStream
.write("commit %s\n" % branch
)
619 # gitStream.write("mark :%s\n" % details["change"])
620 self
.committedChanges
.add(int(details
["change"]))
622 if author
not in self
.users
:
623 self
.getUserMapFromPerforceServer()
624 if author
in self
.users
:
625 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
627 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
629 self
.gitStream
.write("committer %s\n" % committer
)
631 self
.gitStream
.write("data <<EOT\n")
632 self
.gitStream
.write(details
["desc"])
633 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
634 self
.gitStream
.write("EOT\n\n")
638 print "parent %s" % parent
639 self
.gitStream
.write("from %s\n" % parent
)
643 if not path
.startswith(branchPrefix
):
644 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
647 depotPath
= path
+ "#" + rev
648 relPath
= path
[len(branchPrefix
):]
649 action
= file["action"]
651 if file["type"] == "apple":
652 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
655 if action
== "delete":
656 self
.gitStream
.write("D %s\n" % relPath
)
659 if file["type"].startswith("x"):
662 data
= self
.p4File(depotPath
)
664 if self
.isWindows
and file["type"].endswith("text"):
665 data
= data
.replace("\r\n", "\n")
667 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
668 self
.gitStream
.write("data %s\n" % len(data
))
669 self
.gitStream
.write(data
)
670 self
.gitStream
.write("\n")
672 self
.gitStream
.write("\n")
674 change
= int(details
["change"])
676 if self
.labels
.has_key(change
):
677 label
= self
.labels
[change
]
678 labelDetails
= label
[0]
679 labelRevisions
= label
[1]
681 print "Change %s is labelled %s" % (change
, labelDetails
)
683 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
685 if len(files
) == len(labelRevisions
):
689 if info
["action"] == "delete":
691 cleanedFiles
[info
["depotFile"]] = info
["rev"]
693 if cleanedFiles
== labelRevisions
:
694 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
695 self
.gitStream
.write("from %s\n" % branch
)
697 owner
= labelDetails
["Owner"]
699 if author
in self
.users
:
700 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
702 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
703 self
.gitStream
.write("tagger %s\n" % tagger
)
704 self
.gitStream
.write("data <<EOT\n")
705 self
.gitStream
.write(labelDetails
["Description"])
706 self
.gitStream
.write("EOT\n\n")
710 print ("Tag %s does not match with change %s: files do not match."
711 % (labelDetails
["label"], change
))
715 print ("Tag %s does not match with change %s: file count is different."
716 % (labelDetails
["label"], change
))
718 def getUserMapFromPerforceServer(self
):
719 if self
.userMapFromPerforceServer
:
723 for output
in p4CmdList("users"):
724 if not output
.has_key("User"):
726 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
728 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
729 for user
in self
.users
.keys():
730 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
732 self
.userMapFromPerforceServer
= True
734 def loadUserMapFromCache(self
):
736 self
.userMapFromPerforceServer
= False
738 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
739 lines
= cache
.readlines()
742 entry
= line
[:-1].split("\t")
743 self
.users
[entry
[0]] = entry
[1]
745 self
.getUserMapFromPerforceServer()
750 l
= p4CmdList("labels %s..." % self
.depotPath
)
751 if len(l
) > 0 and not self
.silent
:
752 print "Finding files belonging to labels in %s" % self
.depotPath
755 label
= output
["label"]
759 print "Querying files for label %s" % label
760 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
761 revisions
[file["depotFile"]] = file["rev"]
762 change
= int(file["change"])
763 if change
> newestChange
:
764 newestChange
= change
766 self
.labels
[newestChange
] = [output
, revisions
]
769 print "Label changes: %s" % self
.labels
.keys()
771 def getBranchMapping(self
):
772 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
774 for info
in p4CmdList("branches"):
775 details
= p4Cmd("branch -o %s" % info
["branch"])
777 while details
.has_key("View%s" % viewIdx
):
778 paths
= details
["View%s" % viewIdx
].split(" ")
779 viewIdx
= viewIdx
+ 1
780 # require standard //depot/foo/... //depot/bar/... mapping
781 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
784 destination
= paths
[1]
785 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
786 source
= source
[len(self
.depotPath
):-4]
787 destination
= destination
[len(self
.depotPath
):-4]
788 if destination
not in self
.knownBranches
:
789 self
.knownBranches
[destination
] = source
790 if source
not in self
.knownBranches
:
791 self
.knownBranches
[source
] = source
793 def listExistingP4GitBranches(self
):
794 self
.p4BranchesInGit
= []
796 cmdline
= "git rev-parse --symbolic "
797 if self
.importIntoRemotes
:
798 cmdline
+= " --remotes"
800 cmdline
+= " --branches"
802 for line
in mypopen(cmdline
).readlines():
803 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
805 if self
.importIntoRemotes
:
810 self
.p4BranchesInGit
.append(branch
)
811 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
813 def createOrUpdateBranchesFromOrigin(self
):
815 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
817 for line
in mypopen("git rev-parse --symbolic --remotes"):
818 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
821 headName
= line
[len("origin/"):-1]
822 remoteHead
= self
.refPrefix
+ headName
823 originHead
= "origin/" + headName
825 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
826 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
830 if not gitBranchExists(remoteHead
):
832 print "creating %s" % remoteHead
835 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
836 if len(p4Change
) > 0:
837 if originPreviousDepotPath
== p4PreviousDepotPath
:
838 originP4Change
= int(originP4Change
)
839 p4Change
= int(p4Change
)
840 if originP4Change
> p4Change
:
841 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
844 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
847 system("git update-ref %s %s" % (remoteHead
, originHead
))
851 self
.changeRange
= ""
852 self
.initialParent
= ""
853 self
.previousDepotPath
= ""
855 # map from branch depot path to parent branch
856 self
.knownBranches
= {}
857 self
.initialParents
= {}
858 self
.hasOrigin
= gitBranchExists("origin")
860 if self
.importIntoRemotes
:
861 self
.refPrefix
= "refs/remotes/p4/"
863 self
.refPrefix
= "refs/heads/"
865 if self
.syncWithOrigin
and self
.hasOrigin
:
867 print "Syncing with origin first by calling git fetch origin"
868 system("git fetch origin")
870 if len(self
.branch
) == 0:
871 self
.branch
= self
.refPrefix
+ "master"
872 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
873 system("git update-ref %s refs/heads/p4" % self
.branch
)
874 system("git branch -D p4");
875 # create it /after/ importing, when master exists
876 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
877 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
881 self
.createOrUpdateBranchesFromOrigin()
882 self
.listExistingP4GitBranches()
884 if len(self
.p4BranchesInGit
) > 1:
886 print "Importing from/into multiple branches"
887 self
.detectBranches
= True
890 print "branches: %s" % self
.p4BranchesInGit
893 for branch
in self
.p4BranchesInGit
:
894 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
895 (depotPath
, change
) = extractDepotPathAndChangeFromGitLog(logMsg
)
898 print "path %s change %s" % (depotPath
, change
)
900 if len(depotPath
) > 0 and len(change
) > 0:
901 change
= int(change
) + 1
902 p4Change
= max(p4Change
, change
)
904 if len(self
.previousDepotPath
) == 0:
905 self
.previousDepotPath
= depotPath
908 l
= min(len(self
.previousDepotPath
), len(depotPath
))
909 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
911 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
914 self
.depotPath
= self
.previousDepotPath
915 self
.changeRange
= "@%s,#head" % p4Change
916 self
.initialParent
= parseRevision(self
.branch
)
917 if not self
.silent
and not self
.detectBranches
:
918 print "Performing incremental import into %s git branch" % self
.branch
920 if not self
.branch
.startswith("refs/"):
921 self
.branch
= "refs/heads/" + self
.branch
923 if len(self
.depotPath
) != 0:
924 self
.depotPath
= self
.depotPath
[:-1]
926 if len(args
) == 0 and len(self
.depotPath
) != 0:
928 print "Depot path: %s" % self
.depotPath
932 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
933 print ("previous import used depot path %s and now %s was specified. "
934 "This doesn't work!" % (self
.depotPath
, args
[0]))
936 self
.depotPath
= args
[0]
941 if self
.depotPath
.find("@") != -1:
942 atIdx
= self
.depotPath
.index("@")
943 self
.changeRange
= self
.depotPath
[atIdx
:]
944 if self
.changeRange
== "@all":
945 self
.changeRange
= ""
946 elif self
.changeRange
.find(",") == -1:
947 self
.revision
= self
.changeRange
948 self
.changeRange
= ""
949 self
.depotPath
= self
.depotPath
[0:atIdx
]
950 elif self
.depotPath
.find("#") != -1:
951 hashIdx
= self
.depotPath
.index("#")
952 self
.revision
= self
.depotPath
[hashIdx
:]
953 self
.depotPath
= self
.depotPath
[0:hashIdx
]
954 elif len(self
.previousDepotPath
) == 0:
955 self
.revision
= "#head"
957 if self
.depotPath
.endswith("..."):
958 self
.depotPath
= self
.depotPath
[:-3]
960 if not self
.depotPath
.endswith("/"):
961 self
.depotPath
+= "/"
963 self
.loadUserMapFromCache()
965 if self
.detectLabels
:
968 if self
.detectBranches
:
969 self
.getBranchMapping();
971 print "p4-git branches: %s" % self
.p4BranchesInGit
972 print "initial parents: %s" % self
.initialParents
973 for b
in self
.p4BranchesInGit
:
975 b
= b
[len(self
.projectName
):]
976 self
.createdBranches
.add(b
)
978 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
980 importProcess
= subprocess
.Popen(["git", "fast-import"],
981 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
982 self
.gitOutput
= importProcess
.stdout
983 self
.gitStream
= importProcess
.stdin
984 self
.gitError
= importProcess
.stderr
986 if len(self
.revision
) > 0:
987 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
989 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
990 details
["desc"] = ("Initial import of %s from the state at revision %s"
991 % (self
.depotPath
, self
.revision
))
992 details
["change"] = self
.revision
996 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
997 change
= int(info
["change"])
998 if change
> newestRevision
:
999 newestRevision
= change
1001 if info
["action"] == "delete":
1002 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1003 #fileCnt = fileCnt + 1
1006 for prop
in [ "depotFile", "rev", "action", "type" ]:
1007 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1009 fileCnt
= fileCnt
+ 1
1011 details
["change"] = newestRevision
1014 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1016 print "IO error with git fast-import. Is your git version recent enough?"
1017 print self
.gitError
.read()
1022 if len(self
.changesFile
) > 0:
1023 output
= open(self
.changesFile
).readlines()
1026 changeSet
.add(int(line
))
1028 for change
in changeSet
:
1029 changes
.append(change
)
1034 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1035 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
1038 changeNum
= line
.split(" ")[1]
1039 changes
.append(changeNum
)
1043 if len(self
.maxChanges
) > 0:
1044 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1046 if len(changes
) == 0:
1048 print "No changes to import!"
1051 self
.updatedBranches
= set()
1054 for change
in changes
:
1055 description
= p4Cmd("describe %s" % change
)
1058 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1063 if self
.detectBranches
:
1064 branches
= self
.splitFilesIntoBranches(description
)
1065 for branch
in branches
.keys():
1066 branchPrefix
= self
.depotPath
+ branch
+ "/"
1070 filesForCommit
= branches
[branch
]
1073 print "branch is %s" % branch
1075 self
.updatedBranches
.add(branch
)
1077 if branch
not in self
.createdBranches
:
1078 self
.createdBranches
.add(branch
)
1079 parent
= self
.knownBranches
[branch
]
1080 if parent
== branch
:
1083 print "parent determined through known branches: %s" % parent
1085 # main branch? use master
1086 if branch
== "main":
1089 branch
= self
.projectName
+ branch
1091 if parent
== "main":
1093 elif len(parent
) > 0:
1094 parent
= self
.projectName
+ parent
1096 branch
= self
.refPrefix
+ branch
1098 parent
= self
.refPrefix
+ parent
1101 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1103 if len(parent
) == 0 and branch
in self
.initialParents
:
1104 parent
= self
.initialParents
[branch
]
1105 del self
.initialParents
[branch
]
1107 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1109 files
= self
.extractFilesFromCommit(description
)
1110 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1111 self
.initialParent
= ""
1113 print self
.gitError
.read()
1118 if len(self
.updatedBranches
) > 0:
1119 sys
.stdout
.write("Updated branches: ")
1120 for b
in self
.updatedBranches
:
1121 sys
.stdout
.write("%s " % b
)
1122 sys
.stdout
.write("\n")
1125 self
.gitStream
.close()
1126 if importProcess
.wait() != 0:
1127 die("fast-import failed: %s" % self
.gitError
.read())
1128 self
.gitOutput
.close()
1129 self
.gitError
.close()
1133 class P4Rebase(Command
):
1135 Command
.__init
__(self
)
1137 self
.description
= ("Fetches the latest revision from perforce and "
1138 + "rebases the current work (branch) against it")
1140 def run(self
, args
):
1143 print "Rebasing the current branch"
1144 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1145 system("git rebase p4")
1146 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1149 class P4Clone(P4Sync
):
1151 P4Sync
.__init
__(self
)
1152 self
.description
= "Creates a new git repository and imports from Perforce into it"
1153 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1154 self
.needsGit
= False
1156 def run(self
, args
):
1164 destination
= args
[1]
1168 if not depotPath
.startswith("//"):
1171 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1172 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1173 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1174 depotDir
= re
.sub(r
"/$", "", depotDir
)
1177 destination
= os
.path
.split(depotDir
)[-1]
1179 print "Importing from %s into %s" % (depotPath
, destination
)
1180 os
.makedirs(destination
)
1181 os
.chdir(destination
)
1183 gitdir
= os
.getcwd() + "/.git"
1184 if not P4Sync
.run(self
, [depotPath
]):
1186 if self
.branch
!= "master":
1187 if gitBranchExists("refs/remotes/p4/master"):
1188 system("git branch master refs/remotes/p4/master")
1189 system("git checkout -f")
1191 print "Could not detect main branch. No checkout/master branch created."
1194 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1196 optparse
.IndentedHelpFormatter
.__init
__(self
)
1198 def format_description(self
, description
):
1200 return description
+ "\n"
1204 def printUsage(commands
):
1205 print "usage: %s <command> [options]" % sys
.argv
[0]
1207 print "valid commands: %s" % ", ".join(commands
)
1209 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1213 "debug" : P4Debug(),
1214 "submit" : P4Submit(),
1216 "rebase" : P4Rebase(),
1217 "clone" : P4Clone(),
1218 "rollback" : P4RollBack()
1221 if len(sys
.argv
[1:]) == 0:
1222 printUsage(commands
.keys())
1226 cmdName
= sys
.argv
[1]
1228 cmd
= commands
[cmdName
]
1230 print "unknown command %s" % cmdName
1232 printUsage(commands
.keys())
1235 options
= cmd
.options
1240 if len(options
) > 0:
1241 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1243 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1245 description
= cmd
.description
,
1246 formatter
= HelpFormatter())
1248 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1252 if len(gitdir
) == 0:
1254 if not isValidGitDir(gitdir
):
1255 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1256 if os
.path
.exists(gitdir
):
1257 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1261 if not isValidGitDir(gitdir
):
1262 if isValidGitDir(gitdir
+ "/.git"):
1265 die("fatal: cannot locate git repository at %s" % gitdir
)
1267 os
.environ
["GIT_DIR"] = gitdir
1269 if not cmd
.run(args
):