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 def write_pipe(c
, str):
21 sys
.stderr
.write('writing pipe: %s\n' % c
)
23 ## todo: check return status
24 pipe
= os
.popen(c
, 'w')
27 sys
.stderr
.write('Command failed')
34 sys
.stderr
.write('reading pipe: %s\n' % c
)
35 ## todo: check return status
36 pipe
= os
.popen(c
, 'rb')
39 sys
.stderr
.write('Command failed')
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')
59 sys
.stderr
.write("executing %s" % cmd
)
60 if os
.system(cmd
) != 0:
61 die("command failed: %s" % cmd
)
66 cmd
= "p4 -G %s" % cmd
67 pipe
= os
.popen(cmd
, "rb")
72 entry
= marshal
.load(pipe
)
76 exitCode
= pipe
.close()
79 entry
["p4ExitCode"] = exitCode
91 def p4Where(depotPath
):
92 if not depotPath
.endswith("/"):
94 output
= p4Cmd("where %s..." % depotPath
)
95 if output
["code"] == "error":
99 clientPath
= output
.get("path")
100 elif "data" in output
:
101 data
= output
.get("data")
102 lastSpace
= data
.rfind(" ")
103 clientPath
= data
[lastSpace
+ 1:]
105 if clientPath
.endswith("..."):
106 clientPath
= clientPath
[:-3]
110 sys
.stderr
.write(msg
+ "\n")
113 def currentGitBranch():
114 return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
116 def isValidGitDir(path
):
117 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
121 def parseRevision(ref
):
122 return read_pipe("git rev-parse %s" % ref
)[:-1]
124 def extractLogMessageFromGitCommit(commit
):
127 ## fixme: title is first line of commit, not 1st paragraph.
129 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
138 def extractDepotPathAndChangeFromGitLog(log
):
140 for line
in log
.split("\n"):
142 if line
.startswith("[git-p4:") and line
.endswith("]"):
143 line
= line
[8:-1].strip()
144 for assignment
in line
.split(":"):
145 variable
= assignment
.strip()
147 equalPos
= assignment
.find("=")
149 variable
= assignment
[:equalPos
].strip()
150 value
= assignment
[equalPos
+ 1:].strip()
151 if value
.startswith("\"") and value
.endswith("\""):
153 values
[variable
] = value
155 return values
.get("depot-path"), values
.get("change")
157 def gitBranchExists(branch
):
158 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
159 return proc
.wait() == 0;
162 return mypopen("git config %s" % key
).read()[:-1]
166 self
.usage
= "usage: %prog [options]"
169 class P4Debug(Command
):
171 Command
.__init
__(self
)
174 self
.description
= "A tool to debug the output of p4 -G."
175 self
.needsGit
= False
178 for output
in p4CmdList(" ".join(args
)):
182 class P4RollBack(Command
):
184 Command
.__init
__(self
)
186 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
187 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
189 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
191 self
.rollbackLocalBranches
= False
196 maxChange
= int(args
[0])
198 if "p4ExitCode" in p4Cmd("changes -m 1"):
199 die("Problems executing p4");
201 if self
.rollbackLocalBranches
:
202 refPrefix
= "refs/heads/"
203 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
205 refPrefix
= "refs/remotes/"
206 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
209 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
210 ref
= refPrefix
+ line
[:-1]
211 log
= extractLogMessageFromGitCommit(ref
)
212 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
215 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
216 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
217 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
220 while len(change
) > 0 and int(change
) > maxChange
:
223 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
224 system("git update-ref %s \"%s^\"" % (ref
, ref
))
225 log
= extractLogMessageFromGitCommit(ref
)
226 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
229 print "%s rewound to %s" % (ref
, change
)
233 class P4Submit(Command
):
235 Command
.__init
__(self
)
237 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
238 optparse
.make_option("--origin", dest
="origin"),
239 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
240 optparse
.make_option("--log-substitutions", dest
="substFile"),
241 optparse
.make_option("--dry-run", action
="store_true"),
242 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
243 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
245 self
.description
= "Submit changes from git to the perforce depot."
246 self
.usage
+= " [name of git branch to submit into perforce depot]"
247 self
.firstTime
= True
249 self
.interactive
= True
252 self
.firstTime
= True
254 self
.directSubmit
= False
255 self
.trustMeLikeAFool
= False
257 self
.logSubstitutions
= {}
258 self
.logSubstitutions
["<enter description here>"] = "%log%"
259 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
262 if len(p4CmdList("opened ...")) > 0:
263 die("You have files opened with perforce! Close them before starting the sync.")
266 if len(self
.config
) > 0 and not self
.reset
:
267 die("Cannot start sync. Previous sync config found at %s\n"
268 "If you want to start submitting again from scratch "
269 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
272 if self
.directSubmit
:
275 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
276 commits
.append(line
[:-1])
279 self
.config
["commits"] = commits
281 def prepareLogMessage(self
, template
, message
):
284 for line
in template
.split("\n"):
285 if line
.startswith("#"):
286 result
+= line
+ "\n"
290 for key
in self
.logSubstitutions
.keys():
291 if line
.find(key
) != -1:
292 value
= self
.logSubstitutions
[key
]
293 value
= value
.replace("%log%", message
)
294 if value
!= "@remove@":
295 result
+= line
.replace(key
, value
) + "\n"
300 result
+= line
+ "\n"
304 def applyCommit(self
, id):
305 if self
.directSubmit
:
306 print "Applying local change in working directory/index"
307 diff
= self
.diffStatus
309 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
310 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
312 filesToDelete
= set()
316 path
= line
[1:].strip()
318 system("p4 edit \"%s\"" % path
)
319 editedFiles
.add(path
)
320 elif modifier
== "A":
322 if path
in filesToDelete
:
323 filesToDelete
.remove(path
)
324 elif modifier
== "D":
325 filesToDelete
.add(path
)
326 if path
in filesToAdd
:
327 filesToAdd
.remove(path
)
329 die("unknown modifier %s for %s" % (modifier
, path
))
331 if self
.directSubmit
:
332 diffcmd
= "cat \"%s\"" % self
.diffFile
334 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
335 patchcmd
= diffcmd
+ " | git apply "
336 tryPatchCmd
= patchcmd
+ "--check -"
337 applyPatchCmd
= patchcmd
+ "--check --apply -"
339 if os
.system(tryPatchCmd
) != 0:
340 print "Unfortunately applying the change failed!"
341 print "What do you want to do?"
343 while response
!= "s" and response
!= "a" and response
!= "w":
344 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
345 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
347 print "Skipping! Good luck with the next patches..."
349 elif response
== "a":
350 os
.system(applyPatchCmd
)
351 if len(filesToAdd
) > 0:
352 print "You may also want to call p4 add on the following files:"
353 print " ".join(filesToAdd
)
354 if len(filesToDelete
):
355 print "The following files should be scheduled for deletion with p4 delete:"
356 print " ".join(filesToDelete
)
357 die("Please resolve and submit the conflict manually and "
358 + "continue afterwards with git-p4 submit --continue")
359 elif response
== "w":
360 system(diffcmd
+ " > patch.txt")
361 print "Patch saved to patch.txt in %s !" % self
.clientPath
362 die("Please resolve and submit the conflict manually and "
363 "continue afterwards with git-p4 submit --continue")
365 system(applyPatchCmd
)
368 system("p4 add %s" % f
)
369 for f
in filesToDelete
:
370 system("p4 revert %s" % f
)
371 system("p4 delete %s" % f
)
374 if not self
.directSubmit
:
375 logMessage
= extractLogMessageFromGitCommit(id)
376 logMessage
= logMessage
.replace("\n", "\n\t")
377 logMessage
= logMessage
[:-1]
379 template
= read_pipe("p4 change -o")
382 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
383 diff
= read_pipe("p4 diff -du ...")
385 for newFile
in filesToAdd
:
386 diff
+= "==== new file ====\n"
387 diff
+= "--- /dev/null\n"
388 diff
+= "+++ %s\n" % newFile
389 f
= open(newFile
, "r")
390 for line
in f
.readlines():
394 separatorLine
= "######## everything below this line is just the diff #######"
395 if platform
.system() == "Windows":
396 separatorLine
+= "\r"
397 separatorLine
+= "\n"
400 if self
.trustMeLikeAFool
:
403 firstIteration
= True
404 while response
== "e":
405 if not firstIteration
:
406 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
407 firstIteration
= False
409 [handle
, fileName
] = tempfile
.mkstemp()
410 tmpFile
= os
.fdopen(handle
, "w+")
411 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
414 if platform
.system() == "Windows":
415 defaultEditor
= "notepad"
416 editor
= os
.environ
.get("EDITOR", defaultEditor
);
417 system(editor
+ " " + fileName
)
418 tmpFile
= open(fileName
, "rb")
419 message
= tmpFile
.read()
422 submitTemplate
= message
[:message
.index(separatorLine
)]
424 if response
== "y" or response
== "yes":
427 raw_input("Press return to continue...")
429 if self
.directSubmit
:
430 print "Submitting to git first"
431 os
.chdir(self
.oldWorkingDirectory
)
432 write_pipe("git commit -a -F -", submitTemplate
)
433 os
.chdir(self
.clientPath
)
435 write_pipe("p4 submit -i", submitTemplate
)
436 elif response
== "s":
437 for f
in editedFiles
:
438 system("p4 revert \"%s\"" % f
);
440 system("p4 revert \"%s\"" % f
);
442 for f
in filesToDelete
:
443 system("p4 delete \"%s\"" % f
);
446 print "Not submitting!"
447 self
.interactive
= False
449 fileName
= "submit.txt"
450 file = open(fileName
, "w+")
451 file.write(self
.prepareLogMessage(template
, logMessage
))
453 print ("Perforce submit template written as %s. "
454 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
455 % (fileName
, fileName
))
459 # make gitdir absolute so we can cd out into the perforce checkout
460 gitdir
= os
.path
.abspath(gitdir
)
461 os
.environ
["GIT_DIR"] = gitdir
464 self
.master
= currentGitBranch()
465 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
466 die("Detecting current git branch failed!")
468 self
.master
= args
[0]
473 if gitBranchExists("p4"):
474 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
475 if len(depotPath
) == 0 and gitBranchExists("origin"):
476 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
478 if len(depotPath
) == 0:
479 print "Internal error: cannot locate perforce depot path from existing branches"
482 self
.clientPath
= p4Where(depotPath
)
484 if len(self
.clientPath
) == 0:
485 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
488 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
489 self
.oldWorkingDirectory
= os
.getcwd()
491 if self
.directSubmit
:
492 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
493 if len(self
.diffStatus
) == 0:
494 print "No changes in working directory to submit."
496 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
497 self
.diffFile
= gitdir
+ "/p4-git-diff"
498 f
= open(self
.diffFile
, "wb")
502 os
.chdir(self
.clientPath
)
503 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
504 if response
== "y" or response
== "yes":
505 system("p4 sync ...")
507 if len(self
.origin
) == 0:
508 if gitBranchExists("p4"):
511 self
.origin
= "origin"
514 self
.firstTime
= True
516 if len(self
.substFile
) > 0:
517 for line
in open(self
.substFile
, "r").readlines():
518 tokens
= line
[:-1].split("=")
519 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
522 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
523 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
528 commits
= self
.config
.get("commits", [])
530 while len(commits
) > 0:
531 self
.firstTime
= False
533 commits
= commits
[1:]
534 self
.config
["commits"] = commits
535 self
.applyCommit(commit
)
536 if not self
.interactive
:
541 if self
.directSubmit
:
542 os
.remove(self
.diffFile
)
544 if len(commits
) == 0:
546 print "No changes found to apply between %s and current HEAD" % self
.origin
548 print "All changes applied!"
549 os
.chdir(self
.oldWorkingDirectory
)
550 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
551 if response
== "y" or response
== "yes":
554 os
.remove(self
.configFile
)
558 class P4Sync(Command
):
560 Command
.__init
__(self
)
562 optparse
.make_option("--branch", dest
="branch"),
563 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
564 optparse
.make_option("--changesfile", dest
="changesFile"),
565 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
566 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
567 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
568 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
569 optparse
.make_option("--max-changes", dest
="maxChanges")
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
594 if gitConfig("git-p4.syncFromOrigin") == "false":
595 self
.syncWithOrigin
= False
597 def p4File(self
, depotPath
):
598 return read_pipe("p4 print -q \"%s\"" % depotPath
)
600 def extractFilesFromCommit(self
, commit
):
603 while commit
.has_key("depotFile%s" % fnum
):
604 path
= commit
["depotFile%s" % fnum
]
605 if not path
.startswith(self
.depotPath
):
606 # if not self.silent:
607 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
613 file["rev"] = commit
["rev%s" % fnum
]
614 file["action"] = commit
["action%s" % fnum
]
615 file["type"] = commit
["type%s" % fnum
]
620 def stripRepoPath(self
, path
):
621 return path
[len(self
.depotPath
):]
623 def splitFilesIntoBranches(self
, commit
):
626 while commit
.has_key("depotFile%s" % fnum
):
627 path
= commit
["depotFile%s" % fnum
]
628 if not path
.startswith(self
.depotPath
):
629 # if not self.silent:
630 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
636 file["rev"] = commit
["rev%s" % fnum
]
637 file["action"] = commit
["action%s" % fnum
]
638 file["type"] = commit
["type%s" % fnum
]
641 relPath
= self
.stripRepoPath(path
)
643 for branch
in self
.knownBranches
.keys():
645 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
646 if relPath
.startswith(branch
+ "/"):
647 if branch
not in branches
:
648 branches
[branch
] = []
649 branches
[branch
].append(file)
653 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
654 epoch
= details
["time"]
655 author
= details
["user"]
658 print "commit into %s" % branch
660 self
.gitStream
.write("commit %s\n" % branch
)
661 # gitStream.write("mark :%s\n" % details["change"])
662 self
.committedChanges
.add(int(details
["change"]))
664 if author
not in self
.users
:
665 self
.getUserMapFromPerforceServer()
666 if author
in self
.users
:
667 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
669 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
671 self
.gitStream
.write("committer %s\n" % committer
)
673 self
.gitStream
.write("data <<EOT\n")
674 self
.gitStream
.write(details
["desc"])
675 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
676 self
.gitStream
.write("EOT\n\n")
680 print "parent %s" % parent
681 self
.gitStream
.write("from %s\n" % parent
)
685 if not path
.startswith(branchPrefix
):
686 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
689 depotPath
= path
+ "#" + rev
690 relPath
= path
[len(branchPrefix
):]
691 action
= file["action"]
693 if file["type"] == "apple":
694 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
697 if action
== "delete":
698 self
.gitStream
.write("D %s\n" % relPath
)
701 if file["type"].startswith("x"):
704 data
= self
.p4File(depotPath
)
706 if self
.isWindows
and file["type"].endswith("text"):
707 data
= data
.replace("\r\n", "\n")
709 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
710 self
.gitStream
.write("data %s\n" % len(data
))
711 self
.gitStream
.write(data
)
712 self
.gitStream
.write("\n")
714 self
.gitStream
.write("\n")
716 change
= int(details
["change"])
718 if self
.labels
.has_key(change
):
719 label
= self
.labels
[change
]
720 labelDetails
= label
[0]
721 labelRevisions
= label
[1]
723 print "Change %s is labelled %s" % (change
, labelDetails
)
725 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
727 if len(files
) == len(labelRevisions
):
731 if info
["action"] == "delete":
733 cleanedFiles
[info
["depotFile"]] = info
["rev"]
735 if cleanedFiles
== labelRevisions
:
736 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
737 self
.gitStream
.write("from %s\n" % branch
)
739 owner
= labelDetails
["Owner"]
741 if author
in self
.users
:
742 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
744 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
745 self
.gitStream
.write("tagger %s\n" % tagger
)
746 self
.gitStream
.write("data <<EOT\n")
747 self
.gitStream
.write(labelDetails
["Description"])
748 self
.gitStream
.write("EOT\n\n")
752 print ("Tag %s does not match with change %s: files do not match."
753 % (labelDetails
["label"], change
))
757 print ("Tag %s does not match with change %s: file count is different."
758 % (labelDetails
["label"], change
))
760 def getUserMapFromPerforceServer(self
):
761 if self
.userMapFromPerforceServer
:
765 for output
in p4CmdList("users"):
766 if not output
.has_key("User"):
768 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
770 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
771 for user
in self
.users
.keys():
772 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
774 self
.userMapFromPerforceServer
= True
776 def loadUserMapFromCache(self
):
778 self
.userMapFromPerforceServer
= False
780 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
781 lines
= cache
.readlines()
784 entry
= line
[:-1].split("\t")
785 self
.users
[entry
[0]] = entry
[1]
787 self
.getUserMapFromPerforceServer()
792 l
= p4CmdList("labels %s..." % self
.depotPath
)
793 if len(l
) > 0 and not self
.silent
:
794 print "Finding files belonging to labels in %s" % self
.depotPath
797 label
= output
["label"]
801 print "Querying files for label %s" % label
802 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
803 revisions
[file["depotFile"]] = file["rev"]
804 change
= int(file["change"])
805 if change
> newestChange
:
806 newestChange
= change
808 self
.labels
[newestChange
] = [output
, revisions
]
811 print "Label changes: %s" % self
.labels
.keys()
813 def getBranchMapping(self
):
814 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
816 for info
in p4CmdList("branches"):
817 details
= p4Cmd("branch -o %s" % info
["branch"])
819 while details
.has_key("View%s" % viewIdx
):
820 paths
= details
["View%s" % viewIdx
].split(" ")
821 viewIdx
= viewIdx
+ 1
822 # require standard //depot/foo/... //depot/bar/... mapping
823 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
826 destination
= paths
[1]
827 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
828 source
= source
[len(self
.depotPath
):-4]
829 destination
= destination
[len(self
.depotPath
):-4]
830 if destination
not in self
.knownBranches
:
831 self
.knownBranches
[destination
] = source
832 if source
not in self
.knownBranches
:
833 self
.knownBranches
[source
] = source
835 def listExistingP4GitBranches(self
):
836 self
.p4BranchesInGit
= []
838 cmdline
= "git rev-parse --symbolic "
839 if self
.importIntoRemotes
:
840 cmdline
+= " --remotes"
842 cmdline
+= " --branches"
844 for line
in read_pipe_lines(cmdline
):
845 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
847 if self
.importIntoRemotes
:
852 self
.p4BranchesInGit
.append(branch
)
853 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
855 def createOrUpdateBranchesFromOrigin(self
):
857 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
859 for line
in mypopen("git rev-parse --symbolic --remotes"):
860 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
863 headName
= line
[len("origin/"):-1]
864 remoteHead
= self
.refPrefix
+ headName
865 originHead
= "origin/" + headName
867 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
868 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
872 if not gitBranchExists(remoteHead
):
874 print "creating %s" % remoteHead
877 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
878 if len(p4Change
) > 0:
879 if originPreviousDepotPath
== p4PreviousDepotPath
:
880 originP4Change
= int(originP4Change
)
881 p4Change
= int(p4Change
)
882 if originP4Change
> p4Change
:
883 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
886 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
889 system("git update-ref %s %s" % (remoteHead
, originHead
))
893 self
.changeRange
= ""
894 self
.initialParent
= ""
895 self
.previousDepotPath
= ""
897 # map from branch depot path to parent branch
898 self
.knownBranches
= {}
899 self
.initialParents
= {}
900 self
.hasOrigin
= gitBranchExists("origin")
902 if self
.importIntoRemotes
:
903 self
.refPrefix
= "refs/remotes/p4/"
905 self
.refPrefix
= "refs/heads/"
907 if self
.syncWithOrigin
and self
.hasOrigin
:
909 print "Syncing with origin first by calling git fetch origin"
910 system("git fetch origin")
912 if len(self
.branch
) == 0:
913 self
.branch
= self
.refPrefix
+ "master"
914 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
915 system("git update-ref %s refs/heads/p4" % self
.branch
)
916 system("git branch -D p4");
917 # create it /after/ importing, when master exists
918 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
919 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
923 self
.createOrUpdateBranchesFromOrigin()
924 self
.listExistingP4GitBranches()
926 if len(self
.p4BranchesInGit
) > 1:
928 print "Importing from/into multiple branches"
929 self
.detectBranches
= True
932 print "branches: %s" % self
.p4BranchesInGit
935 for branch
in self
.p4BranchesInGit
:
936 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
937 (depotPath
, change
) = extractDepotPathAndChangeFromGitLog(logMsg
)
940 print "path %s change %s" % (depotPath
, change
)
942 if len(depotPath
) > 0 and len(change
) > 0:
943 change
= int(change
) + 1
944 p4Change
= max(p4Change
, change
)
946 if len(self
.previousDepotPath
) == 0:
947 self
.previousDepotPath
= depotPath
950 l
= min(len(self
.previousDepotPath
), len(depotPath
))
951 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
953 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
956 self
.depotPath
= self
.previousDepotPath
957 self
.changeRange
= "@%s,#head" % p4Change
958 self
.initialParent
= parseRevision(self
.branch
)
959 if not self
.silent
and not self
.detectBranches
:
960 print "Performing incremental import into %s git branch" % self
.branch
962 if not self
.branch
.startswith("refs/"):
963 self
.branch
= "refs/heads/" + self
.branch
965 if len(self
.depotPath
) != 0:
966 self
.depotPath
= self
.depotPath
[:-1]
968 if len(args
) == 0 and len(self
.depotPath
) != 0:
970 print "Depot path: %s" % self
.depotPath
974 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
975 print ("previous import used depot path %s and now %s was specified. "
976 "This doesn't work!" % (self
.depotPath
, args
[0]))
978 self
.depotPath
= args
[0]
983 if self
.depotPath
.find("@") != -1:
984 atIdx
= self
.depotPath
.index("@")
985 self
.changeRange
= self
.depotPath
[atIdx
:]
986 if self
.changeRange
== "@all":
987 self
.changeRange
= ""
988 elif self
.changeRange
.find(",") == -1:
989 self
.revision
= self
.changeRange
990 self
.changeRange
= ""
991 self
.depotPath
= self
.depotPath
[0:atIdx
]
992 elif self
.depotPath
.find("#") != -1:
993 hashIdx
= self
.depotPath
.index("#")
994 self
.revision
= self
.depotPath
[hashIdx
:]
995 self
.depotPath
= self
.depotPath
[0:hashIdx
]
996 elif len(self
.previousDepotPath
) == 0:
997 self
.revision
= "#head"
999 self
.depotPath
= re
.sub ("\.\.\.$", "", self
.depotPath
)
1000 if not self
.depotPath
.endswith("/"):
1001 self
.depotPath
+= "/"
1003 self
.loadUserMapFromCache()
1005 if self
.detectLabels
:
1008 if self
.detectBranches
:
1009 self
.getBranchMapping();
1011 print "p4-git branches: %s" % self
.p4BranchesInGit
1012 print "initial parents: %s" % self
.initialParents
1013 for b
in self
.p4BranchesInGit
:
1015 b
= b
[len(self
.projectName
):]
1016 self
.createdBranches
.add(b
)
1018 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1020 importProcess
= subprocess
.Popen(["git", "fast-import"],
1021 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
1022 self
.gitOutput
= importProcess
.stdout
1023 self
.gitStream
= importProcess
.stdin
1024 self
.gitError
= importProcess
.stderr
1026 if len(self
.revision
) > 0:
1027 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
1029 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1030 details
["desc"] = ("Initial import of %s from the state at revision %s"
1031 % (self
.depotPath
, self
.revision
))
1032 details
["change"] = self
.revision
1036 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
1037 change
= int(info
["change"])
1038 if change
> newestRevision
:
1039 newestRevision
= change
1041 if info
["action"] == "delete":
1042 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1043 #fileCnt = fileCnt + 1
1046 for prop
in [ "depotFile", "rev", "action", "type" ]:
1047 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1049 fileCnt
= fileCnt
+ 1
1051 details
["change"] = newestRevision
1054 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1056 print "IO error with git fast-import. Is your git version recent enough?"
1057 print self
.gitError
.read()
1062 if len(self
.changesFile
) > 0:
1063 output
= open(self
.changesFile
).readlines()
1066 changeSet
.add(int(line
))
1068 for change
in changeSet
:
1069 changes
.append(change
)
1074 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1075 output
= read_pipe_lines("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
))
1078 changeNum
= line
.split(" ")[1]
1079 changes
.append(changeNum
)
1083 if len(self
.maxChanges
) > 0:
1084 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1086 if len(changes
) == 0:
1088 print "No changes to import!"
1091 self
.updatedBranches
= set()
1094 for change
in changes
:
1095 description
= p4Cmd("describe %s" % change
)
1098 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1103 if self
.detectBranches
:
1104 branches
= self
.splitFilesIntoBranches(description
)
1105 for branch
in branches
.keys():
1106 branchPrefix
= self
.depotPath
+ branch
+ "/"
1110 filesForCommit
= branches
[branch
]
1113 print "branch is %s" % branch
1115 self
.updatedBranches
.add(branch
)
1117 if branch
not in self
.createdBranches
:
1118 self
.createdBranches
.add(branch
)
1119 parent
= self
.knownBranches
[branch
]
1120 if parent
== branch
:
1123 print "parent determined through known branches: %s" % parent
1125 # main branch? use master
1126 if branch
== "main":
1129 branch
= self
.projectName
+ branch
1131 if parent
== "main":
1133 elif len(parent
) > 0:
1134 parent
= self
.projectName
+ parent
1136 branch
= self
.refPrefix
+ branch
1138 parent
= self
.refPrefix
+ parent
1141 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1143 if len(parent
) == 0 and branch
in self
.initialParents
:
1144 parent
= self
.initialParents
[branch
]
1145 del self
.initialParents
[branch
]
1147 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1149 files
= self
.extractFilesFromCommit(description
)
1150 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1151 self
.initialParent
= ""
1153 print self
.gitError
.read()
1158 if len(self
.updatedBranches
) > 0:
1159 sys
.stdout
.write("Updated branches: ")
1160 for b
in self
.updatedBranches
:
1161 sys
.stdout
.write("%s " % b
)
1162 sys
.stdout
.write("\n")
1165 self
.gitStream
.close()
1166 if importProcess
.wait() != 0:
1167 die("fast-import failed: %s" % self
.gitError
.read())
1168 self
.gitOutput
.close()
1169 self
.gitError
.close()
1173 class P4Rebase(Command
):
1175 Command
.__init
__(self
)
1177 self
.description
= ("Fetches the latest revision from perforce and "
1178 + "rebases the current work (branch) against it")
1180 def run(self
, args
):
1183 print "Rebasing the current branch"
1184 oldHead
= read_pipe("git rev-parse HEAD")[:-1]
1185 system("git rebase p4")
1186 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1189 class P4Clone(P4Sync
):
1191 P4Sync
.__init
__(self
)
1192 self
.description
= "Creates a new git repository and imports from Perforce into it"
1193 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1194 self
.needsGit
= False
1196 def run(self
, args
):
1204 destination
= args
[1]
1208 if not depotPath
.startswith("//"):
1211 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1212 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1213 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1214 depotDir
= re
.sub(r
"/$", "", depotDir
)
1217 destination
= os
.path
.split(depotDir
)[-1]
1219 print "Importing from %s into %s" % (depotPath
, destination
)
1220 os
.makedirs(destination
)
1221 os
.chdir(destination
)
1223 gitdir
= os
.getcwd() + "/.git"
1224 if not P4Sync
.run(self
, [depotPath
]):
1226 if self
.branch
!= "master":
1227 if gitBranchExists("refs/remotes/p4/master"):
1228 system("git branch master refs/remotes/p4/master")
1229 system("git checkout -f")
1231 print "Could not detect main branch. No checkout/master branch created."
1234 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1236 optparse
.IndentedHelpFormatter
.__init
__(self
)
1238 def format_description(self
, description
):
1240 return description
+ "\n"
1244 def printUsage(commands
):
1245 print "usage: %s <command> [options]" % sys
.argv
[0]
1247 print "valid commands: %s" % ", ".join(commands
)
1249 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1253 "debug" : P4Debug(),
1254 "submit" : P4Submit(),
1256 "rebase" : P4Rebase(),
1257 "clone" : P4Clone(),
1258 "rollback" : P4RollBack()
1261 if len(sys
.argv
[1:]) == 0:
1262 printUsage(commands
.keys())
1266 cmdName
= sys
.argv
[1]
1268 cmd
= commands
[cmdName
]
1270 print "unknown command %s" % cmdName
1272 printUsage(commands
.keys())
1275 options
= cmd
.options
1280 if len(options
) > 0:
1281 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1283 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1285 description
= cmd
.description
,
1286 formatter
= HelpFormatter())
1288 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1292 if len(gitdir
) == 0:
1294 if not isValidGitDir(gitdir
):
1295 gitdir
= read_pipe("git rev-parse --git-dir")[:-1]
1296 if os
.path
.exists(gitdir
):
1297 cdup
= read_pipe("git rev-parse --show-cdup")[:-1];
1301 if not isValidGitDir(gitdir
):
1302 if isValidGitDir(gitdir
+ "/.git"):
1305 die("fatal: cannot locate git repository at %s" % gitdir
)
1307 os
.environ
["GIT_DIR"] = gitdir
1309 if not cmd
.run(args
):