@matheusbsbs / matheus-bagliano / commits / 6326aa5866
Fork 0

Extract multiple paths concurrently.

This enables importing just the interesting bits of large repositories. Signed-off-by: Han-Wen Nienhuys <hanwen@google.com>

Han-Wen Nienhuys committed May 23, 2007 at 18:49 UTC 6326aa58662932212678a25c6f482a8da4195ac9
1 file changed +153 -109
contrib/fast-import/git-p4
+153 -109
@@ -133,24 +133,26 @@ def extractLogMessageFromGitCommit(commit):
133 logMessage += log
134 return logMessage
135
136 -def extractDepotPathAndChangeFromGitLog(log):
136 +def extractDepotPathsAndChangeFromGitLog(log):
137 values = {}
138 for line in log.split("\n"):
139 line = line.strip()
140 - if line.startswith("[git-p4:") and line.endswith("]"):
141 - line = line[8:-1].strip()
142 - for assignment in line.split(":"):
143 - variable = assignment.strip()
144 - value = ""
145 - equalPos = assignment.find("=")
146 - if equalPos != -1:
147 - variable = assignment[:equalPos].strip()
148 - value = assignment[equalPos + 1:].strip()
149 - if value.startswith("\"") and value.endswith("\""):
150 - value = value[1:-1]
151 - values[variable] = value
152 -
153 - return values.get("depot-path"), values.get("change")
140 + m = re.search (r"^ *\[git-p4: (.*)\]$", line)
141 + if not m:
142 + continue
143 +
144 + assignments = m.group(1).split (':')
145 + for a in assignments:
146 + vals = a.split ('=')
147 + key = vals[0].strip()
148 + val = ('='.join (vals[1:])).strip()
149 + if val.endswith ('\"') and val.startswith('"'):
150 + val = val[1:-1]
151 +
152 + values[key] = val
153 +
154 + paths = values.get("depot-path").split(',')
155 + return paths, values.get("change")
156
157 def gitBranchExists(branch):
158 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
@@ -209,10 +211,11 @@ class P4RollBack(Command):
211 line = line.strip()
212 ref = refPrefix + line
213 log = extractLogMessageFromGitCommit(ref)
212 - depotPath, change = extractDepotPathAndChangeFromGitLog(log)
214 + depotPaths, change = extractDepotPathsAndChangeFromGitLog(log)
215 changed = False
216
215 - if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
217 + if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
218 + for p in depotPaths]))) == 0:
219 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
220 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
221 continue
@@ -223,7 +226,7 @@ class P4RollBack(Command):
226 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
227 system("git update-ref %s \"%s^\"" % (ref, ref))
228 log = extractLogMessageFromGitCommit(ref)
226 - depotPath, change = extractDepotPathAndChangeFromGitLog(log)
229 + depotPaths, change = extractDepotPathsAndChangeFromGitLog(log)
230
231 if changed:
232 print "%s rewound to %s" % (ref, change)
@@ -472,9 +475,9 @@ class P4Submit(Command):
475
476 depotPath = ""
477 if gitBranchExists("p4"):
475 - [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
478 + [depotPaths, dummy] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
479 if len(depotPath) == 0 and gitBranchExists("origin"):
477 - [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
480 + [depotPaths, dummy] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
481
482 if len(depotPath) == 0:
483 print "Internal error: cannot locate perforce depot path from existing branches"
@@ -568,7 +571,7 @@ class P4Sync(Command):
571 optparse.make_option("--verbose", dest="verbose", action="store_true"),
572 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
573 optparse.make_option("--max-changes", dest="maxChanges"),
571 - optparse.make_option("--keep-path", dest="keepRepoPath")
574 + optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true')
575 ]
576 self.description = """Imports from Perforce into a git repository.\n
577 example:
@@ -591,8 +594,8 @@ class P4Sync(Command):
594 self.importIntoRemotes = True
595 self.maxChanges = ""
596 self.isWindows = (platform.system() == "Windows")
594 - self.depotPath = None
597 self.keepRepoPath = False
598 + self.depotPaths = None
599
600 if gitConfig("git-p4.syncFromOrigin") == "false":
601 self.syncWithOrigin = False
@@ -605,9 +608,10 @@ class P4Sync(Command):
608 fnum = 0
609 while commit.has_key("depotFile%s" % fnum):
610 path = commit["depotFile%s" % fnum]
608 - if not path.startswith(self.depotPath):
609 - # if not self.silent:
610 - # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
611 +
612 + found = [p for p in self.depotPaths
613 + if path.startswith (p)]
614 + if not found:
615 fnum = fnum + 1
616 continue
617
@@ -620,20 +624,24 @@ class P4Sync(Command):
624 fnum = fnum + 1
625 return files
626
623 - def stripRepoPath(self, path, prefix):
627 + def stripRepoPath(self, path, prefixes):
628 if self.keepRepoPath:
625 - prefix = re.sub("^(//[^/]+/).*", r'\1', prefix)
629 + prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
630 +
631 + for p in prefixes:
632 + if path.startswith(p):
633 + path = path[len(p):]
634
627 - return path[len(prefix):]
635 + return path
636
637 def splitFilesIntoBranches(self, commit):
638 branches = {}
639 fnum = 0
640 while commit.has_key("depotFile%s" % fnum):
641 path = commit["depotFile%s" % fnum]
634 - if not path.startswith(self.depotPath):
635 - # if not self.silent:
636 - # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
642 + found = [p for p in self.depotPaths
643 + if path.startswith (p)]
644 + if not found:
645 fnum = fnum + 1
646 continue
647
@@ -644,7 +652,7 @@ class P4Sync(Command):
652 file["type"] = commit["type%s" % fnum]
653 fnum = fnum + 1
654
647 - relPath = self.stripRepoPath(path, self.depotPath)
655 + relPath = self.stripRepoPath(path, self.depotPaths)
656
657 for branch in self.knownBranches.keys():
658
@@ -656,7 +664,7 @@ class P4Sync(Command):
664
665 return branches
666
659 - def commit(self, details, files, branch, branchPrefix, parent = ""):
667 + def commit(self, details, files, branch, branchPrefixes, parent = ""):
668 epoch = details["time"]
669 author = details["user"]
670
@@ -678,7 +686,8 @@ class P4Sync(Command):
686
687 self.gitStream.write("data <<EOT\n")
688 self.gitStream.write(details["desc"])
681 - self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
689 + self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n"
690 + % (','.join (branchPrefixes), details["change"]))
691 self.gitStream.write("EOT\n\n")
692
693 if len(parent) > 0:
@@ -688,12 +697,13 @@ class P4Sync(Command):
697
698 for file in files:
699 path = file["path"]
691 - if not path.startswith(branchPrefix):
692 - # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
700 +
701 +
702 + if not [p for p in branchPrefixes if path.startswith(p)]:
703 continue
704 rev = file["rev"]
705 depotPath = path + "#" + rev
696 - relPath = self.stripRepoPath(path, branchPrefix)
706 + relPath = self.stripRepoPath(path, branchPrefixes)
707 action = file["action"]
708
709 if file["type"] == "apple":
@@ -728,7 +738,8 @@ class P4Sync(Command):
738 if self.verbose:
739 print "Change %s is labelled %s" % (change, labelDetails)
740
731 - files = p4CmdList("files %s...@%s" % (branchPrefix, change))
741 + files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
742 + for p in branchPrefixes]))
743
744 if len(files) == len(labelRevisions):
745
@@ -795,9 +806,9 @@ class P4Sync(Command):
806 def getLabels(self):
807 self.labels = {}
808
798 - l = p4CmdList("labels %s..." % self.depotPath)
809 + l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
810 if len(l) > 0 and not self.silent:
800 - print "Finding files belonging to labels in %s" % self.depotPath
811 + print "Finding files belonging to labels in %s" % `self.depotPath`
812
813 for output in l:
814 label = output["label"]
@@ -805,7 +816,9 @@ class P4Sync(Command):
816 newestChange = 0
817 if self.verbose:
818 print "Querying files for label %s" % label
808 - for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
819 + for file in p4CmdList("files "
820 + + ' '.join (["%s...@%s" % (p, label)
821 + for p in self.depotPaths])):
822 revisions[file["depotFile"]] = file["rev"]
823 change = int(file["change"])
824 if change > newestChange:
@@ -817,6 +830,8 @@ class P4Sync(Command):
830 print "Label changes: %s" % self.labels.keys()
831
832 def getBranchMapping(self):
833 +
834 + ## FIXME - what's a P4 projectName ?
835 self.projectName = self.depotPath[self.depotPath.strip().rfind("/") + 1:]
836
837 for info in p4CmdList("branches"):
@@ -872,8 +887,8 @@ class P4Sync(Command):
887 remoteHead = self.refPrefix + headName
888 originHead = "origin/" + headName
889
875 - [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
876 - if len(originPreviousDepotPath) == 0 or len(originP4Change) == 0:
890 + [originPreviousDepotPaths, originP4Change] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
891 + if len(originPreviousDepotPaths) == 0 or len(originP4Change) == 0:
892 continue
893
894 update = False
@@ -882,25 +897,26 @@ class P4Sync(Command):
897 print "creating %s" % remoteHead
898 update = True
899 else:
885 - [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
900 + [p4PreviousDepotPaths, p4Change] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
901 if len(p4Change) > 0:
887 - if originPreviousDepotPath == p4PreviousDepotPath:
902 + if originPreviousDepotPaths == p4PreviousDepotPaths:
903 originP4Change = int(originP4Change)
904 p4Change = int(p4Change)
905 if originP4Change > p4Change:
906 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
907 update = True
908 else:
894 - print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPath, remoteHead, p4PreviousDepotPath)
909 + print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPaths, remoteHead, p4PreviousDepotPaths)
910
911 if update:
912 system("git update-ref %s %s" % (remoteHead, originHead))
913
914 +
915 def run(self, args):
900 - self.depotPath = ""
916 + self.depotPaths = []
917 self.changeRange = ""
918 self.initialParent = ""
903 - self.previousDepotPath = ""
919 + self.previousDepotPaths = []
920
921 # map from branch depot path to parent branch
922 self.knownBranches = {}
@@ -926,7 +942,7 @@ class P4Sync(Command):
942 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
943 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
944
929 - if len(args) == 0:
945 + if args == []:
946 if self.hasOrigin:
947 self.createOrUpdateBranchesFromOrigin()
948 self.listExistingP4GitBranches()
@@ -942,26 +958,31 @@ class P4Sync(Command):
958 p4Change = 0
959 for branch in self.p4BranchesInGit:
960 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
945 - (depotPath, change) = extractDepotPathAndChangeFromGitLog(logMsg)
961 + (depotPaths, change) = extractDepotPathsAndChangeFromGitLog(logMsg)
962
963 if self.verbose:
948 - print "path %s change %s" % (depotPath, change)
964 + print "path %s change %s" % (','.join(depotPaths), change)
965
950 - if len(depotPath) > 0 and len(change) > 0:
966 + if len(depotPaths) > 0 and len(change) > 0:
967 change = int(change) + 1
968 p4Change = max(p4Change, change)
969
954 - if len(self.previousDepotPath) == 0:
955 - self.previousDepotPath = depotPath
970 + if len(self.previousDepotPaths) == 0:
971 + self.previousDepotPaths = depotPaths
972 else:
957 - i = 0
958 - l = min(len(self.previousDepotPath), len(depotPath))
959 - while i < l and self.previousDepotPath[i] == depotPath[i]:
960 - i = i + 1
961 - self.previousDepotPath = self.previousDepotPath[:i]
973 + ## FIXME
974 + paths = []
975 + for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
976 + for i in range(0, max(len(cur), len(prev))):
977 + if cur[i] <> prev[i]:
978 + break
979 +
980 + paths.append (cur[:i])
981 +
982 + self.previousDepotPaths = paths
983
984 if p4Change > 0:
964 - self.depotPath = self.previousDepotPath
985 + self.depotPaths = self.previousDepotPaths
986 self.changeRange = "@%s,#head" % p4Change
987 self.initialParent = parseRevision(self.branch)
988 if not self.silent and not self.detectBranches:
@@ -970,43 +991,47 @@ class P4Sync(Command):
991 if not self.branch.startswith("refs/"):
992 self.branch = "refs/heads/" + self.branch
993
973 - if len(self.depotPath) != 0:
974 - self.depotPath = self.depotPath.strip()
975 -
976 - if len(args) == 0 and len(self.depotPath) != 0:
994 + if len(args) == 0 and self.depotPaths:
995 if not self.silent:
978 - print "Depot path: %s" % self.depotPath
979 - elif len(args) != 1:
980 - return False
996 + print "Depot paths: %s" % ' '.join(self.depotPaths)
997 else:
982 - if len(self.depotPath) != 0 and self.depotPath != args[0]:
998 + if self.depotPaths and self.depotPaths != args:
999 print ("previous import used depot path %s and now %s was specified. "
984 - "This doesn't work!" % (self.depotPath, args[0]))
1000 + "This doesn't work!" % (' '.join (self.depotPaths),
1001 + ' '.join (args)))
1002 sys.exit(1)
986 - self.depotPath = args[0]
1003 +
1004 + self.depotPaths = args
1005
1006 self.revision = ""
1007 self.users = {}
1008
991 - if self.depotPath.find("@") != -1:
992 - atIdx = self.depotPath.index("@")
993 - self.changeRange = self.depotPath[atIdx:]
994 - if self.changeRange == "@all":
995 - self.changeRange = ""
996 - elif self.changeRange.find(",") == -1:
997 - self.revision = self.changeRange
998 - self.changeRange = ""
999 - self.depotPath = self.depotPath[0:atIdx]
1000 - elif self.depotPath.find("#") != -1:
1001 - hashIdx = self.depotPath.index("#")
1002 - self.revision = self.depotPath[hashIdx:]
1003 - self.depotPath = self.depotPath[0:hashIdx]
1004 - elif len(self.previousDepotPath) == 0:
1005 - self.revision = "#head"
1006 -
1007 - self.depotPath = re.sub ("\.\.\.$", "", self.depotPath)
1008 - if not self.depotPath.endswith("/"):
1009 - self.depotPath += "/"
1009 + newPaths = []
1010 + for p in self.depotPaths:
1011 + if p.find("@") != -1:
1012 + atIdx = p.index("@")
1013 + self.changeRange = p[atIdx:]
1014 + if self.changeRange == "@all":
1015 + self.changeRange = ""
1016 + elif self.changeRange.find(",") == -1:
1017 + self.revision = self.changeRange
1018 + self.changeRange = ""
1019 + p = p[0:atIdx]
1020 + elif p.find("#") != -1:
1021 + hashIdx = p.index("#")
1022 + self.revision = p[hashIdx:]
1023 + p = p[0:hashIdx]
1024 + elif self.previousDepotPaths == []:
1025 + self.revision = "#head"
1026 +
1027 + p = re.sub ("\.\.\.$", "", p)
1028 + if not p.endswith("/"):
1029 + p += "/"
1030 +
1031 + newPaths.append(p)
1032 +
1033 + self.depotPaths = newPaths
1034 +
1035
1036 self.loadUserMapFromCache()
1037 self.labels = {}
@@ -1020,28 +1045,34 @@ class P4Sync(Command):
1045 print "initial parents: %s" % self.initialParents
1046 for b in self.p4BranchesInGit:
1047 if b != "master":
1048 +
1049 + ## FIXME
1050 b = b[len(self.projectName):]
1051 self.createdBranches.add(b)
1052
1053 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1054
1055 importProcess = subprocess.Popen(["git", "fast-import"],
1029 - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
1056 + stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1057 + stderr=subprocess.PIPE);
1058 self.gitOutput = importProcess.stdout
1059 self.gitStream = importProcess.stdin
1060 self.gitError = importProcess.stderr
1061
1062 if len(self.revision) > 0:
1035 - print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
1063 + print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1064
1065 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1066 details["desc"] = ("Initial import of %s from the state at revision %s"
1039 - % (self.depotPath, self.revision))
1067 + % (' '.join(self.depotPaths), self.revision))
1068 details["change"] = self.revision
1069 newestRevision = 0
1070
1071 fileCnt = 0
1044 - for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
1072 + for info in p4CmdList("files "
1073 + + ' '.join(["%s...%s"
1074 + % (p, self.revision)
1075 + for p in self.depotPaths])):
1076 change = int(info["change"])
1077 if change > newestRevision:
1078 newestRevision = change
@@ -1059,7 +1090,7 @@ class P4Sync(Command):
1090 details["change"] = newestRevision
1091
1092 try:
1062 - self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
1093 + self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1094 except IOError:
1095 print "IO error with git fast-import. Is your git version recent enough?"
1096 print self.gitError.read()
@@ -1079,8 +1110,11 @@ class P4Sync(Command):
1110 changes.sort()
1111 else:
1112 if self.verbose:
1082 - print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
1083 - output = read_pipe_lines("p4 changes %s...%s" % (self.depotPath, self.changeRange))
1113 + print "Getting p4 changes for %s...%s" % (`self.depotPaths`,
1114 + self.changeRange)
1115 + assert self.depotPaths
1116 + output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1117 + for p in self.depotPaths]))
1118
1119 for line in output:
1120 changeNum = line.split(" ")[1]
@@ -1111,7 +1145,8 @@ class P4Sync(Command):
1145 if self.detectBranches:
1146 branches = self.splitFilesIntoBranches(description)
1147 for branch in branches.keys():
1114 - branchPrefix = self.depotPath + branch + "/"
1148 + ## HACK --hwn
1149 + branchPrefix = self.depotPaths[0] + branch + "/"
1150
1151 parent = ""
1152
@@ -1134,11 +1169,14 @@ class P4Sync(Command):
1169 if branch == "main":
1170 branch = "master"
1171 else:
1172 +
1173 + ## FIXME
1174 branch = self.projectName + branch
1175
1176 if parent == "main":
1177 parent = "master"
1178 elif len(parent) > 0:
1179 + ## FIXME
1180 parent = self.projectName + parent
1181
1182 branch = self.refPrefix + branch
@@ -1155,7 +1193,8 @@ class P4Sync(Command):
1193 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1194 else:
1195 files = self.extractFilesFromCommit(description)
1158 - self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1196 + self.commit(description, files, self.branch, self.depotPaths,
1197 + self.initialParent)
1198 self.initialParent = ""
1199 except IOError:
1200 print self.gitError.read()
@@ -1206,30 +1245,35 @@ class P4Clone(P4Sync):
1245
1246 if len(args) < 1:
1247 return False
1209 - depotPath = args[0]
1248 destination = ""
1211 - if len(args) == 2:
1249 + if self.keepRepoPath:
1250 + destination = args[-1]
1251 + args = args[:-1]
1252 + elif len(args) == 2:
1253 destination = args[1]
1254 elif len(args) > 2:
1255 return False
1256
1216 - if not depotPath.startswith("//"):
1217 - return False
1218 -
1219 - depotDir = re.sub("(@[^@]*)$", "", depotPath)
1220 - depotDir = re.sub("(#[^#]*)$", "", depotDir)
1221 - depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1222 - depotDir = re.sub(r"/$", "", depotDir)
1257 + depotPaths = args
1258 + for p in depotPaths:
1259 + if not p.startswith("//"):
1260 + return False
1261
1262 if not destination:
1263 + depotPath = args[0]
1264 + depotDir = re.sub("(@[^@]*)$", "", depotPath)
1265 + depotDir = re.sub("(#[^#]*)$", "", depotDir)
1266 + depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1267 + depotDir = re.sub(r"/$", "", depotDir)
1268 +
1269 destination = os.path.split(depotDir)[1]
1270
1227 - print "Importing from %s into %s" % (depotPath, destination)
1271 + print "Importing from %s into %s" % (`depotPaths`, destination)
1272 os.makedirs(destination)
1273 os.chdir(destination)
1274 system("git init")
1275 gitdir = os.getcwd() + "/.git"
1232 - if not P4Sync.run(self, [depotPath]):
1276 + if not P4Sync.run(self, depotPaths):
1277 return False
1278 if self.branch != "master":
1279 if gitBranchExists("refs/remotes/p4/master"):