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