]> git.ipfire.org Git - thirdparty/git.git/blame - contrib/fast-import/git-p4
use p4CmdList() to get file contents in Python dicts. This is more robust.
[thirdparty/git.git] / contrib / fast-import / git-p4
CommitLineData
86949eef
SH
1#!/usr/bin/env python
2#
3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4#
c8cbbee9
SH
5# Author: Simon Hausmann <simon@lst.de>
6# Copyright: 2007 Simon Hausmann <simon@lst.de>
83dce55a 7# 2007 Trolltech ASA
86949eef
SH
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
10
08483580 11import optparse, sys, os, marshal, popen2, subprocess, shelve
25df95cc 12import tempfile, getopt, sha, os.path, time, platform
ce6f33c8 13import re
8b41a97f 14
b984733c 15from sets import Set;
4f5cf76a 16
4addad22 17verbose = False
86949eef 18
bce4c5fc 19def write_pipe(c, str):
4addad22 20 if verbose:
bce4c5fc 21 sys.stderr.write('writing pipe: %s\n' % c)
b016d397 22
bce4c5fc 23 pipe = os.popen(c, 'w')
b016d397 24 val = pipe.write(str)
bce4c5fc 25 if pipe.close():
9226c03c 26 sys.stderr.write('Command failed: %s' % c)
bce4c5fc 27 sys.exit(1)
b016d397
HWN
28
29 return val
30
4addad22
HWN
31def read_pipe(c, ignore_error=False):
32 if verbose:
6754a299 33 sys.stderr.write('reading pipe: %s\n' % c)
8b41a97f 34
bce4c5fc 35 pipe = os.popen(c, 'rb')
b016d397 36 val = pipe.read()
4addad22 37 if pipe.close() and not ignore_error:
5e926eed 38 sys.stderr.write('Command failed: %s\n' % c)
bce4c5fc 39 sys.exit(1)
b016d397
HWN
40
41 return val
42
43
bce4c5fc 44def read_pipe_lines(c):
4addad22 45 if verbose:
6754a299 46 sys.stderr.write('reading pipe: %s\n' % c)
b016d397 47 ## todo: check return status
bce4c5fc 48 pipe = os.popen(c, 'rb')
b016d397 49 val = pipe.readlines()
bce4c5fc 50 if pipe.close():
5e926eed 51 sys.stderr.write('Command failed: %s\n' % c)
bce4c5fc 52 sys.exit(1)
b016d397
HWN
53
54 return val
caace111 55
6754a299 56def system(cmd):
4addad22 57 if verbose:
bb6e09b2 58 sys.stderr.write("executing %s\n" % cmd)
6754a299
HWN
59 if os.system(cmd) != 0:
60 die("command failed: %s" % cmd)
61
86949eef
SH
62def p4CmdList(cmd):
63 cmd = "p4 -G %s" % cmd
6a49f8e2
HWN
64 if verbose:
65 sys.stderr.write("Opening pipe: %s\n" % cmd)
86949eef
SH
66 pipe = os.popen(cmd, "rb")
67
68 result = []
69 try:
70 while True:
71 entry = marshal.load(pipe)
72 result.append(entry)
73 except EOFError:
74 pass
a6d5da36
SH
75 exitCode = pipe.close()
76 if exitCode != None:
ac3e0d79
SH
77 entry = {}
78 entry["p4ExitCode"] = exitCode
79 result.append(entry)
86949eef
SH
80
81 return result
82
83def p4Cmd(cmd):
84 list = p4CmdList(cmd)
85 result = {}
86 for entry in list:
87 result.update(entry)
88 return result;
89
cb2c9db5
SH
90def p4Where(depotPath):
91 if not depotPath.endswith("/"):
92 depotPath += "/"
93 output = p4Cmd("where %s..." % depotPath)
dc524036
SH
94 if output["code"] == "error":
95 return ""
cb2c9db5
SH
96 clientPath = ""
97 if "path" in output:
98 clientPath = output.get("path")
99 elif "data" in output:
100 data = output.get("data")
101 lastSpace = data.rfind(" ")
102 clientPath = data[lastSpace + 1:]
103
104 if clientPath.endswith("..."):
105 clientPath = clientPath[:-3]
106 return clientPath
107
86949eef
SH
108def die(msg):
109 sys.stderr.write(msg + "\n")
110 sys.exit(1)
111
112def currentGitBranch():
b25b2065 113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
86949eef 114
4f5cf76a 115def isValidGitDir(path):
bb6e09b2
HWN
116 if (os.path.exists(path + "/HEAD")
117 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
4f5cf76a
SH
118 return True;
119 return False
120
463e8af6 121def parseRevision(ref):
b25b2065 122 return read_pipe("git rev-parse %s" % ref).strip()
463e8af6 123
6ae8de88
SH
124def extractLogMessageFromGitCommit(commit):
125 logMessage = ""
b016d397
HWN
126
127 ## fixme: title is first line of commit, not 1st paragraph.
6ae8de88 128 foundTitle = False
b016d397 129 for log in read_pipe_lines("git cat-file commit %s" % commit):
6ae8de88
SH
130 if not foundTitle:
131 if len(log) == 1:
1c094184 132 foundTitle = True
6ae8de88
SH
133 continue
134
135 logMessage += log
136 return logMessage
137
bb6e09b2 138def extractSettingsGitLog(log):
6ae8de88
SH
139 values = {}
140 for line in log.split("\n"):
141 line = line.strip()
6326aa58
HWN
142 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
143 if not m:
144 continue
145
146 assignments = m.group(1).split (':')
147 for a in assignments:
148 vals = a.split ('=')
149 key = vals[0].strip()
150 val = ('='.join (vals[1:])).strip()
151 if val.endswith ('\"') and val.startswith('"'):
152 val = val[1:-1]
153
154 values[key] = val
155
bb6e09b2
HWN
156 values['depot-paths'] = values.get("depot-paths").split(',')
157 return values
6ae8de88 158
8136a639 159def gitBranchExists(branch):
bb6e09b2
HWN
160 proc = subprocess.Popen(["git", "rev-parse", branch],
161 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
caace111 162 return proc.wait() == 0;
8136a639 163
01265103 164def gitConfig(key):
4addad22 165 return read_pipe("git config %s" % key, ignore_error=True).strip()
01265103 166
b984733c
SH
167class Command:
168 def __init__(self):
169 self.usage = "usage: %prog [options]"
8910ac0e 170 self.needsGit = True
b984733c
SH
171
172class P4Debug(Command):
86949eef 173 def __init__(self):
6ae8de88 174 Command.__init__(self)
86949eef 175 self.options = [
4addad22
HWN
176 optparse.make_option("--verbose", dest="verbose", action="store_true"),
177 ]
c8c39116 178 self.description = "A tool to debug the output of p4 -G."
8910ac0e 179 self.needsGit = False
86949eef
SH
180
181 def run(self, args):
182 for output in p4CmdList(" ".join(args)):
183 print output
b984733c 184 return True
86949eef 185
5834684d
SH
186class P4RollBack(Command):
187 def __init__(self):
188 Command.__init__(self)
189 self.options = [
0c66a783
SH
190 optparse.make_option("--verbose", dest="verbose", action="store_true"),
191 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
5834684d
SH
192 ]
193 self.description = "A tool to debug the multi-branch import. Don't use :)"
52102d47 194 self.verbose = False
0c66a783 195 self.rollbackLocalBranches = False
5834684d
SH
196
197 def run(self, args):
198 if len(args) != 1:
199 return False
200 maxChange = int(args[0])
0c66a783 201
ad192f28 202 if "p4ExitCode" in p4Cmd("changes -m 1"):
66a2f523
SH
203 die("Problems executing p4");
204
0c66a783
SH
205 if self.rollbackLocalBranches:
206 refPrefix = "refs/heads/"
b016d397 207 lines = read_pipe_lines("git rev-parse --symbolic --branches")
0c66a783
SH
208 else:
209 refPrefix = "refs/remotes/"
b016d397 210 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
0c66a783
SH
211
212 for line in lines:
213 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
b25b2065
HWN
214 line = line.strip()
215 ref = refPrefix + line
5834684d 216 log = extractLogMessageFromGitCommit(ref)
bb6e09b2
HWN
217 settings = extractSettingsGitLog(log)
218
219 depotPaths = settings['depot-paths']
220 change = settings['change']
221
5834684d 222 changed = False
52102d47 223
6326aa58
HWN
224 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
225 for p in depotPaths]))) == 0:
52102d47
SH
226 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
227 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
228 continue
229
bb6e09b2 230 while change and int(change) > maxChange:
5834684d 231 changed = True
52102d47
SH
232 if self.verbose:
233 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
5834684d
SH
234 system("git update-ref %s \"%s^\"" % (ref, ref))
235 log = extractLogMessageFromGitCommit(ref)
bb6e09b2
HWN
236 settings = extractSettingsGitLog(log)
237
238
239 depotPaths = settings['depot-paths']
240 change = settings['change']
5834684d
SH
241
242 if changed:
52102d47 243 print "%s rewound to %s" % (ref, change)
5834684d
SH
244
245 return True
246
711544b0 247class P4Submit(Command):
4f5cf76a 248 def __init__(self):
b984733c 249 Command.__init__(self)
4f5cf76a
SH
250 self.options = [
251 optparse.make_option("--continue", action="store_false", dest="firstTime"),
4addad22 252 optparse.make_option("--verbose", dest="verbose", action="store_true"),
4f5cf76a
SH
253 optparse.make_option("--origin", dest="origin"),
254 optparse.make_option("--reset", action="store_true", dest="reset"),
4f5cf76a 255 optparse.make_option("--log-substitutions", dest="substFile"),
04219c04 256 optparse.make_option("--dry-run", action="store_true"),
c1b296b9 257 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
cb4f1280 258 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
4f5cf76a
SH
259 ]
260 self.description = "Submit changes from git to the perforce depot."
c9b50e63 261 self.usage += " [name of git branch to submit into perforce depot]"
4f5cf76a
SH
262 self.firstTime = True
263 self.reset = False
264 self.interactive = True
265 self.dryRun = False
266 self.substFile = ""
267 self.firstTime = True
9512497b 268 self.origin = ""
c1b296b9 269 self.directSubmit = False
cb4f1280 270 self.trustMeLikeAFool = False
4f5cf76a
SH
271
272 self.logSubstitutions = {}
273 self.logSubstitutions["<enter description here>"] = "%log%"
274 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
275
276 def check(self):
277 if len(p4CmdList("opened ...")) > 0:
278 die("You have files opened with perforce! Close them before starting the sync.")
279
280 def start(self):
281 if len(self.config) > 0 and not self.reset:
cebdf5af
HWN
282 die("Cannot start sync. Previous sync config found at %s\n"
283 "If you want to start submitting again from scratch "
284 "maybe you want to call git-p4 submit --reset" % self.configFile)
4f5cf76a
SH
285
286 commits = []
c1b296b9
SH
287 if self.directSubmit:
288 commits.append("0")
289 else:
b016d397 290 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
b25b2065 291 commits.append(line.strip())
c1b296b9 292 commits.reverse()
4f5cf76a
SH
293
294 self.config["commits"] = commits
295
4f5cf76a
SH
296 def prepareLogMessage(self, template, message):
297 result = ""
298
299 for line in template.split("\n"):
300 if line.startswith("#"):
301 result += line + "\n"
302 continue
303
304 substituted = False
305 for key in self.logSubstitutions.keys():
306 if line.find(key) != -1:
307 value = self.logSubstitutions[key]
308 value = value.replace("%log%", message)
309 if value != "@remove@":
310 result += line.replace(key, value) + "\n"
311 substituted = True
312 break
313
314 if not substituted:
315 result += line + "\n"
316
317 return result
318
7cb5cbef 319 def applyCommit(self, id):
c1b296b9
SH
320 if self.directSubmit:
321 print "Applying local change in working directory/index"
322 diff = self.diffStatus
323 else:
b016d397
HWN
324 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
325 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
4f5cf76a
SH
326 filesToAdd = set()
327 filesToDelete = set()
d336c158 328 editedFiles = set()
4f5cf76a
SH
329 for line in diff:
330 modifier = line[0]
331 path = line[1:].strip()
332 if modifier == "M":
d336c158
SH
333 system("p4 edit \"%s\"" % path)
334 editedFiles.add(path)
4f5cf76a
SH
335 elif modifier == "A":
336 filesToAdd.add(path)
337 if path in filesToDelete:
338 filesToDelete.remove(path)
339 elif modifier == "D":
340 filesToDelete.add(path)
341 if path in filesToAdd:
342 filesToAdd.remove(path)
343 else:
344 die("unknown modifier %s for %s" % (modifier, path))
345
c1b296b9
SH
346 if self.directSubmit:
347 diffcmd = "cat \"%s\"" % self.diffFile
348 else:
349 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
47a130b7 350 patchcmd = diffcmd + " | git apply "
c1b296b9
SH
351 tryPatchCmd = patchcmd + "--check -"
352 applyPatchCmd = patchcmd + "--check --apply -"
51a2640a 353
47a130b7 354 if os.system(tryPatchCmd) != 0:
51a2640a
SH
355 print "Unfortunately applying the change failed!"
356 print "What do you want to do?"
357 response = "x"
358 while response != "s" and response != "a" and response != "w":
cebdf5af
HWN
359 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
360 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
51a2640a
SH
361 if response == "s":
362 print "Skipping! Good luck with the next patches..."
363 return
364 elif response == "a":
47a130b7 365 os.system(applyPatchCmd)
51a2640a
SH
366 if len(filesToAdd) > 0:
367 print "You may also want to call p4 add on the following files:"
368 print " ".join(filesToAdd)
369 if len(filesToDelete):
370 print "The following files should be scheduled for deletion with p4 delete:"
371 print " ".join(filesToDelete)
cebdf5af
HWN
372 die("Please resolve and submit the conflict manually and "
373 + "continue afterwards with git-p4 submit --continue")
51a2640a
SH
374 elif response == "w":
375 system(diffcmd + " > patch.txt")
376 print "Patch saved to patch.txt in %s !" % self.clientPath
cebdf5af
HWN
377 die("Please resolve and submit the conflict manually and "
378 "continue afterwards with git-p4 submit --continue")
51a2640a 379
47a130b7 380 system(applyPatchCmd)
4f5cf76a
SH
381
382 for f in filesToAdd:
383 system("p4 add %s" % f)
384 for f in filesToDelete:
385 system("p4 revert %s" % f)
386 system("p4 delete %s" % f)
387
c1b296b9
SH
388 logMessage = ""
389 if not self.directSubmit:
390 logMessage = extractLogMessageFromGitCommit(id)
391 logMessage = logMessage.replace("\n", "\n\t")
b25b2065 392 logMessage = logMessage.strip()
4f5cf76a 393
b016d397 394 template = read_pipe("p4 change -o")
4f5cf76a
SH
395
396 if self.interactive:
397 submitTemplate = self.prepareLogMessage(template, logMessage)
b016d397 398 diff = read_pipe("p4 diff -du ...")
4f5cf76a
SH
399
400 for newFile in filesToAdd:
401 diff += "==== new file ====\n"
402 diff += "--- /dev/null\n"
403 diff += "+++ %s\n" % newFile
404 f = open(newFile, "r")
405 for line in f.readlines():
406 diff += "+" + line
407 f.close()
408
25df95cc
SH
409 separatorLine = "######## everything below this line is just the diff #######"
410 if platform.system() == "Windows":
411 separatorLine += "\r"
412 separatorLine += "\n"
4f5cf76a
SH
413
414 response = "e"
cb4f1280
SH
415 if self.trustMeLikeAFool:
416 response = "y"
417
53150250 418 firstIteration = True
4f5cf76a 419 while response == "e":
53150250 420 if not firstIteration:
d336c158 421 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
53150250 422 firstIteration = False
4f5cf76a
SH
423 if response == "e":
424 [handle, fileName] = tempfile.mkstemp()
425 tmpFile = os.fdopen(handle, "w+")
53150250 426 tmpFile.write(submitTemplate + separatorLine + diff)
4f5cf76a 427 tmpFile.close()
25df95cc
SH
428 defaultEditor = "vi"
429 if platform.system() == "Windows":
430 defaultEditor = "notepad"
431 editor = os.environ.get("EDITOR", defaultEditor);
4f5cf76a 432 system(editor + " " + fileName)
25df95cc 433 tmpFile = open(fileName, "rb")
53150250 434 message = tmpFile.read()
4f5cf76a
SH
435 tmpFile.close()
436 os.remove(fileName)
53150250 437 submitTemplate = message[:message.index(separatorLine)]
4f5cf76a
SH
438
439 if response == "y" or response == "yes":
440 if self.dryRun:
441 print submitTemplate
442 raw_input("Press return to continue...")
443 else:
7944f142
SH
444 if self.directSubmit:
445 print "Submitting to git first"
446 os.chdir(self.oldWorkingDirectory)
b016d397 447 write_pipe("git commit -a -F -", submitTemplate)
7944f142
SH
448 os.chdir(self.clientPath)
449
b016d397 450 write_pipe("p4 submit -i", submitTemplate)
d336c158
SH
451 elif response == "s":
452 for f in editedFiles:
453 system("p4 revert \"%s\"" % f);
454 for f in filesToAdd:
455 system("p4 revert \"%s\"" % f);
456 system("rm %s" %f)
457 for f in filesToDelete:
458 system("p4 delete \"%s\"" % f);
459 return
4f5cf76a
SH
460 else:
461 print "Not submitting!"
462 self.interactive = False
463 else:
464 fileName = "submit.txt"
465 file = open(fileName, "w+")
466 file.write(self.prepareLogMessage(template, logMessage))
467 file.close()
cebdf5af
HWN
468 print ("Perforce submit template written as %s. "
469 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
470 % (fileName, fileName))
4f5cf76a
SH
471
472 def run(self, args):
9512497b 473 # make gitdir absolute so we can cd out into the perforce checkout
9512497b 474 os.environ["GIT_DIR"] = gitdir
c9b50e63
SH
475
476 if len(args) == 0:
477 self.master = currentGitBranch()
4280e533 478 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
c9b50e63
SH
479 die("Detecting current git branch failed!")
480 elif len(args) == 1:
481 self.master = args[0]
482 else:
483 return False
484
9512497b 485 depotPath = ""
bb6e09b2 486 settings = None
9512497b 487 if gitBranchExists("p4"):
bb6e09b2 488 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
9512497b 489 if len(depotPath) == 0 and gitBranchExists("origin"):
bb6e09b2
HWN
490 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
491 depotPaths = settings['depot-paths']
9512497b
SH
492
493 if len(depotPath) == 0:
494 print "Internal error: cannot locate perforce depot path from existing branches"
495 sys.exit(128)
496
51a2640a 497 self.clientPath = p4Where(depotPath)
9512497b 498
51a2640a 499 if len(self.clientPath) == 0:
9512497b
SH
500 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
501 sys.exit(128)
502
51a2640a 503 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
7944f142 504 self.oldWorkingDirectory = os.getcwd()
c1b296b9
SH
505
506 if self.directSubmit:
b016d397 507 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
cbf5efa6
SH
508 if len(self.diffStatus) == 0:
509 print "No changes in working directory to submit."
510 return True
b016d397 511 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
b86f7378 512 self.diffFile = self.gitdir + "/p4-git-diff"
c1b296b9
SH
513 f = open(self.diffFile, "wb")
514 f.write(patch)
515 f.close();
516
51a2640a
SH
517 os.chdir(self.clientPath)
518 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
9512497b
SH
519 if response == "y" or response == "yes":
520 system("p4 sync ...")
521
522 if len(self.origin) == 0:
523 if gitBranchExists("p4"):
524 self.origin = "p4"
525 else:
526 self.origin = "origin"
527
4f5cf76a
SH
528 if self.reset:
529 self.firstTime = True
530
531 if len(self.substFile) > 0:
532 for line in open(self.substFile, "r").readlines():
b25b2065 533 tokens = line.strip().split("=")
4f5cf76a
SH
534 self.logSubstitutions[tokens[0]] = tokens[1]
535
4f5cf76a 536 self.check()
b86f7378 537 self.configFile = self.gitdir + "/p4-git-sync.cfg"
4f5cf76a
SH
538 self.config = shelve.open(self.configFile, writeback=True)
539
540 if self.firstTime:
541 self.start()
542
543 commits = self.config.get("commits", [])
544
545 while len(commits) > 0:
546 self.firstTime = False
547 commit = commits[0]
548 commits = commits[1:]
549 self.config["commits"] = commits
7cb5cbef 550 self.applyCommit(commit)
4f5cf76a
SH
551 if not self.interactive:
552 break
553
554 self.config.close()
555
c1b296b9
SH
556 if self.directSubmit:
557 os.remove(self.diffFile)
558
4f5cf76a
SH
559 if len(commits) == 0:
560 if self.firstTime:
561 print "No changes found to apply between %s and current HEAD" % self.origin
562 else:
563 print "All changes applied!"
7944f142
SH
564 os.chdir(self.oldWorkingDirectory)
565 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
80b5910f 566 if response == "y" or response == "yes":
80b5910f
SH
567 rebase = P4Rebase()
568 rebase.run([])
4f5cf76a
SH
569 os.remove(self.configFile)
570
b984733c
SH
571 return True
572
711544b0 573class P4Sync(Command):
b984733c
SH
574 def __init__(self):
575 Command.__init__(self)
576 self.options = [
577 optparse.make_option("--branch", dest="branch"),
578 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
579 optparse.make_option("--changesfile", dest="changesFile"),
580 optparse.make_option("--silent", dest="silent", action="store_true"),
ef48f909 581 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
a028a98e 582 optparse.make_option("--verbose", dest="verbose", action="store_true"),
d2c6dd30
HWN
583 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
584 help="Import into refs/heads/ , not refs/remotes"),
8b41a97f 585 optparse.make_option("--max-changes", dest="maxChanges"),
6326aa58 586 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true')
b984733c
SH
587 ]
588 self.description = """Imports from Perforce into a git repository.\n
589 example:
590 //depot/my/project/ -- to import the current head
591 //depot/my/project/@all -- to import everything
592 //depot/my/project/@1,6 -- to import only from revision 1 to 6
593
594 (a ... is not needed in the path p4 specification, it's added implicitly)"""
595
596 self.usage += " //depot/path[@revRange]"
b984733c 597 self.silent = False
b984733c
SH
598 self.createdBranches = Set()
599 self.committedChanges = Set()
569d1bd4 600 self.branch = ""
b984733c 601 self.detectBranches = False
cb53e1f8 602 self.detectLabels = False
b984733c 603 self.changesFile = ""
01265103 604 self.syncWithOrigin = True
4b97ffb1 605 self.verbose = False
a028a98e 606 self.importIntoRemotes = True
01a9c9c5 607 self.maxChanges = ""
c1f9197f 608 self.isWindows = (platform.system() == "Windows")
8b41a97f 609 self.keepRepoPath = False
6326aa58 610 self.depotPaths = None
b984733c 611
01265103
SH
612 if gitConfig("git-p4.syncFromOrigin") == "false":
613 self.syncWithOrigin = False
614
b984733c
SH
615 def extractFilesFromCommit(self, commit):
616 files = []
617 fnum = 0
618 while commit.has_key("depotFile%s" % fnum):
619 path = commit["depotFile%s" % fnum]
6326aa58
HWN
620
621 found = [p for p in self.depotPaths
622 if path.startswith (p)]
623 if not found:
b984733c
SH
624 fnum = fnum + 1
625 continue
626
627 file = {}
628 file["path"] = path
629 file["rev"] = commit["rev%s" % fnum]
630 file["action"] = commit["action%s" % fnum]
631 file["type"] = commit["type%s" % fnum]
632 files.append(file)
633 fnum = fnum + 1
634 return files
635
6326aa58 636 def stripRepoPath(self, path, prefixes):
8b41a97f 637 if self.keepRepoPath:
6326aa58
HWN
638 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
639
640 for p in prefixes:
641 if path.startswith(p):
642 path = path[len(p):]
8b41a97f 643
6326aa58 644 return path
6754a299 645
71b112d4 646 def splitFilesIntoBranches(self, commit):
d5904674 647 branches = {}
71b112d4
SH
648 fnum = 0
649 while commit.has_key("depotFile%s" % fnum):
650 path = commit["depotFile%s" % fnum]
6326aa58
HWN
651 found = [p for p in self.depotPaths
652 if path.startswith (p)]
653 if not found:
71b112d4
SH
654 fnum = fnum + 1
655 continue
656
657 file = {}
658 file["path"] = path
659 file["rev"] = commit["rev%s" % fnum]
660 file["action"] = commit["action%s" % fnum]
661 file["type"] = commit["type%s" % fnum]
662 fnum = fnum + 1
663
6326aa58 664 relPath = self.stripRepoPath(path, self.depotPaths)
b984733c 665
4b97ffb1 666 for branch in self.knownBranches.keys():
6754a299
HWN
667
668 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
669 if relPath.startswith(branch + "/"):
d5904674
SH
670 if branch not in branches:
671 branches[branch] = []
71b112d4 672 branches[branch].append(file)
b984733c
SH
673
674 return branches
675
6a49f8e2
HWN
676 ## Should move this out, doesn't use SELF.
677 def readP4Files(self, files):
982bb8a3
HWN
678 specs = [(f['path'] + "#" + f['rev'], f) for f in files
679 if f['action'] != 'delete']
6a49f8e2 680
f2eda79f
HWN
681 if not specs:
682 return
683
d2c6dd30
HWN
684 filedata = p4CmdList('print %s' % ' '.join(['"%s"' % path
685 for (path, info) in specs]))
6a49f8e2 686
d2c6dd30
HWN
687 j = 0;
688 contents = {}
689 while filedata[j:]:
690 stat = filedata[j]
691 text = filedata[j+1]
692 j += 2
6a49f8e2 693
d2c6dd30
HWN
694 assert stat['code'] == 'stat' and text['code'] == 'text'
695 contents[stat['depotFile']] = text['data']
6a49f8e2 696
d2c6dd30
HWN
697 for f in files:
698 assert not f.has_key('data')
699 f['data'] = contents[f['path']]
6a49f8e2 700
6326aa58 701 def commit(self, details, files, branch, branchPrefixes, parent = ""):
b984733c
SH
702 epoch = details["time"]
703 author = details["user"]
704
4b97ffb1
SH
705 if self.verbose:
706 print "commit into %s" % branch
707
96e07dd2
HWN
708 # start with reading files; if that fails, we should not
709 # create a commit.
710 new_files = []
711 for f in files:
712 if [p for p in branchPrefixes if f['path'].startswith(p)]:
713 new_files.append (f)
714 else:
715 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
716 files = new_files
717 self.readP4Files(files)
718
719
720
721
b984733c 722 self.gitStream.write("commit %s\n" % branch)
6a49f8e2 723# gitStream.write("mark :%s\n" % details["change"])
b984733c
SH
724 self.committedChanges.add(int(details["change"]))
725 committer = ""
b607e71e
SH
726 if author not in self.users:
727 self.getUserMapFromPerforceServer()
b984733c 728 if author in self.users:
0828ab14 729 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
b984733c 730 else:
0828ab14 731 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
b984733c
SH
732
733 self.gitStream.write("committer %s\n" % committer)
734
735 self.gitStream.write("data <<EOT\n")
736 self.gitStream.write(details["desc"])
bb6e09b2
HWN
737 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
738 "options = %s]\n"
739 % (','.join (branchPrefixes), details["change"],
740 details['options']
741 ))
b984733c
SH
742 self.gitStream.write("EOT\n\n")
743
744 if len(parent) > 0:
4b97ffb1
SH
745 if self.verbose:
746 print "parent %s" % parent
b984733c
SH
747 self.gitStream.write("from %s\n" % parent)
748
6a49f8e2 749 for file in files:
b984733c 750 if file["type"] == "apple":
6a49f8e2 751 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
b984733c
SH
752 continue
753
6a49f8e2
HWN
754 relPath = self.stripRepoPath(file['path'], branchPrefixes)
755 if file["action"] == "delete":
b984733c
SH
756 self.gitStream.write("D %s\n" % relPath)
757 else:
758 mode = 644
759 if file["type"].startswith("x"):
760 mode = 755
761
6a49f8e2 762 data = file['data']
b984733c 763
c1f9197f
MSO
764 if self.isWindows and file["type"].endswith("text"):
765 data = data.replace("\r\n", "\n")
766
b984733c
SH
767 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
768 self.gitStream.write("data %s\n" % len(data))
769 self.gitStream.write(data)
770 self.gitStream.write("\n")
771
772 self.gitStream.write("\n")
773
1f4ba1cb
SH
774 change = int(details["change"])
775
9bda3a85 776 if self.labels.has_key(change):
1f4ba1cb
SH
777 label = self.labels[change]
778 labelDetails = label[0]
779 labelRevisions = label[1]
71b112d4
SH
780 if self.verbose:
781 print "Change %s is labelled %s" % (change, labelDetails)
1f4ba1cb 782
6326aa58
HWN
783 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
784 for p in branchPrefixes]))
1f4ba1cb
SH
785
786 if len(files) == len(labelRevisions):
787
788 cleanedFiles = {}
789 for info in files:
790 if info["action"] == "delete":
791 continue
792 cleanedFiles[info["depotFile"]] = info["rev"]
793
794 if cleanedFiles == labelRevisions:
795 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
796 self.gitStream.write("from %s\n" % branch)
797
798 owner = labelDetails["Owner"]
799 tagger = ""
800 if author in self.users:
801 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
802 else:
803 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
804 self.gitStream.write("tagger %s\n" % tagger)
805 self.gitStream.write("data <<EOT\n")
806 self.gitStream.write(labelDetails["Description"])
807 self.gitStream.write("EOT\n\n")
808
809 else:
a46668fa 810 if not self.silent:
cebdf5af
HWN
811 print ("Tag %s does not match with change %s: files do not match."
812 % (labelDetails["label"], change))
1f4ba1cb
SH
813
814 else:
a46668fa 815 if not self.silent:
cebdf5af
HWN
816 print ("Tag %s does not match with change %s: file count is different."
817 % (labelDetails["label"], change))
b984733c 818
183b8ef8 819 def getUserCacheFilename(self):
a3287be5 820 return os.environ["HOME"] + "/.gitp4-usercache.txt"
183b8ef8 821
b607e71e 822 def getUserMapFromPerforceServer(self):
ebd81168
SH
823 if self.userMapFromPerforceServer:
824 return
b984733c
SH
825 self.users = {}
826
827 for output in p4CmdList("users"):
828 if not output.has_key("User"):
829 continue
830 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
831
183b8ef8
HWN
832
833 s = ''
834 for (key, val) in self.users.items():
835 s += "%s\t%s\n" % (key, val)
836
837 open(self.getUserCacheFilename(), "wb").write(s)
ebd81168 838 self.userMapFromPerforceServer = True
b607e71e
SH
839
840 def loadUserMapFromCache(self):
841 self.users = {}
ebd81168 842 self.userMapFromPerforceServer = False
b607e71e 843 try:
183b8ef8 844 cache = open(self.getUserCacheFilename(), "rb")
b607e71e
SH
845 lines = cache.readlines()
846 cache.close()
847 for line in lines:
b25b2065 848 entry = line.strip().split("\t")
b607e71e
SH
849 self.users[entry[0]] = entry[1]
850 except IOError:
851 self.getUserMapFromPerforceServer()
852
1f4ba1cb
SH
853 def getLabels(self):
854 self.labels = {}
855
6326aa58 856 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
10c3211b 857 if len(l) > 0 and not self.silent:
6326aa58 858 print "Finding files belonging to labels in %s" % `self.depotPath`
01ce1fe9
SH
859
860 for output in l:
1f4ba1cb
SH
861 label = output["label"]
862 revisions = {}
863 newestChange = 0
71b112d4
SH
864 if self.verbose:
865 print "Querying files for label %s" % label
6326aa58
HWN
866 for file in p4CmdList("files "
867 + ' '.join (["%s...@%s" % (p, label)
868 for p in self.depotPaths])):
1f4ba1cb
SH
869 revisions[file["depotFile"]] = file["rev"]
870 change = int(file["change"])
871 if change > newestChange:
872 newestChange = change
873
9bda3a85
SH
874 self.labels[newestChange] = [output, revisions]
875
876 if self.verbose:
877 print "Label changes: %s" % self.labels.keys()
1f4ba1cb 878
4b97ffb1 879 def getBranchMapping(self):
6326aa58
HWN
880
881 ## FIXME - what's a P4 projectName ?
b25b2065 882 self.projectName = self.depotPath[self.depotPath.strip().rfind("/") + 1:]
4b97ffb1
SH
883
884 for info in p4CmdList("branches"):
885 details = p4Cmd("branch -o %s" % info["branch"])
886 viewIdx = 0
887 while details.has_key("View%s" % viewIdx):
888 paths = details["View%s" % viewIdx].split(" ")
889 viewIdx = viewIdx + 1
890 # require standard //depot/foo/... //depot/bar/... mapping
891 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
892 continue
893 source = paths[0]
894 destination = paths[1]
895 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
896 source = source[len(self.depotPath):-4]
897 destination = destination[len(self.depotPath):-4]
29bdbac1
SH
898 if destination not in self.knownBranches:
899 self.knownBranches[destination] = source
900 if source not in self.knownBranches:
901 self.knownBranches[source] = source
902
903 def listExistingP4GitBranches(self):
904 self.p4BranchesInGit = []
905
a028a98e
SH
906 cmdline = "git rev-parse --symbolic "
907 if self.importIntoRemotes:
908 cmdline += " --remotes"
909 else:
910 cmdline += " --branches"
911
b016d397 912 for line in read_pipe_lines(cmdline):
cfeb59be
SH
913 line = line.strip()
914 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD"):
57284050 915 continue
b25b2065 916
57284050
SH
917 if self.importIntoRemotes:
918 # strip off p4
b76f0565
HWN
919 branch = re.sub ("^p4/", "", line)
920
57284050 921 self.p4BranchesInGit.append(branch)
b76f0565 922 self.initialParents[self.refPrefix + branch] = parseRevision(line)
4b97ffb1 923
abcd790f 924 def createOrUpdateBranchesFromOrigin(self):
d1874ed3 925 if not self.silent:
abcd790f 926 print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
d1874ed3 927
4addad22
HWN
928 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
929 line = line.strip()
d1874ed3
SH
930 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
931 continue
65c5f3e3 932
bb6e09b2 933 headName = line[len("origin/"):]
d1874ed3 934 remoteHead = self.refPrefix + headName
abcd790f
SH
935 originHead = "origin/" + headName
936
bb6e09b2
HWN
937 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
938 if (not original.has_key('depot-paths')
939 or not original.has_key('change')):
65c5f3e3
SH
940 continue
941
abcd790f 942 update = False
4280e533 943 if not gitBranchExists(remoteHead):
d1874ed3
SH
944 if self.verbose:
945 print "creating %s" % remoteHead
abcd790f
SH
946 update = True
947 else:
bb6e09b2
HWN
948 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
949 if settings.has_key('change') > 0:
950 if settings['depot-paths'] == original['depot-paths']:
951 originP4Change = int(original['change'])
952 p4Change = int(settings['change'])
abcd790f 953 if originP4Change > p4Change:
bb6e09b2
HWN
954 print ("%s (%s) is newer than %s (%s). "
955 "Updating p4 branch from origin."
956 % (originHead, originP4Change,
957 remoteHead, p4Change))
abcd790f
SH
958 update = True
959 else:
bb6e09b2
HWN
960 print ("Ignoring: %s was imported from %s while "
961 "%s was imported from %s"
962 % (originHead, ','.join(original['depot-paths']),
963 remoteHead, ','.join(settings['depot-paths'])))
abcd790f
SH
964
965 if update:
966 system("git update-ref %s %s" % (remoteHead, originHead))
d1874ed3 967
bb6e09b2
HWN
968 def updateOptionDict(self, d):
969 option_keys = {}
970 if self.keepRepoPath:
971 option_keys['keepRepoPath'] = 1
972
973 d["options"] = ' '.join(sorted(option_keys.keys()))
974
975 def readOptions(self, d):
976 self.keepRepoPath = (d.has_key('options')
977 and ('keepRepoPath' in d['options']))
6326aa58 978
b984733c 979 def run(self, args):
6326aa58 980 self.depotPaths = []
179caebf
SH
981 self.changeRange = ""
982 self.initialParent = ""
6326aa58 983 self.previousDepotPaths = []
ce6f33c8 984
29bdbac1
SH
985 # map from branch depot path to parent branch
986 self.knownBranches = {}
987 self.initialParents = {}
d414c74a 988 self.hasOrigin = gitBranchExists("origin")
29bdbac1 989
a028a98e
SH
990 if self.importIntoRemotes:
991 self.refPrefix = "refs/remotes/p4/"
992 else:
57284050 993 self.refPrefix = "refs/heads/"
a028a98e 994
cebdf5af
HWN
995 if self.syncWithOrigin and self.hasOrigin:
996 if not self.silent:
997 print "Syncing with origin first by calling git fetch origin"
998 system("git fetch origin")
10f880f8 999
569d1bd4 1000 if len(self.branch) == 0:
a028a98e
SH
1001 self.branch = self.refPrefix + "master"
1002 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
48df6fd8 1003 system("git update-ref %s refs/heads/p4" % self.branch)
48df6fd8 1004 system("git branch -D p4");
faf1bd20 1005 # create it /after/ importing, when master exists
a028a98e 1006 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
a3c55c09 1007 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
967f72e2 1008
6a49f8e2
HWN
1009 # TODO: should always look at previous commits,
1010 # merge with previous imports, if possible.
1011 if args == []:
d414c74a
SH
1012 if self.hasOrigin:
1013 self.createOrUpdateBranchesFromOrigin()
abcd790f
SH
1014 self.listExistingP4GitBranches()
1015
1016 if len(self.p4BranchesInGit) > 1:
1017 if not self.silent:
1018 print "Importing from/into multiple branches"
1019 self.detectBranches = True
967f72e2 1020
29bdbac1
SH
1021 if self.verbose:
1022 print "branches: %s" % self.p4BranchesInGit
1023
1024 p4Change = 0
1025 for branch in self.p4BranchesInGit:
cebdf5af 1026 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
bb6e09b2
HWN
1027
1028 settings = extractSettingsGitLog(logMsg)
29bdbac1 1029
bb6e09b2
HWN
1030 self.readOptions(settings)
1031 if (settings.has_key('depot-paths')
1032 and settings.has_key ('change')):
1033 change = int(settings['change']) + 1
29bdbac1
SH
1034 p4Change = max(p4Change, change)
1035
bb6e09b2
HWN
1036 depotPaths = sorted(settings['depot-paths'])
1037 if self.previousDepotPaths == []:
6326aa58 1038 self.previousDepotPaths = depotPaths
29bdbac1 1039 else:
6326aa58
HWN
1040 paths = []
1041 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1042 for i in range(0, max(len(cur), len(prev))):
1043 if cur[i] <> prev[i]:
1044 break
1045
1046 paths.append (cur[:i])
1047
1048 self.previousDepotPaths = paths
29bdbac1
SH
1049
1050 if p4Change > 0:
bb6e09b2 1051 self.depotPaths = sorted(self.previousDepotPaths)
d5904674 1052 self.changeRange = "@%s,#head" % p4Change
463e8af6 1053 self.initialParent = parseRevision(self.branch)
341dc1c1 1054 if not self.silent and not self.detectBranches:
967f72e2 1055 print "Performing incremental import into %s git branch" % self.branch
569d1bd4 1056
f9162f6a
SH
1057 if not self.branch.startswith("refs/"):
1058 self.branch = "refs/heads/" + self.branch
179caebf 1059
6326aa58 1060 if len(args) == 0 and self.depotPaths:
b984733c 1061 if not self.silent:
6326aa58 1062 print "Depot paths: %s" % ' '.join(self.depotPaths)
b984733c 1063 else:
6326aa58 1064 if self.depotPaths and self.depotPaths != args:
cebdf5af 1065 print ("previous import used depot path %s and now %s was specified. "
6326aa58
HWN
1066 "This doesn't work!" % (' '.join (self.depotPaths),
1067 ' '.join (args)))
b984733c 1068 sys.exit(1)
6326aa58 1069
bb6e09b2 1070 self.depotPaths = sorted(args)
b984733c 1071
b984733c
SH
1072 self.revision = ""
1073 self.users = {}
b984733c 1074
6326aa58
HWN
1075 newPaths = []
1076 for p in self.depotPaths:
1077 if p.find("@") != -1:
1078 atIdx = p.index("@")
1079 self.changeRange = p[atIdx:]
1080 if self.changeRange == "@all":
1081 self.changeRange = ""
6a49f8e2 1082 elif ',' not in self.changeRange:
6326aa58
HWN
1083 self.revision = self.changeRange
1084 self.changeRange = ""
1085 p = p[0:atIdx]
1086 elif p.find("#") != -1:
1087 hashIdx = p.index("#")
1088 self.revision = p[hashIdx:]
1089 p = p[0:hashIdx]
1090 elif self.previousDepotPaths == []:
1091 self.revision = "#head"
1092
1093 p = re.sub ("\.\.\.$", "", p)
1094 if not p.endswith("/"):
1095 p += "/"
1096
1097 newPaths.append(p)
1098
1099 self.depotPaths = newPaths
1100
b984733c 1101
b607e71e 1102 self.loadUserMapFromCache()
cb53e1f8
SH
1103 self.labels = {}
1104 if self.detectLabels:
1105 self.getLabels();
b984733c 1106
4b97ffb1
SH
1107 if self.detectBranches:
1108 self.getBranchMapping();
29bdbac1
SH
1109 if self.verbose:
1110 print "p4-git branches: %s" % self.p4BranchesInGit
1111 print "initial parents: %s" % self.initialParents
1112 for b in self.p4BranchesInGit:
1113 if b != "master":
6326aa58
HWN
1114
1115 ## FIXME
29bdbac1
SH
1116 b = b[len(self.projectName):]
1117 self.createdBranches.add(b)
4b97ffb1 1118
f291b4e3 1119 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
b984733c 1120
cebdf5af 1121 importProcess = subprocess.Popen(["git", "fast-import"],
6326aa58
HWN
1122 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1123 stderr=subprocess.PIPE);
08483580
SH
1124 self.gitOutput = importProcess.stdout
1125 self.gitStream = importProcess.stdin
1126 self.gitError = importProcess.stderr
b984733c
SH
1127
1128 if len(self.revision) > 0:
6326aa58 1129 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
b984733c
SH
1130
1131 details = { "user" : "git perforce import user", "time" : int(time.time()) }
cebdf5af 1132 details["desc"] = ("Initial import of %s from the state at revision %s"
6326aa58 1133 % (' '.join(self.depotPaths), self.revision))
b984733c
SH
1134 details["change"] = self.revision
1135 newestRevision = 0
1136
1137 fileCnt = 0
6326aa58
HWN
1138 for info in p4CmdList("files "
1139 + ' '.join(["%s...%s"
1140 % (p, self.revision)
1141 for p in self.depotPaths])):
96e07dd2 1142
d2c6dd30
HWN
1143 if info['code'] == 'error':
1144 sys.stderr.write("p4 returned an error: %s\n"
1145 % info['data'])
1146 sys.exit(1)
1147
1148
b984733c
SH
1149 change = int(info["change"])
1150 if change > newestRevision:
1151 newestRevision = change
1152
1153 if info["action"] == "delete":
c45b1cfe
SH
1154 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1155 #fileCnt = fileCnt + 1
b984733c
SH
1156 continue
1157
96e07dd2 1158 for prop in ["depotFile", "rev", "action", "type" ]:
b984733c
SH
1159 details["%s%s" % (prop, fileCnt)] = info[prop]
1160
1161 fileCnt = fileCnt + 1
1162
1163 details["change"] = newestRevision
bb6e09b2 1164 self.updateOptionDict(details)
b984733c 1165 try:
6326aa58 1166 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
c715706b 1167 except IOError:
fd4ca86a 1168 print "IO error with git fast-import. Is your git version recent enough?"
b984733c
SH
1169 print self.gitError.read()
1170
1171 else:
1172 changes = []
1173
0828ab14 1174 if len(self.changesFile) > 0:
b984733c
SH
1175 output = open(self.changesFile).readlines()
1176 changeSet = Set()
1177 for line in output:
1178 changeSet.add(int(line))
1179
1180 for change in changeSet:
1181 changes.append(change)
1182
1183 changes.sort()
1184 else:
29bdbac1 1185 if self.verbose:
6326aa58
HWN
1186 print "Getting p4 changes for %s...%s" % (`self.depotPaths`,
1187 self.changeRange)
1188 assert self.depotPaths
1189 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1190 for p in self.depotPaths]))
b984733c
SH
1191
1192 for line in output:
1193 changeNum = line.split(" ")[1]
1194 changes.append(changeNum)
1195
1196 changes.reverse()
1197
01a9c9c5
SH
1198 if len(self.maxChanges) > 0:
1199 changes = changes[0:min(int(self.maxChanges), len(changes))]
1200
b984733c 1201 if len(changes) == 0:
0828ab14 1202 if not self.silent:
341dc1c1 1203 print "No changes to import!"
1f52af6c 1204 return True
b984733c 1205
341dc1c1
SH
1206 self.updatedBranches = set()
1207
b984733c
SH
1208 cnt = 1
1209 for change in changes:
1210 description = p4Cmd("describe %s" % change)
bb6e09b2 1211 self.updateOptionDict(description)
b984733c 1212
0828ab14 1213 if not self.silent:
341dc1c1 1214 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
b984733c
SH
1215 sys.stdout.flush()
1216 cnt = cnt + 1
1217
1218 try:
b984733c 1219 if self.detectBranches:
71b112d4 1220 branches = self.splitFilesIntoBranches(description)
d5904674 1221 for branch in branches.keys():
6326aa58
HWN
1222 ## HACK --hwn
1223 branchPrefix = self.depotPaths[0] + branch + "/"
b984733c 1224
b984733c 1225 parent = ""
4b97ffb1 1226
d5904674 1227 filesForCommit = branches[branch]
4b97ffb1 1228
29bdbac1
SH
1229 if self.verbose:
1230 print "branch is %s" % branch
1231
341dc1c1
SH
1232 self.updatedBranches.add(branch)
1233
8f9b2e08 1234 if branch not in self.createdBranches:
b984733c 1235 self.createdBranches.add(branch)
4b97ffb1 1236 parent = self.knownBranches[branch]
b984733c
SH
1237 if parent == branch:
1238 parent = ""
29bdbac1
SH
1239 elif self.verbose:
1240 print "parent determined through known branches: %s" % parent
b984733c 1241
8f9b2e08
SH
1242 # main branch? use master
1243 if branch == "main":
1244 branch = "master"
1245 else:
6326aa58
HWN
1246
1247 ## FIXME
29bdbac1 1248 branch = self.projectName + branch
8f9b2e08
SH
1249
1250 if parent == "main":
1251 parent = "master"
1252 elif len(parent) > 0:
6326aa58 1253 ## FIXME
29bdbac1 1254 parent = self.projectName + parent
8f9b2e08 1255
a028a98e 1256 branch = self.refPrefix + branch
b984733c 1257 if len(parent) > 0:
a028a98e 1258 parent = self.refPrefix + parent
29bdbac1
SH
1259
1260 if self.verbose:
1261 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1262
1263 if len(parent) == 0 and branch in self.initialParents:
1264 parent = self.initialParents[branch]
1265 del self.initialParents[branch]
1266
71b112d4 1267 self.commit(description, filesForCommit, branch, branchPrefix, parent)
b984733c 1268 else:
71b112d4 1269 files = self.extractFilesFromCommit(description)
6326aa58
HWN
1270 self.commit(description, files, self.branch, self.depotPaths,
1271 self.initialParent)
b984733c
SH
1272 self.initialParent = ""
1273 except IOError:
1274 print self.gitError.read()
1275 sys.exit(1)
1276
341dc1c1
SH
1277 if not self.silent:
1278 print ""
1279 if len(self.updatedBranches) > 0:
1280 sys.stdout.write("Updated branches: ")
1281 for b in self.updatedBranches:
1282 sys.stdout.write("%s " % b)
1283 sys.stdout.write("\n")
b984733c 1284
b984733c
SH
1285
1286 self.gitStream.close()
29bdbac1
SH
1287 if importProcess.wait() != 0:
1288 die("fast-import failed: %s" % self.gitError.read())
b984733c
SH
1289 self.gitOutput.close()
1290 self.gitError.close()
1291
b984733c
SH
1292 return True
1293
01ce1fe9
SH
1294class P4Rebase(Command):
1295 def __init__(self):
1296 Command.__init__(self)
01265103 1297 self.options = [ ]
cebdf5af
HWN
1298 self.description = ("Fetches the latest revision from perforce and "
1299 + "rebases the current work (branch) against it")
01ce1fe9
SH
1300
1301 def run(self, args):
1302 sync = P4Sync()
1303 sync.run([])
1304 print "Rebasing the current branch"
b25b2065 1305 oldHead = read_pipe("git rev-parse HEAD").strip()
01ce1fe9 1306 system("git rebase p4")
1f52af6c 1307 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
01ce1fe9
SH
1308 return True
1309
f9a3a4f7
SH
1310class P4Clone(P4Sync):
1311 def __init__(self):
1312 P4Sync.__init__(self)
1313 self.description = "Creates a new git repository and imports from Perforce into it"
bb6e09b2
HWN
1314 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1315 self.options.append(
1316 optparse.make_option("--destination", dest="cloneDestination",
1317 action='store', default=None,
1318 help="where to leave result of the clone"))
1319 self.cloneDestination = None
f9a3a4f7 1320 self.needsGit = False
f9a3a4f7 1321
6a49f8e2
HWN
1322 def defaultDestination(self, args):
1323 ## TODO: use common prefix of args?
1324 depotPath = args[0]
1325 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1326 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1327 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1328 depotDir = re.sub(r"/$", "", depotDir)
1329 return os.path.split(depotDir)[1]
1330
f9a3a4f7
SH
1331 def run(self, args):
1332 if len(args) < 1:
1333 return False
bb6e09b2
HWN
1334
1335 if self.keepRepoPath and not self.cloneDestination:
1336 sys.stderr.write("Must specify destination for --keep-path\n")
1337 sys.exit(1)
f9a3a4f7 1338
6326aa58
HWN
1339 depotPaths = args
1340 for p in depotPaths:
1341 if not p.startswith("//"):
1342 return False
f9a3a4f7 1343
bb6e09b2 1344 if not self.cloneDestination:
6a49f8e2 1345 self.cloneDestination = self.defaultDestination()
f9a3a4f7 1346
bb6e09b2
HWN
1347 print "Importing from %s into %s" % (`depotPaths`, self.cloneDestination)
1348 os.makedirs(self.cloneDestination)
1349 os.chdir(self.cloneDestination)
f9a3a4f7 1350 system("git init")
b86f7378 1351 self.gitdir = os.getcwd() + "/.git"
6326aa58 1352 if not P4Sync.run(self, depotPaths):
f9a3a4f7 1353 return False
f9a3a4f7 1354 if self.branch != "master":
8f9b2e08
SH
1355 if gitBranchExists("refs/remotes/p4/master"):
1356 system("git branch master refs/remotes/p4/master")
1357 system("git checkout -f")
1358 else:
1359 print "Could not detect main branch. No checkout/master branch created."
f9a3a4f7
SH
1360 return True
1361
b984733c
SH
1362class HelpFormatter(optparse.IndentedHelpFormatter):
1363 def __init__(self):
1364 optparse.IndentedHelpFormatter.__init__(self)
1365
1366 def format_description(self, description):
1367 if description:
1368 return description + "\n"
1369 else:
1370 return ""
4f5cf76a 1371
86949eef
SH
1372def printUsage(commands):
1373 print "usage: %s <command> [options]" % sys.argv[0]
1374 print ""
1375 print "valid commands: %s" % ", ".join(commands)
1376 print ""
1377 print "Try %s <command> --help for command specific help." % sys.argv[0]
1378 print ""
1379
1380commands = {
b86f7378
HWN
1381 "debug" : P4Debug,
1382 "submit" : P4Submit,
1383 "sync" : P4Sync,
1384 "rebase" : P4Rebase,
1385 "clone" : P4Clone,
1386 "rollback" : P4RollBack
86949eef
SH
1387}
1388
86949eef 1389
bb6e09b2
HWN
1390def main():
1391 if len(sys.argv[1:]) == 0:
1392 printUsage(commands.keys())
1393 sys.exit(2)
4f5cf76a 1394
bb6e09b2
HWN
1395 cmd = ""
1396 cmdName = sys.argv[1]
1397 try:
b86f7378
HWN
1398 klass = commands[cmdName]
1399 cmd = klass()
bb6e09b2
HWN
1400 except KeyError:
1401 print "unknown command %s" % cmdName
1402 print ""
1403 printUsage(commands.keys())
1404 sys.exit(2)
1405
1406 options = cmd.options
b86f7378 1407 cmd.gitdir = os.environ.get("GIT_DIR", None)
bb6e09b2
HWN
1408
1409 args = sys.argv[2:]
1410
1411 if len(options) > 0:
1412 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1413
1414 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1415 options,
1416 description = cmd.description,
1417 formatter = HelpFormatter())
1418
1419 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1420 global verbose
1421 verbose = cmd.verbose
1422 if cmd.needsGit:
b86f7378
HWN
1423 if cmd.gitdir == None:
1424 cmd.gitdir = os.path.abspath(".git")
1425 if not isValidGitDir(cmd.gitdir):
1426 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1427 if os.path.exists(cmd.gitdir):
bb6e09b2
HWN
1428 cdup = read_pipe("git rev-parse --show-cdup").strip()
1429 if len(cdup) > 0:
1430 os.chdir(cdup);
e20a9e53 1431
b86f7378
HWN
1432 if not isValidGitDir(cmd.gitdir):
1433 if isValidGitDir(cmd.gitdir + "/.git"):
1434 cmd.gitdir += "/.git"
bb6e09b2 1435 else:
b86f7378 1436 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
e20a9e53 1437
b86f7378 1438 os.environ["GIT_DIR"] = cmd.gitdir
86949eef 1439
bb6e09b2
HWN
1440 if not cmd.run(args):
1441 parser.print_help()
4f5cf76a 1442
4f5cf76a 1443
bb6e09b2
HWN
1444if __name__ == '__main__':
1445 main()