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