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 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
734 ### needs to be ported to multi branch import
736 print "Syncing with origin first as requested by calling git fetch origin"
737 system("git fetch origin")
738 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
739 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
740 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
741 if originPreviousDepotPath
== p4PreviousDepotPath
:
742 originP4Change
= int(originP4Change
)
743 p4Change
= int(p4Change
)
744 if originP4Change
> p4Change
:
745 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
746 system("git update-ref refs/remotes/p4/master origin");
748 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
750 if len(self
.branch
) == 0:
751 self
.branch
= "refs/remotes/p4/master"
752 if gitBranchExists("refs/heads/p4"):
753 system("git update-ref %s refs/heads/p4" % self
.branch
)
754 system("git branch -D p4");
755 if not gitBranchExists("refs/remotes/p4/HEAD"):
756 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
758 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
759 self
.listExistingP4GitBranches()
760 if len(self
.p4BranchesInGit
) > 1 and not self
.silent
:
761 print "Importing from/into multiple branches"
762 self
.detectBranches
= True
765 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
766 ### needs to be ported to multi branch import
768 print "Creating %s branch in git repository based on origin" % self
.branch
770 if not branch
.startswith("refs"):
771 branch
= "refs/heads/" + branch
772 system("git update-ref %s origin" % branch
)
775 print "branches: %s" % self
.p4BranchesInGit
778 for branch
in self
.p4BranchesInGit
:
779 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
782 print "path %s change %s" % (depotPath
, change
)
784 if len(depotPath
) > 0 and len(change
) > 0:
785 change
= int(change
) + 1
786 p4Change
= max(p4Change
, change
)
788 if len(self
.previousDepotPath
) == 0:
789 self
.previousDepotPath
= depotPath
792 l
= min(len(self
.previousDepotPath
), len(depotPath
))
793 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
795 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
798 self
.depotPath
= self
.previousDepotPath
799 self
.changeRange
= "@%s,#head" % p4Change
800 self
.initialParent
= parseRevision(self
.branch
)
801 if not self
.silent
and not self
.detectBranches
:
802 print "Performing incremental import into %s git branch" % self
.branch
804 if not self
.branch
.startswith("refs/"):
805 self
.branch
= "refs/heads/" + self
.branch
807 if len(self
.depotPath
) != 0:
808 self
.depotPath
= self
.depotPath
[:-1]
810 if len(args
) == 0 and len(self
.depotPath
) != 0:
812 print "Depot path: %s" % self
.depotPath
816 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
817 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
819 self
.depotPath
= args
[0]
824 if self
.depotPath
.find("@") != -1:
825 atIdx
= self
.depotPath
.index("@")
826 self
.changeRange
= self
.depotPath
[atIdx
:]
827 if self
.changeRange
== "@all":
828 self
.changeRange
= ""
829 elif self
.changeRange
.find(",") == -1:
830 self
.revision
= self
.changeRange
831 self
.changeRange
= ""
832 self
.depotPath
= self
.depotPath
[0:atIdx
]
833 elif self
.depotPath
.find("#") != -1:
834 hashIdx
= self
.depotPath
.index("#")
835 self
.revision
= self
.depotPath
[hashIdx
:]
836 self
.depotPath
= self
.depotPath
[0:hashIdx
]
837 elif len(self
.previousDepotPath
) == 0:
838 self
.revision
= "#head"
840 if self
.depotPath
.endswith("..."):
841 self
.depotPath
= self
.depotPath
[:-3]
843 if not self
.depotPath
.endswith("/"):
844 self
.depotPath
+= "/"
846 self
.loadUserMapFromCache()
848 if self
.detectLabels
:
851 if self
.detectBranches
:
852 self
.getBranchMapping();
854 print "p4-git branches: %s" % self
.p4BranchesInGit
855 print "initial parents: %s" % self
.initialParents
856 for b
in self
.p4BranchesInGit
:
858 b
= b
[len(self
.projectName
):]
859 self
.createdBranches
.add(b
)
861 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
863 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
864 self
.gitOutput
= importProcess
.stdout
865 self
.gitStream
= importProcess
.stdin
866 self
.gitError
= importProcess
.stderr
868 if len(self
.revision
) > 0:
869 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
871 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
872 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
873 details
["change"] = self
.revision
877 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
878 change
= int(info
["change"])
879 if change
> newestRevision
:
880 newestRevision
= change
882 if info
["action"] == "delete":
883 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
884 #fileCnt = fileCnt + 1
887 for prop
in [ "depotFile", "rev", "action", "type" ]:
888 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
890 fileCnt
= fileCnt
+ 1
892 details
["change"] = newestRevision
895 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
897 print "IO error with git fast-import. Is your git version recent enough?"
898 print self
.gitError
.read()
903 if len(self
.changesFile
) > 0:
904 output
= open(self
.changesFile
).readlines()
907 changeSet
.add(int(line
))
909 for change
in changeSet
:
910 changes
.append(change
)
915 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
916 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
919 changeNum
= line
.split(" ")[1]
920 changes
.append(changeNum
)
924 if len(changes
) == 0:
926 print "No changes to import!"
929 self
.updatedBranches
= set()
932 for change
in changes
:
933 description
= p4Cmd("describe %s" % change
)
936 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
941 if self
.detectBranches
:
942 branches
= self
.splitFilesIntoBranches(description
)
943 for branch
in branches
.keys():
944 branchPrefix
= self
.depotPath
+ branch
+ "/"
948 filesForCommit
= branches
[branch
]
951 print "branch is %s" % branch
953 self
.updatedBranches
.add(branch
)
955 if branch
not in self
.createdBranches
:
956 self
.createdBranches
.add(branch
)
957 parent
= self
.knownBranches
[branch
]
961 print "parent determined through known branches: %s" % parent
963 # main branch? use master
967 branch
= self
.projectName
+ branch
971 elif len(parent
) > 0:
972 parent
= self
.projectName
+ parent
974 branch
= "refs/remotes/p4/" + branch
976 parent
= "refs/remotes/p4/" + parent
979 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
981 if len(parent
) == 0 and branch
in self
.initialParents
:
982 parent
= self
.initialParents
[branch
]
983 del self
.initialParents
[branch
]
985 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
987 files
= self
.extractFilesFromCommit(description
)
988 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
989 self
.initialParent
= ""
991 print self
.gitError
.read()
996 if len(self
.updatedBranches
) > 0:
997 sys
.stdout
.write("Updated branches: ")
998 for b
in self
.updatedBranches
:
999 sys
.stdout
.write("%s " % b
)
1000 sys
.stdout
.write("\n")
1003 self
.gitStream
.close()
1004 if importProcess
.wait() != 0:
1005 die("fast-import failed: %s" % self
.gitError
.read())
1006 self
.gitOutput
.close()
1007 self
.gitError
.close()
1011 class P4Rebase(Command
):
1013 Command
.__init
__(self
)
1014 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
1015 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1016 self
.syncWithOrigin
= False
1018 def run(self
, args
):
1020 sync
.syncWithOrigin
= self
.syncWithOrigin
1022 print "Rebasing the current branch"
1023 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1024 system("git rebase p4")
1025 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1028 class P4Clone(P4Sync
):
1030 P4Sync
.__init
__(self
)
1031 self
.description
= "Creates a new git repository and imports from Perforce into it"
1032 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1033 self
.needsGit
= False
1035 def run(self
, args
):
1047 if not depotPath
.startswith("//"):
1052 atPos
= dir.rfind("@")
1055 hashPos
= dir.rfind("#")
1057 dir = dir[0:hashPos
]
1059 if dir.endswith("..."):
1062 if dir.endswith("/"):
1065 slashPos
= dir.rfind("/")
1067 dir = dir[slashPos
+ 1:]
1069 print "Importing from %s into %s" % (depotPath
, dir)
1073 gitdir
= os
.getcwd() + "/.git"
1074 if not P4Sync
.run(self
, [depotPath
]):
1076 if self
.branch
!= "master":
1077 if gitBranchExists("refs/remotes/p4/master"):
1078 system("git branch master refs/remotes/p4/master")
1079 system("git checkout -f")
1081 print "Could not detect main branch. No checkout/master branch created."
1084 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1086 optparse
.IndentedHelpFormatter
.__init
__(self
)
1088 def format_description(self
, description
):
1090 return description
+ "\n"
1094 def printUsage(commands
):
1095 print "usage: %s <command> [options]" % sys
.argv
[0]
1097 print "valid commands: %s" % ", ".join(commands
)
1099 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1103 "debug" : P4Debug(),
1104 "submit" : P4Submit(),
1106 "rebase" : P4Rebase(),
1110 if len(sys
.argv
[1:]) == 0:
1111 printUsage(commands
.keys())
1115 cmdName
= sys
.argv
[1]
1117 cmd
= commands
[cmdName
]
1119 print "unknown command %s" % cmdName
1121 printUsage(commands
.keys())
1124 options
= cmd
.options
1129 if len(options
) > 0:
1130 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1132 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1134 description
= cmd
.description
,
1135 formatter
= HelpFormatter())
1137 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1141 if len(gitdir
) == 0:
1143 if not isValidGitDir(gitdir
):
1144 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1145 if os
.path
.exists(gitdir
):
1146 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1150 if not isValidGitDir(gitdir
):
1151 if isValidGitDir(gitdir
+ "/.git"):
1154 die("fatal: cannot locate git repository at %s" % gitdir
)
1156 os
.environ
["GIT_DIR"] = gitdir
1158 if not cmd
.run(args
):