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>
11 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
, platform
15 gitdir
= os
.environ
.get("GIT_DIR", "")
18 return os
.popen(command
, "rb");
21 cmd
= "p4 -G %s" % cmd
22 pipe
= os
.popen(cmd
, "rb")
27 entry
= marshal
.load(pipe
)
42 def p4Where(depotPath
):
43 if not depotPath
.endswith("/"):
45 output
= p4Cmd("where %s..." % depotPath
)
48 clientPath
= output
.get("path")
49 elif "data" in output
:
50 data
= output
.get("data")
51 lastSpace
= data
.rfind(" ")
52 clientPath
= data
[lastSpace
+ 1:]
54 if clientPath
.endswith("..."):
55 clientPath
= clientPath
[:-3]
59 sys
.stderr
.write(msg
+ "\n")
62 def currentGitBranch():
63 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
65 def isValidGitDir(path
):
66 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
70 def parseRevision(ref
):
71 return mypopen("git rev-parse %s" % ref
).read()[:-1]
74 if os
.system(cmd
) != 0:
75 die("command failed: %s" % cmd
)
77 def extractLogMessageFromGitCommit(commit
):
80 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
89 def extractDepotPathAndChangeFromGitLog(log
):
91 for line
in log
.split("\n"):
93 if line
.startswith("[git-p4:") and line
.endswith("]"):
94 line
= line
[8:-1].strip()
95 for assignment
in line
.split(":"):
96 variable
= assignment
.strip()
98 equalPos
= assignment
.find("=")
100 variable
= assignment
[:equalPos
].strip()
101 value
= assignment
[equalPos
+ 1:].strip()
102 if value
.startswith("\"") and value
.endswith("\""):
104 values
[variable
] = value
106 return values
.get("depot-path"), values
.get("change")
108 def gitBranchExists(branch
):
109 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
110 return proc
.wait() == 0;
114 self
.usage
= "usage: %prog [options]"
117 class P4Debug(Command
):
119 Command
.__init
__(self
)
122 self
.description
= "A tool to debug the output of p4 -G."
123 self
.needsGit
= False
126 for output
in p4CmdList(" ".join(args
)):
130 class P4Submit(Command
):
132 Command
.__init
__(self
)
134 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
135 optparse
.make_option("--origin", dest
="origin"),
136 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
137 optparse
.make_option("--log-substitutions", dest
="substFile"),
138 optparse
.make_option("--noninteractive", action
="store_false"),
139 optparse
.make_option("--dry-run", action
="store_true"),
141 self
.description
= "Submit changes from git to the perforce depot."
142 self
.usage
+= " [name of git branch to submit into perforce depot]"
143 self
.firstTime
= True
145 self
.interactive
= True
148 self
.firstTime
= True
151 self
.logSubstitutions
= {}
152 self
.logSubstitutions
["<enter description here>"] = "%log%"
153 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
156 if len(p4CmdList("opened ...")) > 0:
157 die("You have files opened with perforce! Close them before starting the sync.")
160 if len(self
.config
) > 0 and not self
.reset
:
161 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
)
164 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
165 commits
.append(line
[:-1])
168 self
.config
["commits"] = commits
170 def prepareLogMessage(self
, template
, message
):
173 for line
in template
.split("\n"):
174 if line
.startswith("#"):
175 result
+= line
+ "\n"
179 for key
in self
.logSubstitutions
.keys():
180 if line
.find(key
) != -1:
181 value
= self
.logSubstitutions
[key
]
182 value
= value
.replace("%log%", message
)
183 if value
!= "@remove@":
184 result
+= line
.replace(key
, value
) + "\n"
189 result
+= line
+ "\n"
194 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
195 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
197 filesToDelete
= set()
201 path
= line
[1:].strip()
203 system("p4 edit \"%s\"" % path
)
204 editedFiles
.add(path
)
205 elif modifier
== "A":
207 if path
in filesToDelete
:
208 filesToDelete
.remove(path
)
209 elif modifier
== "D":
210 filesToDelete
.add(path
)
211 if path
in filesToAdd
:
212 filesToAdd
.remove(path
)
214 die("unknown modifier %s for %s" % (modifier
, path
))
216 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
217 patchcmd
= diffcmd
+ " | git apply "
218 tryPatchCmd
= diffcmd
+ "--check -"
219 applyPatchCmd
= diffcmd
+ "--check --apply -"
220 print mypopen(diffcmd
).read()
222 if os
.system(tryPatchCmd
) != 0:
223 print "Unfortunately applying the change failed!"
224 print "What do you want to do?"
226 while response
!= "s" and response
!= "a" and response
!= "w":
227 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) ")
229 print "Skipping! Good luck with the next patches..."
231 elif response
== "a":
232 os
.system(applyPatchCmd
)
233 if len(filesToAdd
) > 0:
234 print "You may also want to call p4 add on the following files:"
235 print " ".join(filesToAdd
)
236 if len(filesToDelete
):
237 print "The following files should be scheduled for deletion with p4 delete:"
238 print " ".join(filesToDelete
)
239 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
240 elif response
== "w":
241 system(diffcmd
+ " > patch.txt")
242 print "Patch saved to patch.txt in %s !" % self
.clientPath
243 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
245 system(applyPatchCmd
)
248 system("p4 add %s" % f
)
249 for f
in filesToDelete
:
250 system("p4 revert %s" % f
)
251 system("p4 delete %s" % f
)
253 logMessage
= extractLogMessageFromGitCommit(id)
254 logMessage
= logMessage
.replace("\n", "\n\t")
255 logMessage
= logMessage
[:-1]
257 template
= mypopen("p4 change -o").read()
260 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
261 diff
= mypopen("p4 diff -du ...").read()
263 for newFile
in filesToAdd
:
264 diff
+= "==== new file ====\n"
265 diff
+= "--- /dev/null\n"
266 diff
+= "+++ %s\n" % newFile
267 f
= open(newFile
, "r")
268 for line
in f
.readlines():
272 separatorLine
= "######## everything below this line is just the diff #######"
273 if platform
.system() == "Windows":
274 separatorLine
+= "\r"
275 separatorLine
+= "\n"
278 firstIteration
= True
279 while response
== "e":
280 if not firstIteration
:
281 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
282 firstIteration
= False
284 [handle
, fileName
] = tempfile
.mkstemp()
285 tmpFile
= os
.fdopen(handle
, "w+")
286 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
289 if platform
.system() == "Windows":
290 defaultEditor
= "notepad"
291 editor
= os
.environ
.get("EDITOR", defaultEditor
);
292 system(editor
+ " " + fileName
)
293 tmpFile
= open(fileName
, "rb")
294 message
= tmpFile
.read()
297 submitTemplate
= message
[:message
.index(separatorLine
)]
299 if response
== "y" or response
== "yes":
302 raw_input("Press return to continue...")
304 pipe
= os
.popen("p4 submit -i", "wb")
305 pipe
.write(submitTemplate
)
307 elif response
== "s":
308 for f
in editedFiles
:
309 system("p4 revert \"%s\"" % f
);
311 system("p4 revert \"%s\"" % f
);
313 for f
in filesToDelete
:
314 system("p4 delete \"%s\"" % f
);
317 print "Not submitting!"
318 self
.interactive
= False
320 fileName
= "submit.txt"
321 file = open(fileName
, "w+")
322 file.write(self
.prepareLogMessage(template
, logMessage
))
324 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
328 # make gitdir absolute so we can cd out into the perforce checkout
329 gitdir
= os
.path
.abspath(gitdir
)
330 os
.environ
["GIT_DIR"] = gitdir
333 self
.master
= currentGitBranch()
334 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
335 die("Detecting current git branch failed!")
337 self
.master
= args
[0]
342 if gitBranchExists("p4"):
343 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
344 if len(depotPath
) == 0 and gitBranchExists("origin"):
345 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
347 if len(depotPath
) == 0:
348 print "Internal error: cannot locate perforce depot path from existing branches"
351 self
.clientPath
= p4Where(depotPath
)
353 if len(self
.clientPath
) == 0:
354 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
357 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
358 oldWorkingDirectory
= os
.getcwd()
359 os
.chdir(self
.clientPath
)
360 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
361 if response
== "y" or response
== "yes":
362 system("p4 sync ...")
364 if len(self
.origin
) == 0:
365 if gitBranchExists("p4"):
368 self
.origin
= "origin"
371 self
.firstTime
= True
373 if len(self
.substFile
) > 0:
374 for line
in open(self
.substFile
, "r").readlines():
375 tokens
= line
[:-1].split("=")
376 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
379 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
380 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
385 commits
= self
.config
.get("commits", [])
387 while len(commits
) > 0:
388 self
.firstTime
= False
390 commits
= commits
[1:]
391 self
.config
["commits"] = commits
393 if not self
.interactive
:
398 if len(commits
) == 0:
400 print "No changes found to apply between %s and current HEAD" % self
.origin
402 print "All changes applied!"
403 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
404 if response
== "y" or response
== "yes":
405 os
.chdir(oldWorkingDirectory
)
408 os
.remove(self
.configFile
)
412 class P4Sync(Command
):
414 Command
.__init
__(self
)
416 optparse
.make_option("--branch", dest
="branch"),
417 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
418 optparse
.make_option("--changesfile", dest
="changesFile"),
419 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
420 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
421 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
422 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
424 self
.description
= """Imports from Perforce into a git repository.\n
426 //depot/my/project/ -- to import the current head
427 //depot/my/project/@all -- to import everything
428 //depot/my/project/@1,6 -- to import only from revision 1 to 6
430 (a ... is not needed in the path p4 specification, it's added implicitly)"""
432 self
.usage
+= " //depot/path[@revRange]"
435 self
.createdBranches
= Set()
436 self
.committedChanges
= Set()
438 self
.detectBranches
= False
439 self
.detectLabels
= False
440 self
.changesFile
= ""
441 self
.syncWithOrigin
= False
444 def p4File(self
, depotPath
):
445 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
447 def extractFilesFromCommit(self
, commit
):
450 while commit
.has_key("depotFile%s" % fnum
):
451 path
= commit
["depotFile%s" % fnum
]
452 if not path
.startswith(self
.depotPath
):
453 # if not self.silent:
454 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
460 file["rev"] = commit
["rev%s" % fnum
]
461 file["action"] = commit
["action%s" % fnum
]
462 file["type"] = commit
["type%s" % fnum
]
467 def splitFilesIntoBranches(self
, commit
):
471 while commit
.has_key("depotFile%s" % fnum
):
472 path
= commit
["depotFile%s" % fnum
]
473 if not path
.startswith(self
.depotPath
):
474 # if not self.silent:
475 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
481 file["rev"] = commit
["rev%s" % fnum
]
482 file["action"] = commit
["action%s" % fnum
]
483 file["type"] = commit
["type%s" % fnum
]
486 relPath
= path
[len(self
.depotPath
):]
488 for branch
in self
.knownBranches
.keys():
489 if relPath
.startswith(branch
):
490 if branch
not in branches
:
491 branches
[branch
] = []
492 branches
[branch
].append(file)
496 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
497 epoch
= details
["time"]
498 author
= details
["user"]
501 print "commit into %s" % branch
503 self
.gitStream
.write("commit %s\n" % branch
)
504 # gitStream.write("mark :%s\n" % details["change"])
505 self
.committedChanges
.add(int(details
["change"]))
507 if author
not in self
.users
:
508 self
.getUserMapFromPerforceServer()
509 if author
in self
.users
:
510 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
512 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
514 self
.gitStream
.write("committer %s\n" % committer
)
516 self
.gitStream
.write("data <<EOT\n")
517 self
.gitStream
.write(details
["desc"])
518 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
519 self
.gitStream
.write("EOT\n\n")
523 print "parent %s" % parent
524 self
.gitStream
.write("from %s\n" % parent
)
528 if not path
.startswith(branchPrefix
):
530 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
533 depotPath
= path
+ "#" + rev
534 relPath
= path
[len(branchPrefix
):]
535 action
= file["action"]
537 if file["type"] == "apple":
538 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
541 if action
== "delete":
542 self
.gitStream
.write("D %s\n" % relPath
)
545 if file["type"].startswith("x"):
548 data
= self
.p4File(depotPath
)
550 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
551 self
.gitStream
.write("data %s\n" % len(data
))
552 self
.gitStream
.write(data
)
553 self
.gitStream
.write("\n")
555 self
.gitStream
.write("\n")
557 change
= int(details
["change"])
559 if self
.labels
.has_key(change
):
560 label
= self
.labels
[change
]
561 labelDetails
= label
[0]
562 labelRevisions
= label
[1]
564 print "Change %s is labelled %s" % (change
, labelDetails
)
566 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
568 if len(files
) == len(labelRevisions
):
572 if info
["action"] == "delete":
574 cleanedFiles
[info
["depotFile"]] = info
["rev"]
576 if cleanedFiles
== labelRevisions
:
577 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
578 self
.gitStream
.write("from %s\n" % branch
)
580 owner
= labelDetails
["Owner"]
582 if author
in self
.users
:
583 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
585 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
586 self
.gitStream
.write("tagger %s\n" % tagger
)
587 self
.gitStream
.write("data <<EOT\n")
588 self
.gitStream
.write(labelDetails
["Description"])
589 self
.gitStream
.write("EOT\n\n")
593 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
597 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
599 def getUserMapFromPerforceServer(self
):
602 for output
in p4CmdList("users"):
603 if not output
.has_key("User"):
605 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
607 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
608 for user
in self
.users
.keys():
609 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
612 def loadUserMapFromCache(self
):
615 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
616 lines
= cache
.readlines()
619 entry
= line
[:-1].split("\t")
620 self
.users
[entry
[0]] = entry
[1]
622 self
.getUserMapFromPerforceServer()
627 l
= p4CmdList("labels %s..." % self
.depotPath
)
628 if len(l
) > 0 and not self
.silent
:
629 print "Finding files belonging to labels in %s" % self
.depotPath
632 label
= output
["label"]
636 print "Querying files for label %s" % label
637 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
638 revisions
[file["depotFile"]] = file["rev"]
639 change
= int(file["change"])
640 if change
> newestChange
:
641 newestChange
= change
643 self
.labels
[newestChange
] = [output
, revisions
]
646 print "Label changes: %s" % self
.labels
.keys()
648 def getBranchMapping(self
):
649 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
651 for info
in p4CmdList("branches"):
652 details
= p4Cmd("branch -o %s" % info
["branch"])
654 while details
.has_key("View%s" % viewIdx
):
655 paths
= details
["View%s" % viewIdx
].split(" ")
656 viewIdx
= viewIdx
+ 1
657 # require standard //depot/foo/... //depot/bar/... mapping
658 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
661 destination
= paths
[1]
662 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
663 source
= source
[len(self
.depotPath
):-4]
664 destination
= destination
[len(self
.depotPath
):-4]
665 if destination
not in self
.knownBranches
:
666 self
.knownBranches
[destination
] = source
667 if source
not in self
.knownBranches
:
668 self
.knownBranches
[source
] = source
670 def listExistingP4GitBranches(self
):
671 self
.p4BranchesInGit
= []
673 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
674 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
676 self
.p4BranchesInGit
.append(branch
)
677 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
681 self
.changeRange
= ""
682 self
.initialParent
= ""
683 self
.previousDepotPath
= ""
684 # map from branch depot path to parent branch
685 self
.knownBranches
= {}
686 self
.initialParents
= {}
688 self
.listExistingP4GitBranches()
690 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
691 ### needs to be ported to multi branch import
693 print "Syncing with origin first as requested by calling git fetch origin"
694 system("git fetch origin")
695 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
696 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
697 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
698 if originPreviousDepotPath
== p4PreviousDepotPath
:
699 originP4Change
= int(originP4Change
)
700 p4Change
= int(p4Change
)
701 if originP4Change
> p4Change
:
702 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
703 system("git update-ref refs/remotes/p4/master origin");
705 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
707 if len(self
.branch
) == 0:
708 self
.branch
= "refs/remotes/p4/master"
709 if gitBranchExists("refs/heads/p4"):
710 system("git update-ref %s refs/heads/p4" % self
.branch
)
711 system("git branch -D p4");
712 if not gitBranchExists("refs/remotes/p4/HEAD"):
713 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
716 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
717 ### needs to be ported to multi branch import
719 print "Creating %s branch in git repository based on origin" % self
.branch
721 if not branch
.startswith("refs"):
722 branch
= "refs/heads/" + branch
723 system("git update-ref %s origin" % branch
)
726 print "branches: %s" % self
.p4BranchesInGit
729 for branch
in self
.p4BranchesInGit
:
730 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
733 print "path %s change %s" % (depotPath
, change
)
735 if len(depotPath
) > 0 and len(change
) > 0:
736 change
= int(change
) + 1
737 p4Change
= max(p4Change
, change
)
739 if len(self
.previousDepotPath
) == 0:
740 self
.previousDepotPath
= depotPath
743 l
= min(len(self
.previousDepotPath
), len(depotPath
))
744 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
746 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
749 self
.depotPath
= self
.previousDepotPath
750 self
.changeRange
= "@%s,#head" % p4Change
751 self
.initialParent
= parseRevision(self
.branch
)
753 print "Performing incremental import into %s git branch" % self
.branch
755 if not self
.branch
.startswith("refs/"):
756 self
.branch
= "refs/heads/" + self
.branch
758 if len(self
.depotPath
) != 0:
759 self
.depotPath
= self
.depotPath
[:-1]
761 if len(args
) == 0 and len(self
.depotPath
) != 0:
763 print "Depot path: %s" % self
.depotPath
767 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
768 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
770 self
.depotPath
= args
[0]
775 if self
.depotPath
.find("@") != -1:
776 atIdx
= self
.depotPath
.index("@")
777 self
.changeRange
= self
.depotPath
[atIdx
:]
778 if self
.changeRange
== "@all":
779 self
.changeRange
= ""
780 elif self
.changeRange
.find(",") == -1:
781 self
.revision
= self
.changeRange
782 self
.changeRange
= ""
783 self
.depotPath
= self
.depotPath
[0:atIdx
]
784 elif self
.depotPath
.find("#") != -1:
785 hashIdx
= self
.depotPath
.index("#")
786 self
.revision
= self
.depotPath
[hashIdx
:]
787 self
.depotPath
= self
.depotPath
[0:hashIdx
]
788 elif len(self
.previousDepotPath
) == 0:
789 self
.revision
= "#head"
791 if self
.depotPath
.endswith("..."):
792 self
.depotPath
= self
.depotPath
[:-3]
794 if not self
.depotPath
.endswith("/"):
795 self
.depotPath
+= "/"
797 self
.loadUserMapFromCache()
799 if self
.detectLabels
:
802 if self
.detectBranches
:
803 self
.getBranchMapping();
805 print "p4-git branches: %s" % self
.p4BranchesInGit
806 print "initial parents: %s" % self
.initialParents
807 for b
in self
.p4BranchesInGit
:
809 b
= b
[len(self
.projectName
):]
810 self
.createdBranches
.add(b
)
812 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
814 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
815 self
.gitOutput
= importProcess
.stdout
816 self
.gitStream
= importProcess
.stdin
817 self
.gitError
= importProcess
.stderr
819 if len(self
.revision
) > 0:
820 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
822 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
823 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
824 details
["change"] = self
.revision
828 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
829 change
= int(info
["change"])
830 if change
> newestRevision
:
831 newestRevision
= change
833 if info
["action"] == "delete":
834 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
835 #fileCnt = fileCnt + 1
838 for prop
in [ "depotFile", "rev", "action", "type" ]:
839 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
841 fileCnt
= fileCnt
+ 1
843 details
["change"] = newestRevision
846 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
848 print "IO error with git fast-import. Is your git version recent enough?"
849 print self
.gitError
.read()
854 if len(self
.changesFile
) > 0:
855 output
= open(self
.changesFile
).readlines()
858 changeSet
.add(int(line
))
860 for change
in changeSet
:
861 changes
.append(change
)
866 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
867 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
870 changeNum
= line
.split(" ")[1]
871 changes
.append(changeNum
)
875 if len(changes
) == 0:
877 print "no changes to import!"
881 for change
in changes
:
882 description
= p4Cmd("describe %s" % change
)
885 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
890 if self
.detectBranches
:
891 branches
= self
.splitFilesIntoBranches(description
)
892 for branch
in branches
.keys():
893 branchPrefix
= self
.depotPath
+ branch
+ "/"
897 filesForCommit
= branches
[branch
]
900 print "branch is %s" % branch
902 if branch
not in self
.createdBranches
:
903 self
.createdBranches
.add(branch
)
904 parent
= self
.knownBranches
[branch
]
908 print "parent determined through known branches: %s" % parent
910 # main branch? use master
914 branch
= self
.projectName
+ branch
918 elif len(parent
) > 0:
919 parent
= self
.projectName
+ parent
921 branch
= "refs/remotes/p4/" + branch
923 parent
= "refs/remotes/p4/" + parent
926 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
928 if len(parent
) == 0 and branch
in self
.initialParents
:
929 parent
= self
.initialParents
[branch
]
930 del self
.initialParents
[branch
]
932 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
934 files
= self
.extractFilesFromCommit(description
)
935 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
936 self
.initialParent
= ""
938 print self
.gitError
.read()
945 self
.gitStream
.close()
946 if importProcess
.wait() != 0:
947 die("fast-import failed: %s" % self
.gitError
.read())
948 self
.gitOutput
.close()
949 self
.gitError
.close()
953 class P4Rebase(Command
):
955 Command
.__init
__(self
)
956 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
957 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
958 self
.syncWithOrigin
= False
962 sync
.syncWithOrigin
= self
.syncWithOrigin
964 print "Rebasing the current branch"
965 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
966 system("git rebase p4")
967 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
970 class P4Clone(P4Sync
):
972 P4Sync
.__init
__(self
)
973 self
.description
= "Creates a new git repository and imports from Perforce into it"
974 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
975 self
.needsGit
= False
989 if not depotPath
.startswith("//"):
994 atPos
= dir.rfind("@")
997 hashPos
= dir.rfind("#")
1001 if dir.endswith("..."):
1004 if dir.endswith("/"):
1007 slashPos
= dir.rfind("/")
1009 dir = dir[slashPos
+ 1:]
1011 print "Importing from %s into %s" % (depotPath
, dir)
1015 gitdir
= os
.getcwd() + "/.git"
1016 if not P4Sync
.run(self
, [depotPath
]):
1018 if self
.branch
!= "master":
1019 if gitBranchExists("refs/remotes/p4/master"):
1020 system("git branch master refs/remotes/p4/master")
1021 system("git checkout -f")
1023 print "Could not detect main branch. No checkout/master branch created."
1026 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1028 optparse
.IndentedHelpFormatter
.__init
__(self
)
1030 def format_description(self
, description
):
1032 return description
+ "\n"
1036 def printUsage(commands
):
1037 print "usage: %s <command> [options]" % sys
.argv
[0]
1039 print "valid commands: %s" % ", ".join(commands
)
1041 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1045 "debug" : P4Debug(),
1046 "submit" : P4Submit(),
1048 "rebase" : P4Rebase(),
1052 if len(sys
.argv
[1:]) == 0:
1053 printUsage(commands
.keys())
1057 cmdName
= sys
.argv
[1]
1059 cmd
= commands
[cmdName
]
1061 print "unknown command %s" % cmdName
1063 printUsage(commands
.keys())
1066 options
= cmd
.options
1071 if len(options
) > 0:
1072 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1074 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1076 description
= cmd
.description
,
1077 formatter
= HelpFormatter())
1079 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1083 if len(gitdir
) == 0:
1085 if not isValidGitDir(gitdir
):
1086 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1087 if os
.path
.exists(gitdir
):
1088 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1092 if not isValidGitDir(gitdir
):
1093 if isValidGitDir(gitdir
+ "/.git"):
1096 die("fatal: cannot locate git repository at %s" % gitdir
)
1098 os
.environ
["GIT_DIR"] = gitdir
1100 if not cmd
.run(args
):