PageRenderTime 38ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/git-p4.py

https://bitbucket.org/nbargnesi/git
Python | 3297 lines | 3146 code | 78 blank | 73 comment | 170 complexity | 2bd29f330a41bc7e555643acbb4e1742 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, BSD-2-Clause
  1. #!/usr/bin/env python
  2. #
  3. # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
  4. #
  5. # Author: Simon Hausmann <simon@lst.de>
  6. # Copyright: 2007 Simon Hausmann <simon@lst.de>
  7. # 2007 Trolltech ASA
  8. # License: MIT <http://www.opensource.org/licenses/mit-license.php>
  9. #
  10. import sys
  11. if sys.hexversion < 0x02040000:
  12. # The limiter is the subprocess module
  13. sys.stderr.write("git-p4: requires Python 2.4 or later.\n")
  14. sys.exit(1)
  15. import os
  16. import optparse
  17. import marshal
  18. import subprocess
  19. import tempfile
  20. import time
  21. import platform
  22. import re
  23. import shutil
  24. import stat
  25. try:
  26. from subprocess import CalledProcessError
  27. except ImportError:
  28. # from python2.7:subprocess.py
  29. # Exception classes used by this module.
  30. class CalledProcessError(Exception):
  31. """This exception is raised when a process run by check_call() returns
  32. a non-zero exit status. The exit status will be stored in the
  33. returncode attribute."""
  34. def __init__(self, returncode, cmd):
  35. self.returncode = returncode
  36. self.cmd = cmd
  37. def __str__(self):
  38. return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  39. verbose = False
  40. # Only labels/tags matching this will be imported/exported
  41. defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
  42. def p4_build_cmd(cmd):
  43. """Build a suitable p4 command line.
  44. This consolidates building and returning a p4 command line into one
  45. location. It means that hooking into the environment, or other configuration
  46. can be done more easily.
  47. """
  48. real_cmd = ["p4"]
  49. user = gitConfig("git-p4.user")
  50. if len(user) > 0:
  51. real_cmd += ["-u",user]
  52. password = gitConfig("git-p4.password")
  53. if len(password) > 0:
  54. real_cmd += ["-P", password]
  55. port = gitConfig("git-p4.port")
  56. if len(port) > 0:
  57. real_cmd += ["-p", port]
  58. host = gitConfig("git-p4.host")
  59. if len(host) > 0:
  60. real_cmd += ["-H", host]
  61. client = gitConfig("git-p4.client")
  62. if len(client) > 0:
  63. real_cmd += ["-c", client]
  64. if isinstance(cmd,basestring):
  65. real_cmd = ' '.join(real_cmd) + ' ' + cmd
  66. else:
  67. real_cmd += cmd
  68. return real_cmd
  69. def chdir(path, is_client_path=False):
  70. """Do chdir to the given path, and set the PWD environment
  71. variable for use by P4. It does not look at getcwd() output.
  72. Since we're not using the shell, it is necessary to set the
  73. PWD environment variable explicitly.
  74. Normally, expand the path to force it to be absolute. This
  75. addresses the use of relative path names inside P4 settings,
  76. e.g. P4CONFIG=.p4config. P4 does not simply open the filename
  77. as given; it looks for .p4config using PWD.
  78. If is_client_path, the path was handed to us directly by p4,
  79. and may be a symbolic link. Do not call os.getcwd() in this
  80. case, because it will cause p4 to think that PWD is not inside
  81. the client path.
  82. """
  83. os.chdir(path)
  84. if not is_client_path:
  85. path = os.getcwd()
  86. os.environ['PWD'] = path
  87. def die(msg):
  88. if verbose:
  89. raise Exception(msg)
  90. else:
  91. sys.stderr.write(msg + "\n")
  92. sys.exit(1)
  93. def write_pipe(c, stdin):
  94. if verbose:
  95. sys.stderr.write('Writing pipe: %s\n' % str(c))
  96. expand = isinstance(c,basestring)
  97. p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
  98. pipe = p.stdin
  99. val = pipe.write(stdin)
  100. pipe.close()
  101. if p.wait():
  102. die('Command failed: %s' % str(c))
  103. return val
  104. def p4_write_pipe(c, stdin):
  105. real_cmd = p4_build_cmd(c)
  106. return write_pipe(real_cmd, stdin)
  107. def read_pipe(c, ignore_error=False):
  108. if verbose:
  109. sys.stderr.write('Reading pipe: %s\n' % str(c))
  110. expand = isinstance(c,basestring)
  111. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  112. pipe = p.stdout
  113. val = pipe.read()
  114. if p.wait() and not ignore_error:
  115. die('Command failed: %s' % str(c))
  116. return val
  117. def p4_read_pipe(c, ignore_error=False):
  118. real_cmd = p4_build_cmd(c)
  119. return read_pipe(real_cmd, ignore_error)
  120. def read_pipe_lines(c):
  121. if verbose:
  122. sys.stderr.write('Reading pipe: %s\n' % str(c))
  123. expand = isinstance(c, basestring)
  124. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  125. pipe = p.stdout
  126. val = pipe.readlines()
  127. if pipe.close() or p.wait():
  128. die('Command failed: %s' % str(c))
  129. return val
  130. def p4_read_pipe_lines(c):
  131. """Specifically invoke p4 on the command supplied. """
  132. real_cmd = p4_build_cmd(c)
  133. return read_pipe_lines(real_cmd)
  134. def p4_has_command(cmd):
  135. """Ask p4 for help on this command. If it returns an error, the
  136. command does not exist in this version of p4."""
  137. real_cmd = p4_build_cmd(["help", cmd])
  138. p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
  139. stderr=subprocess.PIPE)
  140. p.communicate()
  141. return p.returncode == 0
  142. def p4_has_move_command():
  143. """See if the move command exists, that it supports -k, and that
  144. it has not been administratively disabled. The arguments
  145. must be correct, but the filenames do not have to exist. Use
  146. ones with wildcards so even if they exist, it will fail."""
  147. if not p4_has_command("move"):
  148. return False
  149. cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
  150. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  151. (out, err) = p.communicate()
  152. # return code will be 1 in either case
  153. if err.find("Invalid option") >= 0:
  154. return False
  155. if err.find("disabled") >= 0:
  156. return False
  157. # assume it failed because @... was invalid changelist
  158. return True
  159. def system(cmd):
  160. expand = isinstance(cmd,basestring)
  161. if verbose:
  162. sys.stderr.write("executing %s\n" % str(cmd))
  163. retcode = subprocess.call(cmd, shell=expand)
  164. if retcode:
  165. raise CalledProcessError(retcode, cmd)
  166. def p4_system(cmd):
  167. """Specifically invoke p4 as the system command. """
  168. real_cmd = p4_build_cmd(cmd)
  169. expand = isinstance(real_cmd, basestring)
  170. retcode = subprocess.call(real_cmd, shell=expand)
  171. if retcode:
  172. raise CalledProcessError(retcode, real_cmd)
  173. _p4_version_string = None
  174. def p4_version_string():
  175. """Read the version string, showing just the last line, which
  176. hopefully is the interesting version bit.
  177. $ p4 -V
  178. Perforce - The Fast Software Configuration Management System.
  179. Copyright 1995-2011 Perforce Software. All rights reserved.
  180. Rev. P4/NTX86/2011.1/393975 (2011/12/16).
  181. """
  182. global _p4_version_string
  183. if not _p4_version_string:
  184. a = p4_read_pipe_lines(["-V"])
  185. _p4_version_string = a[-1].rstrip()
  186. return _p4_version_string
  187. def p4_integrate(src, dest):
  188. p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
  189. def p4_sync(f, *options):
  190. p4_system(["sync"] + list(options) + [wildcard_encode(f)])
  191. def p4_add(f):
  192. # forcibly add file names with wildcards
  193. if wildcard_present(f):
  194. p4_system(["add", "-f", f])
  195. else:
  196. p4_system(["add", f])
  197. def p4_delete(f):
  198. p4_system(["delete", wildcard_encode(f)])
  199. def p4_edit(f):
  200. p4_system(["edit", wildcard_encode(f)])
  201. def p4_revert(f):
  202. p4_system(["revert", wildcard_encode(f)])
  203. def p4_reopen(type, f):
  204. p4_system(["reopen", "-t", type, wildcard_encode(f)])
  205. def p4_move(src, dest):
  206. p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
  207. def p4_describe(change):
  208. """Make sure it returns a valid result by checking for
  209. the presence of field "time". Return a dict of the
  210. results."""
  211. ds = p4CmdList(["describe", "-s", str(change)])
  212. if len(ds) != 1:
  213. die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
  214. d = ds[0]
  215. if "p4ExitCode" in d:
  216. die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
  217. str(d)))
  218. if "code" in d:
  219. if d["code"] == "error":
  220. die("p4 describe -s %d returned error code: %s" % (change, str(d)))
  221. if "time" not in d:
  222. die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
  223. return d
  224. #
  225. # Canonicalize the p4 type and return a tuple of the
  226. # base type, plus any modifiers. See "p4 help filetypes"
  227. # for a list and explanation.
  228. #
  229. def split_p4_type(p4type):
  230. p4_filetypes_historical = {
  231. "ctempobj": "binary+Sw",
  232. "ctext": "text+C",
  233. "cxtext": "text+Cx",
  234. "ktext": "text+k",
  235. "kxtext": "text+kx",
  236. "ltext": "text+F",
  237. "tempobj": "binary+FSw",
  238. "ubinary": "binary+F",
  239. "uresource": "resource+F",
  240. "uxbinary": "binary+Fx",
  241. "xbinary": "binary+x",
  242. "xltext": "text+Fx",
  243. "xtempobj": "binary+Swx",
  244. "xtext": "text+x",
  245. "xunicode": "unicode+x",
  246. "xutf16": "utf16+x",
  247. }
  248. if p4type in p4_filetypes_historical:
  249. p4type = p4_filetypes_historical[p4type]
  250. mods = ""
  251. s = p4type.split("+")
  252. base = s[0]
  253. mods = ""
  254. if len(s) > 1:
  255. mods = s[1]
  256. return (base, mods)
  257. #
  258. # return the raw p4 type of a file (text, text+ko, etc)
  259. #
  260. def p4_type(f):
  261. results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
  262. return results[0]['headType']
  263. #
  264. # Given a type base and modifier, return a regexp matching
  265. # the keywords that can be expanded in the file
  266. #
  267. def p4_keywords_regexp_for_type(base, type_mods):
  268. if base in ("text", "unicode", "binary"):
  269. kwords = None
  270. if "ko" in type_mods:
  271. kwords = 'Id|Header'
  272. elif "k" in type_mods:
  273. kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
  274. else:
  275. return None
  276. pattern = r"""
  277. \$ # Starts with a dollar, followed by...
  278. (%s) # one of the keywords, followed by...
  279. (:[^$\n]+)? # possibly an old expansion, followed by...
  280. \$ # another dollar
  281. """ % kwords
  282. return pattern
  283. else:
  284. return None
  285. #
  286. # Given a file, return a regexp matching the possible
  287. # RCS keywords that will be expanded, or None for files
  288. # with kw expansion turned off.
  289. #
  290. def p4_keywords_regexp_for_file(file):
  291. if not os.path.exists(file):
  292. return None
  293. else:
  294. (type_base, type_mods) = split_p4_type(p4_type(file))
  295. return p4_keywords_regexp_for_type(type_base, type_mods)
  296. def setP4ExecBit(file, mode):
  297. # Reopens an already open file and changes the execute bit to match
  298. # the execute bit setting in the passed in mode.
  299. p4Type = "+x"
  300. if not isModeExec(mode):
  301. p4Type = getP4OpenedType(file)
  302. p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
  303. p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
  304. if p4Type[-1] == "+":
  305. p4Type = p4Type[0:-1]
  306. p4_reopen(p4Type, file)
  307. def getP4OpenedType(file):
  308. # Returns the perforce file type for the given file.
  309. result = p4_read_pipe(["opened", wildcard_encode(file)])
  310. match = re.match(".*\((.+)\)\r?$", result)
  311. if match:
  312. return match.group(1)
  313. else:
  314. die("Could not determine file type for %s (result: '%s')" % (file, result))
  315. # Return the set of all p4 labels
  316. def getP4Labels(depotPaths):
  317. labels = set()
  318. if isinstance(depotPaths,basestring):
  319. depotPaths = [depotPaths]
  320. for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
  321. label = l['label']
  322. labels.add(label)
  323. return labels
  324. # Return the set of all git tags
  325. def getGitTags():
  326. gitTags = set()
  327. for line in read_pipe_lines(["git", "tag"]):
  328. tag = line.strip()
  329. gitTags.add(tag)
  330. return gitTags
  331. def diffTreePattern():
  332. # This is a simple generator for the diff tree regex pattern. This could be
  333. # a class variable if this and parseDiffTreeEntry were a part of a class.
  334. pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
  335. while True:
  336. yield pattern
  337. def parseDiffTreeEntry(entry):
  338. """Parses a single diff tree entry into its component elements.
  339. See git-diff-tree(1) manpage for details about the format of the diff
  340. output. This method returns a dictionary with the following elements:
  341. src_mode - The mode of the source file
  342. dst_mode - The mode of the destination file
  343. src_sha1 - The sha1 for the source file
  344. dst_sha1 - The sha1 fr the destination file
  345. status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
  346. status_score - The score for the status (applicable for 'C' and 'R'
  347. statuses). This is None if there is no score.
  348. src - The path for the source file.
  349. dst - The path for the destination file. This is only present for
  350. copy or renames. If it is not present, this is None.
  351. If the pattern is not matched, None is returned."""
  352. match = diffTreePattern().next().match(entry)
  353. if match:
  354. return {
  355. 'src_mode': match.group(1),
  356. 'dst_mode': match.group(2),
  357. 'src_sha1': match.group(3),
  358. 'dst_sha1': match.group(4),
  359. 'status': match.group(5),
  360. 'status_score': match.group(6),
  361. 'src': match.group(7),
  362. 'dst': match.group(10)
  363. }
  364. return None
  365. def isModeExec(mode):
  366. # Returns True if the given git mode represents an executable file,
  367. # otherwise False.
  368. return mode[-3:] == "755"
  369. def isModeExecChanged(src_mode, dst_mode):
  370. return isModeExec(src_mode) != isModeExec(dst_mode)
  371. def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
  372. if isinstance(cmd,basestring):
  373. cmd = "-G " + cmd
  374. expand = True
  375. else:
  376. cmd = ["-G"] + cmd
  377. expand = False
  378. cmd = p4_build_cmd(cmd)
  379. if verbose:
  380. sys.stderr.write("Opening pipe: %s\n" % str(cmd))
  381. # Use a temporary file to avoid deadlocks without
  382. # subprocess.communicate(), which would put another copy
  383. # of stdout into memory.
  384. stdin_file = None
  385. if stdin is not None:
  386. stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
  387. if isinstance(stdin,basestring):
  388. stdin_file.write(stdin)
  389. else:
  390. for i in stdin:
  391. stdin_file.write(i + '\n')
  392. stdin_file.flush()
  393. stdin_file.seek(0)
  394. p4 = subprocess.Popen(cmd,
  395. shell=expand,
  396. stdin=stdin_file,
  397. stdout=subprocess.PIPE)
  398. result = []
  399. try:
  400. while True:
  401. entry = marshal.load(p4.stdout)
  402. if cb is not None:
  403. cb(entry)
  404. else:
  405. result.append(entry)
  406. except EOFError:
  407. pass
  408. exitCode = p4.wait()
  409. if exitCode != 0:
  410. entry = {}
  411. entry["p4ExitCode"] = exitCode
  412. result.append(entry)
  413. return result
  414. def p4Cmd(cmd):
  415. list = p4CmdList(cmd)
  416. result = {}
  417. for entry in list:
  418. result.update(entry)
  419. return result;
  420. def p4Where(depotPath):
  421. if not depotPath.endswith("/"):
  422. depotPath += "/"
  423. depotPath = depotPath + "..."
  424. outputList = p4CmdList(["where", depotPath])
  425. output = None
  426. for entry in outputList:
  427. if "depotFile" in entry:
  428. if entry["depotFile"] == depotPath:
  429. output = entry
  430. break
  431. elif "data" in entry:
  432. data = entry.get("data")
  433. space = data.find(" ")
  434. if data[:space] == depotPath:
  435. output = entry
  436. break
  437. if output == None:
  438. return ""
  439. if output["code"] == "error":
  440. return ""
  441. clientPath = ""
  442. if "path" in output:
  443. clientPath = output.get("path")
  444. elif "data" in output:
  445. data = output.get("data")
  446. lastSpace = data.rfind(" ")
  447. clientPath = data[lastSpace + 1:]
  448. if clientPath.endswith("..."):
  449. clientPath = clientPath[:-3]
  450. return clientPath
  451. def currentGitBranch():
  452. return read_pipe("git name-rev HEAD").split(" ")[1].strip()
  453. def isValidGitDir(path):
  454. if (os.path.exists(path + "/HEAD")
  455. and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
  456. return True;
  457. return False
  458. def parseRevision(ref):
  459. return read_pipe("git rev-parse %s" % ref).strip()
  460. def branchExists(ref):
  461. rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
  462. ignore_error=True)
  463. return len(rev) > 0
  464. def extractLogMessageFromGitCommit(commit):
  465. logMessage = ""
  466. ## fixme: title is first line of commit, not 1st paragraph.
  467. foundTitle = False
  468. for log in read_pipe_lines("git cat-file commit %s" % commit):
  469. if not foundTitle:
  470. if len(log) == 1:
  471. foundTitle = True
  472. continue
  473. logMessage += log
  474. return logMessage
  475. def extractSettingsGitLog(log):
  476. values = {}
  477. for line in log.split("\n"):
  478. line = line.strip()
  479. m = re.search (r"^ *\[git-p4: (.*)\]$", line)
  480. if not m:
  481. continue
  482. assignments = m.group(1).split (':')
  483. for a in assignments:
  484. vals = a.split ('=')
  485. key = vals[0].strip()
  486. val = ('='.join (vals[1:])).strip()
  487. if val.endswith ('\"') and val.startswith('"'):
  488. val = val[1:-1]
  489. values[key] = val
  490. paths = values.get("depot-paths")
  491. if not paths:
  492. paths = values.get("depot-path")
  493. if paths:
  494. values['depot-paths'] = paths.split(',')
  495. return values
  496. def gitBranchExists(branch):
  497. proc = subprocess.Popen(["git", "rev-parse", branch],
  498. stderr=subprocess.PIPE, stdout=subprocess.PIPE);
  499. return proc.wait() == 0;
  500. _gitConfig = {}
  501. def gitConfig(key):
  502. if not _gitConfig.has_key(key):
  503. cmd = [ "git", "config", key ]
  504. s = read_pipe(cmd, ignore_error=True)
  505. _gitConfig[key] = s.strip()
  506. return _gitConfig[key]
  507. def gitConfigBool(key):
  508. """Return a bool, using git config --bool. It is True only if the
  509. variable is set to true, and False if set to false or not present
  510. in the config."""
  511. if not _gitConfig.has_key(key):
  512. cmd = [ "git", "config", "--bool", key ]
  513. s = read_pipe(cmd, ignore_error=True)
  514. v = s.strip()
  515. _gitConfig[key] = v == "true"
  516. return _gitConfig[key]
  517. def gitConfigList(key):
  518. if not _gitConfig.has_key(key):
  519. s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
  520. _gitConfig[key] = s.strip().split(os.linesep)
  521. return _gitConfig[key]
  522. def p4BranchesInGit(branchesAreInRemotes=True):
  523. """Find all the branches whose names start with "p4/", looking
  524. in remotes or heads as specified by the argument. Return
  525. a dictionary of { branch: revision } for each one found.
  526. The branch names are the short names, without any
  527. "p4/" prefix."""
  528. branches = {}
  529. cmdline = "git rev-parse --symbolic "
  530. if branchesAreInRemotes:
  531. cmdline += "--remotes"
  532. else:
  533. cmdline += "--branches"
  534. for line in read_pipe_lines(cmdline):
  535. line = line.strip()
  536. # only import to p4/
  537. if not line.startswith('p4/'):
  538. continue
  539. # special symbolic ref to p4/master
  540. if line == "p4/HEAD":
  541. continue
  542. # strip off p4/ prefix
  543. branch = line[len("p4/"):]
  544. branches[branch] = parseRevision(line)
  545. return branches
  546. def branch_exists(branch):
  547. """Make sure that the given ref name really exists."""
  548. cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
  549. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  550. out, _ = p.communicate()
  551. if p.returncode:
  552. return False
  553. # expect exactly one line of output: the branch name
  554. return out.rstrip() == branch
  555. def findUpstreamBranchPoint(head = "HEAD"):
  556. branches = p4BranchesInGit()
  557. # map from depot-path to branch name
  558. branchByDepotPath = {}
  559. for branch in branches.keys():
  560. tip = branches[branch]
  561. log = extractLogMessageFromGitCommit(tip)
  562. settings = extractSettingsGitLog(log)
  563. if settings.has_key("depot-paths"):
  564. paths = ",".join(settings["depot-paths"])
  565. branchByDepotPath[paths] = "remotes/p4/" + branch
  566. settings = None
  567. parent = 0
  568. while parent < 65535:
  569. commit = head + "~%s" % parent
  570. log = extractLogMessageFromGitCommit(commit)
  571. settings = extractSettingsGitLog(log)
  572. if settings.has_key("depot-paths"):
  573. paths = ",".join(settings["depot-paths"])
  574. if branchByDepotPath.has_key(paths):
  575. return [branchByDepotPath[paths], settings]
  576. parent = parent + 1
  577. return ["", settings]
  578. def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
  579. if not silent:
  580. print ("Creating/updating branch(es) in %s based on origin branch(es)"
  581. % localRefPrefix)
  582. originPrefix = "origin/p4/"
  583. for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
  584. line = line.strip()
  585. if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
  586. continue
  587. headName = line[len(originPrefix):]
  588. remoteHead = localRefPrefix + headName
  589. originHead = line
  590. original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
  591. if (not original.has_key('depot-paths')
  592. or not original.has_key('change')):
  593. continue
  594. update = False
  595. if not gitBranchExists(remoteHead):
  596. if verbose:
  597. print "creating %s" % remoteHead
  598. update = True
  599. else:
  600. settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
  601. if settings.has_key('change') > 0:
  602. if settings['depot-paths'] == original['depot-paths']:
  603. originP4Change = int(original['change'])
  604. p4Change = int(settings['change'])
  605. if originP4Change > p4Change:
  606. print ("%s (%s) is newer than %s (%s). "
  607. "Updating p4 branch from origin."
  608. % (originHead, originP4Change,
  609. remoteHead, p4Change))
  610. update = True
  611. else:
  612. print ("Ignoring: %s was imported from %s while "
  613. "%s was imported from %s"
  614. % (originHead, ','.join(original['depot-paths']),
  615. remoteHead, ','.join(settings['depot-paths'])))
  616. if update:
  617. system("git update-ref %s %s" % (remoteHead, originHead))
  618. def originP4BranchesExist():
  619. return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
  620. def p4ChangesForPaths(depotPaths, changeRange):
  621. assert depotPaths
  622. cmd = ['changes']
  623. for p in depotPaths:
  624. cmd += ["%s...%s" % (p, changeRange)]
  625. output = p4_read_pipe_lines(cmd)
  626. changes = {}
  627. for line in output:
  628. changeNum = int(line.split(" ")[1])
  629. changes[changeNum] = True
  630. changelist = changes.keys()
  631. changelist.sort()
  632. return changelist
  633. def p4PathStartsWith(path, prefix):
  634. # This method tries to remedy a potential mixed-case issue:
  635. #
  636. # If UserA adds //depot/DirA/file1
  637. # and UserB adds //depot/dira/file2
  638. #
  639. # we may or may not have a problem. If you have core.ignorecase=true,
  640. # we treat DirA and dira as the same directory
  641. if gitConfigBool("core.ignorecase"):
  642. return path.lower().startswith(prefix.lower())
  643. return path.startswith(prefix)
  644. def getClientSpec():
  645. """Look at the p4 client spec, create a View() object that contains
  646. all the mappings, and return it."""
  647. specList = p4CmdList("client -o")
  648. if len(specList) != 1:
  649. die('Output from "client -o" is %d lines, expecting 1' %
  650. len(specList))
  651. # dictionary of all client parameters
  652. entry = specList[0]
  653. # the //client/ name
  654. client_name = entry["Client"]
  655. # just the keys that start with "View"
  656. view_keys = [ k for k in entry.keys() if k.startswith("View") ]
  657. # hold this new View
  658. view = View(client_name)
  659. # append the lines, in order, to the view
  660. for view_num in range(len(view_keys)):
  661. k = "View%d" % view_num
  662. if k not in view_keys:
  663. die("Expected view key %s missing" % k)
  664. view.append(entry[k])
  665. return view
  666. def getClientRoot():
  667. """Grab the client directory."""
  668. output = p4CmdList("client -o")
  669. if len(output) != 1:
  670. die('Output from "client -o" is %d lines, expecting 1' % len(output))
  671. entry = output[0]
  672. if "Root" not in entry:
  673. die('Client has no "Root"')
  674. return entry["Root"]
  675. #
  676. # P4 wildcards are not allowed in filenames. P4 complains
  677. # if you simply add them, but you can force it with "-f", in
  678. # which case it translates them into %xx encoding internally.
  679. #
  680. def wildcard_decode(path):
  681. # Search for and fix just these four characters. Do % last so
  682. # that fixing it does not inadvertently create new %-escapes.
  683. # Cannot have * in a filename in windows; untested as to
  684. # what p4 would do in such a case.
  685. if not platform.system() == "Windows":
  686. path = path.replace("%2A", "*")
  687. path = path.replace("%23", "#") \
  688. .replace("%40", "@") \
  689. .replace("%25", "%")
  690. return path
  691. def wildcard_encode(path):
  692. # do % first to avoid double-encoding the %s introduced here
  693. path = path.replace("%", "%25") \
  694. .replace("*", "%2A") \
  695. .replace("#", "%23") \
  696. .replace("@", "%40")
  697. return path
  698. def wildcard_present(path):
  699. m = re.search("[*#@%]", path)
  700. return m is not None
  701. class Command:
  702. def __init__(self):
  703. self.usage = "usage: %prog [options]"
  704. self.needsGit = True
  705. self.verbose = False
  706. class P4UserMap:
  707. def __init__(self):
  708. self.userMapFromPerforceServer = False
  709. self.myP4UserId = None
  710. def p4UserId(self):
  711. if self.myP4UserId:
  712. return self.myP4UserId
  713. results = p4CmdList("user -o")
  714. for r in results:
  715. if r.has_key('User'):
  716. self.myP4UserId = r['User']
  717. return r['User']
  718. die("Could not find your p4 user id")
  719. def p4UserIsMe(self, p4User):
  720. # return True if the given p4 user is actually me
  721. me = self.p4UserId()
  722. if not p4User or p4User != me:
  723. return False
  724. else:
  725. return True
  726. def getUserCacheFilename(self):
  727. home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
  728. return home + "/.gitp4-usercache.txt"
  729. def getUserMapFromPerforceServer(self):
  730. if self.userMapFromPerforceServer:
  731. return
  732. self.users = {}
  733. self.emails = {}
  734. for output in p4CmdList("users"):
  735. if not output.has_key("User"):
  736. continue
  737. self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
  738. self.emails[output["Email"]] = output["User"]
  739. s = ''
  740. for (key, val) in self.users.items():
  741. s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
  742. open(self.getUserCacheFilename(), "wb").write(s)
  743. self.userMapFromPerforceServer = True
  744. def loadUserMapFromCache(self):
  745. self.users = {}
  746. self.userMapFromPerforceServer = False
  747. try:
  748. cache = open(self.getUserCacheFilename(), "rb")
  749. lines = cache.readlines()
  750. cache.close()
  751. for line in lines:
  752. entry = line.strip().split("\t")
  753. self.users[entry[0]] = entry[1]
  754. except IOError:
  755. self.getUserMapFromPerforceServer()
  756. class P4Debug(Command):
  757. def __init__(self):
  758. Command.__init__(self)
  759. self.options = []
  760. self.description = "A tool to debug the output of p4 -G."
  761. self.needsGit = False
  762. def run(self, args):
  763. j = 0
  764. for output in p4CmdList(args):
  765. print 'Element: %d' % j
  766. j += 1
  767. print output
  768. return True
  769. class P4RollBack(Command):
  770. def __init__(self):
  771. Command.__init__(self)
  772. self.options = [
  773. optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
  774. ]
  775. self.description = "A tool to debug the multi-branch import. Don't use :)"
  776. self.rollbackLocalBranches = False
  777. def run(self, args):
  778. if len(args) != 1:
  779. return False
  780. maxChange = int(args[0])
  781. if "p4ExitCode" in p4Cmd("changes -m 1"):
  782. die("Problems executing p4");
  783. if self.rollbackLocalBranches:
  784. refPrefix = "refs/heads/"
  785. lines = read_pipe_lines("git rev-parse --symbolic --branches")
  786. else:
  787. refPrefix = "refs/remotes/"
  788. lines = read_pipe_lines("git rev-parse --symbolic --remotes")
  789. for line in lines:
  790. if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
  791. line = line.strip()
  792. ref = refPrefix + line
  793. log = extractLogMessageFromGitCommit(ref)
  794. settings = extractSettingsGitLog(log)
  795. depotPaths = settings['depot-paths']
  796. change = settings['change']
  797. changed = False
  798. if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
  799. for p in depotPaths]))) == 0:
  800. print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
  801. system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
  802. continue
  803. while change and int(change) > maxChange:
  804. changed = True
  805. if self.verbose:
  806. print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
  807. system("git update-ref %s \"%s^\"" % (ref, ref))
  808. log = extractLogMessageFromGitCommit(ref)
  809. settings = extractSettingsGitLog(log)
  810. depotPaths = settings['depot-paths']
  811. change = settings['change']
  812. if changed:
  813. print "%s rewound to %s" % (ref, change)
  814. return True
  815. class P4Submit(Command, P4UserMap):
  816. conflict_behavior_choices = ("ask", "skip", "quit")
  817. def __init__(self):
  818. Command.__init__(self)
  819. P4UserMap.__init__(self)
  820. self.options = [
  821. optparse.make_option("--origin", dest="origin"),
  822. optparse.make_option("-M", dest="detectRenames", action="store_true"),
  823. # preserve the user, requires relevant p4 permissions
  824. optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
  825. optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
  826. optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
  827. optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
  828. optparse.make_option("--conflict", dest="conflict_behavior",
  829. choices=self.conflict_behavior_choices),
  830. optparse.make_option("--branch", dest="branch"),
  831. ]
  832. self.description = "Submit changes from git to the perforce depot."
  833. self.usage += " [name of git branch to submit into perforce depot]"
  834. self.origin = ""
  835. self.detectRenames = False
  836. self.preserveUser = gitConfigBool("git-p4.preserveUser")
  837. self.dry_run = False
  838. self.prepare_p4_only = False
  839. self.conflict_behavior = None
  840. self.isWindows = (platform.system() == "Windows")
  841. self.exportLabels = False
  842. self.p4HasMoveCommand = p4_has_move_command()
  843. self.branch = None
  844. def check(self):
  845. if len(p4CmdList("opened ...")) > 0:
  846. die("You have files opened with perforce! Close them before starting the sync.")
  847. def separate_jobs_from_description(self, message):
  848. """Extract and return a possible Jobs field in the commit
  849. message. It goes into a separate section in the p4 change
  850. specification.
  851. A jobs line starts with "Jobs:" and looks like a new field
  852. in a form. Values are white-space separated on the same
  853. line or on following lines that start with a tab.
  854. This does not parse and extract the full git commit message
  855. like a p4 form. It just sees the Jobs: line as a marker
  856. to pass everything from then on directly into the p4 form,
  857. but outside the description section.
  858. Return a tuple (stripped log message, jobs string)."""
  859. m = re.search(r'^Jobs:', message, re.MULTILINE)
  860. if m is None:
  861. return (message, None)
  862. jobtext = message[m.start():]
  863. stripped_message = message[:m.start()].rstrip()
  864. return (stripped_message, jobtext)
  865. def prepareLogMessage(self, template, message, jobs):
  866. """Edits the template returned from "p4 change -o" to insert
  867. the message in the Description field, and the jobs text in
  868. the Jobs field."""
  869. result = ""
  870. inDescriptionSection = False
  871. for line in template.split("\n"):
  872. if line.startswith("#"):
  873. result += line + "\n"
  874. continue
  875. if inDescriptionSection:
  876. if line.startswith("Files:") or line.startswith("Jobs:"):
  877. inDescriptionSection = False
  878. # insert Jobs section
  879. if jobs:
  880. result += jobs + "\n"
  881. else:
  882. continue
  883. else:
  884. if line.startswith("Description:"):
  885. inDescriptionSection = True
  886. line += "\n"
  887. for messageLine in message.split("\n"):
  888. line += "\t" + messageLine + "\n"
  889. result += line + "\n"
  890. return result
  891. def patchRCSKeywords(self, file, pattern):
  892. # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
  893. (handle, outFileName) = tempfile.mkstemp(dir='.')
  894. try:
  895. outFile = os.fdopen(handle, "w+")
  896. inFile = open(file, "r")
  897. regexp = re.compile(pattern, re.VERBOSE)
  898. for line in inFile.readlines():
  899. line = regexp.sub(r'$\1$', line)
  900. outFile.write(line)
  901. inFile.close()
  902. outFile.close()
  903. # Forcibly overwrite the original file
  904. os.unlink(file)
  905. shutil.move(outFileName, file)
  906. except:
  907. # cleanup our temporary file
  908. os.unlink(outFileName)
  909. print "Failed to strip RCS keywords in %s" % file
  910. raise
  911. print "Patched up RCS keywords in %s" % file
  912. def p4UserForCommit(self,id):
  913. # Return the tuple (perforce user,git email) for a given git commit id
  914. self.getUserMapFromPerforceServer()
  915. gitEmail = read_pipe(["git", "log", "--max-count=1",
  916. "--format=%ae", id])
  917. gitEmail = gitEmail.strip()
  918. if not self.emails.has_key(gitEmail):
  919. return (None,gitEmail)
  920. else:
  921. return (self.emails[gitEmail],gitEmail)
  922. def checkValidP4Users(self,commits):
  923. # check if any git authors cannot be mapped to p4 users
  924. for id in commits:
  925. (user,email) = self.p4UserForCommit(id)
  926. if not user:
  927. msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
  928. if gitConfigBool("git-p4.allowMissingP4Users"):
  929. print "%s" % msg
  930. else:
  931. die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
  932. def lastP4Changelist(self):
  933. # Get back the last changelist number submitted in this client spec. This
  934. # then gets used to patch up the username in the change. If the same
  935. # client spec is being used by multiple processes then this might go
  936. # wrong.
  937. results = p4CmdList("client -o") # find the current client
  938. client = None
  939. for r in results:
  940. if r.has_key('Client'):
  941. client = r['Client']
  942. break
  943. if not client:
  944. die("could not get client spec")
  945. results = p4CmdList(["changes", "-c", client, "-m", "1"])
  946. for r in results:
  947. if r.has_key('change'):
  948. return r['change']
  949. die("Could not get changelist number for last submit - cannot patch up user details")
  950. def modifyChangelistUser(self, changelist, newUser):
  951. # fixup the user field of a changelist after it has been submitted.
  952. changes = p4CmdList("change -o %s" % changelist)
  953. if len(changes) != 1:
  954. die("Bad output from p4 change modifying %s to user %s" %
  955. (changelist, newUser))
  956. c = changes[0]
  957. if c['User'] == newUser: return # nothing to do
  958. c['User'] = newUser
  959. input = marshal.dumps(c)
  960. result = p4CmdList("change -f -i", stdin=input)
  961. for r in result:
  962. if r.has_key('code'):
  963. if r['code'] == 'error':
  964. die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
  965. if r.has_key('data'):
  966. print("Updated user field for changelist %s to %s" % (changelist, newUser))
  967. return
  968. die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
  969. def canChangeChangelists(self):
  970. # check to see if we have p4 admin or super-user permissions, either of
  971. # which are required to modify changelists.
  972. results = p4CmdList(["protects", self.depotPath])
  973. for r in results:
  974. if r.has_key('perm'):
  975. if r['perm'] == 'admin':
  976. return 1
  977. if r['perm'] == 'super':
  978. return 1
  979. return 0
  980. def prepareSubmitTemplate(self):
  981. """Run "p4 change -o" to grab a change specification template.
  982. This does not use "p4 -G", as it is nice to keep the submission
  983. template in original order, since a human might edit it.
  984. Remove lines in the Files section that show changes to files
  985. outside the depot path we're committing into."""
  986. template = ""
  987. inFilesSection = False
  988. for line in p4_read_pipe_lines(['change', '-o']):
  989. if line.endswith("\r\n"):
  990. line = line[:-2] + "\n"
  991. if inFilesSection:
  992. if line.startswith("\t"):
  993. # path starts and ends with a tab
  994. path = line[1:]
  995. lastTab = path.rfind("\t")
  996. if lastTab != -1:
  997. path = path[:lastTab]
  998. if not p4PathStartsWith(path, self.depotPath):
  999. continue
  1000. else:
  1001. inFilesSection = False
  1002. else:
  1003. if line.startswith("Files:"):
  1004. inFilesSection = True
  1005. template += line
  1006. return template
  1007. def edit_template(self, template_file):
  1008. """Invoke the editor to let the user change the submission
  1009. message. Return true if okay to continue with the submit."""
  1010. # if configured to skip the editing part, just submit
  1011. if gitConfigBool("git-p4.skipSubmitEdit"):
  1012. return True
  1013. # look at the modification time, to check later if the user saved
  1014. # the file
  1015. mtime = os.stat(template_file).st_mtime
  1016. # invoke the editor
  1017. if os.environ.has_key("P4EDITOR") and (os.environ.get("P4EDITOR") != ""):
  1018. editor = os.environ.get("P4EDITOR")
  1019. else:
  1020. editor = read_pipe("git var GIT_EDITOR").strip()
  1021. system([editor, template_file])
  1022. # If the file was not saved, prompt to see if this patch should
  1023. # be skipped. But skip this verification step if configured so.
  1024. if gitConfigBool("git-p4.skipSubmitEditCheck"):
  1025. return True
  1026. # modification time updated means user saved the file
  1027. if os.stat(template_file).st_mtime > mtime:
  1028. return True
  1029. while True:
  1030. response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
  1031. if response == 'y':
  1032. return True
  1033. if response == 'n':
  1034. return False
  1035. def get_diff_description(self, editedFiles, filesToAdd):
  1036. # diff
  1037. if os.environ.has_key("P4DIFF"):
  1038. del(os.environ["P4DIFF"])
  1039. diff = ""
  1040. for editedFile in editedFiles:
  1041. diff += p4_read_pipe(['diff', '-du',
  1042. wildcard_encode(editedFile)])
  1043. # new file diff
  1044. newdiff = ""
  1045. for newFile in filesToAdd:
  1046. newdiff += "==== new file ====\n"
  1047. newdiff += "--- /dev/null\n"
  1048. newdiff += "+++ %s\n" % newFile
  1049. f = open(newFile, "r")
  1050. for line in f.readlines():
  1051. newdiff += "+" + line
  1052. f.close()
  1053. return (diff + newdiff).replace('\r\n', '\n')
  1054. def applyCommit(self, id):
  1055. """Apply one commit, return True if it succeeded."""
  1056. print "Applying", read_pipe(["git", "show", "-s",
  1057. "--format=format:%h %s", id])
  1058. (p4User, gitEmail) = self.p4UserForCommit(id)
  1059. diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
  1060. filesToAdd = set()
  1061. filesToDelete = set()
  1062. editedFiles = set()
  1063. pureRenameCopy = set()
  1064. filesToChangeExecBit = {}
  1065. for line in diff:
  1066. diff = parseDiffTreeEntry(line)
  1067. modifier = diff['status']
  1068. path = diff['src']
  1069. if modifier == "M":
  1070. p4_edit(path)
  1071. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1072. filesToChangeExecBit[path] = diff['dst_mode']
  1073. editedFiles.add(path)
  1074. elif modifier == "A":
  1075. filesToAdd.add(path)
  1076. filesToChangeExecBit[path] = diff['dst_mode']
  1077. if path in filesToDelete:
  1078. filesToDelete.remove(path)
  1079. elif modifier == "D":
  1080. filesToDelete.add(path)
  1081. if path in filesToAdd:
  1082. filesToAdd.remove(path)
  1083. elif modifier == "C":
  1084. src, dest = diff['src'], diff['dst']
  1085. p4_integrate(src, dest)
  1086. pureRenameCopy.add(dest)
  1087. if diff['src_sha1'] != diff['dst_sha1']:
  1088. p4_edit(dest)
  1089. pureRenameCopy.discard(dest)
  1090. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1091. p4_edit(dest)
  1092. pureRenameCopy.discard(dest)
  1093. filesToChangeExecBit[dest] = diff['dst_mode']
  1094. if self.isWindows:
  1095. # turn off read-only attribute
  1096. os.chmod(dest, stat.S_IWRITE)
  1097. os.unlink(dest)
  1098. editedFiles.add(dest)
  1099. elif modifier == "R":
  1100. src, dest = diff['src'], diff['dst']
  1101. if self.p4HasMoveCommand:
  1102. p4_edit(src) # src must be open before move
  1103. p4_move(src, dest) # opens for (move/delete, move/add)
  1104. else:
  1105. p4_integrate(src, dest)
  1106. if diff['src_sha1'] != diff['dst_sha1']:
  1107. p4_edit(dest)
  1108. else:
  1109. pureRenameCopy.add(dest)
  1110. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1111. if not self.p4HasMoveCommand:
  1112. p4_edit(dest) # with move: already open, writable
  1113. filesToChangeExecBit[dest] = diff['dst_mode']
  1114. if not self.p4HasMoveCommand:
  1115. if self.isWindows:
  1116. os.chmod(dest, stat.S_IWRITE)
  1117. os.unlink(dest)
  1118. filesToDelete.add(src)
  1119. editedFiles.add(dest)
  1120. else:
  1121. die("unknown modifier %s for %s" % (modifier, path))
  1122. diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
  1123. patchcmd = diffcmd + " | git apply "
  1124. tryPatchCmd = patchcmd + "--check -"
  1125. applyPatchCmd = patchcmd + "--check --apply -"
  1126. patch_succeeded = True
  1127. if os.system(tryPatchCmd) != 0:
  1128. fixed_rcs_keywords = False
  1129. patch_succeeded = False
  1130. print "Unfortunately applying the change failed!"
  1131. # Patch failed, maybe it's just RCS keyword woes. Look through
  1132. # the patch to see if that's possible.
  1133. if gitConfigBool("git-p4.attemptRCSCleanup"):
  1134. file = None
  1135. pattern = None
  1136. kwfiles = {}
  1137. for file in editedFiles | filesToDelete:
  1138. # did this file's delta contain RCS keywords?
  1139. pattern = p4_keywords_regexp_for_file(file)
  1140. if pattern:
  1141. # this file is a possibility...look for RCS keywords.
  1142. regexp = re.compile(pattern, re.VERBOSE)
  1143. for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
  1144. if regexp.search(line):
  1145. if verbose:
  1146. print "got keyword match on %s in %s in %s" % (pattern, line, file)
  1147. kwfiles[file] = pattern
  1148. break
  1149. for file in kwfiles:
  1150. if verbose:
  1151. print "zapping %s with %s" % (line,pattern)
  1152. # File is being deleted, so not open in p4. Must
  1153. # disable the read-only bit on windows.
  1154. if self.isWindows and file not in editedFiles:
  1155. os.chmod(file, stat.S_IWRITE)
  1156. self.patchRCSKeywords(file, kwfiles[file])
  1157. fixed_rcs_keywords = True
  1158. if fixed_rcs_keywords:
  1159. print "Retrying the patch with RCS keywords cleaned up"
  1160. if os.system(tryPatchCmd) == 0:
  1161. patch_succeeded = True
  1162. if not patch_succeeded:
  1163. for f in editedFiles:
  1164. p4_revert(f)
  1165. return False
  1166. #
  1167. # Apply the patch for real, and do add/delete/+x handling.
  1168. #
  1169. system(applyPatchCmd)
  1170. for f in filesToAdd:
  1171. p4_add(f)
  1172. for f in filesToDelete:
  1173. p4_revert(f)
  1174. p4_delete(f)
  1175. # Set/clear executable bits
  1176. for f in filesToChangeExecBit.keys():
  1177. mode = filesToChangeExecBit[f]
  1178. setP4ExecBit(f, mode)
  1179. #
  1180. # Build p4 change description, starting with the contents
  1181. # of the git commit message.
  1182. #
  1183. logMessage = extractLogMessageFromGitCommit(id)
  1184. logMessage = logMessage.strip()
  1185. (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
  1186. template = self.prepareSubmitTemplate()
  1187. submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
  1188. if self.preserveUser:
  1189. submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
  1190. if self.checkAuthorship and not self.p4UserIsMe(p4User):
  1191. submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
  1192. submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
  1193. submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
  1194. separatorLine = "######## everything below this line is just the diff #######\n"
  1195. if not self.prepare_p4_only:
  1196. submitTemplate += separatorLine
  1197. submitTemplate += self.get_diff_description(editedFiles, filesToAdd)
  1198. (handle, fileName) = tempfile.mkstemp()
  1199. tmpFile = os.fdopen(handle, "w+b")
  1200. if self.isWindows:
  1201. submitTemplate = submitTemplate.replace("\n", "\r\n")
  1202. tmpFile.write(submitTemplate)
  1203. tmpFile.close()
  1204. if self.prepare_p4_only:
  1205. #
  1206. # Leave the p4 tree prepared, and the submit template around
  1207. # and let the user decide what to do next
  1208. #
  1209. print
  1210. print "P4 workspace prepared for submission."
  1211. print "To submit or revert, go to client workspace"
  1212. print " " + self.clientPath
  1213. print
  1214. print "To submit, use \"p4 submit\" to write a new description,"
  1215. print "or \"p4 submit -i %s\" to use the one prepared by" \
  1216. " \"git p4\"." % fileName
  1217. print "You can delete the file \"%s\" when finished." % fileName
  1218. if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
  1219. print "To preserve change ownership by user %s, you must\n" \
  1220. "do \"p4 change -f <change>\" after submitting and\n" \
  1221. "edit the User field."
  1222. if pureRenameCopy:
  1223. print "After submitting, renamed files must be re-synced."
  1224. print "Invoke \"p4 sync -f\" on each of these files:"
  1225. for f in pureRenameCopy:
  1226. print " " + f
  1227. print
  1228. print "To revert the changes, use \"p4 revert ...\", and delete"
  1229. print "the submit template file \"%s\"" % fileName
  1230. if filesToAdd:
  1231. print "Since the commit adds new files, they must be deleted:"
  1232. for f in filesToAdd:
  1233. print " " + f
  1234. print
  1235. return True
  1236. #
  1237. # Let the user edit the change description, then submit it.
  1238. #
  1239. if self.edit_template(fileName):
  1240. # read the edited message and submit
  1241. ret = True
  1242. tmpFile = open(fileName, "rb")
  1243. message = tmpFile.read()
  1244. tmpFile.close()
  1245. if self.isWindows:
  1246. message = message.replace("\r\n", "\n")
  1247. submitTemplate = message[:message.index(separatorLine)]
  1248. p4_write_pipe(['submit', '-i'], submitTemplate)
  1249. if self.preserveUser:
  1250. if p4User:
  1251. # Get last changelist number. Cannot easily get it from
  1252. # the submit command output as the output is
  1253. # unmarshalled.
  1254. changelist = self.lastP4Changelist()
  1255. self.modifyChangelistUser(changelist, p4User)
  1256. # The rename/copy happened by applying a patch that created a
  1257. # new file. This leaves it writable, which confuses p4.
  1258. for f in pureRenameCopy:
  1259. p4_sync(f, "-f")
  1260. else:
  1261. # skip this patch
  1262. ret = False
  1263. print "Submission cancelled, undoing p4 changes."
  1264. for f in editedFiles:
  1265. p4_revert(f)
  1266. for f in filesToAdd:
  1267. p4_revert(f)
  1268. os.remove(f)
  1269. for f in filesToDelete:
  1270. p4_revert(f)
  1271. os.remove(fileName)
  1272. return ret
  1273. # Export git tags as p4 labels. Create a p4 label and then tag
  1274. # with that.
  1275. def exportGitTags(self, gitTags):
  1276. validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
  1277. if len(validLabelRegexp) == 0:
  1278. validLabelRegexp = defaultLabelRegexp
  1279. m = re.compile(validLabelRegexp)
  1280. for name in gitTags:
  1281. if not m.match(name):
  1282. if verbose:
  1283. print "tag %s does not match regexp %s" % (name, validLabelRegexp)
  1284. continue
  1285. # Get the p4 commit this corresponds to
  1286. logMessage = extractLogMessageFromGitCommit(name)
  1287. values = extractSettingsGitLog(logMessage)
  1288. if not values.has_key('change'):
  1289. # a tag pointing to something not sent to p4; ignore
  1290. if verbose:
  1291. print "git tag %s does not give a p4 commit" % name
  1292. continue
  1293. else:
  1294. changelist = values['change']
  1295. # Get the tag details.
  1296. inHeader = True
  1297. isAnnotated = False
  1298. body = []
  1299. for l in read_pipe_lines(["git", "cat-file", "-p", name]):
  1300. l = l.strip()
  1301. if inHeader:
  1302. if re.match(r'tag\s+', l):
  1303. isAnnotated = True
  1304. elif re.match(r'\s*$', l):
  1305. inHeader = False
  1306. continue
  1307. else:
  1308. body.append(l)
  1309. if not isAnnotated:
  1310. body = ["lightweight tag imported by git p4\n"]
  1311. # Create the label - use the same view as the client spec we are using
  1312. clientSpec = getClientSpec()
  1313. labelTemplate = "Label: %s\n" % name
  1314. labelTemplate += "Description:\n"
  1315. for b in body:
  1316. labelTemplate += "\t" + b + "\n"
  1317. labelTemplate += "View:\n"
  1318. for depot_side in clientSpec.mappings:
  1319. labelTemplate += "\t%s\n" % depot_side
  1320. if self.dry_run:
  1321. print "Would create p4 label %s for tag" % name
  1322. elif self.prepare_p4_only:
  1323. print "Not creating p4 label %s for tag due to option" \
  1324. " --prepare-p4-only" % name
  1325. else:
  1326. p4_write_pipe(["label", "-i"], labelTemplate)
  1327. # Use the label
  1328. p4_system(["tag", "-l", name] +
  1329. ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
  1330. if verbose:
  1331. print "created p4 label for tag %s" % name
  1332. def run(self, args):
  1333. if len(args) == 0:
  1334. self.master = currentGitBranch()
  1335. if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
  1336. die("Detecting current git branch failed!")
  1337. elif len(args) == 1:
  1338. self.master = args[0]
  1339. if not branchExists(self.master):
  1340. die("Branch %s does not exist" % self.master)
  1341. else:
  1342. return False
  1343. allowSubmit = gitConfig("git-p4.allowSubmit")
  1344. if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
  1345. die("%s is not in git-p4.allowSubmit" % self.master)
  1346. [upstream, settings] = findUpstreamBranchPoint()
  1347. self.depotPath = settings['depot-paths'][0]
  1348. if len(self.origin) == 0:
  1349. self.origin = upstream
  1350. if self.preserveUser:
  1351. if not self.canChangeChangelists():
  1352. die("Cannot preserve user names without p4 super-user or admin permissions")
  1353. # if not set from the command line, try the config file
  1354. if self.conflict_behavior is None:
  1355. val = gitConfig("git-p4.conflict")
  1356. if val:
  1357. if val not in self.conflict_behavior_choices:
  1358. die("Invalid value '%s' for config git-p4.conflict" % val)
  1359. else:
  1360. val = "ask"
  1361. self.conflict_behavior = val
  1362. if self.verbose:
  1363. print "Origin branch is " + self.origin
  1364. if len(self.depotPath) == 0:
  1365. print "Internal error: cannot locate perforce depot path from existing branches"
  1366. sys.exit(128)
  1367. self.useClientSpec = False
  1368. if gitConfigBool("git-p4.useclientspec"):
  1369. self.useClientSpec = True
  1370. if self.useClientSpec:
  1371. self.clientSpecDirs = getClientSpec()
  1372. if self.useClientSpec:
  1373. # all files are relative to the client spec
  1374. self.clientPath = getClientRoot()
  1375. else:
  1376. self.clientPath = p4Where(self.depotPath)
  1377. if self.clientPath == "":
  1378. die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
  1379. print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
  1380. self.oldWorkingDirectory = os.getcwd()
  1381. # ensure the clientPath exists
  1382. new_client_dir = False
  1383. if not os.path.exists(self.clientPath):
  1384. new_client_dir = True
  1385. os.makedirs(self.clientPath)
  1386. chdir(self.clientPath, is_client_path=True)
  1387. if self.dry_run:
  1388. print "Would synchronize p4 checkout in %s" % self.clientPath
  1389. else:
  1390. print "Synchronizing p4 checkout..."
  1391. if new_client_dir:
  1392. # old one was destroyed, and maybe nobody told p4
  1393. p4_sync("...", "-f")
  1394. else:
  1395. p4_sync("...")
  1396. self.check()
  1397. commits = []
  1398. for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, self.master)]):
  1399. commits.append(line.strip())
  1400. commits.reverse()
  1401. if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
  1402. self.checkAuthorship = False
  1403. else:
  1404. self.checkAuthorship = True
  1405. if self.preserveUser:
  1406. self.checkValidP4Users(commits)
  1407. #
  1408. # Build up a set of options to be passed to diff when
  1409. # submitting each commit to p4.
  1410. #
  1411. if self.detectRenames:
  1412. # command-line -M arg
  1413. self.diffOpts = "-M"
  1414. else:
  1415. # If not explicitly set check the config variable
  1416. detectRenames = gitConfig("git-p4.detectRenames")
  1417. if detectRenames.lower() == "false" or detectRenames == "":
  1418. self.diffOpts = ""
  1419. elif detectRenames.lower() == "true":
  1420. self.diffOpts = "-M"
  1421. else:
  1422. self.diffOpts = "-M%s" % detectRenames
  1423. # no command-line arg for -C or --find-copies-harder, just
  1424. # config variables
  1425. detectCopies = gitConfig("git-p4.detectCopies")
  1426. if detectCopies.lower() == "false" or detectCopies == "":
  1427. pass
  1428. elif detectCopies.lower() == "true":
  1429. self.diffOpts += " -C"
  1430. else:
  1431. self.diffOpts += " -C%s" % detectCopies
  1432. if gitConfigBool("git-p4.detectCopiesHarder"):
  1433. self.diffOpts += " --find-copies-harder"
  1434. #
  1435. # Apply the commits, one at a time. On failure, ask if should
  1436. # continue to try the rest of the patches, or quit.
  1437. #
  1438. if self.dry_run:
  1439. print "Would apply"
  1440. applied = []
  1441. last = len(commits) - 1
  1442. for i, commit in enumerate(commits):
  1443. if self.dry_run:
  1444. print " ", read_pipe(["git", "show", "-s",
  1445. "--format=format:%h %s", commit])
  1446. ok = True
  1447. else:
  1448. ok = self.applyCommit(commit)
  1449. if ok:
  1450. applied.append(commit)
  1451. else:
  1452. if self.prepare_p4_only and i < last:
  1453. print "Processing only the first commit due to option" \
  1454. " --prepare-p4-only"
  1455. break
  1456. if i < last:
  1457. quit = False
  1458. while True:
  1459. # prompt for what to do, or use the option/variable
  1460. if self.conflict_behavior == "ask":
  1461. print "What do you want to do?"
  1462. response = raw_input("[s]kip this commit but apply"
  1463. " the rest, or [q]uit? ")
  1464. if not response:
  1465. continue
  1466. elif self.conflict_behavior == "skip":
  1467. response = "s"
  1468. elif self.conflict_behavior == "quit":
  1469. response = "q"
  1470. else:
  1471. die("Unknown conflict_behavior '%s'" %
  1472. self.conflict_behavior)
  1473. if response[0] == "s":
  1474. print "Skipping this commit, but applying the rest"
  1475. break
  1476. if response[0] == "q":
  1477. print "Quitting"
  1478. quit = True
  1479. break
  1480. if quit:
  1481. break
  1482. chdir(self.oldWorkingDirectory)
  1483. if self.dry_run:
  1484. pass
  1485. elif self.prepare_p4_only:
  1486. pass
  1487. elif len(commits) == len(applied):
  1488. print "All commits applied!"
  1489. sync = P4Sync()
  1490. if self.branch:
  1491. sync.branch = self.branch
  1492. sync.run([])
  1493. rebase = P4Rebase()
  1494. rebase.rebase()
  1495. else:
  1496. if len(applied) == 0:
  1497. print "No commits applied."
  1498. else:
  1499. print "Applied only the commits marked with '*':"
  1500. for c in commits:
  1501. if c in applied:
  1502. star = "*"
  1503. else:
  1504. star = " "
  1505. print star, read_pipe(["git", "show", "-s",
  1506. "--format=format:%h %s", c])
  1507. print "You will have to do 'git p4 sync' and rebase."
  1508. if gitConfigBool("git-p4.exportLabels"):
  1509. self.exportLabels = True
  1510. if self.exportLabels:
  1511. p4Labels = getP4Labels(self.depotPath)
  1512. gitTags = getGitTags()
  1513. missingGitTags = gitTags - p4Labels
  1514. self.exportGitTags(missingGitTags)
  1515. # exit with error unless everything applied perfectly
  1516. if len(commits) != len(applied):
  1517. sys.exit(1)
  1518. return True
  1519. class View(object):
  1520. """Represent a p4 view ("p4 help views"), and map files in a
  1521. repo according to the view."""
  1522. def __init__(self, client_name):
  1523. self.mappings = []
  1524. self.client_prefix = "//%s/" % client_name
  1525. # cache results of "p4 where" to lookup client file locations
  1526. self.client_spec_path_cache = {}
  1527. def append(self, view_line):
  1528. """Parse a view line, splitting it into depot and client
  1529. sides. Append to self.mappings, preserving order. This
  1530. is only needed for tag creation."""
  1531. # Split the view line into exactly two words. P4 enforces
  1532. # structure on these lines that simplifies this quite a bit.
  1533. #
  1534. # Either or both words may be double-quoted.
  1535. # Single quotes do not matter.
  1536. # Double-quote marks cannot occur inside the words.
  1537. # A + or - prefix is also inside the quotes.
  1538. # There are no quotes unless they contain a space.
  1539. # The line is already white-space stripped.
  1540. # The two words are separated by a single space.
  1541. #
  1542. if view_line[0] == '"':
  1543. # First word is double quoted. Find its end.
  1544. close_quote_index = view_line.find('"', 1)
  1545. if close_quote_index <= 0:
  1546. die("No first-word closing quote found: %s" % view_line)
  1547. depot_side = view_line[1:close_quote_index]
  1548. # skip closing quote and space
  1549. rhs_index = close_quote_index + 1 + 1
  1550. else:
  1551. space_index = view_line.find(" ")
  1552. if space_index <= 0:
  1553. die("No word-splitting space found: %s" % view_line)
  1554. depot_side = view_line[0:space_index]
  1555. rhs_index = space_index + 1
  1556. # prefix + means overlay on previous mapping
  1557. if depot_side.startswith("+"):
  1558. depot_side = depot_side[1:]
  1559. # prefix - means exclude this path, leave out of mappings
  1560. exclude = False
  1561. if depot_side.startswith("-"):
  1562. exclude = True
  1563. depot_side = depot_side[1:]
  1564. if not exclude:
  1565. self.mappings.append(depot_side)
  1566. def convert_client_path(self, clientFile):
  1567. # chop off //client/ part to make it relative
  1568. if not clientFile.startswith(self.client_prefix):
  1569. die("No prefix '%s' on clientFile '%s'" %
  1570. (self.client_prefix, clientFile))
  1571. return clientFile[len(self.client_prefix):]
  1572. def update_client_spec_path_cache(self, files):
  1573. """ Caching file paths by "p4 where" batch query """
  1574. # List depot file paths exclude that already cached
  1575. fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache]
  1576. if len(fileArgs) == 0:
  1577. return # All files in cache
  1578. where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
  1579. for res in where_result:
  1580. if "code" in res and res["code"] == "error":
  1581. # assume error is "... file(s) not in client view"
  1582. continue
  1583. if "clientFile" not in res:
  1584. die("No clientFile in 'p4 where' output")
  1585. if "unmap" in res:
  1586. # it will list all of them, but only one not unmap-ped
  1587. continue
  1588. self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])
  1589. # not found files or unmap files set to ""
  1590. for depotFile in fileArgs:
  1591. if depotFile not in self.client_spec_path_cache:
  1592. self.client_spec_path_cache[depotFile] = ""
  1593. def map_in_client(self, depot_path):
  1594. """Return the relative location in the client where this
  1595. depot file should live. Returns "" if the file should
  1596. not be mapped in the client."""
  1597. if depot_path in self.client_spec_path_cache:
  1598. return self.client_spec_path_cache[depot_path]
  1599. die( "Error: %s is not found in client spec path" % depot_path )
  1600. return ""
  1601. class P4Sync(Command, P4UserMap):
  1602. delete_actions = ( "delete", "move/delete", "purge" )
  1603. def __init__(self):
  1604. Command.__init__(self)
  1605. P4UserMap.__init__(self)
  1606. self.options = [
  1607. optparse.make_option("--branch", dest="branch"),
  1608. optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
  1609. optparse.make_option("--changesfile", dest="changesFile"),
  1610. optparse.make_option("--silent", dest="silent", action="store_true"),
  1611. optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
  1612. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  1613. optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
  1614. help="Import into refs/heads/ , not refs/remotes"),
  1615. optparse.make_option("--max-changes", dest="maxChanges"),
  1616. optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
  1617. help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
  1618. optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
  1619. help="Only sync files that are included in the Perforce Client Spec")
  1620. ]
  1621. self.description = """Imports from Perforce into a git repository.\n
  1622. example:
  1623. //depot/my/project/ -- to import the current head
  1624. //depot/my/project/@all -- to import everything
  1625. //depot/my/project/@1,6 -- to import only from revision 1 to 6
  1626. (a ... is not needed in the path p4 specification, it's added implicitly)"""
  1627. self.usage += " //depot/path[@revRange]"
  1628. self.silent = False
  1629. self.createdBranches = set()
  1630. self.committedChanges = set()
  1631. self.branch = ""
  1632. self.detectBranches = False
  1633. self.detectLabels = False
  1634. self.importLabels = False
  1635. self.changesFile = ""
  1636. self.syncWithOrigin = True
  1637. self.importIntoRemotes = True
  1638. self.maxChanges = ""
  1639. self.keepRepoPath = False
  1640. self.depotPaths = None
  1641. self.p4BranchesInGit = []
  1642. self.cloneExclude = []
  1643. self.useClientSpec = False
  1644. self.useClientSpec_from_options = False
  1645. self.clientSpecDirs = None
  1646. self.tempBranches = []
  1647. self.tempBranchLocation = "git-p4-tmp"
  1648. if gitConfig("git-p4.syncFromOrigin") == "false":
  1649. self.syncWithOrigin = False
  1650. # Force a checkpoint in fast-import and wait for it to finish
  1651. def checkpoint(self):
  1652. self.gitStream.write("checkpoint\n\n")
  1653. self.gitStream.write("progress checkpoint\n\n")
  1654. out = self.gitOutput.readline()
  1655. if self.verbose:
  1656. print "checkpoint finished: " + out
  1657. def extractFilesFromCommit(self, commit):
  1658. self.cloneExclude = [re.sub(r"\.\.\.$", "", path)
  1659. for path in self.cloneExclude]
  1660. files = []
  1661. fnum = 0
  1662. while commit.has_key("depotFile%s" % fnum):
  1663. path = commit["depotFile%s" % fnum]
  1664. if [p for p in self.cloneExclude
  1665. if p4PathStartsWith(path, p)]:
  1666. found = False
  1667. else:
  1668. found = [p for p in self.depotPaths
  1669. if p4PathStartsWith(path, p)]
  1670. if not found:
  1671. fnum = fnum + 1
  1672. continue
  1673. file = {}
  1674. file["path"] = path
  1675. file["rev"] = commit["rev%s" % fnum]
  1676. file["action"] = commit["action%s" % fnum]
  1677. file["type"] = commit["type%s" % fnum]
  1678. files.append(file)
  1679. fnum = fnum + 1
  1680. return files
  1681. def stripRepoPath(self, path, prefixes):
  1682. """When streaming files, this is called to map a p4 depot path
  1683. to where it should go in git. The prefixes are either
  1684. self.depotPaths, or self.branchPrefixes in the case of
  1685. branch detection."""
  1686. if self.useClientSpec:
  1687. # branch detection moves files up a level (the branch name)
  1688. # from what client spec interpretation gives
  1689. path = self.clientSpecDirs.map_in_client(path)
  1690. if self.detectBranches:
  1691. for b in self.knownBranches:
  1692. if path.startswith(b + "/"):
  1693. path = path[len(b)+1:]
  1694. elif self.keepRepoPath:
  1695. # Preserve everything in relative path name except leading
  1696. # //depot/; just look at first prefix as they all should
  1697. # be in the same depot.
  1698. depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
  1699. if p4PathStartsWith(path, depot):
  1700. path = path[len(depot):]
  1701. else:
  1702. for p in prefixes:
  1703. if p4PathStartsWith(path, p):
  1704. path = path[len(p):]
  1705. break
  1706. path = wildcard_decode(path)
  1707. return path
  1708. def splitFilesIntoBranches(self, commit):
  1709. """Look at each depotFile in the commit to figure out to what
  1710. branch it belongs."""
  1711. if self.clientSpecDirs:
  1712. files = self.extractFilesFromCommit(commit)
  1713. self.clientSpecDirs.update_client_spec_path_cache(files)
  1714. branches = {}
  1715. fnum = 0
  1716. while commit.has_key("depotFile%s" % fnum):
  1717. path = commit["depotFile%s" % fnum]
  1718. found = [p for p in self.depotPaths
  1719. if p4PathStartsWith(path, p)]
  1720. if not found:
  1721. fnum = fnum + 1
  1722. continue
  1723. file = {}
  1724. file["path"] = path
  1725. file["rev"] = commit["rev%s" % fnum]
  1726. file["action"] = commit["action%s" % fnum]
  1727. file["type"] = commit["type%s" % fnum]
  1728. fnum = fnum + 1
  1729. # start with the full relative path where this file would
  1730. # go in a p4 client
  1731. if self.useClientSpec:
  1732. relPath = self.clientSpecDirs.map_in_client(path)
  1733. else:
  1734. relPath = self.stripRepoPath(path, self.depotPaths)
  1735. for branch in self.knownBranches.keys():
  1736. # add a trailing slash so that a commit into qt/4.2foo
  1737. # doesn't end up in qt/4.2, e.g.
  1738. if relPath.startswith(branch + "/"):
  1739. if branch not in branches:
  1740. branches[branch] = []
  1741. branches[branch].append(file)
  1742. break
  1743. return branches
  1744. # output one file from the P4 stream
  1745. # - helper for streamP4Files
  1746. def streamOneP4File(self, file, contents):
  1747. relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
  1748. if verbose:
  1749. sys.stderr.write("%s\n" % relPath)
  1750. (type_base, type_mods) = split_p4_type(file["type"])
  1751. git_mode = "100644"
  1752. if "x" in type_mods:
  1753. git_mode = "100755"
  1754. if type_base == "symlink":
  1755. git_mode = "120000"
  1756. # p4 print on a symlink sometimes contains "target\n";
  1757. # if it does, remove the newline
  1758. data = ''.join(contents)
  1759. if not data:
  1760. # Some version of p4 allowed creating a symlink that pointed
  1761. # to nothing. This causes p4 errors when checking out such
  1762. # a change, and errors here too. Work around it by ignoring
  1763. # the bad symlink; hopefully a future change fixes it.
  1764. print "\nIgnoring empty symlink in %s" % file['depotFile']
  1765. return
  1766. elif data[-1] == '\n':
  1767. contents = [data[:-1]]
  1768. else:
  1769. contents = [data]
  1770. if type_base == "utf16":
  1771. # p4 delivers different text in the python output to -G
  1772. # than it does when using "print -o", or normal p4 client
  1773. # operations. utf16 is converted to ascii or utf8, perhaps.
  1774. # But ascii text saved as -t utf16 is completely mangled.
  1775. # Invoke print -o to get the real contents.
  1776. #
  1777. # On windows, the newlines will always be mangled by print, so put
  1778. # them back too. This is not needed to the cygwin windows version,
  1779. # just the native "NT" type.
  1780. #
  1781. text = p4_read_pipe(['print', '-q', '-o', '-', file['depotFile']])
  1782. if p4_version_string().find("/NT") >= 0:
  1783. text = text.replace("\r\n", "\n")
  1784. contents = [ text ]
  1785. if type_base == "apple":
  1786. # Apple filetype files will be streamed as a concatenation of
  1787. # its appledouble header and the contents. This is useless
  1788. # on both macs and non-macs. If using "print -q -o xx", it
  1789. # will create "xx" with the data, and "%xx" with the header.
  1790. # This is also not very useful.
  1791. #
  1792. # Ideally, someday, this script can learn how to generate
  1793. # appledouble files directly and import those to git, but
  1794. # non-mac machines can never find a use for apple filetype.
  1795. print "\nIgnoring apple filetype file %s" % file['depotFile']
  1796. return
  1797. # Note that we do not try to de-mangle keywords on utf16 files,
  1798. # even though in theory somebody may want that.
  1799. pattern = p4_keywords_regexp_for_type(type_base, type_mods)
  1800. if pattern:
  1801. regexp = re.compile(pattern, re.VERBOSE)
  1802. text = ''.join(contents)
  1803. text = regexp.sub(r'$\1$', text)
  1804. contents = [ text ]
  1805. self.gitStream.write("M %s inline %s\n" % (git_mode, relPath))
  1806. # total length...
  1807. length = 0
  1808. for d in contents:
  1809. length = length + len(d)
  1810. self.gitStream.write("data %d\n" % length)
  1811. for d in contents:
  1812. self.gitStream.write(d)
  1813. self.gitStream.write("\n")
  1814. def streamOneP4Deletion(self, file):
  1815. relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
  1816. if verbose:
  1817. sys.stderr.write("delete %s\n" % relPath)
  1818. self.gitStream.write("D %s\n" % relPath)
  1819. # handle another chunk of streaming data
  1820. def streamP4FilesCb(self, marshalled):
  1821. # catch p4 errors and complain
  1822. err = None
  1823. if "code" in marshalled:
  1824. if marshalled["code"] == "error":
  1825. if "data" in marshalled:
  1826. err = marshalled["data"].rstrip()
  1827. if err:
  1828. f = None
  1829. if self.stream_have_file_info:
  1830. if "depotFile" in self.stream_file:
  1831. f = self.stream_file["depotFile"]
  1832. # force a failure in fast-import, else an empty
  1833. # commit will be made
  1834. self.gitStream.write("\n")
  1835. self.gitStream.write("die-now\n")
  1836. self.gitStream.close()
  1837. # ignore errors, but make sure it exits first
  1838. self.importProcess.wait()
  1839. if f:
  1840. die("Error from p4 print for %s: %s" % (f, err))
  1841. else:
  1842. die("Error from p4 print: %s" % err)
  1843. if marshalled.has_key('depotFile') and self.stream_have_file_info:
  1844. # start of a new file - output the old one first
  1845. self.streamOneP4File(self.stream_file, self.stream_contents)
  1846. self.stream_file = {}
  1847. self.stream_contents = []
  1848. self.stream_have_file_info = False
  1849. # pick up the new file information... for the
  1850. # 'data' field we need to append to our array
  1851. for k in marshalled.keys():
  1852. if k == 'data':
  1853. self.stream_contents.append(marshalled['data'])
  1854. else:
  1855. self.stream_file[k] = marshalled[k]
  1856. self.stream_have_file_info = True
  1857. # Stream directly from "p4 files" into "git fast-import"
  1858. def streamP4Files(self, files):
  1859. filesForCommit = []
  1860. filesToRead = []
  1861. filesToDelete = []
  1862. for f in files:
  1863. # if using a client spec, only add the files that have
  1864. # a path in the client
  1865. if self.clientSpecDirs:
  1866. if self.clientSpecDirs.map_in_client(f['path']) == "":
  1867. continue
  1868. filesForCommit.append(f)
  1869. if f['action'] in self.delete_actions:
  1870. filesToDelete.append(f)
  1871. else:
  1872. filesToRead.append(f)
  1873. # deleted files...
  1874. for f in filesToDelete:
  1875. self.streamOneP4Deletion(f)
  1876. if len(filesToRead) > 0:
  1877. self.stream_file = {}
  1878. self.stream_contents = []
  1879. self.stream_have_file_info = False
  1880. # curry self argument
  1881. def streamP4FilesCbSelf(entry):
  1882. self.streamP4FilesCb(entry)
  1883. fileArgs = ['%s#%s' % (f['path'], f['rev']) for f in filesToRead]
  1884. p4CmdList(["-x", "-", "print"],
  1885. stdin=fileArgs,
  1886. cb=streamP4FilesCbSelf)
  1887. # do the last chunk
  1888. if self.stream_file.has_key('depotFile'):
  1889. self.streamOneP4File(self.stream_file, self.stream_contents)
  1890. def make_email(self, userid):
  1891. if userid in self.users:
  1892. return self.users[userid]
  1893. else:
  1894. return "%s <a@b>" % userid
  1895. # Stream a p4 tag
  1896. def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
  1897. if verbose:
  1898. print "writing tag %s for commit %s" % (labelName, commit)
  1899. gitStream.write("tag %s\n" % labelName)
  1900. gitStream.write("from %s\n" % commit)
  1901. if labelDetails.has_key('Owner'):
  1902. owner = labelDetails["Owner"]
  1903. else:
  1904. owner = None
  1905. # Try to use the owner of the p4 label, or failing that,
  1906. # the current p4 user id.
  1907. if owner:
  1908. email = self.make_email(owner)
  1909. else:
  1910. email = self.make_email(self.p4UserId())
  1911. tagger = "%s %s %s" % (email, epoch, self.tz)
  1912. gitStream.write("tagger %s\n" % tagger)
  1913. print "labelDetails=",labelDetails
  1914. if labelDetails.has_key('Description'):
  1915. description = labelDetails['Description']
  1916. else:
  1917. description = 'Label from git p4'
  1918. gitStream.write("data %d\n" % len(description))
  1919. gitStream.write(description)
  1920. gitStream.write("\n")
  1921. def commit(self, details, files, branch, parent = ""):
  1922. epoch = details["time"]
  1923. author = details["user"]
  1924. if self.verbose:
  1925. print "commit into %s" % branch
  1926. # start with reading files; if that fails, we should not
  1927. # create a commit.
  1928. new_files = []
  1929. for f in files:
  1930. if [p for p in self.branchPrefixes if p4PathStartsWith(f['path'], p)]:
  1931. new_files.append (f)
  1932. else:
  1933. sys.stderr.write("Ignoring file outside of prefix: %s\n" % f['path'])
  1934. if self.clientSpecDirs:
  1935. self.clientSpecDirs.update_client_spec_path_cache(files)
  1936. self.gitStream.write("commit %s\n" % branch)
  1937. # gitStream.write("mark :%s\n" % details["change"])
  1938. self.committedChanges.add(int(details["change"]))
  1939. committer = ""
  1940. if author not in self.users:
  1941. self.getUserMapFromPerforceServer()
  1942. committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
  1943. self.gitStream.write("committer %s\n" % committer)
  1944. self.gitStream.write("data <<EOT\n")
  1945. self.gitStream.write(details["desc"])
  1946. self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
  1947. (','.join(self.branchPrefixes), details["change"]))
  1948. if len(details['options']) > 0:
  1949. self.gitStream.write(": options = %s" % details['options'])
  1950. self.gitStream.write("]\nEOT\n\n")
  1951. if len(parent) > 0:
  1952. if self.verbose:
  1953. print "parent %s" % parent
  1954. self.gitStream.write("from %s\n" % parent)
  1955. self.streamP4Files(new_files)
  1956. self.gitStream.write("\n")
  1957. change = int(details["change"])
  1958. if self.labels.has_key(change):
  1959. label = self.labels[change]
  1960. labelDetails = label[0]
  1961. labelRevisions = label[1]
  1962. if self.verbose:
  1963. print "Change %s is labelled %s" % (change, labelDetails)
  1964. files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
  1965. for p in self.branchPrefixes])
  1966. if len(files) == len(labelRevisions):
  1967. cleanedFiles = {}
  1968. for info in files:
  1969. if info["action"] in self.delete_actions:
  1970. continue
  1971. cleanedFiles[info["depotFile"]] = info["rev"]
  1972. if cleanedFiles == labelRevisions:
  1973. self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
  1974. else:
  1975. if not self.silent:
  1976. print ("Tag %s does not match with change %s: files do not match."
  1977. % (labelDetails["label"], change))
  1978. else:
  1979. if not self.silent:
  1980. print ("Tag %s does not match with change %s: file count is different."
  1981. % (labelDetails["label"], change))
  1982. # Build a dictionary of changelists and labels, for "detect-labels" option.
  1983. def getLabels(self):
  1984. self.labels = {}
  1985. l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
  1986. if len(l) > 0 and not self.silent:
  1987. print "Finding files belonging to labels in %s" % `self.depotPaths`
  1988. for output in l:
  1989. label = output["label"]
  1990. revisions = {}
  1991. newestChange = 0
  1992. if self.verbose:
  1993. print "Querying files for label %s" % label
  1994. for file in p4CmdList(["files"] +
  1995. ["%s...@%s" % (p, label)
  1996. for p in self.depotPaths]):
  1997. revisions[file["depotFile"]] = file["rev"]
  1998. change = int(file["change"])
  1999. if change > newestChange:
  2000. newestChange = change
  2001. self.labels[newestChange] = [output, revisions]
  2002. if self.verbose:
  2003. print "Label changes: %s" % self.labels.keys()
  2004. # Import p4 labels as git tags. A direct mapping does not
  2005. # exist, so assume that if all the files are at the same revision
  2006. # then we can use that, or it's something more complicated we should
  2007. # just ignore.
  2008. def importP4Labels(self, stream, p4Labels):
  2009. if verbose:
  2010. print "import p4 labels: " + ' '.join(p4Labels)
  2011. ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
  2012. validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
  2013. if len(validLabelRegexp) == 0:
  2014. validLabelRegexp = defaultLabelRegexp
  2015. m = re.compile(validLabelRegexp)
  2016. for name in p4Labels:
  2017. commitFound = False
  2018. if not m.match(name):
  2019. if verbose:
  2020. print "label %s does not match regexp %s" % (name,validLabelRegexp)
  2021. continue
  2022. if name in ignoredP4Labels:
  2023. continue
  2024. labelDetails = p4CmdList(['label', "-o", name])[0]
  2025. # get the most recent changelist for each file in this label
  2026. change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
  2027. for p in self.depotPaths])
  2028. if change.has_key('change'):
  2029. # find the corresponding git commit; take the oldest commit
  2030. changelist = int(change['change'])
  2031. gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
  2032. "--reverse", ":/\[git-p4:.*change = %d\]" % changelist])
  2033. if len(gitCommit) == 0:
  2034. print "could not find git commit for changelist %d" % changelist
  2035. else:
  2036. gitCommit = gitCommit.strip()
  2037. commitFound = True
  2038. # Convert from p4 time format
  2039. try:
  2040. tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
  2041. except ValueError:
  2042. print "Could not convert label time %s" % labelDetails['Update']
  2043. tmwhen = 1
  2044. when = int(time.mktime(tmwhen))
  2045. self.streamTag(stream, name, labelDetails, gitCommit, when)
  2046. if verbose:
  2047. print "p4 label %s mapped to git commit %s" % (name, gitCommit)
  2048. else:
  2049. if verbose:
  2050. print "Label %s has no changelists - possibly deleted?" % name
  2051. if not commitFound:
  2052. # We can't import this label; don't try again as it will get very
  2053. # expensive repeatedly fetching all the files for labels that will
  2054. # never be imported. If the label is moved in the future, the
  2055. # ignore will need to be removed manually.
  2056. system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
  2057. def guessProjectName(self):
  2058. for p in self.depotPaths:
  2059. if p.endswith("/"):
  2060. p = p[:-1]
  2061. p = p[p.strip().rfind("/") + 1:]
  2062. if not p.endswith("/"):
  2063. p += "/"
  2064. return p
  2065. def getBranchMapping(self):
  2066. lostAndFoundBranches = set()
  2067. user = gitConfig("git-p4.branchUser")
  2068. if len(user) > 0:
  2069. command = "branches -u %s" % user
  2070. else:
  2071. command = "branches"
  2072. for info in p4CmdList(command):
  2073. details = p4Cmd(["branch", "-o", info["branch"]])
  2074. viewIdx = 0
  2075. while details.has_key("View%s" % viewIdx):
  2076. paths = details["View%s" % viewIdx].split(" ")
  2077. viewIdx = viewIdx + 1
  2078. # require standard //depot/foo/... //depot/bar/... mapping
  2079. if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
  2080. continue
  2081. source = paths[0]
  2082. destination = paths[1]
  2083. ## HACK
  2084. if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
  2085. source = source[len(self.depotPaths[0]):-4]
  2086. destination = destination[len(self.depotPaths[0]):-4]
  2087. if destination in self.knownBranches:
  2088. if not self.silent:
  2089. print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
  2090. print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
  2091. continue
  2092. self.knownBranches[destination] = source
  2093. lostAndFoundBranches.discard(destination)
  2094. if source not in self.knownBranches:
  2095. lostAndFoundBranches.add(source)
  2096. # Perforce does not strictly require branches to be defined, so we also
  2097. # check git config for a branch list.
  2098. #
  2099. # Example of branch definition in git config file:
  2100. # [git-p4]
  2101. # branchList=main:branchA
  2102. # branchList=main:branchB
  2103. # branchList=branchA:branchC
  2104. configBranches = gitConfigList("git-p4.branchList")
  2105. for branch in configBranches:
  2106. if branch:
  2107. (source, destination) = branch.split(":")
  2108. self.knownBranches[destination] = source
  2109. lostAndFoundBranches.discard(destination)
  2110. if source not in self.knownBranches:
  2111. lostAndFoundBranches.add(source)
  2112. for branch in lostAndFoundBranches:
  2113. self.knownBranches[branch] = branch
  2114. def getBranchMappingFromGitBranches(self):
  2115. branches = p4BranchesInGit(self.importIntoRemotes)
  2116. for branch in branches.keys():
  2117. if branch == "master":
  2118. branch = "main"
  2119. else:
  2120. branch = branch[len(self.projectName):]
  2121. self.knownBranches[branch] = branch
  2122. def updateOptionDict(self, d):
  2123. option_keys = {}
  2124. if self.keepRepoPath:
  2125. option_keys['keepRepoPath'] = 1
  2126. d["options"] = ' '.join(sorted(option_keys.keys()))
  2127. def readOptions(self, d):
  2128. self.keepRepoPath = (d.has_key('options')
  2129. and ('keepRepoPath' in d['options']))
  2130. def gitRefForBranch(self, branch):
  2131. if branch == "main":
  2132. return self.refPrefix + "master"
  2133. if len(branch) <= 0:
  2134. return branch
  2135. return self.refPrefix + self.projectName + branch
  2136. def gitCommitByP4Change(self, ref, change):
  2137. if self.verbose:
  2138. print "looking in ref " + ref + " for change %s using bisect..." % change
  2139. earliestCommit = ""
  2140. latestCommit = parseRevision(ref)
  2141. while True:
  2142. if self.verbose:
  2143. print "trying: earliest %s latest %s" % (earliestCommit, latestCommit)
  2144. next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
  2145. if len(next) == 0:
  2146. if self.verbose:
  2147. print "argh"
  2148. return ""
  2149. log = extractLogMessageFromGitCommit(next)
  2150. settings = extractSettingsGitLog(log)
  2151. currentChange = int(settings['change'])
  2152. if self.verbose:
  2153. print "current change %s" % currentChange
  2154. if currentChange == change:
  2155. if self.verbose:
  2156. print "found %s" % next
  2157. return next
  2158. if currentChange < change:
  2159. earliestCommit = "^%s" % next
  2160. else:
  2161. latestCommit = "%s" % next
  2162. return ""
  2163. def importNewBranch(self, branch, maxChange):
  2164. # make fast-import flush all changes to disk and update the refs using the checkpoint
  2165. # command so that we can try to find the branch parent in the git history
  2166. self.gitStream.write("checkpoint\n\n");
  2167. self.gitStream.flush();
  2168. branchPrefix = self.depotPaths[0] + branch + "/"
  2169. range = "@1,%s" % maxChange
  2170. #print "prefix" + branchPrefix
  2171. changes = p4ChangesForPaths([branchPrefix], range)
  2172. if len(changes) <= 0:
  2173. return False
  2174. firstChange = changes[0]
  2175. #print "first change in branch: %s" % firstChange
  2176. sourceBranch = self.knownBranches[branch]
  2177. sourceDepotPath = self.depotPaths[0] + sourceBranch
  2178. sourceRef = self.gitRefForBranch(sourceBranch)
  2179. #print "source " + sourceBranch
  2180. branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
  2181. #print "branch parent: %s" % branchParentChange
  2182. gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
  2183. if len(gitParent) > 0:
  2184. self.initialParents[self.gitRefForBranch(branch)] = gitParent
  2185. #print "parent git commit: %s" % gitParent
  2186. self.importChanges(changes)
  2187. return True
  2188. def searchParent(self, parent, branch, target):
  2189. parentFound = False
  2190. for blob in read_pipe_lines(["git", "rev-list", "--reverse",
  2191. "--no-merges", parent]):
  2192. blob = blob.strip()
  2193. if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
  2194. parentFound = True
  2195. if self.verbose:
  2196. print "Found parent of %s in commit %s" % (branch, blob)
  2197. break
  2198. if parentFound:
  2199. return blob
  2200. else:
  2201. return None
  2202. def importChanges(self, changes):
  2203. cnt = 1
  2204. for change in changes:
  2205. description = p4_describe(change)
  2206. self.updateOptionDict(description)
  2207. if not self.silent:
  2208. sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
  2209. sys.stdout.flush()
  2210. cnt = cnt + 1
  2211. try:
  2212. if self.detectBranches:
  2213. branches = self.splitFilesIntoBranches(description)
  2214. for branch in branches.keys():
  2215. ## HACK --hwn
  2216. branchPrefix = self.depotPaths[0] + branch + "/"
  2217. self.branchPrefixes = [ branchPrefix ]
  2218. parent = ""
  2219. filesForCommit = branches[branch]
  2220. if self.verbose:
  2221. print "branch is %s" % branch
  2222. self.updatedBranches.add(branch)
  2223. if branch not in self.createdBranches:
  2224. self.createdBranches.add(branch)
  2225. parent = self.knownBranches[branch]
  2226. if parent == branch:
  2227. parent = ""
  2228. else:
  2229. fullBranch = self.projectName + branch
  2230. if fullBranch not in self.p4BranchesInGit:
  2231. if not self.silent:
  2232. print("\n Importing new branch %s" % fullBranch);
  2233. if self.importNewBranch(branch, change - 1):
  2234. parent = ""
  2235. self.p4BranchesInGit.append(fullBranch)
  2236. if not self.silent:
  2237. print("\n Resuming with change %s" % change);
  2238. if self.verbose:
  2239. print "parent determined through known branches: %s" % parent
  2240. branch = self.gitRefForBranch(branch)
  2241. parent = self.gitRefForBranch(parent)
  2242. if self.verbose:
  2243. print "looking for initial parent for %s; current parent is %s" % (branch, parent)
  2244. if len(parent) == 0 and branch in self.initialParents:
  2245. parent = self.initialParents[branch]
  2246. del self.initialParents[branch]
  2247. blob = None
  2248. if len(parent) > 0:
  2249. tempBranch = "%s/%d" % (self.tempBranchLocation, change)
  2250. if self.verbose:
  2251. print "Creating temporary branch: " + tempBranch
  2252. self.commit(description, filesForCommit, tempBranch)
  2253. self.tempBranches.append(tempBranch)
  2254. self.checkpoint()
  2255. blob = self.searchParent(parent, branch, tempBranch)
  2256. if blob:
  2257. self.commit(description, filesForCommit, branch, blob)
  2258. else:
  2259. if self.verbose:
  2260. print "Parent of %s not found. Committing into head of %s" % (branch, parent)
  2261. self.commit(description, filesForCommit, branch, parent)
  2262. else:
  2263. files = self.extractFilesFromCommit(description)
  2264. self.commit(description, files, self.branch,
  2265. self.initialParent)
  2266. # only needed once, to connect to the previous commit
  2267. self.initialParent = ""
  2268. except IOError:
  2269. print self.gitError.read()
  2270. sys.exit(1)
  2271. def importHeadRevision(self, revision):
  2272. print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch)
  2273. details = {}
  2274. details["user"] = "git perforce import user"
  2275. details["desc"] = ("Initial import of %s from the state at revision %s\n"
  2276. % (' '.join(self.depotPaths), revision))
  2277. details["change"] = revision
  2278. newestRevision = 0
  2279. fileCnt = 0
  2280. fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
  2281. for info in p4CmdList(["files"] + fileArgs):
  2282. if 'code' in info and info['code'] == 'error':
  2283. sys.stderr.write("p4 returned an error: %s\n"
  2284. % info['data'])
  2285. if info['data'].find("must refer to client") >= 0:
  2286. sys.stderr.write("This particular p4 error is misleading.\n")
  2287. sys.stderr.write("Perhaps the depot path was misspelled.\n");
  2288. sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
  2289. sys.exit(1)
  2290. if 'p4ExitCode' in info:
  2291. sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
  2292. sys.exit(1)
  2293. change = int(info["change"])
  2294. if change > newestRevision:
  2295. newestRevision = change
  2296. if info["action"] in self.delete_actions:
  2297. # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
  2298. #fileCnt = fileCnt + 1
  2299. continue
  2300. for prop in ["depotFile", "rev", "action", "type" ]:
  2301. details["%s%s" % (prop, fileCnt)] = info[prop]
  2302. fileCnt = fileCnt + 1
  2303. details["change"] = newestRevision
  2304. # Use time from top-most change so that all git p4 clones of
  2305. # the same p4 repo have the same commit SHA1s.
  2306. res = p4_describe(newestRevision)
  2307. details["time"] = res["time"]
  2308. self.updateOptionDict(details)
  2309. try:
  2310. self.commit(details, self.extractFilesFromCommit(details), self.branch)
  2311. except IOError:
  2312. print "IO error with git fast-import. Is your git version recent enough?"
  2313. print self.gitError.read()
  2314. def run(self, args):
  2315. self.depotPaths = []
  2316. self.changeRange = ""
  2317. self.previousDepotPaths = []
  2318. self.hasOrigin = False
  2319. # map from branch depot path to parent branch
  2320. self.knownBranches = {}
  2321. self.initialParents = {}
  2322. if self.importIntoRemotes:
  2323. self.refPrefix = "refs/remotes/p4/"
  2324. else:
  2325. self.refPrefix = "refs/heads/p4/"
  2326. if self.syncWithOrigin:
  2327. self.hasOrigin = originP4BranchesExist()
  2328. if self.hasOrigin:
  2329. if not self.silent:
  2330. print 'Syncing with origin first, using "git fetch origin"'
  2331. system("git fetch origin")
  2332. branch_arg_given = bool(self.branch)
  2333. if len(self.branch) == 0:
  2334. self.branch = self.refPrefix + "master"
  2335. if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
  2336. system("git update-ref %s refs/heads/p4" % self.branch)
  2337. system("git branch -D p4")
  2338. # accept either the command-line option, or the configuration variable
  2339. if self.useClientSpec:
  2340. # will use this after clone to set the variable
  2341. self.useClientSpec_from_options = True
  2342. else:
  2343. if gitConfigBool("git-p4.useclientspec"):
  2344. self.useClientSpec = True
  2345. if self.useClientSpec:
  2346. self.clientSpecDirs = getClientSpec()
  2347. # TODO: should always look at previous commits,
  2348. # merge with previous imports, if possible.
  2349. if args == []:
  2350. if self.hasOrigin:
  2351. createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
  2352. # branches holds mapping from branch name to sha1
  2353. branches = p4BranchesInGit(self.importIntoRemotes)
  2354. # restrict to just this one, disabling detect-branches
  2355. if branch_arg_given:
  2356. short = self.branch.split("/")[-1]
  2357. if short in branches:
  2358. self.p4BranchesInGit = [ short ]
  2359. else:
  2360. self.p4BranchesInGit = branches.keys()
  2361. if len(self.p4BranchesInGit) > 1:
  2362. if not self.silent:
  2363. print "Importing from/into multiple branches"
  2364. self.detectBranches = True
  2365. for branch in branches.keys():
  2366. self.initialParents[self.refPrefix + branch] = \
  2367. branches[branch]
  2368. if self.verbose:
  2369. print "branches: %s" % self.p4BranchesInGit
  2370. p4Change = 0
  2371. for branch in self.p4BranchesInGit:
  2372. logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
  2373. settings = extractSettingsGitLog(logMsg)
  2374. self.readOptions(settings)
  2375. if (settings.has_key('depot-paths')
  2376. and settings.has_key ('change')):
  2377. change = int(settings['change']) + 1
  2378. p4Change = max(p4Change, change)
  2379. depotPaths = sorted(settings['depot-paths'])
  2380. if self.previousDepotPaths == []:
  2381. self.previousDepotPaths = depotPaths
  2382. else:
  2383. paths = []
  2384. for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
  2385. prev_list = prev.split("/")
  2386. cur_list = cur.split("/")
  2387. for i in range(0, min(len(cur_list), len(prev_list))):
  2388. if cur_list[i] <> prev_list[i]:
  2389. i = i - 1
  2390. break
  2391. paths.append ("/".join(cur_list[:i + 1]))
  2392. self.previousDepotPaths = paths
  2393. if p4Change > 0:
  2394. self.depotPaths = sorted(self.previousDepotPaths)
  2395. self.changeRange = "@%s,#head" % p4Change
  2396. if not self.silent and not self.detectBranches:
  2397. print "Performing incremental import into %s git branch" % self.branch
  2398. # accept multiple ref name abbreviations:
  2399. # refs/foo/bar/branch -> use it exactly
  2400. # p4/branch -> prepend refs/remotes/ or refs/heads/
  2401. # branch -> prepend refs/remotes/p4/ or refs/heads/p4/
  2402. if not self.branch.startswith("refs/"):
  2403. if self.importIntoRemotes:
  2404. prepend = "refs/remotes/"
  2405. else:
  2406. prepend = "refs/heads/"
  2407. if not self.branch.startswith("p4/"):
  2408. prepend += "p4/"
  2409. self.branch = prepend + self.branch
  2410. if len(args) == 0 and self.depotPaths:
  2411. if not self.silent:
  2412. print "Depot paths: %s" % ' '.join(self.depotPaths)
  2413. else:
  2414. if self.depotPaths and self.depotPaths != args:
  2415. print ("previous import used depot path %s and now %s was specified. "
  2416. "This doesn't work!" % (' '.join (self.depotPaths),
  2417. ' '.join (args)))
  2418. sys.exit(1)
  2419. self.depotPaths = sorted(args)
  2420. revision = ""
  2421. self.users = {}
  2422. # Make sure no revision specifiers are used when --changesfile
  2423. # is specified.
  2424. bad_changesfile = False
  2425. if len(self.changesFile) > 0:
  2426. for p in self.depotPaths:
  2427. if p.find("@") >= 0 or p.find("#") >= 0:
  2428. bad_changesfile = True
  2429. break
  2430. if bad_changesfile:
  2431. die("Option --changesfile is incompatible with revision specifiers")
  2432. newPaths = []
  2433. for p in self.depotPaths:
  2434. if p.find("@") != -1:
  2435. atIdx = p.index("@")
  2436. self.changeRange = p[atIdx:]
  2437. if self.changeRange == "@all":
  2438. self.changeRange = ""
  2439. elif ',' not in self.changeRange:
  2440. revision = self.changeRange
  2441. self.changeRange = ""
  2442. p = p[:atIdx]
  2443. elif p.find("#") != -1:
  2444. hashIdx = p.index("#")
  2445. revision = p[hashIdx:]
  2446. p = p[:hashIdx]
  2447. elif self.previousDepotPaths == []:
  2448. # pay attention to changesfile, if given, else import
  2449. # the entire p4 tree at the head revision
  2450. if len(self.changesFile) == 0:
  2451. revision = "#head"
  2452. p = re.sub ("\.\.\.$", "", p)
  2453. if not p.endswith("/"):
  2454. p += "/"
  2455. newPaths.append(p)
  2456. self.depotPaths = newPaths
  2457. # --detect-branches may change this for each branch
  2458. self.branchPrefixes = self.depotPaths
  2459. self.loadUserMapFromCache()
  2460. self.labels = {}
  2461. if self.detectLabels:
  2462. self.getLabels();
  2463. if self.detectBranches:
  2464. ## FIXME - what's a P4 projectName ?
  2465. self.projectName = self.guessProjectName()
  2466. if self.hasOrigin:
  2467. self.getBranchMappingFromGitBranches()
  2468. else:
  2469. self.getBranchMapping()
  2470. if self.verbose:
  2471. print "p4-git branches: %s" % self.p4BranchesInGit
  2472. print "initial parents: %s" % self.initialParents
  2473. for b in self.p4BranchesInGit:
  2474. if b != "master":
  2475. ## FIXME
  2476. b = b[len(self.projectName):]
  2477. self.createdBranches.add(b)
  2478. self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
  2479. self.importProcess = subprocess.Popen(["git", "fast-import"],
  2480. stdin=subprocess.PIPE,
  2481. stdout=subprocess.PIPE,
  2482. stderr=subprocess.PIPE);
  2483. self.gitOutput = self.importProcess.stdout
  2484. self.gitStream = self.importProcess.stdin
  2485. self.gitError = self.importProcess.stderr
  2486. if revision:
  2487. self.importHeadRevision(revision)
  2488. else:
  2489. changes = []
  2490. if len(self.changesFile) > 0:
  2491. output = open(self.changesFile).readlines()
  2492. changeSet = set()
  2493. for line in output:
  2494. changeSet.add(int(line))
  2495. for change in changeSet:
  2496. changes.append(change)
  2497. changes.sort()
  2498. else:
  2499. # catch "git p4 sync" with no new branches, in a repo that
  2500. # does not have any existing p4 branches
  2501. if len(args) == 0:
  2502. if not self.p4BranchesInGit:
  2503. die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
  2504. # The default branch is master, unless --branch is used to
  2505. # specify something else. Make sure it exists, or complain
  2506. # nicely about how to use --branch.
  2507. if not self.detectBranches:
  2508. if not branch_exists(self.branch):
  2509. if branch_arg_given:
  2510. die("Error: branch %s does not exist." % self.branch)
  2511. else:
  2512. die("Error: no branch %s; perhaps specify one with --branch." %
  2513. self.branch)
  2514. if self.verbose:
  2515. print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
  2516. self.changeRange)
  2517. changes = p4ChangesForPaths(self.depotPaths, self.changeRange)
  2518. if len(self.maxChanges) > 0:
  2519. changes = changes[:min(int(self.maxChanges), len(changes))]
  2520. if len(changes) == 0:
  2521. if not self.silent:
  2522. print "No changes to import!"
  2523. else:
  2524. if not self.silent and not self.detectBranches:
  2525. print "Import destination: %s" % self.branch
  2526. self.updatedBranches = set()
  2527. if not self.detectBranches:
  2528. if args:
  2529. # start a new branch
  2530. self.initialParent = ""
  2531. else:
  2532. # build on a previous revision
  2533. self.initialParent = parseRevision(self.branch)
  2534. self.importChanges(changes)
  2535. if not self.silent:
  2536. print ""
  2537. if len(self.updatedBranches) > 0:
  2538. sys.stdout.write("Updated branches: ")
  2539. for b in self.updatedBranches:
  2540. sys.stdout.write("%s " % b)
  2541. sys.stdout.write("\n")
  2542. if gitConfigBool("git-p4.importLabels"):
  2543. self.importLabels = True
  2544. if self.importLabels:
  2545. p4Labels = getP4Labels(self.depotPaths)
  2546. gitTags = getGitTags()
  2547. missingP4Labels = p4Labels - gitTags
  2548. self.importP4Labels(self.gitStream, missingP4Labels)
  2549. self.gitStream.close()
  2550. if self.importProcess.wait() != 0:
  2551. die("fast-import failed: %s" % self.gitError.read())
  2552. self.gitOutput.close()
  2553. self.gitError.close()
  2554. # Cleanup temporary branches created during import
  2555. if self.tempBranches != []:
  2556. for branch in self.tempBranches:
  2557. read_pipe("git update-ref -d %s" % branch)
  2558. os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
  2559. # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
  2560. # a convenient shortcut refname "p4".
  2561. if self.importIntoRemotes:
  2562. head_ref = self.refPrefix + "HEAD"
  2563. if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
  2564. system(["git", "symbolic-ref", head_ref, self.branch])
  2565. return True
  2566. class P4Rebase(Command):
  2567. def __init__(self):
  2568. Command.__init__(self)
  2569. self.options = [
  2570. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  2571. ]
  2572. self.importLabels = False
  2573. self.description = ("Fetches the latest revision from perforce and "
  2574. + "rebases the current work (branch) against it")
  2575. def run(self, args):
  2576. sync = P4Sync()
  2577. sync.importLabels = self.importLabels
  2578. sync.run([])
  2579. return self.rebase()
  2580. def rebase(self):
  2581. if os.system("git update-index --refresh") != 0:
  2582. die("Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up-to-date or stash away all your changes with git stash.");
  2583. if len(read_pipe("git diff-index HEAD --")) > 0:
  2584. die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
  2585. [upstream, settings] = findUpstreamBranchPoint()
  2586. if len(upstream) == 0:
  2587. die("Cannot find upstream branchpoint for rebase")
  2588. # the branchpoint may be p4/foo~3, so strip off the parent
  2589. upstream = re.sub("~[0-9]+$", "", upstream)
  2590. print "Rebasing the current branch onto %s" % upstream
  2591. oldHead = read_pipe("git rev-parse HEAD").strip()
  2592. system("git rebase %s" % upstream)
  2593. system("git diff-tree --stat --summary -M %s HEAD --" % oldHead)
  2594. return True
  2595. class P4Clone(P4Sync):
  2596. def __init__(self):
  2597. P4Sync.__init__(self)
  2598. self.description = "Creates a new git repository and imports from Perforce into it"
  2599. self.usage = "usage: %prog [options] //depot/path[@revRange]"
  2600. self.options += [
  2601. optparse.make_option("--destination", dest="cloneDestination",
  2602. action='store', default=None,
  2603. help="where to leave result of the clone"),
  2604. optparse.make_option("-/", dest="cloneExclude",
  2605. action="append", type="string",
  2606. help="exclude depot path"),
  2607. optparse.make_option("--bare", dest="cloneBare",
  2608. action="store_true", default=False),
  2609. ]
  2610. self.cloneDestination = None
  2611. self.needsGit = False
  2612. self.cloneBare = False
  2613. # This is required for the "append" cloneExclude action
  2614. def ensure_value(self, attr, value):
  2615. if not hasattr(self, attr) or getattr(self, attr) is None:
  2616. setattr(self, attr, value)
  2617. return getattr(self, attr)
  2618. def defaultDestination(self, args):
  2619. ## TODO: use common prefix of args?
  2620. depotPath = args[0]
  2621. depotDir = re.sub("(@[^@]*)$", "", depotPath)
  2622. depotDir = re.sub("(#[^#]*)$", "", depotDir)
  2623. depotDir = re.sub(r"\.\.\.$", "", depotDir)
  2624. depotDir = re.sub(r"/$", "", depotDir)
  2625. return os.path.split(depotDir)[1]
  2626. def run(self, args):
  2627. if len(args) < 1:
  2628. return False
  2629. if self.keepRepoPath and not self.cloneDestination:
  2630. sys.stderr.write("Must specify destination for --keep-path\n")
  2631. sys.exit(1)
  2632. depotPaths = args
  2633. if not self.cloneDestination and len(depotPaths) > 1:
  2634. self.cloneDestination = depotPaths[-1]
  2635. depotPaths = depotPaths[:-1]
  2636. self.cloneExclude = ["/"+p for p in self.cloneExclude]
  2637. for p in depotPaths:
  2638. if not p.startswith("//"):
  2639. sys.stderr.write('Depot paths must start with "//": %s\n' % p)
  2640. return False
  2641. if not self.cloneDestination:
  2642. self.cloneDestination = self.defaultDestination(args)
  2643. print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
  2644. if not os.path.exists(self.cloneDestination):
  2645. os.makedirs(self.cloneDestination)
  2646. chdir(self.cloneDestination)
  2647. init_cmd = [ "git", "init" ]
  2648. if self.cloneBare:
  2649. init_cmd.append("--bare")
  2650. retcode = subprocess.call(init_cmd)
  2651. if retcode:
  2652. raise CalledProcessError(retcode, init_cmd)
  2653. if not P4Sync.run(self, depotPaths):
  2654. return False
  2655. # create a master branch and check out a work tree
  2656. if gitBranchExists(self.branch):
  2657. system([ "git", "branch", "master", self.branch ])
  2658. if not self.cloneBare:
  2659. system([ "git", "checkout", "-f" ])
  2660. else:
  2661. print 'Not checking out any branch, use ' \
  2662. '"git checkout -q -b master <branch>"'
  2663. # auto-set this variable if invoked with --use-client-spec
  2664. if self.useClientSpec_from_options:
  2665. system("git config --bool git-p4.useclientspec true")
  2666. return True
  2667. class P4Branches(Command):
  2668. def __init__(self):
  2669. Command.__init__(self)
  2670. self.options = [ ]
  2671. self.description = ("Shows the git branches that hold imports and their "
  2672. + "corresponding perforce depot paths")
  2673. self.verbose = False
  2674. def run(self, args):
  2675. if originP4BranchesExist():
  2676. createOrUpdateBranchesFromOrigin()
  2677. cmdline = "git rev-parse --symbolic "
  2678. cmdline += " --remotes"
  2679. for line in read_pipe_lines(cmdline):
  2680. line = line.strip()
  2681. if not line.startswith('p4/') or line == "p4/HEAD":
  2682. continue
  2683. branch = line
  2684. log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
  2685. settings = extractSettingsGitLog(log)
  2686. print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
  2687. return True
  2688. class HelpFormatter(optparse.IndentedHelpFormatter):
  2689. def __init__(self):
  2690. optparse.IndentedHelpFormatter.__init__(self)
  2691. def format_description(self, description):
  2692. if description:
  2693. return description + "\n"
  2694. else:
  2695. return ""
  2696. def printUsage(commands):
  2697. print "usage: %s <command> [options]" % sys.argv[0]
  2698. print ""
  2699. print "valid commands: %s" % ", ".join(commands)
  2700. print ""
  2701. print "Try %s <command> --help for command specific help." % sys.argv[0]
  2702. print ""
  2703. commands = {
  2704. "debug" : P4Debug,
  2705. "submit" : P4Submit,
  2706. "commit" : P4Submit,
  2707. "sync" : P4Sync,
  2708. "rebase" : P4Rebase,
  2709. "clone" : P4Clone,
  2710. "rollback" : P4RollBack,
  2711. "branches" : P4Branches
  2712. }
  2713. def main():
  2714. if len(sys.argv[1:]) == 0:
  2715. printUsage(commands.keys())
  2716. sys.exit(2)
  2717. cmdName = sys.argv[1]
  2718. try:
  2719. klass = commands[cmdName]
  2720. cmd = klass()
  2721. except KeyError:
  2722. print "unknown command %s" % cmdName
  2723. print ""
  2724. printUsage(commands.keys())
  2725. sys.exit(2)
  2726. options = cmd.options
  2727. cmd.gitdir = os.environ.get("GIT_DIR", None)
  2728. args = sys.argv[2:]
  2729. options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
  2730. if cmd.needsGit:
  2731. options.append(optparse.make_option("--git-dir", dest="gitdir"))
  2732. parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
  2733. options,
  2734. description = cmd.description,
  2735. formatter = HelpFormatter())
  2736. (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
  2737. global verbose
  2738. verbose = cmd.verbose
  2739. if cmd.needsGit:
  2740. if cmd.gitdir == None:
  2741. cmd.gitdir = os.path.abspath(".git")
  2742. if not isValidGitDir(cmd.gitdir):
  2743. cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
  2744. if os.path.exists(cmd.gitdir):
  2745. cdup = read_pipe("git rev-parse --show-cdup").strip()
  2746. if len(cdup) > 0:
  2747. chdir(cdup);
  2748. if not isValidGitDir(cmd.gitdir):
  2749. if isValidGitDir(cmd.gitdir + "/.git"):
  2750. cmd.gitdir += "/.git"
  2751. else:
  2752. die("fatal: cannot locate git repository at %s" % cmd.gitdir)
  2753. os.environ["GIT_DIR"] = cmd.gitdir
  2754. if not cmd.run(args):
  2755. parser.print_help()
  2756. sys.exit(2)
  2757. if __name__ == '__main__':
  2758. main()