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