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