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