3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
10 # TODO: * implement git-p4 rollback <perforce change number> for debugging
11 # to roll back all p4 remote branches to a commit older or equal to
12 # the specified change.
13 # * for git-p4 submit --direct it would be nice to still create a
14 # git commit without updating HEAD before submitting to perforce.
15 # With the commit sha1 printed (or recoded in a .git/foo file?)
16 # it's possible to recover if anything goes wrong instead of potentially
17 # loosing a change entirely because it was never comitted to git and
18 # the p4 submit failed (or resulted in lots of conflicts, etc.)
19 # * Consider making --with-origin the default, assuming that the git
20 # protocol is always more efficient. (needs manual testing first :)
23 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
24 import tempfile
, getopt
, sha
, os
.path
, time
, platform
27 gitdir
= os
.environ
.get("GIT_DIR", "")
30 return os
.popen(command
, "rb");
33 cmd
= "p4 -G %s" % cmd
34 pipe
= os
.popen(cmd
, "rb")
39 entry
= marshal
.load(pipe
)
54 def p4Where(depotPath
):
55 if not depotPath
.endswith("/"):
57 output
= p4Cmd("where %s..." % depotPath
)
60 clientPath
= output
.get("path")
61 elif "data" in output
:
62 data
= output
.get("data")
63 lastSpace
= data
.rfind(" ")
64 clientPath
= data
[lastSpace
+ 1:]
66 if clientPath
.endswith("..."):
67 clientPath
= clientPath
[:-3]
71 sys
.stderr
.write(msg
+ "\n")
74 def currentGitBranch():
75 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
77 def isValidGitDir(path
):
78 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
82 def parseRevision(ref
):
83 return mypopen("git rev-parse %s" % ref
).read()[:-1]
86 if os
.system(cmd
) != 0:
87 die("command failed: %s" % cmd
)
89 def extractLogMessageFromGitCommit(commit
):
92 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
101 def extractDepotPathAndChangeFromGitLog(log
):
103 for line
in log
.split("\n"):
105 if line
.startswith("[git-p4:") and line
.endswith("]"):
106 line
= line
[8:-1].strip()
107 for assignment
in line
.split(":"):
108 variable
= assignment
.strip()
110 equalPos
= assignment
.find("=")
112 variable
= assignment
[:equalPos
].strip()
113 value
= assignment
[equalPos
+ 1:].strip()
114 if value
.startswith("\"") and value
.endswith("\""):
116 values
[variable
] = value
118 return values
.get("depot-path"), values
.get("change")
120 def gitBranchExists(branch
):
121 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
122 return proc
.wait() == 0;
126 self
.usage
= "usage: %prog [options]"
129 class P4Debug(Command
):
131 Command
.__init
__(self
)
134 self
.description
= "A tool to debug the output of p4 -G."
135 self
.needsGit
= False
138 for output
in p4CmdList(" ".join(args
)):
142 class P4Submit(Command
):
144 Command
.__init
__(self
)
146 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
147 optparse
.make_option("--origin", dest
="origin"),
148 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
149 optparse
.make_option("--log-substitutions", dest
="substFile"),
150 optparse
.make_option("--noninteractive", action
="store_false"),
151 optparse
.make_option("--dry-run", action
="store_true"),
152 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
154 self
.description
= "Submit changes from git to the perforce depot."
155 self
.usage
+= " [name of git branch to submit into perforce depot]"
156 self
.firstTime
= True
158 self
.interactive
= True
161 self
.firstTime
= True
163 self
.directSubmit
= False
165 self
.logSubstitutions
= {}
166 self
.logSubstitutions
["<enter description here>"] = "%log%"
167 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
170 if len(p4CmdList("opened ...")) > 0:
171 die("You have files opened with perforce! Close them before starting the sync.")
174 if len(self
.config
) > 0 and not self
.reset
:
175 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self
.configFile
)
178 if self
.directSubmit
:
181 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
182 commits
.append(line
[:-1])
185 self
.config
["commits"] = commits
187 def prepareLogMessage(self
, template
, message
):
190 for line
in template
.split("\n"):
191 if line
.startswith("#"):
192 result
+= line
+ "\n"
196 for key
in self
.logSubstitutions
.keys():
197 if line
.find(key
) != -1:
198 value
= self
.logSubstitutions
[key
]
199 value
= value
.replace("%log%", message
)
200 if value
!= "@remove@":
201 result
+= line
.replace(key
, value
) + "\n"
206 result
+= line
+ "\n"
211 if self
.directSubmit
:
212 print "Applying local change in working directory/index"
213 diff
= self
.diffStatus
215 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
216 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
218 filesToDelete
= set()
222 path
= line
[1:].strip()
224 system("p4 edit \"%s\"" % path
)
225 editedFiles
.add(path
)
226 elif modifier
== "A":
228 if path
in filesToDelete
:
229 filesToDelete
.remove(path
)
230 elif modifier
== "D":
231 filesToDelete
.add(path
)
232 if path
in filesToAdd
:
233 filesToAdd
.remove(path
)
235 die("unknown modifier %s for %s" % (modifier
, path
))
237 if self
.directSubmit
:
238 diffcmd
= "cat \"%s\"" % self
.diffFile
240 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
241 patchcmd
= diffcmd
+ " | git apply "
242 tryPatchCmd
= patchcmd
+ "--check -"
243 applyPatchCmd
= patchcmd
+ "--check --apply -"
245 if os
.system(tryPatchCmd
) != 0:
246 print "Unfortunately applying the change failed!"
247 print "What do you want to do?"
249 while response
!= "s" and response
!= "a" and response
!= "w":
250 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
252 print "Skipping! Good luck with the next patches..."
254 elif response
== "a":
255 os
.system(applyPatchCmd
)
256 if len(filesToAdd
) > 0:
257 print "You may also want to call p4 add on the following files:"
258 print " ".join(filesToAdd
)
259 if len(filesToDelete
):
260 print "The following files should be scheduled for deletion with p4 delete:"
261 print " ".join(filesToDelete
)
262 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
263 elif response
== "w":
264 system(diffcmd
+ " > patch.txt")
265 print "Patch saved to patch.txt in %s !" % self
.clientPath
266 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
268 system(applyPatchCmd
)
271 system("p4 add %s" % f
)
272 for f
in filesToDelete
:
273 system("p4 revert %s" % f
)
274 system("p4 delete %s" % f
)
277 if not self
.directSubmit
:
278 logMessage
= extractLogMessageFromGitCommit(id)
279 logMessage
= logMessage
.replace("\n", "\n\t")
280 logMessage
= logMessage
[:-1]
282 template
= mypopen("p4 change -o").read()
285 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
286 diff
= mypopen("p4 diff -du ...").read()
288 for newFile
in filesToAdd
:
289 diff
+= "==== new file ====\n"
290 diff
+= "--- /dev/null\n"
291 diff
+= "+++ %s\n" % newFile
292 f
= open(newFile
, "r")
293 for line
in f
.readlines():
297 separatorLine
= "######## everything below this line is just the diff #######"
298 if platform
.system() == "Windows":
299 separatorLine
+= "\r"
300 separatorLine
+= "\n"
303 firstIteration
= True
304 while response
== "e":
305 if not firstIteration
:
306 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
307 firstIteration
= False
309 [handle
, fileName
] = tempfile
.mkstemp()
310 tmpFile
= os
.fdopen(handle
, "w+")
311 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
314 if platform
.system() == "Windows":
315 defaultEditor
= "notepad"
316 editor
= os
.environ
.get("EDITOR", defaultEditor
);
317 system(editor
+ " " + fileName
)
318 tmpFile
= open(fileName
, "rb")
319 message
= tmpFile
.read()
322 submitTemplate
= message
[:message
.index(separatorLine
)]
324 if response
== "y" or response
== "yes":
327 raw_input("Press return to continue...")
329 pipe
= os
.popen("p4 submit -i", "wb")
330 pipe
.write(submitTemplate
)
332 elif response
== "s":
333 for f
in editedFiles
:
334 system("p4 revert \"%s\"" % f
);
336 system("p4 revert \"%s\"" % f
);
338 for f
in filesToDelete
:
339 system("p4 delete \"%s\"" % f
);
342 print "Not submitting!"
343 self
.interactive
= False
345 fileName
= "submit.txt"
346 file = open(fileName
, "w+")
347 file.write(self
.prepareLogMessage(template
, logMessage
))
349 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
353 # make gitdir absolute so we can cd out into the perforce checkout
354 gitdir
= os
.path
.abspath(gitdir
)
355 os
.environ
["GIT_DIR"] = gitdir
358 self
.master
= currentGitBranch()
359 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
360 die("Detecting current git branch failed!")
362 self
.master
= args
[0]
367 if gitBranchExists("p4"):
368 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
369 if len(depotPath
) == 0 and gitBranchExists("origin"):
370 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
372 if len(depotPath
) == 0:
373 print "Internal error: cannot locate perforce depot path from existing branches"
376 self
.clientPath
= p4Where(depotPath
)
378 if len(self
.clientPath
) == 0:
379 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
382 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
383 oldWorkingDirectory
= os
.getcwd()
385 if self
.directSubmit
:
386 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
387 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
388 self
.diffFile
= gitdir
+ "/p4-git-diff"
389 f
= open(self
.diffFile
, "wb")
393 os
.chdir(self
.clientPath
)
394 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
395 if response
== "y" or response
== "yes":
396 system("p4 sync ...")
398 if len(self
.origin
) == 0:
399 if gitBranchExists("p4"):
402 self
.origin
= "origin"
405 self
.firstTime
= True
407 if len(self
.substFile
) > 0:
408 for line
in open(self
.substFile
, "r").readlines():
409 tokens
= line
[:-1].split("=")
410 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
413 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
414 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
419 commits
= self
.config
.get("commits", [])
421 while len(commits
) > 0:
422 self
.firstTime
= False
424 commits
= commits
[1:]
425 self
.config
["commits"] = commits
427 if not self
.interactive
:
432 if self
.directSubmit
:
433 os
.remove(self
.diffFile
)
435 if len(commits
) == 0:
437 print "No changes found to apply between %s and current HEAD" % self
.origin
439 print "All changes applied!"
441 os
.chdir(oldWorkingDirectory
)
443 if self
.directSubmit
:
444 response
= raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
445 if response
== "y" or response
== "yes":
446 system("git reset --hard")
448 if len(response
) == 0:
449 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
450 if response
== "y" or response
== "yes":
453 os
.remove(self
.configFile
)
457 class P4Sync(Command
):
459 Command
.__init
__(self
)
461 optparse
.make_option("--branch", dest
="branch"),
462 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
463 optparse
.make_option("--changesfile", dest
="changesFile"),
464 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
465 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
466 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
467 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
469 self
.description
= """Imports from Perforce into a git repository.\n
471 //depot/my/project/ -- to import the current head
472 //depot/my/project/@all -- to import everything
473 //depot/my/project/@1,6 -- to import only from revision 1 to 6
475 (a ... is not needed in the path p4 specification, it's added implicitly)"""
477 self
.usage
+= " //depot/path[@revRange]"
480 self
.createdBranches
= Set()
481 self
.committedChanges
= Set()
483 self
.detectBranches
= False
484 self
.detectLabels
= False
485 self
.changesFile
= ""
486 self
.syncWithOrigin
= False
489 def p4File(self
, depotPath
):
490 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
492 def extractFilesFromCommit(self
, commit
):
495 while commit
.has_key("depotFile%s" % fnum
):
496 path
= commit
["depotFile%s" % fnum
]
497 if not path
.startswith(self
.depotPath
):
498 # if not self.silent:
499 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
505 file["rev"] = commit
["rev%s" % fnum
]
506 file["action"] = commit
["action%s" % fnum
]
507 file["type"] = commit
["type%s" % fnum
]
512 def splitFilesIntoBranches(self
, commit
):
516 while commit
.has_key("depotFile%s" % fnum
):
517 path
= commit
["depotFile%s" % fnum
]
518 if not path
.startswith(self
.depotPath
):
519 # if not self.silent:
520 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
526 file["rev"] = commit
["rev%s" % fnum
]
527 file["action"] = commit
["action%s" % fnum
]
528 file["type"] = commit
["type%s" % fnum
]
531 relPath
= path
[len(self
.depotPath
):]
533 for branch
in self
.knownBranches
.keys():
534 if relPath
.startswith(branch
):
535 if branch
not in branches
:
536 branches
[branch
] = []
537 branches
[branch
].append(file)
541 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
542 epoch
= details
["time"]
543 author
= details
["user"]
546 print "commit into %s" % branch
548 self
.gitStream
.write("commit %s\n" % branch
)
549 # gitStream.write("mark :%s\n" % details["change"])
550 self
.committedChanges
.add(int(details
["change"]))
552 if author
not in self
.users
:
553 self
.getUserMapFromPerforceServer()
554 if author
in self
.users
:
555 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
557 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
559 self
.gitStream
.write("committer %s\n" % committer
)
561 self
.gitStream
.write("data <<EOT\n")
562 self
.gitStream
.write(details
["desc"])
563 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
564 self
.gitStream
.write("EOT\n\n")
568 print "parent %s" % parent
569 self
.gitStream
.write("from %s\n" % parent
)
573 if not path
.startswith(branchPrefix
):
575 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
578 depotPath
= path
+ "#" + rev
579 relPath
= path
[len(branchPrefix
):]
580 action
= file["action"]
582 if file["type"] == "apple":
583 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
586 if action
== "delete":
587 self
.gitStream
.write("D %s\n" % relPath
)
590 if file["type"].startswith("x"):
593 data
= self
.p4File(depotPath
)
595 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
596 self
.gitStream
.write("data %s\n" % len(data
))
597 self
.gitStream
.write(data
)
598 self
.gitStream
.write("\n")
600 self
.gitStream
.write("\n")
602 change
= int(details
["change"])
604 if self
.labels
.has_key(change
):
605 label
= self
.labels
[change
]
606 labelDetails
= label
[0]
607 labelRevisions
= label
[1]
609 print "Change %s is labelled %s" % (change
, labelDetails
)
611 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
613 if len(files
) == len(labelRevisions
):
617 if info
["action"] == "delete":
619 cleanedFiles
[info
["depotFile"]] = info
["rev"]
621 if cleanedFiles
== labelRevisions
:
622 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
623 self
.gitStream
.write("from %s\n" % branch
)
625 owner
= labelDetails
["Owner"]
627 if author
in self
.users
:
628 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
630 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
631 self
.gitStream
.write("tagger %s\n" % tagger
)
632 self
.gitStream
.write("data <<EOT\n")
633 self
.gitStream
.write(labelDetails
["Description"])
634 self
.gitStream
.write("EOT\n\n")
638 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
642 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
644 def getUserMapFromPerforceServer(self
):
647 for output
in p4CmdList("users"):
648 if not output
.has_key("User"):
650 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
652 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
653 for user
in self
.users
.keys():
654 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
657 def loadUserMapFromCache(self
):
660 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
661 lines
= cache
.readlines()
664 entry
= line
[:-1].split("\t")
665 self
.users
[entry
[0]] = entry
[1]
667 self
.getUserMapFromPerforceServer()
672 l
= p4CmdList("labels %s..." % self
.depotPath
)
673 if len(l
) > 0 and not self
.silent
:
674 print "Finding files belonging to labels in %s" % self
.depotPath
677 label
= output
["label"]
681 print "Querying files for label %s" % label
682 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
683 revisions
[file["depotFile"]] = file["rev"]
684 change
= int(file["change"])
685 if change
> newestChange
:
686 newestChange
= change
688 self
.labels
[newestChange
] = [output
, revisions
]
691 print "Label changes: %s" % self
.labels
.keys()
693 def getBranchMapping(self
):
694 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
696 for info
in p4CmdList("branches"):
697 details
= p4Cmd("branch -o %s" % info
["branch"])
699 while details
.has_key("View%s" % viewIdx
):
700 paths
= details
["View%s" % viewIdx
].split(" ")
701 viewIdx
= viewIdx
+ 1
702 # require standard //depot/foo/... //depot/bar/... mapping
703 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
706 destination
= paths
[1]
707 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
708 source
= source
[len(self
.depotPath
):-4]
709 destination
= destination
[len(self
.depotPath
):-4]
710 if destination
not in self
.knownBranches
:
711 self
.knownBranches
[destination
] = source
712 if source
not in self
.knownBranches
:
713 self
.knownBranches
[source
] = source
715 def listExistingP4GitBranches(self
):
716 self
.p4BranchesInGit
= []
718 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
719 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
721 self
.p4BranchesInGit
.append(branch
)
722 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
726 self
.changeRange
= ""
727 self
.initialParent
= ""
728 self
.previousDepotPath
= ""
729 # map from branch depot path to parent branch
730 self
.knownBranches
= {}
731 self
.initialParents
= {}
733 self
.listExistingP4GitBranches()
734 if len(self
.p4BranchesInGit
) > 1 and not self
.silent
:
735 print "Importing from/into multiple branches"
736 self
.detectBranches
= True
738 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
739 ### needs to be ported to multi branch import
741 print "Syncing with origin first as requested by calling git fetch origin"
742 system("git fetch origin")
743 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
744 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
745 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
746 if originPreviousDepotPath
== p4PreviousDepotPath
:
747 originP4Change
= int(originP4Change
)
748 p4Change
= int(p4Change
)
749 if originP4Change
> p4Change
:
750 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
751 system("git update-ref refs/remotes/p4/master origin");
753 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
755 if len(self
.branch
) == 0:
756 self
.branch
= "refs/remotes/p4/master"
757 if gitBranchExists("refs/heads/p4"):
758 system("git update-ref %s refs/heads/p4" % self
.branch
)
759 system("git branch -D p4");
760 if not gitBranchExists("refs/remotes/p4/HEAD"):
761 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
764 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
765 ### needs to be ported to multi branch import
767 print "Creating %s branch in git repository based on origin" % self
.branch
769 if not branch
.startswith("refs"):
770 branch
= "refs/heads/" + branch
771 system("git update-ref %s origin" % branch
)
774 print "branches: %s" % self
.p4BranchesInGit
777 for branch
in self
.p4BranchesInGit
:
778 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
781 print "path %s change %s" % (depotPath
, change
)
783 if len(depotPath
) > 0 and len(change
) > 0:
784 change
= int(change
) + 1
785 p4Change
= max(p4Change
, change
)
787 if len(self
.previousDepotPath
) == 0:
788 self
.previousDepotPath
= depotPath
791 l
= min(len(self
.previousDepotPath
), len(depotPath
))
792 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
794 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
797 self
.depotPath
= self
.previousDepotPath
798 self
.changeRange
= "@%s,#head" % p4Change
799 self
.initialParent
= parseRevision(self
.branch
)
800 if not self
.silent
and not self
.detectBranches
:
801 print "Performing incremental import into %s git branch" % self
.branch
803 if not self
.branch
.startswith("refs/"):
804 self
.branch
= "refs/heads/" + self
.branch
806 if len(self
.depotPath
) != 0:
807 self
.depotPath
= self
.depotPath
[:-1]
809 if len(args
) == 0 and len(self
.depotPath
) != 0:
811 print "Depot path: %s" % self
.depotPath
815 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
816 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
818 self
.depotPath
= args
[0]
823 if self
.depotPath
.find("@") != -1:
824 atIdx
= self
.depotPath
.index("@")
825 self
.changeRange
= self
.depotPath
[atIdx
:]
826 if self
.changeRange
== "@all":
827 self
.changeRange
= ""
828 elif self
.changeRange
.find(",") == -1:
829 self
.revision
= self
.changeRange
830 self
.changeRange
= ""
831 self
.depotPath
= self
.depotPath
[0:atIdx
]
832 elif self
.depotPath
.find("#") != -1:
833 hashIdx
= self
.depotPath
.index("#")
834 self
.revision
= self
.depotPath
[hashIdx
:]
835 self
.depotPath
= self
.depotPath
[0:hashIdx
]
836 elif len(self
.previousDepotPath
) == 0:
837 self
.revision
= "#head"
839 if self
.depotPath
.endswith("..."):
840 self
.depotPath
= self
.depotPath
[:-3]
842 if not self
.depotPath
.endswith("/"):
843 self
.depotPath
+= "/"
845 self
.loadUserMapFromCache()
847 if self
.detectLabels
:
850 if self
.detectBranches
:
851 self
.getBranchMapping();
853 print "p4-git branches: %s" % self
.p4BranchesInGit
854 print "initial parents: %s" % self
.initialParents
855 for b
in self
.p4BranchesInGit
:
857 b
= b
[len(self
.projectName
):]
858 self
.createdBranches
.add(b
)
860 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
862 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
863 self
.gitOutput
= importProcess
.stdout
864 self
.gitStream
= importProcess
.stdin
865 self
.gitError
= importProcess
.stderr
867 if len(self
.revision
) > 0:
868 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
870 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
871 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
872 details
["change"] = self
.revision
876 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
877 change
= int(info
["change"])
878 if change
> newestRevision
:
879 newestRevision
= change
881 if info
["action"] == "delete":
882 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
883 #fileCnt = fileCnt + 1
886 for prop
in [ "depotFile", "rev", "action", "type" ]:
887 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
889 fileCnt
= fileCnt
+ 1
891 details
["change"] = newestRevision
894 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
896 print "IO error with git fast-import. Is your git version recent enough?"
897 print self
.gitError
.read()
902 if len(self
.changesFile
) > 0:
903 output
= open(self
.changesFile
).readlines()
906 changeSet
.add(int(line
))
908 for change
in changeSet
:
909 changes
.append(change
)
914 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
915 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
918 changeNum
= line
.split(" ")[1]
919 changes
.append(changeNum
)
923 if len(changes
) == 0:
925 print "No changes to import!"
928 self
.updatedBranches
= set()
931 for change
in changes
:
932 description
= p4Cmd("describe %s" % change
)
935 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
940 if self
.detectBranches
:
941 branches
= self
.splitFilesIntoBranches(description
)
942 for branch
in branches
.keys():
943 branchPrefix
= self
.depotPath
+ branch
+ "/"
947 filesForCommit
= branches
[branch
]
950 print "branch is %s" % branch
952 self
.updatedBranches
.add(branch
)
954 if branch
not in self
.createdBranches
:
955 self
.createdBranches
.add(branch
)
956 parent
= self
.knownBranches
[branch
]
960 print "parent determined through known branches: %s" % parent
962 # main branch? use master
966 branch
= self
.projectName
+ branch
970 elif len(parent
) > 0:
971 parent
= self
.projectName
+ parent
973 branch
= "refs/remotes/p4/" + branch
975 parent
= "refs/remotes/p4/" + parent
978 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
980 if len(parent
) == 0 and branch
in self
.initialParents
:
981 parent
= self
.initialParents
[branch
]
982 del self
.initialParents
[branch
]
984 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
986 files
= self
.extractFilesFromCommit(description
)
987 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
988 self
.initialParent
= ""
990 print self
.gitError
.read()
995 if len(self
.updatedBranches
) > 0:
996 sys
.stdout
.write("Updated branches: ")
997 for b
in self
.updatedBranches
:
998 sys
.stdout
.write("%s " % b
)
999 sys
.stdout
.write("\n")
1002 self
.gitStream
.close()
1003 if importProcess
.wait() != 0:
1004 die("fast-import failed: %s" % self
.gitError
.read())
1005 self
.gitOutput
.close()
1006 self
.gitError
.close()
1010 class P4Rebase(Command
):
1012 Command
.__init
__(self
)
1013 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
1014 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1015 self
.syncWithOrigin
= False
1017 def run(self
, args
):
1019 sync
.syncWithOrigin
= self
.syncWithOrigin
1021 print "Rebasing the current branch"
1022 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1023 system("git rebase p4")
1024 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1027 class P4Clone(P4Sync
):
1029 P4Sync
.__init
__(self
)
1030 self
.description
= "Creates a new git repository and imports from Perforce into it"
1031 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1032 self
.needsGit
= False
1034 def run(self
, args
):
1046 if not depotPath
.startswith("//"):
1051 atPos
= dir.rfind("@")
1054 hashPos
= dir.rfind("#")
1056 dir = dir[0:hashPos
]
1058 if dir.endswith("..."):
1061 if dir.endswith("/"):
1064 slashPos
= dir.rfind("/")
1066 dir = dir[slashPos
+ 1:]
1068 print "Importing from %s into %s" % (depotPath
, dir)
1072 gitdir
= os
.getcwd() + "/.git"
1073 if not P4Sync
.run(self
, [depotPath
]):
1075 if self
.branch
!= "master":
1076 if gitBranchExists("refs/remotes/p4/master"):
1077 system("git branch master refs/remotes/p4/master")
1078 system("git checkout -f")
1080 print "Could not detect main branch. No checkout/master branch created."
1083 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1085 optparse
.IndentedHelpFormatter
.__init
__(self
)
1087 def format_description(self
, description
):
1089 return description
+ "\n"
1093 def printUsage(commands
):
1094 print "usage: %s <command> [options]" % sys
.argv
[0]
1096 print "valid commands: %s" % ", ".join(commands
)
1098 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1102 "debug" : P4Debug(),
1103 "submit" : P4Submit(),
1105 "rebase" : P4Rebase(),
1109 if len(sys
.argv
[1:]) == 0:
1110 printUsage(commands
.keys())
1114 cmdName
= sys
.argv
[1]
1116 cmd
= commands
[cmdName
]
1118 print "unknown command %s" % cmdName
1120 printUsage(commands
.keys())
1123 options
= cmd
.options
1128 if len(options
) > 0:
1129 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1131 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1133 description
= cmd
.description
,
1134 formatter
= HelpFormatter())
1136 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1140 if len(gitdir
) == 0:
1142 if not isValidGitDir(gitdir
):
1143 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1144 if os
.path
.exists(gitdir
):
1145 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1149 if not isValidGitDir(gitdir
):
1150 if isValidGitDir(gitdir
+ "/.git"):
1153 die("fatal: cannot locate git repository at %s" % gitdir
)
1155 os
.environ
["GIT_DIR"] = gitdir
1157 if not cmd
.run(args
):