]>
Commit | Line | Data |
---|---|---|
86949eef SH |
1 | #!/usr/bin/env python |
2 | # | |
3 | # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. | |
4 | # | |
5 | # Author: Simon Hausmann <hausmann@kde.org> | |
83dce55a SH |
6 | # Copyright: 2007 Simon Hausmann <hausmann@kde.org> |
7 | # 2007 Trolltech ASA | |
86949eef SH |
8 | # License: MIT <http://www.opensource.org/licenses/mit-license.php> |
9 | # | |
ca0affe7 SH |
10 | # TODO: Add an option to sync/rebase to fetch and rebase from origin first. |
11 | # | |
86949eef | 12 | |
08483580 | 13 | import optparse, sys, os, marshal, popen2, subprocess, shelve |
25df95cc | 14 | import tempfile, getopt, sha, os.path, time, platform |
b984733c | 15 | from sets import Set; |
4f5cf76a SH |
16 | |
17 | gitdir = os.environ.get("GIT_DIR", "") | |
86949eef | 18 | |
caace111 SH |
19 | def mypopen(command): |
20 | return os.popen(command, "rb"); | |
21 | ||
86949eef SH |
22 | def p4CmdList(cmd): |
23 | cmd = "p4 -G %s" % cmd | |
24 | pipe = os.popen(cmd, "rb") | |
25 | ||
26 | result = [] | |
27 | try: | |
28 | while True: | |
29 | entry = marshal.load(pipe) | |
30 | result.append(entry) | |
31 | except EOFError: | |
32 | pass | |
33 | pipe.close() | |
34 | ||
35 | return result | |
36 | ||
37 | def p4Cmd(cmd): | |
38 | list = p4CmdList(cmd) | |
39 | result = {} | |
40 | for entry in list: | |
41 | result.update(entry) | |
42 | return result; | |
43 | ||
cb2c9db5 SH |
44 | def p4Where(depotPath): |
45 | if not depotPath.endswith("/"): | |
46 | depotPath += "/" | |
47 | output = p4Cmd("where %s..." % depotPath) | |
48 | clientPath = "" | |
49 | if "path" in output: | |
50 | clientPath = output.get("path") | |
51 | elif "data" in output: | |
52 | data = output.get("data") | |
53 | lastSpace = data.rfind(" ") | |
54 | clientPath = data[lastSpace + 1:] | |
55 | ||
56 | if clientPath.endswith("..."): | |
57 | clientPath = clientPath[:-3] | |
58 | return clientPath | |
59 | ||
86949eef SH |
60 | def die(msg): |
61 | sys.stderr.write(msg + "\n") | |
62 | sys.exit(1) | |
63 | ||
64 | def currentGitBranch(): | |
caace111 | 65 | return mypopen("git name-rev HEAD").read().split(" ")[1][:-1] |
86949eef | 66 | |
4f5cf76a SH |
67 | def isValidGitDir(path): |
68 | if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"): | |
69 | return True; | |
70 | return False | |
71 | ||
72 | def system(cmd): | |
73 | if os.system(cmd) != 0: | |
74 | die("command failed: %s" % cmd) | |
75 | ||
6ae8de88 SH |
76 | def extractLogMessageFromGitCommit(commit): |
77 | logMessage = "" | |
78 | foundTitle = False | |
caace111 | 79 | for log in mypopen("git cat-file commit %s" % commit).readlines(): |
6ae8de88 SH |
80 | if not foundTitle: |
81 | if len(log) == 1: | |
1c094184 | 82 | foundTitle = True |
6ae8de88 SH |
83 | continue |
84 | ||
85 | logMessage += log | |
86 | return logMessage | |
87 | ||
88 | def extractDepotPathAndChangeFromGitLog(log): | |
89 | values = {} | |
90 | for line in log.split("\n"): | |
91 | line = line.strip() | |
92 | if line.startswith("[git-p4:") and line.endswith("]"): | |
93 | line = line[8:-1].strip() | |
94 | for assignment in line.split(":"): | |
95 | variable = assignment.strip() | |
96 | value = "" | |
97 | equalPos = assignment.find("=") | |
98 | if equalPos != -1: | |
99 | variable = assignment[:equalPos].strip() | |
100 | value = assignment[equalPos + 1:].strip() | |
101 | if value.startswith("\"") and value.endswith("\""): | |
102 | value = value[1:-1] | |
103 | values[variable] = value | |
104 | ||
105 | return values.get("depot-path"), values.get("change") | |
106 | ||
8136a639 | 107 | def gitBranchExists(branch): |
caace111 SH |
108 | proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE); |
109 | return proc.wait() == 0; | |
8136a639 | 110 | |
b984733c SH |
111 | class Command: |
112 | def __init__(self): | |
113 | self.usage = "usage: %prog [options]" | |
8910ac0e | 114 | self.needsGit = True |
b984733c SH |
115 | |
116 | class P4Debug(Command): | |
86949eef | 117 | def __init__(self): |
6ae8de88 | 118 | Command.__init__(self) |
86949eef SH |
119 | self.options = [ |
120 | ] | |
c8c39116 | 121 | self.description = "A tool to debug the output of p4 -G." |
8910ac0e | 122 | self.needsGit = False |
86949eef SH |
123 | |
124 | def run(self, args): | |
125 | for output in p4CmdList(" ".join(args)): | |
126 | print output | |
b984733c | 127 | return True |
86949eef | 128 | |
b984733c | 129 | class P4CleanTags(Command): |
86949eef | 130 | def __init__(self): |
b984733c | 131 | Command.__init__(self) |
86949eef SH |
132 | self.options = [ |
133 | # optparse.make_option("--branch", dest="branch", default="refs/heads/master") | |
134 | ] | |
c8c39116 | 135 | self.description = "A tool to remove stale unused tags from incremental perforce imports." |
86949eef SH |
136 | def run(self, args): |
137 | branch = currentGitBranch() | |
138 | print "Cleaning out stale p4 import tags..." | |
9863f405 | 139 | sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % branch) |
86949eef SH |
140 | output = sout.read() |
141 | try: | |
142 | tagIdx = output.index(" tags/p4/") | |
143 | except: | |
144 | print "Cannot find any p4/* tag. Nothing to do." | |
145 | sys.exit(0) | |
146 | ||
147 | try: | |
148 | caretIdx = output.index("^") | |
149 | except: | |
150 | caretIdx = len(output) - 1 | |
151 | rev = int(output[tagIdx + 9 : caretIdx]) | |
152 | ||
caace111 | 153 | allTags = mypopen("git tag -l p4/").readlines() |
86949eef SH |
154 | for i in range(len(allTags)): |
155 | allTags[i] = int(allTags[i][3:-1]) | |
156 | ||
157 | allTags.sort() | |
158 | ||
159 | allTags.remove(rev) | |
160 | ||
161 | for rev in allTags: | |
caace111 | 162 | print mypopen("git tag -d p4/%s" % rev).read() |
86949eef SH |
163 | |
164 | print "%s tags removed." % len(allTags) | |
b984733c | 165 | return True |
86949eef | 166 | |
711544b0 | 167 | class P4Submit(Command): |
4f5cf76a | 168 | def __init__(self): |
b984733c | 169 | Command.__init__(self) |
4f5cf76a SH |
170 | self.options = [ |
171 | optparse.make_option("--continue", action="store_false", dest="firstTime"), | |
172 | optparse.make_option("--origin", dest="origin"), | |
173 | optparse.make_option("--reset", action="store_true", dest="reset"), | |
4f5cf76a SH |
174 | optparse.make_option("--log-substitutions", dest="substFile"), |
175 | optparse.make_option("--noninteractive", action="store_false"), | |
04219c04 | 176 | optparse.make_option("--dry-run", action="store_true"), |
4f5cf76a SH |
177 | ] |
178 | self.description = "Submit changes from git to the perforce depot." | |
c9b50e63 | 179 | self.usage += " [name of git branch to submit into perforce depot]" |
4f5cf76a SH |
180 | self.firstTime = True |
181 | self.reset = False | |
182 | self.interactive = True | |
183 | self.dryRun = False | |
184 | self.substFile = "" | |
185 | self.firstTime = True | |
9512497b | 186 | self.origin = "" |
4f5cf76a SH |
187 | |
188 | self.logSubstitutions = {} | |
189 | self.logSubstitutions["<enter description here>"] = "%log%" | |
190 | self.logSubstitutions["\tDetails:"] = "\tDetails: %log%" | |
191 | ||
192 | def check(self): | |
193 | if len(p4CmdList("opened ...")) > 0: | |
194 | die("You have files opened with perforce! Close them before starting the sync.") | |
195 | ||
196 | def start(self): | |
197 | if len(self.config) > 0 and not self.reset: | |
c3c46244 | 198 | 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) |
4f5cf76a SH |
199 | |
200 | commits = [] | |
caace111 | 201 | for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines(): |
4f5cf76a SH |
202 | commits.append(line[:-1]) |
203 | commits.reverse() | |
204 | ||
205 | self.config["commits"] = commits | |
206 | ||
4f5cf76a SH |
207 | def prepareLogMessage(self, template, message): |
208 | result = "" | |
209 | ||
210 | for line in template.split("\n"): | |
211 | if line.startswith("#"): | |
212 | result += line + "\n" | |
213 | continue | |
214 | ||
215 | substituted = False | |
216 | for key in self.logSubstitutions.keys(): | |
217 | if line.find(key) != -1: | |
218 | value = self.logSubstitutions[key] | |
219 | value = value.replace("%log%", message) | |
220 | if value != "@remove@": | |
221 | result += line.replace(key, value) + "\n" | |
222 | substituted = True | |
223 | break | |
224 | ||
225 | if not substituted: | |
226 | result += line + "\n" | |
227 | ||
228 | return result | |
229 | ||
230 | def apply(self, id): | |
caace111 SH |
231 | print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read()) |
232 | diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines() | |
4f5cf76a SH |
233 | filesToAdd = set() |
234 | filesToDelete = set() | |
d336c158 | 235 | editedFiles = set() |
4f5cf76a SH |
236 | for line in diff: |
237 | modifier = line[0] | |
238 | path = line[1:].strip() | |
239 | if modifier == "M": | |
d336c158 SH |
240 | system("p4 edit \"%s\"" % path) |
241 | editedFiles.add(path) | |
4f5cf76a SH |
242 | elif modifier == "A": |
243 | filesToAdd.add(path) | |
244 | if path in filesToDelete: | |
245 | filesToDelete.remove(path) | |
246 | elif modifier == "D": | |
247 | filesToDelete.add(path) | |
248 | if path in filesToAdd: | |
249 | filesToAdd.remove(path) | |
250 | else: | |
251 | die("unknown modifier %s for %s" % (modifier, path)) | |
252 | ||
51a2640a SH |
253 | diffcmd = "git diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\"" % (id, id) |
254 | patchcmd = diffcmd + " | patch -p1" | |
255 | ||
256 | if os.system(patchcmd + " --dry-run --silent") != 0: | |
257 | print "Unfortunately applying the change failed!" | |
258 | print "What do you want to do?" | |
259 | response = "x" | |
260 | while response != "s" and response != "a" and response != "w": | |
261 | 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) ") | |
262 | if response == "s": | |
263 | print "Skipping! Good luck with the next patches..." | |
264 | return | |
265 | elif response == "a": | |
266 | os.system(patchcmd) | |
267 | if len(filesToAdd) > 0: | |
268 | print "You may also want to call p4 add on the following files:" | |
269 | print " ".join(filesToAdd) | |
270 | if len(filesToDelete): | |
271 | print "The following files should be scheduled for deletion with p4 delete:" | |
272 | print " ".join(filesToDelete) | |
273 | die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue") | |
274 | elif response == "w": | |
275 | system(diffcmd + " > patch.txt") | |
276 | print "Patch saved to patch.txt in %s !" % self.clientPath | |
277 | die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue") | |
278 | ||
279 | system(patchcmd) | |
4f5cf76a SH |
280 | |
281 | for f in filesToAdd: | |
282 | system("p4 add %s" % f) | |
283 | for f in filesToDelete: | |
284 | system("p4 revert %s" % f) | |
285 | system("p4 delete %s" % f) | |
286 | ||
6ae8de88 SH |
287 | logMessage = extractLogMessageFromGitCommit(id) |
288 | logMessage = logMessage.replace("\n", "\n\t") | |
289 | logMessage = logMessage[:-1] | |
4f5cf76a | 290 | |
caace111 | 291 | template = mypopen("p4 change -o").read() |
4f5cf76a SH |
292 | |
293 | if self.interactive: | |
294 | submitTemplate = self.prepareLogMessage(template, logMessage) | |
caace111 | 295 | diff = mypopen("p4 diff -du ...").read() |
4f5cf76a SH |
296 | |
297 | for newFile in filesToAdd: | |
298 | diff += "==== new file ====\n" | |
299 | diff += "--- /dev/null\n" | |
300 | diff += "+++ %s\n" % newFile | |
301 | f = open(newFile, "r") | |
302 | for line in f.readlines(): | |
303 | diff += "+" + line | |
304 | f.close() | |
305 | ||
25df95cc SH |
306 | separatorLine = "######## everything below this line is just the diff #######" |
307 | if platform.system() == "Windows": | |
308 | separatorLine += "\r" | |
309 | separatorLine += "\n" | |
4f5cf76a SH |
310 | |
311 | response = "e" | |
53150250 | 312 | firstIteration = True |
4f5cf76a | 313 | while response == "e": |
53150250 | 314 | if not firstIteration: |
d336c158 | 315 | response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ") |
53150250 | 316 | firstIteration = False |
4f5cf76a SH |
317 | if response == "e": |
318 | [handle, fileName] = tempfile.mkstemp() | |
319 | tmpFile = os.fdopen(handle, "w+") | |
53150250 | 320 | tmpFile.write(submitTemplate + separatorLine + diff) |
4f5cf76a | 321 | tmpFile.close() |
25df95cc SH |
322 | defaultEditor = "vi" |
323 | if platform.system() == "Windows": | |
324 | defaultEditor = "notepad" | |
325 | editor = os.environ.get("EDITOR", defaultEditor); | |
4f5cf76a | 326 | system(editor + " " + fileName) |
25df95cc | 327 | tmpFile = open(fileName, "rb") |
53150250 | 328 | message = tmpFile.read() |
4f5cf76a SH |
329 | tmpFile.close() |
330 | os.remove(fileName) | |
53150250 | 331 | submitTemplate = message[:message.index(separatorLine)] |
4f5cf76a SH |
332 | |
333 | if response == "y" or response == "yes": | |
334 | if self.dryRun: | |
335 | print submitTemplate | |
336 | raw_input("Press return to continue...") | |
337 | else: | |
25df95cc | 338 | pipe = os.popen("p4 submit -i", "wb") |
4f5cf76a SH |
339 | pipe.write(submitTemplate) |
340 | pipe.close() | |
d336c158 SH |
341 | elif response == "s": |
342 | for f in editedFiles: | |
343 | system("p4 revert \"%s\"" % f); | |
344 | for f in filesToAdd: | |
345 | system("p4 revert \"%s\"" % f); | |
346 | system("rm %s" %f) | |
347 | for f in filesToDelete: | |
348 | system("p4 delete \"%s\"" % f); | |
349 | return | |
4f5cf76a SH |
350 | else: |
351 | print "Not submitting!" | |
352 | self.interactive = False | |
353 | else: | |
354 | fileName = "submit.txt" | |
355 | file = open(fileName, "w+") | |
356 | file.write(self.prepareLogMessage(template, logMessage)) | |
357 | file.close() | |
358 | print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName) | |
359 | ||
360 | def run(self, args): | |
9512497b SH |
361 | global gitdir |
362 | # make gitdir absolute so we can cd out into the perforce checkout | |
363 | gitdir = os.path.abspath(gitdir) | |
364 | os.environ["GIT_DIR"] = gitdir | |
c9b50e63 SH |
365 | |
366 | if len(args) == 0: | |
367 | self.master = currentGitBranch() | |
368 | if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)): | |
369 | die("Detecting current git branch failed!") | |
370 | elif len(args) == 1: | |
371 | self.master = args[0] | |
372 | else: | |
373 | return False | |
374 | ||
9512497b SH |
375 | depotPath = "" |
376 | if gitBranchExists("p4"): | |
377 | [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4")) | |
378 | if len(depotPath) == 0 and gitBranchExists("origin"): | |
379 | [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin")) | |
380 | ||
381 | if len(depotPath) == 0: | |
382 | print "Internal error: cannot locate perforce depot path from existing branches" | |
383 | sys.exit(128) | |
384 | ||
51a2640a | 385 | self.clientPath = p4Where(depotPath) |
9512497b | 386 | |
51a2640a | 387 | if len(self.clientPath) == 0: |
9512497b SH |
388 | print "Error: Cannot locate perforce checkout of %s in client view" % depotPath |
389 | sys.exit(128) | |
390 | ||
51a2640a | 391 | print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath) |
80b5910f | 392 | oldWorkingDirectory = os.getcwd() |
51a2640a SH |
393 | os.chdir(self.clientPath) |
394 | response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath) | |
9512497b SH |
395 | if response == "y" or response == "yes": |
396 | system("p4 sync ...") | |
397 | ||
398 | if len(self.origin) == 0: | |
399 | if gitBranchExists("p4"): | |
400 | self.origin = "p4" | |
401 | else: | |
402 | self.origin = "origin" | |
403 | ||
4f5cf76a SH |
404 | if self.reset: |
405 | self.firstTime = True | |
406 | ||
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] | |
411 | ||
4f5cf76a SH |
412 | self.check() |
413 | self.configFile = gitdir + "/p4-git-sync.cfg" | |
414 | self.config = shelve.open(self.configFile, writeback=True) | |
415 | ||
416 | if self.firstTime: | |
417 | self.start() | |
418 | ||
419 | commits = self.config.get("commits", []) | |
420 | ||
421 | while len(commits) > 0: | |
422 | self.firstTime = False | |
423 | commit = commits[0] | |
424 | commits = commits[1:] | |
425 | self.config["commits"] = commits | |
426 | self.apply(commit) | |
427 | if not self.interactive: | |
428 | break | |
429 | ||
430 | self.config.close() | |
431 | ||
432 | if len(commits) == 0: | |
433 | if self.firstTime: | |
434 | print "No changes found to apply between %s and current HEAD" % self.origin | |
435 | else: | |
436 | print "All changes applied!" | |
5e80dd4d | 437 | response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ") |
80b5910f SH |
438 | if response == "y" or response == "yes": |
439 | os.chdir(oldWorkingDirectory) | |
440 | rebase = P4Rebase() | |
441 | rebase.run([]) | |
4f5cf76a SH |
442 | os.remove(self.configFile) |
443 | ||
b984733c SH |
444 | return True |
445 | ||
711544b0 | 446 | class P4Sync(Command): |
b984733c SH |
447 | def __init__(self): |
448 | Command.__init__(self) | |
449 | self.options = [ | |
450 | optparse.make_option("--branch", dest="branch"), | |
451 | optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"), | |
452 | optparse.make_option("--changesfile", dest="changesFile"), | |
453 | optparse.make_option("--silent", dest="silent", action="store_true"), | |
454 | optparse.make_option("--known-branches", dest="knownBranches"), | |
2a9489c0 | 455 | optparse.make_option("--data-cache", dest="dataCache", action="store_true"), |
cb53e1f8 SH |
456 | optparse.make_option("--command-cache", dest="commandCache", action="store_true"), |
457 | optparse.make_option("--detect-labels", dest="detectLabels", action="store_true") | |
b984733c SH |
458 | ] |
459 | self.description = """Imports from Perforce into a git repository.\n | |
460 | example: | |
461 | //depot/my/project/ -- to import the current head | |
462 | //depot/my/project/@all -- to import everything | |
463 | //depot/my/project/@1,6 -- to import only from revision 1 to 6 | |
464 | ||
465 | (a ... is not needed in the path p4 specification, it's added implicitly)""" | |
466 | ||
467 | self.usage += " //depot/path[@revRange]" | |
468 | ||
469 | self.dataCache = False | |
470 | self.commandCache = False | |
471 | self.silent = False | |
472 | self.knownBranches = Set() | |
473 | self.createdBranches = Set() | |
474 | self.committedChanges = Set() | |
569d1bd4 | 475 | self.branch = "" |
b984733c | 476 | self.detectBranches = False |
cb53e1f8 | 477 | self.detectLabels = False |
b984733c SH |
478 | self.changesFile = "" |
479 | ||
480 | def p4File(self, depotPath): | |
481 | return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read() | |
482 | ||
483 | def extractFilesFromCommit(self, commit): | |
484 | files = [] | |
485 | fnum = 0 | |
486 | while commit.has_key("depotFile%s" % fnum): | |
487 | path = commit["depotFile%s" % fnum] | |
8f872531 | 488 | if not path.startswith(self.depotPath): |
b984733c | 489 | # if not self.silent: |
8f872531 | 490 | # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change) |
b984733c SH |
491 | fnum = fnum + 1 |
492 | continue | |
493 | ||
494 | file = {} | |
495 | file["path"] = path | |
496 | file["rev"] = commit["rev%s" % fnum] | |
497 | file["action"] = commit["action%s" % fnum] | |
498 | file["type"] = commit["type%s" % fnum] | |
499 | files.append(file) | |
500 | fnum = fnum + 1 | |
501 | return files | |
502 | ||
503 | def isSubPathOf(self, first, second): | |
504 | if not first.startswith(second): | |
505 | return False | |
506 | if first == second: | |
507 | return True | |
508 | return first[len(second)] == "/" | |
509 | ||
510 | def branchesForCommit(self, files): | |
511 | branches = Set() | |
512 | ||
513 | for file in files: | |
8f872531 | 514 | relativePath = file["path"][len(self.depotPath):] |
b984733c SH |
515 | # strip off the filename |
516 | relativePath = relativePath[0:relativePath.rfind("/")] | |
517 | ||
518 | # if len(branches) == 0: | |
519 | # branches.add(relativePath) | |
520 | # knownBranches.add(relativePath) | |
521 | # continue | |
522 | ||
523 | ###### this needs more testing :) | |
524 | knownBranch = False | |
525 | for branch in branches: | |
526 | if relativePath == branch: | |
527 | knownBranch = True | |
528 | break | |
529 | # if relativePath.startswith(branch): | |
530 | if self.isSubPathOf(relativePath, branch): | |
531 | knownBranch = True | |
532 | break | |
533 | # if branch.startswith(relativePath): | |
534 | if self.isSubPathOf(branch, relativePath): | |
535 | branches.remove(branch) | |
536 | break | |
537 | ||
538 | if knownBranch: | |
539 | continue | |
540 | ||
2a9489c0 | 541 | for branch in self.knownBranches: |
b984733c SH |
542 | #if relativePath.startswith(branch): |
543 | if self.isSubPathOf(relativePath, branch): | |
544 | if len(branches) == 0: | |
545 | relativePath = branch | |
546 | else: | |
547 | knownBranch = True | |
548 | break | |
549 | ||
550 | if knownBranch: | |
551 | continue | |
552 | ||
553 | branches.add(relativePath) | |
554 | self.knownBranches.add(relativePath) | |
555 | ||
556 | return branches | |
557 | ||
558 | def findBranchParent(self, branchPrefix, files): | |
559 | for file in files: | |
560 | path = file["path"] | |
561 | if not path.startswith(branchPrefix): | |
562 | continue | |
563 | action = file["action"] | |
564 | if action != "integrate" and action != "branch": | |
565 | continue | |
566 | rev = file["rev"] | |
567 | depotPath = path + "#" + rev | |
568 | ||
569 | log = p4CmdList("filelog \"%s\"" % depotPath) | |
570 | if len(log) != 1: | |
571 | print "eek! I got confused by the filelog of %s" % depotPath | |
572 | sys.exit(1); | |
573 | ||
574 | log = log[0] | |
575 | if log["action0"] != action: | |
576 | print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action) | |
577 | sys.exit(1); | |
578 | ||
579 | branchAction = log["how0,0"] | |
580 | # if branchAction == "branch into" or branchAction == "ignored": | |
581 | # continue # ignore for branching | |
582 | ||
583 | if not branchAction.endswith(" from"): | |
584 | continue # ignore for branching | |
585 | # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction) | |
586 | # sys.exit(1); | |
587 | ||
588 | source = log["file0,0"] | |
589 | if source.startswith(branchPrefix): | |
590 | continue | |
591 | ||
592 | lastSourceRev = log["erev0,0"] | |
593 | ||
594 | sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev)) | |
595 | if len(sourceLog) != 1: | |
596 | print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev) | |
597 | sys.exit(1); | |
598 | sourceLog = sourceLog[0] | |
599 | ||
8f872531 | 600 | relPath = source[len(self.depotPath):] |
b984733c SH |
601 | # strip off the filename |
602 | relPath = relPath[0:relPath.rfind("/")] | |
603 | ||
604 | for branch in self.knownBranches: | |
605 | if self.isSubPathOf(relPath, branch): | |
606 | # print "determined parent branch branch %s due to change in file %s" % (branch, source) | |
607 | return branch | |
608 | # else: | |
609 | # print "%s is not a subpath of branch %s" % (relPath, branch) | |
610 | ||
611 | return "" | |
612 | ||
c715706b | 613 | def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""): |
b984733c SH |
614 | epoch = details["time"] |
615 | author = details["user"] | |
616 | ||
617 | self.gitStream.write("commit %s\n" % branch) | |
618 | # gitStream.write("mark :%s\n" % details["change"]) | |
619 | self.committedChanges.add(int(details["change"])) | |
620 | committer = "" | |
621 | if author in self.users: | |
0828ab14 | 622 | committer = "%s %s %s" % (self.users[author], epoch, self.tz) |
b984733c | 623 | else: |
0828ab14 | 624 | committer = "%s <a@b> %s %s" % (author, epoch, self.tz) |
b984733c SH |
625 | |
626 | self.gitStream.write("committer %s\n" % committer) | |
627 | ||
628 | self.gitStream.write("data <<EOT\n") | |
629 | self.gitStream.write(details["desc"]) | |
6ae8de88 | 630 | self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"])) |
b984733c SH |
631 | self.gitStream.write("EOT\n\n") |
632 | ||
633 | if len(parent) > 0: | |
634 | self.gitStream.write("from %s\n" % parent) | |
635 | ||
636 | if len(merged) > 0: | |
637 | self.gitStream.write("merge %s\n" % merged) | |
638 | ||
639 | for file in files: | |
640 | path = file["path"] | |
641 | if not path.startswith(branchPrefix): | |
642 | # if not silent: | |
643 | # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"]) | |
644 | continue | |
645 | rev = file["rev"] | |
646 | depotPath = path + "#" + rev | |
647 | relPath = path[len(branchPrefix):] | |
648 | action = file["action"] | |
649 | ||
650 | if file["type"] == "apple": | |
651 | print "\nfile %s is a strange apple file that forks. Ignoring!" % path | |
652 | continue | |
653 | ||
654 | if action == "delete": | |
655 | self.gitStream.write("D %s\n" % relPath) | |
656 | else: | |
657 | mode = 644 | |
658 | if file["type"].startswith("x"): | |
659 | mode = 755 | |
660 | ||
661 | data = self.p4File(depotPath) | |
662 | ||
663 | self.gitStream.write("M %s inline %s\n" % (mode, relPath)) | |
664 | self.gitStream.write("data %s\n" % len(data)) | |
665 | self.gitStream.write(data) | |
666 | self.gitStream.write("\n") | |
667 | ||
668 | self.gitStream.write("\n") | |
669 | ||
1f4ba1cb SH |
670 | change = int(details["change"]) |
671 | ||
672 | self.lastChange = change | |
673 | ||
674 | if change in self.labels: | |
675 | label = self.labels[change] | |
676 | labelDetails = label[0] | |
677 | labelRevisions = label[1] | |
678 | ||
679 | files = p4CmdList("files %s...@%s" % (branchPrefix, change)) | |
680 | ||
681 | if len(files) == len(labelRevisions): | |
682 | ||
683 | cleanedFiles = {} | |
684 | for info in files: | |
685 | if info["action"] == "delete": | |
686 | continue | |
687 | cleanedFiles[info["depotFile"]] = info["rev"] | |
688 | ||
689 | if cleanedFiles == labelRevisions: | |
690 | self.gitStream.write("tag tag_%s\n" % labelDetails["label"]) | |
691 | self.gitStream.write("from %s\n" % branch) | |
692 | ||
693 | owner = labelDetails["Owner"] | |
694 | tagger = "" | |
695 | if author in self.users: | |
696 | tagger = "%s %s %s" % (self.users[owner], epoch, self.tz) | |
697 | else: | |
698 | tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz) | |
699 | self.gitStream.write("tagger %s\n" % tagger) | |
700 | self.gitStream.write("data <<EOT\n") | |
701 | self.gitStream.write(labelDetails["Description"]) | |
702 | self.gitStream.write("EOT\n\n") | |
703 | ||
704 | else: | |
a46668fa | 705 | if not self.silent: |
1f4ba1cb SH |
706 | print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change) |
707 | ||
708 | else: | |
a46668fa | 709 | if not self.silent: |
1f4ba1cb | 710 | print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change) |
b984733c SH |
711 | |
712 | def extractFilesInCommitToBranch(self, files, branchPrefix): | |
713 | newFiles = [] | |
714 | ||
715 | for file in files: | |
716 | path = file["path"] | |
717 | if path.startswith(branchPrefix): | |
718 | newFiles.append(file) | |
719 | ||
720 | return newFiles | |
721 | ||
722 | def findBranchSourceHeuristic(self, files, branch, branchPrefix): | |
723 | for file in files: | |
724 | action = file["action"] | |
725 | if action != "integrate" and action != "branch": | |
726 | continue | |
727 | path = file["path"] | |
728 | rev = file["rev"] | |
729 | depotPath = path + "#" + rev | |
730 | ||
731 | log = p4CmdList("filelog \"%s\"" % depotPath) | |
732 | if len(log) != 1: | |
733 | print "eek! I got confused by the filelog of %s" % depotPath | |
734 | sys.exit(1); | |
735 | ||
736 | log = log[0] | |
737 | if log["action0"] != action: | |
738 | print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action) | |
739 | sys.exit(1); | |
740 | ||
741 | branchAction = log["how0,0"] | |
742 | ||
743 | if not branchAction.endswith(" from"): | |
744 | continue # ignore for branching | |
745 | # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction) | |
746 | # sys.exit(1); | |
747 | ||
748 | source = log["file0,0"] | |
749 | if source.startswith(branchPrefix): | |
750 | continue | |
751 | ||
752 | lastSourceRev = log["erev0,0"] | |
753 | ||
754 | sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev)) | |
755 | if len(sourceLog) != 1: | |
756 | print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev) | |
757 | sys.exit(1); | |
758 | sourceLog = sourceLog[0] | |
759 | ||
8f872531 | 760 | relPath = source[len(self.depotPath):] |
b984733c SH |
761 | # strip off the filename |
762 | relPath = relPath[0:relPath.rfind("/")] | |
763 | ||
764 | for candidate in self.knownBranches: | |
765 | if self.isSubPathOf(relPath, candidate) and candidate != branch: | |
766 | return candidate | |
767 | ||
768 | return "" | |
769 | ||
770 | def changeIsBranchMerge(self, sourceBranch, destinationBranch, change): | |
771 | sourceFiles = {} | |
8f872531 | 772 | for file in p4CmdList("files %s...@%s" % (self.depotPath + sourceBranch + "/", change)): |
b984733c SH |
773 | if file["action"] == "delete": |
774 | continue | |
775 | sourceFiles[file["depotFile"]] = file | |
776 | ||
777 | destinationFiles = {} | |
8f872531 | 778 | for file in p4CmdList("files %s...@%s" % (self.depotPath + destinationBranch + "/", change)): |
b984733c SH |
779 | destinationFiles[file["depotFile"]] = file |
780 | ||
781 | for fileName in sourceFiles.keys(): | |
782 | integrations = [] | |
783 | deleted = False | |
784 | integrationCount = 0 | |
785 | for integration in p4CmdList("integrated \"%s\"" % fileName): | |
786 | toFile = integration["fromFile"] # yes, it's true, it's fromFile | |
787 | if not toFile in destinationFiles: | |
788 | continue | |
789 | destFile = destinationFiles[toFile] | |
790 | if destFile["action"] == "delete": | |
791 | # print "file %s has been deleted in %s" % (fileName, toFile) | |
792 | deleted = True | |
793 | break | |
794 | integrationCount += 1 | |
795 | if integration["how"] == "branch from": | |
796 | continue | |
797 | ||
798 | if int(integration["change"]) == change: | |
799 | integrations.append(integration) | |
800 | continue | |
801 | if int(integration["change"]) > change: | |
802 | continue | |
803 | ||
804 | destRev = int(destFile["rev"]) | |
805 | ||
806 | startRev = integration["startFromRev"][1:] | |
807 | if startRev == "none": | |
808 | startRev = 0 | |
809 | else: | |
810 | startRev = int(startRev) | |
811 | ||
812 | endRev = integration["endFromRev"][1:] | |
813 | if endRev == "none": | |
814 | endRev = 0 | |
815 | else: | |
816 | endRev = int(endRev) | |
817 | ||
818 | initialBranch = (destRev == 1 and integration["how"] != "branch into") | |
819 | inRange = (destRev >= startRev and destRev <= endRev) | |
820 | newer = (destRev > startRev and destRev > endRev) | |
821 | ||
822 | if initialBranch or inRange or newer: | |
823 | integrations.append(integration) | |
824 | ||
825 | if deleted: | |
826 | continue | |
827 | ||
828 | if len(integrations) == 0 and integrationCount > 1: | |
829 | print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch) | |
830 | return False | |
831 | ||
832 | return True | |
833 | ||
834 | def getUserMap(self): | |
835 | self.users = {} | |
836 | ||
837 | for output in p4CmdList("users"): | |
838 | if not output.has_key("User"): | |
839 | continue | |
840 | self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">" | |
841 | ||
1f4ba1cb SH |
842 | def getLabels(self): |
843 | self.labels = {} | |
844 | ||
8f872531 | 845 | l = p4CmdList("labels %s..." % self.depotPath) |
10c3211b | 846 | if len(l) > 0 and not self.silent: |
8f872531 | 847 | print "Finding files belonging to labels in %s" % self.depotPath |
01ce1fe9 SH |
848 | |
849 | for output in l: | |
1f4ba1cb SH |
850 | label = output["label"] |
851 | revisions = {} | |
852 | newestChange = 0 | |
853 | for file in p4CmdList("files //...@%s" % label): | |
854 | revisions[file["depotFile"]] = file["rev"] | |
855 | change = int(file["change"]) | |
856 | if change > newestChange: | |
857 | newestChange = change | |
858 | ||
859 | self.labels[newestChange] = [output, revisions] | |
860 | ||
b984733c | 861 | def run(self, args): |
8f872531 | 862 | self.depotPath = "" |
179caebf SH |
863 | self.changeRange = "" |
864 | self.initialParent = "" | |
cd6cc0d3 | 865 | self.previousDepotPath = "" |
179caebf | 866 | |
569d1bd4 SH |
867 | if len(self.branch) == 0: |
868 | self.branch = "p4" | |
967f72e2 SH |
869 | |
870 | if len(args) == 0: | |
871 | if not gitBranchExists(self.branch) and gitBranchExists("origin"): | |
872 | if not self.silent: | |
873 | print "Creating %s branch in git repository based on origin" % self.branch | |
874 | system("git branch %s origin" % self.branch) | |
875 | ||
876 | [self.previousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.branch)) | |
877 | if len(self.previousDepotPath) > 0 and len(p4Change) > 0: | |
878 | p4Change = int(p4Change) + 1 | |
8f872531 | 879 | self.depotPath = self.previousDepotPath |
967f72e2 SH |
880 | self.changeRange = "@%s,#head" % p4Change |
881 | self.initialParent = self.branch | |
967f72e2 SH |
882 | if not self.silent: |
883 | print "Performing incremental import into %s git branch" % self.branch | |
569d1bd4 | 884 | |
b984733c | 885 | self.branch = "refs/heads/" + self.branch |
179caebf | 886 | |
8f872531 SH |
887 | if len(self.depotPath) != 0: |
888 | self.depotPath = self.depotPath[:-1] | |
b984733c | 889 | |
8f872531 | 890 | if len(args) == 0 and len(self.depotPath) != 0: |
b984733c | 891 | if not self.silent: |
8f872531 | 892 | print "Depot path: %s" % self.depotPath |
b984733c SH |
893 | elif len(args) != 1: |
894 | return False | |
895 | else: | |
8f872531 SH |
896 | if len(self.depotPath) != 0 and self.depotPath != args[0]: |
897 | print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0]) | |
b984733c | 898 | sys.exit(1) |
8f872531 | 899 | self.depotPath = args[0] |
b984733c | 900 | |
b984733c SH |
901 | self.revision = "" |
902 | self.users = {} | |
b984733c | 903 | self.lastChange = 0 |
b984733c | 904 | |
8f872531 SH |
905 | if self.depotPath.find("@") != -1: |
906 | atIdx = self.depotPath.index("@") | |
907 | self.changeRange = self.depotPath[atIdx:] | |
b984733c SH |
908 | if self.changeRange == "@all": |
909 | self.changeRange = "" | |
910 | elif self.changeRange.find(",") == -1: | |
911 | self.revision = self.changeRange | |
912 | self.changeRange = "" | |
8f872531 SH |
913 | self.depotPath = self.depotPath[0:atIdx] |
914 | elif self.depotPath.find("#") != -1: | |
915 | hashIdx = self.depotPath.index("#") | |
916 | self.revision = self.depotPath[hashIdx:] | |
917 | self.depotPath = self.depotPath[0:hashIdx] | |
b984733c SH |
918 | elif len(self.previousDepotPath) == 0: |
919 | self.revision = "#head" | |
920 | ||
8f872531 SH |
921 | if self.depotPath.endswith("..."): |
922 | self.depotPath = self.depotPath[:-3] | |
b984733c | 923 | |
8f872531 SH |
924 | if not self.depotPath.endswith("/"): |
925 | self.depotPath += "/" | |
b984733c SH |
926 | |
927 | self.getUserMap() | |
cb53e1f8 SH |
928 | self.labels = {} |
929 | if self.detectLabels: | |
930 | self.getLabels(); | |
b984733c SH |
931 | |
932 | if len(self.changeRange) == 0: | |
933 | try: | |
9863f405 | 934 | sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % self.branch) |
b984733c SH |
935 | output = sout.read() |
936 | if output.endswith("\n"): | |
937 | output = output[:-1] | |
938 | tagIdx = output.index(" tags/p4/") | |
939 | caretIdx = output.find("^") | |
940 | endPos = len(output) | |
941 | if caretIdx != -1: | |
942 | endPos = caretIdx | |
943 | self.rev = int(output[tagIdx + 9 : endPos]) + 1 | |
944 | self.changeRange = "@%s,#head" % self.rev | |
caace111 | 945 | self.initialParent = mypopen("git rev-parse %s" % self.branch).read()[:-1] |
b984733c SH |
946 | except: |
947 | pass | |
948 | ||
f291b4e3 | 949 | self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60)) |
b984733c | 950 | |
08483580 SH |
951 | importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE); |
952 | self.gitOutput = importProcess.stdout | |
953 | self.gitStream = importProcess.stdin | |
954 | self.gitError = importProcess.stderr | |
b984733c SH |
955 | |
956 | if len(self.revision) > 0: | |
8f872531 | 957 | print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision) |
b984733c SH |
958 | |
959 | details = { "user" : "git perforce import user", "time" : int(time.time()) } | |
8f872531 | 960 | details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision) |
b984733c SH |
961 | details["change"] = self.revision |
962 | newestRevision = 0 | |
963 | ||
964 | fileCnt = 0 | |
8f872531 | 965 | for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)): |
b984733c SH |
966 | change = int(info["change"]) |
967 | if change > newestRevision: | |
968 | newestRevision = change | |
969 | ||
970 | if info["action"] == "delete": | |
c45b1cfe SH |
971 | # don't increase the file cnt, otherwise details["depotFile123"] will have gaps! |
972 | #fileCnt = fileCnt + 1 | |
b984733c SH |
973 | continue |
974 | ||
975 | for prop in [ "depotFile", "rev", "action", "type" ]: | |
976 | details["%s%s" % (prop, fileCnt)] = info[prop] | |
977 | ||
978 | fileCnt = fileCnt + 1 | |
979 | ||
980 | details["change"] = newestRevision | |
981 | ||
982 | try: | |
8f872531 | 983 | self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath) |
c715706b | 984 | except IOError: |
fd4ca86a | 985 | print "IO error with git fast-import. Is your git version recent enough?" |
b984733c SH |
986 | print self.gitError.read() |
987 | ||
988 | else: | |
989 | changes = [] | |
990 | ||
0828ab14 | 991 | if len(self.changesFile) > 0: |
b984733c SH |
992 | output = open(self.changesFile).readlines() |
993 | changeSet = Set() | |
994 | for line in output: | |
995 | changeSet.add(int(line)) | |
996 | ||
997 | for change in changeSet: | |
998 | changes.append(change) | |
999 | ||
1000 | changes.sort() | |
1001 | else: | |
caace111 | 1002 | output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines() |
b984733c SH |
1003 | |
1004 | for line in output: | |
1005 | changeNum = line.split(" ")[1] | |
1006 | changes.append(changeNum) | |
1007 | ||
1008 | changes.reverse() | |
1009 | ||
1010 | if len(changes) == 0: | |
0828ab14 | 1011 | if not self.silent: |
b984733c | 1012 | print "no changes to import!" |
1f52af6c | 1013 | return True |
b984733c SH |
1014 | |
1015 | cnt = 1 | |
1016 | for change in changes: | |
1017 | description = p4Cmd("describe %s" % change) | |
1018 | ||
0828ab14 | 1019 | if not self.silent: |
b984733c SH |
1020 | sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes))) |
1021 | sys.stdout.flush() | |
1022 | cnt = cnt + 1 | |
1023 | ||
1024 | try: | |
1025 | files = self.extractFilesFromCommit(description) | |
1026 | if self.detectBranches: | |
1027 | for branch in self.branchesForCommit(files): | |
1028 | self.knownBranches.add(branch) | |
8f872531 | 1029 | branchPrefix = self.depotPath + branch + "/" |
b984733c SH |
1030 | |
1031 | filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix) | |
1032 | ||
1033 | merged = "" | |
1034 | parent = "" | |
1035 | ########### remove cnt!!! | |
1036 | if branch not in self.createdBranches and cnt > 2: | |
1037 | self.createdBranches.add(branch) | |
1038 | parent = self.findBranchParent(branchPrefix, files) | |
1039 | if parent == branch: | |
1040 | parent = "" | |
1041 | # elif len(parent) > 0: | |
1042 | # print "%s branched off of %s" % (branch, parent) | |
1043 | ||
1044 | if len(parent) == 0: | |
1045 | merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix) | |
1046 | if len(merged) > 0: | |
1047 | print "change %s could be a merge from %s into %s" % (description["change"], merged, branch) | |
1048 | if not self.changeIsBranchMerge(merged, branch, int(description["change"])): | |
1049 | merged = "" | |
1050 | ||
1051 | branch = "refs/heads/" + branch | |
1052 | if len(parent) > 0: | |
1053 | parent = "refs/heads/" + parent | |
1054 | if len(merged) > 0: | |
1055 | merged = "refs/heads/" + merged | |
1056 | self.commit(description, files, branch, branchPrefix, parent, merged) | |
1057 | else: | |
8f872531 | 1058 | self.commit(description, files, self.branch, self.depotPath, self.initialParent) |
b984733c SH |
1059 | self.initialParent = "" |
1060 | except IOError: | |
1061 | print self.gitError.read() | |
1062 | sys.exit(1) | |
1063 | ||
1064 | if not self.silent: | |
1065 | print "" | |
1066 | ||
b984733c SH |
1067 | |
1068 | self.gitStream.close() | |
1069 | self.gitOutput.close() | |
1070 | self.gitError.close() | |
90865adc | 1071 | importProcess.wait() |
b984733c | 1072 | |
b984733c SH |
1073 | return True |
1074 | ||
01ce1fe9 SH |
1075 | class P4Rebase(Command): |
1076 | def __init__(self): | |
1077 | Command.__init__(self) | |
1078 | self.options = [ ] | |
1079 | self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it" | |
1080 | ||
1081 | def run(self, args): | |
1082 | sync = P4Sync() | |
1083 | sync.run([]) | |
1084 | print "Rebasing the current branch" | |
caace111 | 1085 | oldHead = mypopen("git rev-parse HEAD").read()[:-1] |
01ce1fe9 | 1086 | system("git rebase p4") |
1f52af6c | 1087 | system("git diff-tree --stat --summary -M %s HEAD" % oldHead) |
01ce1fe9 SH |
1088 | return True |
1089 | ||
f9a3a4f7 SH |
1090 | class P4Clone(P4Sync): |
1091 | def __init__(self): | |
1092 | P4Sync.__init__(self) | |
1093 | self.description = "Creates a new git repository and imports from Perforce into it" | |
1094 | self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]" | |
1095 | self.needsGit = False | |
f9a3a4f7 SH |
1096 | |
1097 | def run(self, args): | |
1098 | if len(args) < 1: | |
1099 | return False | |
1100 | depotPath = args[0] | |
1101 | dir = "" | |
1102 | if len(args) == 2: | |
1103 | dir = args[1] | |
1104 | elif len(args) > 2: | |
1105 | return False | |
1106 | ||
1107 | if not depotPath.startswith("//"): | |
1108 | return False | |
1109 | ||
1110 | if len(dir) == 0: | |
1111 | dir = depotPath | |
1112 | atPos = dir.rfind("@") | |
1113 | if atPos != -1: | |
1114 | dir = dir[0:atPos] | |
1115 | hashPos = dir.rfind("#") | |
1116 | if hashPos != -1: | |
1117 | dir = dir[0:hashPos] | |
1118 | ||
1119 | if dir.endswith("..."): | |
1120 | dir = dir[:-3] | |
1121 | ||
1122 | if dir.endswith("/"): | |
1123 | dir = dir[:-1] | |
1124 | ||
1125 | slashPos = dir.rfind("/") | |
1126 | if slashPos != -1: | |
1127 | dir = dir[slashPos + 1:] | |
1128 | ||
1129 | print "Importing from %s into %s" % (depotPath, dir) | |
1130 | os.makedirs(dir) | |
1131 | os.chdir(dir) | |
1132 | system("git init") | |
1133 | if not P4Sync.run(self, [depotPath]): | |
1134 | return False | |
f9a3a4f7 SH |
1135 | if self.branch != "master": |
1136 | system("git branch master p4") | |
1137 | system("git checkout -f") | |
1138 | return True | |
1139 | ||
b984733c SH |
1140 | class HelpFormatter(optparse.IndentedHelpFormatter): |
1141 | def __init__(self): | |
1142 | optparse.IndentedHelpFormatter.__init__(self) | |
1143 | ||
1144 | def format_description(self, description): | |
1145 | if description: | |
1146 | return description + "\n" | |
1147 | else: | |
1148 | return "" | |
4f5cf76a | 1149 | |
86949eef SH |
1150 | def printUsage(commands): |
1151 | print "usage: %s <command> [options]" % sys.argv[0] | |
1152 | print "" | |
1153 | print "valid commands: %s" % ", ".join(commands) | |
1154 | print "" | |
1155 | print "Try %s <command> --help for command specific help." % sys.argv[0] | |
1156 | print "" | |
1157 | ||
1158 | commands = { | |
1159 | "debug" : P4Debug(), | |
4f5cf76a | 1160 | "clean-tags" : P4CleanTags(), |
711544b0 | 1161 | "submit" : P4Submit(), |
01ce1fe9 | 1162 | "sync" : P4Sync(), |
f9a3a4f7 SH |
1163 | "rebase" : P4Rebase(), |
1164 | "clone" : P4Clone() | |
86949eef SH |
1165 | } |
1166 | ||
1167 | if len(sys.argv[1:]) == 0: | |
1168 | printUsage(commands.keys()) | |
1169 | sys.exit(2) | |
1170 | ||
1171 | cmd = "" | |
1172 | cmdName = sys.argv[1] | |
1173 | try: | |
1174 | cmd = commands[cmdName] | |
1175 | except KeyError: | |
1176 | print "unknown command %s" % cmdName | |
1177 | print "" | |
1178 | printUsage(commands.keys()) | |
1179 | sys.exit(2) | |
1180 | ||
4f5cf76a SH |
1181 | options = cmd.options |
1182 | cmd.gitdir = gitdir | |
4f5cf76a | 1183 | |
e20a9e53 | 1184 | args = sys.argv[2:] |
86949eef | 1185 | |
e20a9e53 SH |
1186 | if len(options) > 0: |
1187 | options.append(optparse.make_option("--git-dir", dest="gitdir")) | |
1188 | ||
1189 | parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName), | |
1190 | options, | |
1191 | description = cmd.description, | |
1192 | formatter = HelpFormatter()) | |
1193 | ||
1194 | (cmd, args) = parser.parse_args(sys.argv[2:], cmd); | |
86949eef | 1195 | |
8910ac0e SH |
1196 | if cmd.needsGit: |
1197 | gitdir = cmd.gitdir | |
1198 | if len(gitdir) == 0: | |
1199 | gitdir = ".git" | |
1200 | if not isValidGitDir(gitdir): | |
81f2373f | 1201 | gitdir = mypopen("git rev-parse --git-dir").read()[:-1] |
dc1a93b6 | 1202 | if os.path.exists(gitdir): |
5c4153e4 SH |
1203 | cdup = mypopen("git rev-parse --show-cdup").read()[:-1]; |
1204 | if len(cdup) > 0: | |
1205 | os.chdir(cdup); | |
4f5cf76a | 1206 | |
8910ac0e SH |
1207 | if not isValidGitDir(gitdir): |
1208 | if isValidGitDir(gitdir + "/.git"): | |
1209 | gitdir += "/.git" | |
1210 | else: | |
1211 | die("fatal: cannot locate git repository at %s" % gitdir) | |
4f5cf76a | 1212 | |
8910ac0e | 1213 | os.environ["GIT_DIR"] = gitdir |
4f5cf76a | 1214 | |
b984733c SH |
1215 | if not cmd.run(args): |
1216 | parser.print_help() | |
1217 |