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
17 gitdir
= os
.environ
.get("GIT_DIR", "")
20 def write_pipe(c
, str):
22 sys
.stderr
.write('writing pipe: %s\n' % c
)
24 pipe
= os
.popen(c
, 'w')
27 sys
.stderr
.write('Command failed: %s' % c
)
34 sys
.stderr
.write('reading pipe: %s\n' % c
)
36 pipe
= os
.popen(c
, 'rb')
39 sys
.stderr
.write('Command failed: %s' % c
)
45 def read_pipe_lines(c
):
47 sys
.stderr
.write('reading pipe: %s\n' % c
)
48 ## todo: check return status
49 pipe
= os
.popen(c
, 'rb')
50 val
= pipe
.readlines()
52 sys
.stderr
.write('Command failed: %s' % c
)
59 sys
.stderr
.write("executing %s" % cmd
)
60 if os
.system(cmd
) != 0:
61 die("command failed: %s" % cmd
)
64 cmd
= "p4 -G %s" % cmd
65 pipe
= os
.popen(cmd
, "rb")
70 entry
= marshal
.load(pipe
)
74 exitCode
= pipe
.close()
77 entry
["p4ExitCode"] = exitCode
89 def p4Where(depotPath
):
90 if not depotPath
.endswith("/"):
92 output
= p4Cmd("where %s..." % depotPath
)
93 if output
["code"] == "error":
97 clientPath
= output
.get("path")
98 elif "data" in output
:
99 data
= output
.get("data")
100 lastSpace
= data
.rfind(" ")
101 clientPath
= data
[lastSpace
+ 1:]
103 if clientPath
.endswith("..."):
104 clientPath
= clientPath
[:-3]
108 sys
.stderr
.write(msg
+ "\n")
111 def currentGitBranch():
112 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
114 def isValidGitDir(path
):
115 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
119 def parseRevision(ref
):
120 return read_pipe("git rev-parse %s" % ref
).strip()
122 def extractLogMessageFromGitCommit(commit
):
125 ## fixme: title is first line of commit, not 1st paragraph.
127 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
136 def extractDepotPathAndChangeFromGitLog(log
):
138 for line
in log
.split("\n"):
140 if line
.startswith("[git-p4:") and line
.endswith("]"):
141 line
= line
[8:-1].strip()
142 for assignment
in line
.split(":"):
143 variable
= assignment
.strip()
145 equalPos
= assignment
.find("=")
147 variable
= assignment
[:equalPos
].strip()
148 value
= assignment
[equalPos
+ 1:].strip()
149 if value
.startswith("\"") and value
.endswith("\""):
151 values
[variable
] = value
153 return values
.get("depot-path"), values
.get("change")
155 def gitBranchExists(branch
):
156 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
157 return proc
.wait() == 0;
160 return os
.popen("git config %s" % key
, "rb").read()[:-1]
164 self
.usage
= "usage: %prog [options]"
167 class P4Debug(Command
):
169 Command
.__init
__(self
)
172 self
.description
= "A tool to debug the output of p4 -G."
173 self
.needsGit
= False
176 for output
in p4CmdList(" ".join(args
)):
180 class P4RollBack(Command
):
182 Command
.__init
__(self
)
184 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
185 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
187 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
189 self
.rollbackLocalBranches
= False
194 maxChange
= int(args
[0])
196 if "p4ExitCode" in p4Cmd("changes -m 1"):
197 die("Problems executing p4");
199 if self
.rollbackLocalBranches
:
200 refPrefix
= "refs/heads/"
201 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
203 refPrefix
= "refs/remotes/"
204 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
207 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
209 ref
= refPrefix
+ line
210 log
= extractLogMessageFromGitCommit(ref
)
211 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
214 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
215 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
216 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
219 while len(change
) > 0 and int(change
) > maxChange
:
222 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
223 system("git update-ref %s \"%s^\"" % (ref
, ref
))
224 log
= extractLogMessageFromGitCommit(ref
)
225 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
228 print "%s rewound to %s" % (ref
, change
)
232 class P4Submit(Command
):
234 Command
.__init
__(self
)
236 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
237 optparse
.make_option("--origin", dest
="origin"),
238 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
239 optparse
.make_option("--log-substitutions", dest
="substFile"),
240 optparse
.make_option("--dry-run", action
="store_true"),
241 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
242 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
244 self
.description
= "Submit changes from git to the perforce depot."
245 self
.usage
+= " [name of git branch to submit into perforce depot]"
246 self
.firstTime
= True
248 self
.interactive
= True
251 self
.firstTime
= True
253 self
.directSubmit
= False
254 self
.trustMeLikeAFool
= False
256 self
.logSubstitutions
= {}
257 self
.logSubstitutions
["<enter description here>"] = "%log%"
258 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
261 if len(p4CmdList("opened ...")) > 0:
262 die("You have files opened with perforce! Close them before starting the sync.")
265 if len(self
.config
) > 0 and not self
.reset
:
266 die("Cannot start sync. Previous sync config found at %s\n"
267 "If you want to start submitting again from scratch "
268 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
271 if self
.directSubmit
:
274 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
275 commits
.append(line
.strip())
278 self
.config
["commits"] = commits
280 def prepareLogMessage(self
, template
, message
):
283 for line
in template
.split("\n"):
284 if line
.startswith("#"):
285 result
+= line
+ "\n"
289 for key
in self
.logSubstitutions
.keys():
290 if line
.find(key
) != -1:
291 value
= self
.logSubstitutions
[key
]
292 value
= value
.replace("%log%", message
)
293 if value
!= "@remove@":
294 result
+= line
.replace(key
, value
) + "\n"
299 result
+= line
+ "\n"
303 def applyCommit(self
, id):
304 if self
.directSubmit
:
305 print "Applying local change in working directory/index"
306 diff
= self
.diffStatus
308 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
309 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
311 filesToDelete
= set()
315 path
= line
[1:].strip()
317 system("p4 edit \"%s\"" % path
)
318 editedFiles
.add(path
)
319 elif modifier
== "A":
321 if path
in filesToDelete
:
322 filesToDelete
.remove(path
)
323 elif modifier
== "D":
324 filesToDelete
.add(path
)
325 if path
in filesToAdd
:
326 filesToAdd
.remove(path
)
328 die("unknown modifier %s for %s" % (modifier
, path
))
330 if self
.directSubmit
:
331 diffcmd
= "cat \"%s\"" % self
.diffFile
333 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
334 patchcmd
= diffcmd
+ " | git apply "
335 tryPatchCmd
= patchcmd
+ "--check -"
336 applyPatchCmd
= patchcmd
+ "--check --apply -"
338 if os
.system(tryPatchCmd
) != 0:
339 print "Unfortunately applying the change failed!"
340 print "What do you want to do?"
342 while response
!= "s" and response
!= "a" and response
!= "w":
343 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
344 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
346 print "Skipping! Good luck with the next patches..."
348 elif response
== "a":
349 os
.system(applyPatchCmd
)
350 if len(filesToAdd
) > 0:
351 print "You may also want to call p4 add on the following files:"
352 print " ".join(filesToAdd
)
353 if len(filesToDelete
):
354 print "The following files should be scheduled for deletion with p4 delete:"
355 print " ".join(filesToDelete
)
356 die("Please resolve and submit the conflict manually and "
357 + "continue afterwards with git-p4 submit --continue")
358 elif response
== "w":
359 system(diffcmd
+ " > patch.txt")
360 print "Patch saved to patch.txt in %s !" % self
.clientPath
361 die("Please resolve and submit the conflict manually and "
362 "continue afterwards with git-p4 submit --continue")
364 system(applyPatchCmd
)
367 system("p4 add %s" % f
)
368 for f
in filesToDelete
:
369 system("p4 revert %s" % f
)
370 system("p4 delete %s" % f
)
373 if not self
.directSubmit
:
374 logMessage
= extractLogMessageFromGitCommit(id)
375 logMessage
= logMessage
.replace("\n", "\n\t")
376 logMessage
= logMessage
.strip()
378 template
= read_pipe("p4 change -o")
381 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
382 diff
= read_pipe("p4 diff -du ...")
384 for newFile
in filesToAdd
:
385 diff
+= "==== new file ====\n"
386 diff
+= "--- /dev/null\n"
387 diff
+= "+++ %s\n" % newFile
388 f
= open(newFile
, "r")
389 for line
in f
.readlines():
393 separatorLine
= "######## everything below this line is just the diff #######"
394 if platform
.system() == "Windows":
395 separatorLine
+= "\r"
396 separatorLine
+= "\n"
399 if self
.trustMeLikeAFool
:
402 firstIteration
= True
403 while response
== "e":
404 if not firstIteration
:
405 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
406 firstIteration
= False
408 [handle
, fileName
] = tempfile
.mkstemp()
409 tmpFile
= os
.fdopen(handle
, "w+")
410 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
413 if platform
.system() == "Windows":
414 defaultEditor
= "notepad"
415 editor
= os
.environ
.get("EDITOR", defaultEditor
);
416 system(editor
+ " " + fileName
)
417 tmpFile
= open(fileName
, "rb")
418 message
= tmpFile
.read()
421 submitTemplate
= message
[:message
.index(separatorLine
)]
423 if response
== "y" or response
== "yes":
426 raw_input("Press return to continue...")
428 if self
.directSubmit
:
429 print "Submitting to git first"
430 os
.chdir(self
.oldWorkingDirectory
)
431 write_pipe("git commit -a -F -", submitTemplate
)
432 os
.chdir(self
.clientPath
)
434 write_pipe("p4 submit -i", submitTemplate
)
435 elif response
== "s":
436 for f
in editedFiles
:
437 system("p4 revert \"%s\"" % f
);
439 system("p4 revert \"%s\"" % f
);
441 for f
in filesToDelete
:
442 system("p4 delete \"%s\"" % f
);
445 print "Not submitting!"
446 self
.interactive
= False
448 fileName
= "submit.txt"
449 file = open(fileName
, "w+")
450 file.write(self
.prepareLogMessage(template
, logMessage
))
452 print ("Perforce submit template written as %s. "
453 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
454 % (fileName
, fileName
))
458 # make gitdir absolute so we can cd out into the perforce checkout
459 gitdir
= os
.path
.abspath(gitdir
)
460 os
.environ
["GIT_DIR"] = gitdir
463 self
.master
= currentGitBranch()
464 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
465 die("Detecting current git branch failed!")
467 self
.master
= args
[0]
472 if gitBranchExists("p4"):
473 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
474 if len(depotPath
) == 0 and gitBranchExists("origin"):
475 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
477 if len(depotPath
) == 0:
478 print "Internal error: cannot locate perforce depot path from existing branches"
481 self
.clientPath
= p4Where(depotPath
)
483 if len(self
.clientPath
) == 0:
484 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
487 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
488 self
.oldWorkingDirectory
= os
.getcwd()
490 if self
.directSubmit
:
491 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
492 if len(self
.diffStatus
) == 0:
493 print "No changes in working directory to submit."
495 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
496 self
.diffFile
= gitdir
+ "/p4-git-diff"
497 f
= open(self
.diffFile
, "wb")
501 os
.chdir(self
.clientPath
)
502 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
503 if response
== "y" or response
== "yes":
504 system("p4 sync ...")
506 if len(self
.origin
) == 0:
507 if gitBranchExists("p4"):
510 self
.origin
= "origin"
513 self
.firstTime
= True
515 if len(self
.substFile
) > 0:
516 for line
in open(self
.substFile
, "r").readlines():
517 tokens
= line
.strip().split("=")
518 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
521 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
522 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
527 commits
= self
.config
.get("commits", [])
529 while len(commits
) > 0:
530 self
.firstTime
= False
532 commits
= commits
[1:]
533 self
.config
["commits"] = commits
534 self
.applyCommit(commit
)
535 if not self
.interactive
:
540 if self
.directSubmit
:
541 os
.remove(self
.diffFile
)
543 if len(commits
) == 0:
545 print "No changes found to apply between %s and current HEAD" % self
.origin
547 print "All changes applied!"
548 os
.chdir(self
.oldWorkingDirectory
)
549 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
550 if response
== "y" or response
== "yes":
553 os
.remove(self
.configFile
)
557 class P4Sync(Command
):
559 Command
.__init
__(self
)
561 optparse
.make_option("--branch", dest
="branch"),
562 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
563 optparse
.make_option("--changesfile", dest
="changesFile"),
564 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
565 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
566 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
567 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
568 optparse
.make_option("--max-changes", dest
="maxChanges"),
569 optparse
.make_option("--keep-path", dest
="keepRepoPath")
571 self
.description
= """Imports from Perforce into a git repository.\n
573 //depot/my/project/ -- to import the current head
574 //depot/my/project/@all -- to import everything
575 //depot/my/project/@1,6 -- to import only from revision 1 to 6
577 (a ... is not needed in the path p4 specification, it's added implicitly)"""
579 self
.usage
+= " //depot/path[@revRange]"
581 self
.createdBranches
= Set()
582 self
.committedChanges
= Set()
584 self
.detectBranches
= False
585 self
.detectLabels
= False
586 self
.changesFile
= ""
587 self
.syncWithOrigin
= True
589 self
.importIntoRemotes
= True
591 self
.isWindows
= (platform
.system() == "Windows")
592 self
.depotPath
= None
593 self
.keepRepoPath
= False
595 if gitConfig("git-p4.syncFromOrigin") == "false":
596 self
.syncWithOrigin
= False
598 def p4File(self
, depotPath
):
599 return read_pipe("p4 print -q \"%s\"" % depotPath
)
601 def extractFilesFromCommit(self
, commit
):
604 while commit
.has_key("depotFile%s" % fnum
):
605 path
= commit
["depotFile%s" % fnum
]
606 if not path
.startswith(self
.depotPath
):
607 # if not self.silent:
608 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
614 file["rev"] = commit
["rev%s" % fnum
]
615 file["action"] = commit
["action%s" % fnum
]
616 file["type"] = commit
["type%s" % fnum
]
621 def stripRepoPath(self
, path
, prefix
):
622 if self
.keepRepoPath
:
623 prefix
= re
.sub("^(//[^/]+/).*", r
'\1', prefix
)
625 return path
[len(prefix
):]
627 def splitFilesIntoBranches(self
, commit
):
630 while commit
.has_key("depotFile%s" % fnum
):
631 path
= commit
["depotFile%s" % fnum
]
632 if not path
.startswith(self
.depotPath
):
633 # if not self.silent:
634 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
640 file["rev"] = commit
["rev%s" % fnum
]
641 file["action"] = commit
["action%s" % fnum
]
642 file["type"] = commit
["type%s" % fnum
]
645 relPath
= self
.stripRepoPath(path
, self
.depotPath
)
647 for branch
in self
.knownBranches
.keys():
649 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
650 if relPath
.startswith(branch
+ "/"):
651 if branch
not in branches
:
652 branches
[branch
] = []
653 branches
[branch
].append(file)
657 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
658 epoch
= details
["time"]
659 author
= details
["user"]
662 print "commit into %s" % branch
664 self
.gitStream
.write("commit %s\n" % branch
)
665 # gitStream.write("mark :%s\n" % details["change"])
666 self
.committedChanges
.add(int(details
["change"]))
668 if author
not in self
.users
:
669 self
.getUserMapFromPerforceServer()
670 if author
in self
.users
:
671 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
673 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
675 self
.gitStream
.write("committer %s\n" % committer
)
677 self
.gitStream
.write("data <<EOT\n")
678 self
.gitStream
.write(details
["desc"])
679 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
680 self
.gitStream
.write("EOT\n\n")
684 print "parent %s" % parent
685 self
.gitStream
.write("from %s\n" % parent
)
689 if not path
.startswith(branchPrefix
):
690 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
693 depotPath
= path
+ "#" + rev
694 relPath
= self
.stripRepoPath(path
, branchPrefix
)
695 action
= file["action"]
697 if file["type"] == "apple":
698 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
701 if action
== "delete":
702 self
.gitStream
.write("D %s\n" % relPath
)
705 if file["type"].startswith("x"):
708 data
= self
.p4File(depotPath
)
710 if self
.isWindows
and file["type"].endswith("text"):
711 data
= data
.replace("\r\n", "\n")
713 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
714 self
.gitStream
.write("data %s\n" % len(data
))
715 self
.gitStream
.write(data
)
716 self
.gitStream
.write("\n")
718 self
.gitStream
.write("\n")
720 change
= int(details
["change"])
722 if self
.labels
.has_key(change
):
723 label
= self
.labels
[change
]
724 labelDetails
= label
[0]
725 labelRevisions
= label
[1]
727 print "Change %s is labelled %s" % (change
, labelDetails
)
729 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
731 if len(files
) == len(labelRevisions
):
735 if info
["action"] == "delete":
737 cleanedFiles
[info
["depotFile"]] = info
["rev"]
739 if cleanedFiles
== labelRevisions
:
740 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
741 self
.gitStream
.write("from %s\n" % branch
)
743 owner
= labelDetails
["Owner"]
745 if author
in self
.users
:
746 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
748 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
749 self
.gitStream
.write("tagger %s\n" % tagger
)
750 self
.gitStream
.write("data <<EOT\n")
751 self
.gitStream
.write(labelDetails
["Description"])
752 self
.gitStream
.write("EOT\n\n")
756 print ("Tag %s does not match with change %s: files do not match."
757 % (labelDetails
["label"], change
))
761 print ("Tag %s does not match with change %s: file count is different."
762 % (labelDetails
["label"], change
))
764 def getUserMapFromPerforceServer(self
):
765 if self
.userMapFromPerforceServer
:
769 for output
in p4CmdList("users"):
770 if not output
.has_key("User"):
772 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
774 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
775 for user
in self
.users
.keys():
776 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
778 self
.userMapFromPerforceServer
= True
780 def loadUserMapFromCache(self
):
782 self
.userMapFromPerforceServer
= False
784 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
785 lines
= cache
.readlines()
788 entry
= line
.strip().split("\t")
789 self
.users
[entry
[0]] = entry
[1]
791 self
.getUserMapFromPerforceServer()
796 l
= p4CmdList("labels %s..." % self
.depotPath
)
797 if len(l
) > 0 and not self
.silent
:
798 print "Finding files belonging to labels in %s" % self
.depotPath
801 label
= output
["label"]
805 print "Querying files for label %s" % label
806 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
807 revisions
[file["depotFile"]] = file["rev"]
808 change
= int(file["change"])
809 if change
> newestChange
:
810 newestChange
= change
812 self
.labels
[newestChange
] = [output
, revisions
]
815 print "Label changes: %s" % self
.labels
.keys()
817 def getBranchMapping(self
):
818 self
.projectName
= self
.depotPath
[self
.depotPath
.strip().rfind("/") + 1:]
820 for info
in p4CmdList("branches"):
821 details
= p4Cmd("branch -o %s" % info
["branch"])
823 while details
.has_key("View%s" % viewIdx
):
824 paths
= details
["View%s" % viewIdx
].split(" ")
825 viewIdx
= viewIdx
+ 1
826 # require standard //depot/foo/... //depot/bar/... mapping
827 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
830 destination
= paths
[1]
831 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
832 source
= source
[len(self
.depotPath
):-4]
833 destination
= destination
[len(self
.depotPath
):-4]
834 if destination
not in self
.knownBranches
:
835 self
.knownBranches
[destination
] = source
836 if source
not in self
.knownBranches
:
837 self
.knownBranches
[source
] = source
839 def listExistingP4GitBranches(self
):
840 self
.p4BranchesInGit
= []
842 cmdline
= "git rev-parse --symbolic "
843 if self
.importIntoRemotes
:
844 cmdline
+= " --remotes"
846 cmdline
+= " --branches"
848 for line
in read_pipe_lines(cmdline
):
850 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
853 if self
.importIntoRemotes
:
855 branch
= re
.sub ("^p4/", "", line
)
857 self
.p4BranchesInGit
.append(branch
)
858 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
860 def createOrUpdateBranchesFromOrigin(self
):
862 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
864 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
865 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
868 headName
= line
[len("origin/"):-1]
869 remoteHead
= self
.refPrefix
+ headName
870 originHead
= "origin/" + headName
872 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
873 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
877 if not gitBranchExists(remoteHead
):
879 print "creating %s" % remoteHead
882 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
883 if len(p4Change
) > 0:
884 if originPreviousDepotPath
== p4PreviousDepotPath
:
885 originP4Change
= int(originP4Change
)
886 p4Change
= int(p4Change
)
887 if originP4Change
> p4Change
:
888 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
891 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
894 system("git update-ref %s %s" % (remoteHead
, originHead
))
898 self
.changeRange
= ""
899 self
.initialParent
= ""
900 self
.previousDepotPath
= ""
902 # map from branch depot path to parent branch
903 self
.knownBranches
= {}
904 self
.initialParents
= {}
905 self
.hasOrigin
= gitBranchExists("origin")
907 if self
.importIntoRemotes
:
908 self
.refPrefix
= "refs/remotes/p4/"
910 self
.refPrefix
= "refs/heads/"
912 if self
.syncWithOrigin
and self
.hasOrigin
:
914 print "Syncing with origin first by calling git fetch origin"
915 system("git fetch origin")
917 if len(self
.branch
) == 0:
918 self
.branch
= self
.refPrefix
+ "master"
919 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
920 system("git update-ref %s refs/heads/p4" % self
.branch
)
921 system("git branch -D p4");
922 # create it /after/ importing, when master exists
923 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
924 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
928 self
.createOrUpdateBranchesFromOrigin()
929 self
.listExistingP4GitBranches()
931 if len(self
.p4BranchesInGit
) > 1:
933 print "Importing from/into multiple branches"
934 self
.detectBranches
= True
937 print "branches: %s" % self
.p4BranchesInGit
940 for branch
in self
.p4BranchesInGit
:
941 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
942 (depotPath
, change
) = extractDepotPathAndChangeFromGitLog(logMsg
)
945 print "path %s change %s" % (depotPath
, change
)
947 if len(depotPath
) > 0 and len(change
) > 0:
948 change
= int(change
) + 1
949 p4Change
= max(p4Change
, change
)
951 if len(self
.previousDepotPath
) == 0:
952 self
.previousDepotPath
= depotPath
955 l
= min(len(self
.previousDepotPath
), len(depotPath
))
956 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
958 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
961 self
.depotPath
= self
.previousDepotPath
962 self
.changeRange
= "@%s,#head" % p4Change
963 self
.initialParent
= parseRevision(self
.branch
)
964 if not self
.silent
and not self
.detectBranches
:
965 print "Performing incremental import into %s git branch" % self
.branch
967 if not self
.branch
.startswith("refs/"):
968 self
.branch
= "refs/heads/" + self
.branch
970 if len(self
.depotPath
) != 0:
971 self
.depotPath
= self
.depotPath
.strip()
973 if len(args
) == 0 and len(self
.depotPath
) != 0:
975 print "Depot path: %s" % self
.depotPath
979 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
980 print ("previous import used depot path %s and now %s was specified. "
981 "This doesn't work!" % (self
.depotPath
, args
[0]))
983 self
.depotPath
= args
[0]
988 if self
.depotPath
.find("@") != -1:
989 atIdx
= self
.depotPath
.index("@")
990 self
.changeRange
= self
.depotPath
[atIdx
:]
991 if self
.changeRange
== "@all":
992 self
.changeRange
= ""
993 elif self
.changeRange
.find(",") == -1:
994 self
.revision
= self
.changeRange
995 self
.changeRange
= ""
996 self
.depotPath
= self
.depotPath
[0:atIdx
]
997 elif self
.depotPath
.find("#") != -1:
998 hashIdx
= self
.depotPath
.index("#")
999 self
.revision
= self
.depotPath
[hashIdx
:]
1000 self
.depotPath
= self
.depotPath
[0:hashIdx
]
1001 elif len(self
.previousDepotPath
) == 0:
1002 self
.revision
= "#head"
1004 self
.depotPath
= re
.sub ("\.\.\.$", "", self
.depotPath
)
1005 if not self
.depotPath
.endswith("/"):
1006 self
.depotPath
+= "/"
1008 self
.loadUserMapFromCache()
1010 if self
.detectLabels
:
1013 if self
.detectBranches
:
1014 self
.getBranchMapping();
1016 print "p4-git branches: %s" % self
.p4BranchesInGit
1017 print "initial parents: %s" % self
.initialParents
1018 for b
in self
.p4BranchesInGit
:
1020 b
= b
[len(self
.projectName
):]
1021 self
.createdBranches
.add(b
)
1023 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1025 importProcess
= subprocess
.Popen(["git", "fast-import"],
1026 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
1027 self
.gitOutput
= importProcess
.stdout
1028 self
.gitStream
= importProcess
.stdin
1029 self
.gitError
= importProcess
.stderr
1031 if len(self
.revision
) > 0:
1032 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
1034 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1035 details
["desc"] = ("Initial import of %s from the state at revision %s"
1036 % (self
.depotPath
, self
.revision
))
1037 details
["change"] = self
.revision
1041 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
1042 change
= int(info
["change"])
1043 if change
> newestRevision
:
1044 newestRevision
= change
1046 if info
["action"] == "delete":
1047 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1048 #fileCnt = fileCnt + 1
1051 for prop
in [ "depotFile", "rev", "action", "type" ]:
1052 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1054 fileCnt
= fileCnt
+ 1
1056 details
["change"] = newestRevision
1059 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1061 print "IO error with git fast-import. Is your git version recent enough?"
1062 print self
.gitError
.read()
1067 if len(self
.changesFile
) > 0:
1068 output
= open(self
.changesFile
).readlines()
1071 changeSet
.add(int(line
))
1073 for change
in changeSet
:
1074 changes
.append(change
)
1079 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1080 output
= read_pipe_lines("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
))
1083 changeNum
= line
.split(" ")[1]
1084 changes
.append(changeNum
)
1088 if len(self
.maxChanges
) > 0:
1089 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1091 if len(changes
) == 0:
1093 print "No changes to import!"
1096 self
.updatedBranches
= set()
1099 for change
in changes
:
1100 description
= p4Cmd("describe %s" % change
)
1103 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1108 if self
.detectBranches
:
1109 branches
= self
.splitFilesIntoBranches(description
)
1110 for branch
in branches
.keys():
1111 branchPrefix
= self
.depotPath
+ branch
+ "/"
1115 filesForCommit
= branches
[branch
]
1118 print "branch is %s" % branch
1120 self
.updatedBranches
.add(branch
)
1122 if branch
not in self
.createdBranches
:
1123 self
.createdBranches
.add(branch
)
1124 parent
= self
.knownBranches
[branch
]
1125 if parent
== branch
:
1128 print "parent determined through known branches: %s" % parent
1130 # main branch? use master
1131 if branch
== "main":
1134 branch
= self
.projectName
+ branch
1136 if parent
== "main":
1138 elif len(parent
) > 0:
1139 parent
= self
.projectName
+ parent
1141 branch
= self
.refPrefix
+ branch
1143 parent
= self
.refPrefix
+ parent
1146 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1148 if len(parent
) == 0 and branch
in self
.initialParents
:
1149 parent
= self
.initialParents
[branch
]
1150 del self
.initialParents
[branch
]
1152 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1154 files
= self
.extractFilesFromCommit(description
)
1155 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1156 self
.initialParent
= ""
1158 print self
.gitError
.read()
1163 if len(self
.updatedBranches
) > 0:
1164 sys
.stdout
.write("Updated branches: ")
1165 for b
in self
.updatedBranches
:
1166 sys
.stdout
.write("%s " % b
)
1167 sys
.stdout
.write("\n")
1170 self
.gitStream
.close()
1171 if importProcess
.wait() != 0:
1172 die("fast-import failed: %s" % self
.gitError
.read())
1173 self
.gitOutput
.close()
1174 self
.gitError
.close()
1178 class P4Rebase(Command
):
1180 Command
.__init
__(self
)
1182 self
.description
= ("Fetches the latest revision from perforce and "
1183 + "rebases the current work (branch) against it")
1185 def run(self
, args
):
1188 print "Rebasing the current branch"
1189 oldHead
= read_pipe("git rev-parse HEAD").strip()
1190 system("git rebase p4")
1191 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1194 class P4Clone(P4Sync
):
1196 P4Sync
.__init
__(self
)
1197 self
.description
= "Creates a new git repository and imports from Perforce into it"
1198 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1199 self
.needsGit
= False
1201 def run(self
, args
):
1209 destination
= args
[1]
1213 if not depotPath
.startswith("//"):
1216 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1217 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1218 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1219 depotDir
= re
.sub(r
"/$", "", depotDir
)
1222 destination
= os
.path
.split(depotDir
)[1]
1224 print "Importing from %s into %s" % (depotPath
, destination
)
1225 os
.makedirs(destination
)
1226 os
.chdir(destination
)
1228 gitdir
= os
.getcwd() + "/.git"
1229 if not P4Sync
.run(self
, [depotPath
]):
1231 if self
.branch
!= "master":
1232 if gitBranchExists("refs/remotes/p4/master"):
1233 system("git branch master refs/remotes/p4/master")
1234 system("git checkout -f")
1236 print "Could not detect main branch. No checkout/master branch created."
1239 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1241 optparse
.IndentedHelpFormatter
.__init
__(self
)
1243 def format_description(self
, description
):
1245 return description
+ "\n"
1249 def printUsage(commands
):
1250 print "usage: %s <command> [options]" % sys
.argv
[0]
1252 print "valid commands: %s" % ", ".join(commands
)
1254 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1258 "debug" : P4Debug(),
1259 "submit" : P4Submit(),
1261 "rebase" : P4Rebase(),
1262 "clone" : P4Clone(),
1263 "rollback" : P4RollBack()
1266 if len(sys
.argv
[1:]) == 0:
1267 printUsage(commands
.keys())
1271 cmdName
= sys
.argv
[1]
1273 cmd
= commands
[cmdName
]
1275 print "unknown command %s" % cmdName
1277 printUsage(commands
.keys())
1280 options
= cmd
.options
1285 if len(options
) > 0:
1286 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1288 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1290 description
= cmd
.description
,
1291 formatter
= HelpFormatter())
1293 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1297 if len(gitdir
) == 0:
1299 if not isValidGitDir(gitdir
):
1300 gitdir
= read_pipe("git rev-parse --git-dir").strip()
1301 if os
.path
.exists(gitdir
):
1302 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1306 if not isValidGitDir(gitdir
):
1307 if isValidGitDir(gitdir
+ "/.git"):
1310 die("fatal: cannot locate git repository at %s" % gitdir
)
1312 os
.environ
["GIT_DIR"] = gitdir
1314 if not cmd
.run(args
):