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