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