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
)
58 if output
["code"] == "error":
62 clientPath
= output
.get("path")
63 elif "data" in output
:
64 data
= output
.get("data")
65 lastSpace
= data
.rfind(" ")
66 clientPath
= data
[lastSpace
+ 1:]
68 if clientPath
.endswith("..."):
69 clientPath
= clientPath
[:-3]
73 sys
.stderr
.write(msg
+ "\n")
76 def currentGitBranch():
77 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
79 def isValidGitDir(path
):
80 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
84 def parseRevision(ref
):
85 return mypopen("git rev-parse %s" % ref
).read()[:-1]
88 if os
.system(cmd
) != 0:
89 die("command failed: %s" % cmd
)
91 def extractLogMessageFromGitCommit(commit
):
94 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
103 def extractDepotPathAndChangeFromGitLog(log
):
105 for line
in log
.split("\n"):
107 if line
.startswith("[git-p4:") and line
.endswith("]"):
108 line
= line
[8:-1].strip()
109 for assignment
in line
.split(":"):
110 variable
= assignment
.strip()
112 equalPos
= assignment
.find("=")
114 variable
= assignment
[:equalPos
].strip()
115 value
= assignment
[equalPos
+ 1:].strip()
116 if value
.startswith("\"") and value
.endswith("\""):
118 values
[variable
] = value
120 return values
.get("depot-path"), values
.get("change")
122 def gitBranchExists(branch
):
123 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
124 return proc
.wait() == 0;
128 self
.usage
= "usage: %prog [options]"
131 class P4Debug(Command
):
133 Command
.__init
__(self
)
136 self
.description
= "A tool to debug the output of p4 -G."
137 self
.needsGit
= False
140 for output
in p4CmdList(" ".join(args
)):
144 class P4Submit(Command
):
146 Command
.__init
__(self
)
148 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
149 optparse
.make_option("--origin", dest
="origin"),
150 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
151 optparse
.make_option("--log-substitutions", dest
="substFile"),
152 optparse
.make_option("--noninteractive", action
="store_false"),
153 optparse
.make_option("--dry-run", action
="store_true"),
154 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
156 self
.description
= "Submit changes from git to the perforce depot."
157 self
.usage
+= " [name of git branch to submit into perforce depot]"
158 self
.firstTime
= True
160 self
.interactive
= True
163 self
.firstTime
= True
165 self
.directSubmit
= False
167 self
.logSubstitutions
= {}
168 self
.logSubstitutions
["<enter description here>"] = "%log%"
169 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
172 if len(p4CmdList("opened ...")) > 0:
173 die("You have files opened with perforce! Close them before starting the sync.")
176 if len(self
.config
) > 0 and not self
.reset
:
177 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
)
180 if self
.directSubmit
:
183 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
184 commits
.append(line
[:-1])
187 self
.config
["commits"] = commits
189 def prepareLogMessage(self
, template
, message
):
192 for line
in template
.split("\n"):
193 if line
.startswith("#"):
194 result
+= line
+ "\n"
198 for key
in self
.logSubstitutions
.keys():
199 if line
.find(key
) != -1:
200 value
= self
.logSubstitutions
[key
]
201 value
= value
.replace("%log%", message
)
202 if value
!= "@remove@":
203 result
+= line
.replace(key
, value
) + "\n"
208 result
+= line
+ "\n"
213 if self
.directSubmit
:
214 print "Applying local change in working directory/index"
215 diff
= self
.diffStatus
217 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
218 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
220 filesToDelete
= set()
224 path
= line
[1:].strip()
226 system("p4 edit \"%s\"" % path
)
227 editedFiles
.add(path
)
228 elif modifier
== "A":
230 if path
in filesToDelete
:
231 filesToDelete
.remove(path
)
232 elif modifier
== "D":
233 filesToDelete
.add(path
)
234 if path
in filesToAdd
:
235 filesToAdd
.remove(path
)
237 die("unknown modifier %s for %s" % (modifier
, path
))
239 if self
.directSubmit
:
240 diffcmd
= "cat \"%s\"" % self
.diffFile
242 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
243 patchcmd
= diffcmd
+ " | git apply "
244 tryPatchCmd
= patchcmd
+ "--check -"
245 applyPatchCmd
= patchcmd
+ "--check --apply -"
247 if os
.system(tryPatchCmd
) != 0:
248 print "Unfortunately applying the change failed!"
249 print "What do you want to do?"
251 while response
!= "s" and response
!= "a" and response
!= "w":
252 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) ")
254 print "Skipping! Good luck with the next patches..."
256 elif response
== "a":
257 os
.system(applyPatchCmd
)
258 if len(filesToAdd
) > 0:
259 print "You may also want to call p4 add on the following files:"
260 print " ".join(filesToAdd
)
261 if len(filesToDelete
):
262 print "The following files should be scheduled for deletion with p4 delete:"
263 print " ".join(filesToDelete
)
264 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
265 elif response
== "w":
266 system(diffcmd
+ " > patch.txt")
267 print "Patch saved to patch.txt in %s !" % self
.clientPath
268 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
270 system(applyPatchCmd
)
273 system("p4 add %s" % f
)
274 for f
in filesToDelete
:
275 system("p4 revert %s" % f
)
276 system("p4 delete %s" % f
)
279 if not self
.directSubmit
:
280 logMessage
= extractLogMessageFromGitCommit(id)
281 logMessage
= logMessage
.replace("\n", "\n\t")
282 logMessage
= logMessage
[:-1]
284 template
= mypopen("p4 change -o").read()
287 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
288 diff
= mypopen("p4 diff -du ...").read()
290 for newFile
in filesToAdd
:
291 diff
+= "==== new file ====\n"
292 diff
+= "--- /dev/null\n"
293 diff
+= "+++ %s\n" % newFile
294 f
= open(newFile
, "r")
295 for line
in f
.readlines():
299 separatorLine
= "######## everything below this line is just the diff #######"
300 if platform
.system() == "Windows":
301 separatorLine
+= "\r"
302 separatorLine
+= "\n"
305 firstIteration
= True
306 while response
== "e":
307 if not firstIteration
:
308 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
309 firstIteration
= False
311 [handle
, fileName
] = tempfile
.mkstemp()
312 tmpFile
= os
.fdopen(handle
, "w+")
313 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
316 if platform
.system() == "Windows":
317 defaultEditor
= "notepad"
318 editor
= os
.environ
.get("EDITOR", defaultEditor
);
319 system(editor
+ " " + fileName
)
320 tmpFile
= open(fileName
, "rb")
321 message
= tmpFile
.read()
324 submitTemplate
= message
[:message
.index(separatorLine
)]
326 if response
== "y" or response
== "yes":
329 raw_input("Press return to continue...")
331 pipe
= os
.popen("p4 submit -i", "wb")
332 pipe
.write(submitTemplate
)
334 elif response
== "s":
335 for f
in editedFiles
:
336 system("p4 revert \"%s\"" % f
);
338 system("p4 revert \"%s\"" % f
);
340 for f
in filesToDelete
:
341 system("p4 delete \"%s\"" % f
);
344 print "Not submitting!"
345 self
.interactive
= False
347 fileName
= "submit.txt"
348 file = open(fileName
, "w+")
349 file.write(self
.prepareLogMessage(template
, logMessage
))
351 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
355 # make gitdir absolute so we can cd out into the perforce checkout
356 gitdir
= os
.path
.abspath(gitdir
)
357 os
.environ
["GIT_DIR"] = gitdir
360 self
.master
= currentGitBranch()
361 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
362 die("Detecting current git branch failed!")
364 self
.master
= args
[0]
369 if gitBranchExists("p4"):
370 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
371 if len(depotPath
) == 0 and gitBranchExists("origin"):
372 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
374 if len(depotPath
) == 0:
375 print "Internal error: cannot locate perforce depot path from existing branches"
378 self
.clientPath
= p4Where(depotPath
)
380 if len(self
.clientPath
) == 0:
381 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
384 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
385 oldWorkingDirectory
= os
.getcwd()
387 if self
.directSubmit
:
388 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
389 if len(self
.diffStatus
) == 0:
390 print "No changes in working directory to submit."
392 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
393 self
.diffFile
= gitdir
+ "/p4-git-diff"
394 f
= open(self
.diffFile
, "wb")
398 os
.chdir(self
.clientPath
)
399 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
400 if response
== "y" or response
== "yes":
401 system("p4 sync ...")
403 if len(self
.origin
) == 0:
404 if gitBranchExists("p4"):
407 self
.origin
= "origin"
410 self
.firstTime
= True
412 if len(self
.substFile
) > 0:
413 for line
in open(self
.substFile
, "r").readlines():
414 tokens
= line
[:-1].split("=")
415 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
418 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
419 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
424 commits
= self
.config
.get("commits", [])
426 while len(commits
) > 0:
427 self
.firstTime
= False
429 commits
= commits
[1:]
430 self
.config
["commits"] = commits
432 if not self
.interactive
:
437 if self
.directSubmit
:
438 os
.remove(self
.diffFile
)
440 if len(commits
) == 0:
442 print "No changes found to apply between %s and current HEAD" % self
.origin
444 print "All changes applied!"
446 os
.chdir(oldWorkingDirectory
)
448 if self
.directSubmit
:
449 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 ")
450 if response
== "y" or response
== "yes":
451 system("git reset --hard")
453 if len(response
) == 0:
454 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
455 if response
== "y" or response
== "yes":
458 os
.remove(self
.configFile
)
462 class P4Sync(Command
):
464 Command
.__init
__(self
)
466 optparse
.make_option("--branch", dest
="branch"),
467 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
468 optparse
.make_option("--changesfile", dest
="changesFile"),
469 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
470 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
471 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
472 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
474 self
.description
= """Imports from Perforce into a git repository.\n
476 //depot/my/project/ -- to import the current head
477 //depot/my/project/@all -- to import everything
478 //depot/my/project/@1,6 -- to import only from revision 1 to 6
480 (a ... is not needed in the path p4 specification, it's added implicitly)"""
482 self
.usage
+= " //depot/path[@revRange]"
485 self
.createdBranches
= Set()
486 self
.committedChanges
= Set()
488 self
.detectBranches
= False
489 self
.detectLabels
= False
490 self
.changesFile
= ""
491 self
.syncWithOrigin
= False
494 def p4File(self
, depotPath
):
495 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
497 def extractFilesFromCommit(self
, commit
):
500 while commit
.has_key("depotFile%s" % fnum
):
501 path
= commit
["depotFile%s" % fnum
]
502 if not path
.startswith(self
.depotPath
):
503 # if not self.silent:
504 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
510 file["rev"] = commit
["rev%s" % fnum
]
511 file["action"] = commit
["action%s" % fnum
]
512 file["type"] = commit
["type%s" % fnum
]
517 def splitFilesIntoBranches(self
, commit
):
521 while commit
.has_key("depotFile%s" % fnum
):
522 path
= commit
["depotFile%s" % fnum
]
523 if not path
.startswith(self
.depotPath
):
524 # if not self.silent:
525 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
531 file["rev"] = commit
["rev%s" % fnum
]
532 file["action"] = commit
["action%s" % fnum
]
533 file["type"] = commit
["type%s" % fnum
]
536 relPath
= path
[len(self
.depotPath
):]
538 for branch
in self
.knownBranches
.keys():
539 if relPath
.startswith(branch
):
540 if branch
not in branches
:
541 branches
[branch
] = []
542 branches
[branch
].append(file)
546 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
547 epoch
= details
["time"]
548 author
= details
["user"]
551 print "commit into %s" % branch
553 self
.gitStream
.write("commit %s\n" % branch
)
554 # gitStream.write("mark :%s\n" % details["change"])
555 self
.committedChanges
.add(int(details
["change"]))
557 if author
not in self
.users
:
558 self
.getUserMapFromPerforceServer()
559 if author
in self
.users
:
560 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
562 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
564 self
.gitStream
.write("committer %s\n" % committer
)
566 self
.gitStream
.write("data <<EOT\n")
567 self
.gitStream
.write(details
["desc"])
568 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
569 self
.gitStream
.write("EOT\n\n")
573 print "parent %s" % parent
574 self
.gitStream
.write("from %s\n" % parent
)
578 if not path
.startswith(branchPrefix
):
580 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
583 depotPath
= path
+ "#" + rev
584 relPath
= path
[len(branchPrefix
):]
585 action
= file["action"]
587 if file["type"] == "apple":
588 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
591 if action
== "delete":
592 self
.gitStream
.write("D %s\n" % relPath
)
595 if file["type"].startswith("x"):
598 data
= self
.p4File(depotPath
)
600 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
601 self
.gitStream
.write("data %s\n" % len(data
))
602 self
.gitStream
.write(data
)
603 self
.gitStream
.write("\n")
605 self
.gitStream
.write("\n")
607 change
= int(details
["change"])
609 if self
.labels
.has_key(change
):
610 label
= self
.labels
[change
]
611 labelDetails
= label
[0]
612 labelRevisions
= label
[1]
614 print "Change %s is labelled %s" % (change
, labelDetails
)
616 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
618 if len(files
) == len(labelRevisions
):
622 if info
["action"] == "delete":
624 cleanedFiles
[info
["depotFile"]] = info
["rev"]
626 if cleanedFiles
== labelRevisions
:
627 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
628 self
.gitStream
.write("from %s\n" % branch
)
630 owner
= labelDetails
["Owner"]
632 if author
in self
.users
:
633 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
635 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
636 self
.gitStream
.write("tagger %s\n" % tagger
)
637 self
.gitStream
.write("data <<EOT\n")
638 self
.gitStream
.write(labelDetails
["Description"])
639 self
.gitStream
.write("EOT\n\n")
643 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
647 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
649 def getUserMapFromPerforceServer(self
):
652 for output
in p4CmdList("users"):
653 if not output
.has_key("User"):
655 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
657 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
658 for user
in self
.users
.keys():
659 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
662 def loadUserMapFromCache(self
):
665 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
666 lines
= cache
.readlines()
669 entry
= line
[:-1].split("\t")
670 self
.users
[entry
[0]] = entry
[1]
672 self
.getUserMapFromPerforceServer()
677 l
= p4CmdList("labels %s..." % self
.depotPath
)
678 if len(l
) > 0 and not self
.silent
:
679 print "Finding files belonging to labels in %s" % self
.depotPath
682 label
= output
["label"]
686 print "Querying files for label %s" % label
687 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
688 revisions
[file["depotFile"]] = file["rev"]
689 change
= int(file["change"])
690 if change
> newestChange
:
691 newestChange
= change
693 self
.labels
[newestChange
] = [output
, revisions
]
696 print "Label changes: %s" % self
.labels
.keys()
698 def getBranchMapping(self
):
699 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
701 for info
in p4CmdList("branches"):
702 details
= p4Cmd("branch -o %s" % info
["branch"])
704 while details
.has_key("View%s" % viewIdx
):
705 paths
= details
["View%s" % viewIdx
].split(" ")
706 viewIdx
= viewIdx
+ 1
707 # require standard //depot/foo/... //depot/bar/... mapping
708 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
711 destination
= paths
[1]
712 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
713 source
= source
[len(self
.depotPath
):-4]
714 destination
= destination
[len(self
.depotPath
):-4]
715 if destination
not in self
.knownBranches
:
716 self
.knownBranches
[destination
] = source
717 if source
not in self
.knownBranches
:
718 self
.knownBranches
[source
] = source
720 def listExistingP4GitBranches(self
):
721 self
.p4BranchesInGit
= []
723 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
724 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
726 self
.p4BranchesInGit
.append(branch
)
727 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
731 self
.changeRange
= ""
732 self
.initialParent
= ""
733 self
.previousDepotPath
= ""
734 # map from branch depot path to parent branch
735 self
.knownBranches
= {}
736 self
.initialParents
= {}
738 createP4HeadRef
= False;
740 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
741 ### needs to be ported to multi branch import
743 print "Syncing with origin first as requested by calling git fetch origin"
744 system("git fetch origin")
745 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
746 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
747 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
748 if originPreviousDepotPath
== p4PreviousDepotPath
:
749 originP4Change
= int(originP4Change
)
750 p4Change
= int(p4Change
)
751 if originP4Change
> p4Change
:
752 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
753 system("git update-ref refs/remotes/p4/master origin");
755 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
757 if len(self
.branch
) == 0:
758 self
.branch
= "refs/remotes/p4/master"
759 if gitBranchExists("refs/heads/p4"):
760 system("git update-ref %s refs/heads/p4" % self
.branch
)
761 system("git branch -D p4");
762 # create it /after/ importing, when master exists
763 if not gitBranchExists("refs/remotes/p4/HEAD"):
764 createP4HeadRef
= True
766 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
767 self
.listExistingP4GitBranches()
768 if len(self
.p4BranchesInGit
) > 1 and not self
.silent
:
769 print "Importing from/into multiple branches"
770 self
.detectBranches
= True
773 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
774 ### needs to be ported to multi branch import
776 print "Creating %s branch in git repository based on origin" % self
.branch
778 if not branch
.startswith("refs"):
779 branch
= "refs/heads/" + branch
780 system("git update-ref %s origin" % branch
)
783 print "branches: %s" % self
.p4BranchesInGit
786 for branch
in self
.p4BranchesInGit
:
787 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
790 print "path %s change %s" % (depotPath
, change
)
792 if len(depotPath
) > 0 and len(change
) > 0:
793 change
= int(change
) + 1
794 p4Change
= max(p4Change
, change
)
796 if len(self
.previousDepotPath
) == 0:
797 self
.previousDepotPath
= depotPath
800 l
= min(len(self
.previousDepotPath
), len(depotPath
))
801 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
803 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
806 self
.depotPath
= self
.previousDepotPath
807 self
.changeRange
= "@%s,#head" % p4Change
808 self
.initialParent
= parseRevision(self
.branch
)
809 if not self
.silent
and not self
.detectBranches
:
810 print "Performing incremental import into %s git branch" % self
.branch
812 if not self
.branch
.startswith("refs/"):
813 self
.branch
= "refs/heads/" + self
.branch
815 if len(self
.depotPath
) != 0:
816 self
.depotPath
= self
.depotPath
[:-1]
818 if len(args
) == 0 and len(self
.depotPath
) != 0:
820 print "Depot path: %s" % self
.depotPath
824 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
825 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
827 self
.depotPath
= args
[0]
832 if self
.depotPath
.find("@") != -1:
833 atIdx
= self
.depotPath
.index("@")
834 self
.changeRange
= self
.depotPath
[atIdx
:]
835 if self
.changeRange
== "@all":
836 self
.changeRange
= ""
837 elif self
.changeRange
.find(",") == -1:
838 self
.revision
= self
.changeRange
839 self
.changeRange
= ""
840 self
.depotPath
= self
.depotPath
[0:atIdx
]
841 elif self
.depotPath
.find("#") != -1:
842 hashIdx
= self
.depotPath
.index("#")
843 self
.revision
= self
.depotPath
[hashIdx
:]
844 self
.depotPath
= self
.depotPath
[0:hashIdx
]
845 elif len(self
.previousDepotPath
) == 0:
846 self
.revision
= "#head"
848 if self
.depotPath
.endswith("..."):
849 self
.depotPath
= self
.depotPath
[:-3]
851 if not self
.depotPath
.endswith("/"):
852 self
.depotPath
+= "/"
854 self
.loadUserMapFromCache()
856 if self
.detectLabels
:
859 if self
.detectBranches
:
860 self
.getBranchMapping();
862 print "p4-git branches: %s" % self
.p4BranchesInGit
863 print "initial parents: %s" % self
.initialParents
864 for b
in self
.p4BranchesInGit
:
866 b
= b
[len(self
.projectName
):]
867 self
.createdBranches
.add(b
)
869 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
871 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
872 self
.gitOutput
= importProcess
.stdout
873 self
.gitStream
= importProcess
.stdin
874 self
.gitError
= importProcess
.stderr
876 if len(self
.revision
) > 0:
877 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
879 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
880 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
881 details
["change"] = self
.revision
885 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
886 change
= int(info
["change"])
887 if change
> newestRevision
:
888 newestRevision
= change
890 if info
["action"] == "delete":
891 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
892 #fileCnt = fileCnt + 1
895 for prop
in [ "depotFile", "rev", "action", "type" ]:
896 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
898 fileCnt
= fileCnt
+ 1
900 details
["change"] = newestRevision
903 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
905 print "IO error with git fast-import. Is your git version recent enough?"
906 print self
.gitError
.read()
911 if len(self
.changesFile
) > 0:
912 output
= open(self
.changesFile
).readlines()
915 changeSet
.add(int(line
))
917 for change
in changeSet
:
918 changes
.append(change
)
923 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
924 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
927 changeNum
= line
.split(" ")[1]
928 changes
.append(changeNum
)
932 if len(changes
) == 0:
934 print "No changes to import!"
937 self
.updatedBranches
= set()
940 for change
in changes
:
941 description
= p4Cmd("describe %s" % change
)
944 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
949 if self
.detectBranches
:
950 branches
= self
.splitFilesIntoBranches(description
)
951 for branch
in branches
.keys():
952 branchPrefix
= self
.depotPath
+ branch
+ "/"
956 filesForCommit
= branches
[branch
]
959 print "branch is %s" % branch
961 self
.updatedBranches
.add(branch
)
963 if branch
not in self
.createdBranches
:
964 self
.createdBranches
.add(branch
)
965 parent
= self
.knownBranches
[branch
]
969 print "parent determined through known branches: %s" % parent
971 # main branch? use master
975 branch
= self
.projectName
+ branch
979 elif len(parent
) > 0:
980 parent
= self
.projectName
+ parent
982 branch
= "refs/remotes/p4/" + branch
984 parent
= "refs/remotes/p4/" + parent
987 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
989 if len(parent
) == 0 and branch
in self
.initialParents
:
990 parent
= self
.initialParents
[branch
]
991 del self
.initialParents
[branch
]
993 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
995 files
= self
.extractFilesFromCommit(description
)
996 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
997 self
.initialParent
= ""
999 print self
.gitError
.read()
1004 if len(self
.updatedBranches
) > 0:
1005 sys
.stdout
.write("Updated branches: ")
1006 for b
in self
.updatedBranches
:
1007 sys
.stdout
.write("%s " % b
)
1008 sys
.stdout
.write("\n")
1011 self
.gitStream
.close()
1012 if importProcess
.wait() != 0:
1013 die("fast-import failed: %s" % self
.gitError
.read())
1014 self
.gitOutput
.close()
1015 self
.gitError
.close()
1018 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
1022 class P4Rebase(Command
):
1024 Command
.__init
__(self
)
1025 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
1026 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1027 self
.syncWithOrigin
= False
1029 def run(self
, args
):
1031 sync
.syncWithOrigin
= self
.syncWithOrigin
1033 print "Rebasing the current branch"
1034 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1035 system("git rebase p4")
1036 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1039 class P4Clone(P4Sync
):
1041 P4Sync
.__init
__(self
)
1042 self
.description
= "Creates a new git repository and imports from Perforce into it"
1043 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1044 self
.needsGit
= False
1046 def run(self
, args
):
1058 if not depotPath
.startswith("//"):
1063 atPos
= dir.rfind("@")
1066 hashPos
= dir.rfind("#")
1068 dir = dir[0:hashPos
]
1070 if dir.endswith("..."):
1073 if dir.endswith("/"):
1076 slashPos
= dir.rfind("/")
1078 dir = dir[slashPos
+ 1:]
1080 print "Importing from %s into %s" % (depotPath
, dir)
1084 gitdir
= os
.getcwd() + "/.git"
1085 if not P4Sync
.run(self
, [depotPath
]):
1087 if self
.branch
!= "master":
1088 if gitBranchExists("refs/remotes/p4/master"):
1089 system("git branch master refs/remotes/p4/master")
1090 system("git checkout -f")
1092 print "Could not detect main branch. No checkout/master branch created."
1095 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1097 optparse
.IndentedHelpFormatter
.__init
__(self
)
1099 def format_description(self
, description
):
1101 return description
+ "\n"
1105 def printUsage(commands
):
1106 print "usage: %s <command> [options]" % sys
.argv
[0]
1108 print "valid commands: %s" % ", ".join(commands
)
1110 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1114 "debug" : P4Debug(),
1115 "submit" : P4Submit(),
1117 "rebase" : P4Rebase(),
1121 if len(sys
.argv
[1:]) == 0:
1122 printUsage(commands
.keys())
1126 cmdName
= sys
.argv
[1]
1128 cmd
= commands
[cmdName
]
1130 print "unknown command %s" % cmdName
1132 printUsage(commands
.keys())
1135 options
= cmd
.options
1140 if len(options
) > 0:
1141 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1143 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1145 description
= cmd
.description
,
1146 formatter
= HelpFormatter())
1148 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1152 if len(gitdir
) == 0:
1154 if not isValidGitDir(gitdir
):
1155 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1156 if os
.path
.exists(gitdir
):
1157 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1161 if not isValidGitDir(gitdir
):
1162 if isValidGitDir(gitdir
+ "/.git"):
1165 die("fatal: cannot locate git repository at %s" % gitdir
)
1167 os
.environ
["GIT_DIR"] = gitdir
1169 if not cmd
.run(args
):