THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4173 lines
154KB

  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. import zipfile
  26. import zlib
  27. import ctypes
  28. import errno
  29. # support basestring in python3
  30. try:
  31. unicode = unicode
  32. except NameError:
  33. # 'unicode' is undefined, must be Python 3
  34. str = str
  35. unicode = str
  36. bytes = bytes
  37. basestring = (str,bytes)
  38. else:
  39. # 'unicode' exists, must be Python 2
  40. str = str
  41. unicode = unicode
  42. bytes = str
  43. basestring = basestring
  44. try:
  45. from subprocess import CalledProcessError
  46. except ImportError:
  47. # from python2.7:subprocess.py
  48. # Exception classes used by this module.
  49. class CalledProcessError(Exception):
  50. """This exception is raised when a process run by check_call() returns
  51. a non-zero exit status. The exit status will be stored in the
  52. returncode attribute."""
  53. def __init__(self, returncode, cmd):
  54. self.returncode = returncode
  55. self.cmd = cmd
  56. def __str__(self):
  57. return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  58. verbose = False
  59. # Only labels/tags matching this will be imported/exported
  60. defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
  61. # The block size is reduced automatically if required
  62. defaultBlockSize = 1<<20
  63. p4_access_checked = False
  64. def p4_build_cmd(cmd):
  65. """Build a suitable p4 command line.
  66. This consolidates building and returning a p4 command line into one
  67. location. It means that hooking into the environment, or other configuration
  68. can be done more easily.
  69. """
  70. real_cmd = ["p4"]
  71. user = gitConfig("git-p4.user")
  72. if len(user) > 0:
  73. real_cmd += ["-u",user]
  74. password = gitConfig("git-p4.password")
  75. if len(password) > 0:
  76. real_cmd += ["-P", password]
  77. port = gitConfig("git-p4.port")
  78. if len(port) > 0:
  79. real_cmd += ["-p", port]
  80. host = gitConfig("git-p4.host")
  81. if len(host) > 0:
  82. real_cmd += ["-H", host]
  83. client = gitConfig("git-p4.client")
  84. if len(client) > 0:
  85. real_cmd += ["-c", client]
  86. retries = gitConfigInt("git-p4.retries")
  87. if retries is None:
  88. # Perform 3 retries by default
  89. retries = 3
  90. if retries > 0:
  91. # Provide a way to not pass this option by setting git-p4.retries to 0
  92. real_cmd += ["-r", str(retries)]
  93. if isinstance(cmd,basestring):
  94. real_cmd = ' '.join(real_cmd) + ' ' + cmd
  95. else:
  96. real_cmd += cmd
  97. # now check that we can actually talk to the server
  98. global p4_access_checked
  99. if not p4_access_checked:
  100. p4_access_checked = True # suppress access checks in p4_check_access itself
  101. p4_check_access()
  102. return real_cmd
  103. def git_dir(path):
  104. """ Return TRUE if the given path is a git directory (/path/to/dir/.git).
  105. This won't automatically add ".git" to a directory.
  106. """
  107. d = read_pipe(["git", "--git-dir", path, "rev-parse", "--git-dir"], True).strip()
  108. if not d or len(d) == 0:
  109. return None
  110. else:
  111. return d
  112. def chdir(path, is_client_path=False):
  113. """Do chdir to the given path, and set the PWD environment
  114. variable for use by P4. It does not look at getcwd() output.
  115. Since we're not using the shell, it is necessary to set the
  116. PWD environment variable explicitly.
  117. Normally, expand the path to force it to be absolute. This
  118. addresses the use of relative path names inside P4 settings,
  119. e.g. P4CONFIG=.p4config. P4 does not simply open the filename
  120. as given; it looks for .p4config using PWD.
  121. If is_client_path, the path was handed to us directly by p4,
  122. and may be a symbolic link. Do not call os.getcwd() in this
  123. case, because it will cause p4 to think that PWD is not inside
  124. the client path.
  125. """
  126. os.chdir(path)
  127. if not is_client_path:
  128. path = os.getcwd()
  129. os.environ['PWD'] = path
  130. def calcDiskFree():
  131. """Return free space in bytes on the disk of the given dirname."""
  132. if platform.system() == 'Windows':
  133. free_bytes = ctypes.c_ulonglong(0)
  134. ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()), None, None, ctypes.pointer(free_bytes))
  135. return free_bytes.value
  136. else:
  137. st = os.statvfs(os.getcwd())
  138. return st.f_bavail * st.f_frsize
  139. def die(msg):
  140. if verbose:
  141. raise Exception(msg)
  142. else:
  143. sys.stderr.write(msg + "\n")
  144. sys.exit(1)
  145. def write_pipe(c, stdin):
  146. if verbose:
  147. sys.stderr.write('Writing pipe: %s\n' % str(c))
  148. expand = isinstance(c,basestring)
  149. p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
  150. pipe = p.stdin
  151. val = pipe.write(stdin)
  152. pipe.close()
  153. if p.wait():
  154. die('Command failed: %s' % str(c))
  155. return val
  156. def p4_write_pipe(c, stdin):
  157. real_cmd = p4_build_cmd(c)
  158. return write_pipe(real_cmd, stdin)
  159. def read_pipe_full(c):
  160. """ Read output from command. Returns a tuple
  161. of the return status, stdout text and stderr
  162. text.
  163. """
  164. if verbose:
  165. sys.stderr.write('Reading pipe: %s\n' % str(c))
  166. expand = isinstance(c,basestring)
  167. p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
  168. (out, err) = p.communicate()
  169. return (p.returncode, out, err)
  170. def read_pipe(c, ignore_error=False):
  171. """ Read output from command. Returns the output text on
  172. success. On failure, terminates execution, unless
  173. ignore_error is True, when it returns an empty string.
  174. """
  175. (retcode, out, err) = read_pipe_full(c)
  176. if retcode != 0:
  177. if ignore_error:
  178. out = ""
  179. else:
  180. die('Command failed: %s\nError: %s' % (str(c), err))
  181. return out
  182. def read_pipe_text(c):
  183. """ Read output from a command with trailing whitespace stripped.
  184. On error, returns None.
  185. """
  186. (retcode, out, err) = read_pipe_full(c)
  187. if retcode != 0:
  188. return None
  189. else:
  190. return out.rstrip()
  191. def p4_read_pipe(c, ignore_error=False):
  192. real_cmd = p4_build_cmd(c)
  193. return read_pipe(real_cmd, ignore_error)
  194. def read_pipe_lines(c):
  195. if verbose:
  196. sys.stderr.write('Reading pipe: %s\n' % str(c))
  197. expand = isinstance(c, basestring)
  198. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  199. pipe = p.stdout
  200. val = pipe.readlines()
  201. if pipe.close() or p.wait():
  202. die('Command failed: %s' % str(c))
  203. return val
  204. def p4_read_pipe_lines(c):
  205. """Specifically invoke p4 on the command supplied. """
  206. real_cmd = p4_build_cmd(c)
  207. return read_pipe_lines(real_cmd)
  208. def p4_has_command(cmd):
  209. """Ask p4 for help on this command. If it returns an error, the
  210. command does not exist in this version of p4."""
  211. real_cmd = p4_build_cmd(["help", cmd])
  212. p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
  213. stderr=subprocess.PIPE)
  214. p.communicate()
  215. return p.returncode == 0
  216. def p4_has_move_command():
  217. """See if the move command exists, that it supports -k, and that
  218. it has not been administratively disabled. The arguments
  219. must be correct, but the filenames do not have to exist. Use
  220. ones with wildcards so even if they exist, it will fail."""
  221. if not p4_has_command("move"):
  222. return False
  223. cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
  224. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  225. (out, err) = p.communicate()
  226. # return code will be 1 in either case
  227. if err.find("Invalid option") >= 0:
  228. return False
  229. if err.find("disabled") >= 0:
  230. return False
  231. # assume it failed because @... was invalid changelist
  232. return True
  233. def system(cmd, ignore_error=False):
  234. expand = isinstance(cmd,basestring)
  235. if verbose:
  236. sys.stderr.write("executing %s\n" % str(cmd))
  237. retcode = subprocess.call(cmd, shell=expand)
  238. if retcode and not ignore_error:
  239. raise CalledProcessError(retcode, cmd)
  240. return retcode
  241. def p4_system(cmd):
  242. """Specifically invoke p4 as the system command. """
  243. real_cmd = p4_build_cmd(cmd)
  244. expand = isinstance(real_cmd, basestring)
  245. retcode = subprocess.call(real_cmd, shell=expand)
  246. if retcode:
  247. raise CalledProcessError(retcode, real_cmd)
  248. def die_bad_access(s):
  249. die("failure accessing depot: {0}".format(s.rstrip()))
  250. def p4_check_access(min_expiration=1):
  251. """ Check if we can access Perforce - account still logged in
  252. """
  253. results = p4CmdList(["login", "-s"])
  254. if len(results) == 0:
  255. # should never get here: always get either some results, or a p4ExitCode
  256. assert("could not parse response from perforce")
  257. result = results[0]
  258. if 'p4ExitCode' in result:
  259. # p4 returned non-zero status, e.g. P4PORT invalid, or p4 not in path
  260. die_bad_access("could not run p4")
  261. code = result.get("code")
  262. if not code:
  263. # we get here if we couldn't connect and there was nothing to unmarshal
  264. die_bad_access("could not connect")
  265. elif code == "stat":
  266. expiry = result.get("TicketExpiration")
  267. if expiry:
  268. expiry = int(expiry)
  269. if expiry > min_expiration:
  270. # ok to carry on
  271. return
  272. else:
  273. die_bad_access("perforce ticket expires in {0} seconds".format(expiry))
  274. else:
  275. # account without a timeout - all ok
  276. return
  277. elif code == "error":
  278. data = result.get("data")
  279. if data:
  280. die_bad_access("p4 error: {0}".format(data))
  281. else:
  282. die_bad_access("unknown error")
  283. elif code == "info":
  284. return
  285. else:
  286. die_bad_access("unknown error code {0}".format(code))
  287. _p4_version_string = None
  288. def p4_version_string():
  289. """Read the version string, showing just the last line, which
  290. hopefully is the interesting version bit.
  291. $ p4 -V
  292. Perforce - The Fast Software Configuration Management System.
  293. Copyright 1995-2011 Perforce Software. All rights reserved.
  294. Rev. P4/NTX86/2011.1/393975 (2011/12/16).
  295. """
  296. global _p4_version_string
  297. if not _p4_version_string:
  298. a = p4_read_pipe_lines(["-V"])
  299. _p4_version_string = a[-1].rstrip()
  300. return _p4_version_string
  301. def p4_integrate(src, dest):
  302. p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
  303. def p4_sync(f, *options):
  304. p4_system(["sync"] + list(options) + [wildcard_encode(f)])
  305. def p4_add(f):
  306. # forcibly add file names with wildcards
  307. if wildcard_present(f):
  308. p4_system(["add", "-f", f])
  309. else:
  310. p4_system(["add", f])
  311. def p4_delete(f):
  312. p4_system(["delete", wildcard_encode(f)])
  313. def p4_edit(f, *options):
  314. p4_system(["edit"] + list(options) + [wildcard_encode(f)])
  315. def p4_revert(f):
  316. p4_system(["revert", wildcard_encode(f)])
  317. def p4_reopen(type, f):
  318. p4_system(["reopen", "-t", type, wildcard_encode(f)])
  319. def p4_reopen_in_change(changelist, files):
  320. cmd = ["reopen", "-c", str(changelist)] + files
  321. p4_system(cmd)
  322. def p4_move(src, dest):
  323. p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
  324. def p4_last_change():
  325. results = p4CmdList(["changes", "-m", "1"], skip_info=True)
  326. return int(results[0]['change'])
  327. def p4_describe(change, shelved=False):
  328. """Make sure it returns a valid result by checking for
  329. the presence of field "time". Return a dict of the
  330. results."""
  331. cmd = ["describe", "-s"]
  332. if shelved:
  333. cmd += ["-S"]
  334. cmd += [str(change)]
  335. ds = p4CmdList(cmd, skip_info=True)
  336. if len(ds) != 1:
  337. die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
  338. d = ds[0]
  339. if "p4ExitCode" in d:
  340. die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
  341. str(d)))
  342. if "code" in d:
  343. if d["code"] == "error":
  344. die("p4 describe -s %d returned error code: %s" % (change, str(d)))
  345. if "time" not in d:
  346. die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
  347. return d
  348. #
  349. # Canonicalize the p4 type and return a tuple of the
  350. # base type, plus any modifiers. See "p4 help filetypes"
  351. # for a list and explanation.
  352. #
  353. def split_p4_type(p4type):
  354. p4_filetypes_historical = {
  355. "ctempobj": "binary+Sw",
  356. "ctext": "text+C",
  357. "cxtext": "text+Cx",
  358. "ktext": "text+k",
  359. "kxtext": "text+kx",
  360. "ltext": "text+F",
  361. "tempobj": "binary+FSw",
  362. "ubinary": "binary+F",
  363. "uresource": "resource+F",
  364. "uxbinary": "binary+Fx",
  365. "xbinary": "binary+x",
  366. "xltext": "text+Fx",
  367. "xtempobj": "binary+Swx",
  368. "xtext": "text+x",
  369. "xunicode": "unicode+x",
  370. "xutf16": "utf16+x",
  371. }
  372. if p4type in p4_filetypes_historical:
  373. p4type = p4_filetypes_historical[p4type]
  374. mods = ""
  375. s = p4type.split("+")
  376. base = s[0]
  377. mods = ""
  378. if len(s) > 1:
  379. mods = s[1]
  380. return (base, mods)
  381. #
  382. # return the raw p4 type of a file (text, text+ko, etc)
  383. #
  384. def p4_type(f):
  385. results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
  386. return results[0]['headType']
  387. #
  388. # Given a type base and modifier, return a regexp matching
  389. # the keywords that can be expanded in the file
  390. #
  391. def p4_keywords_regexp_for_type(base, type_mods):
  392. if base in ("text", "unicode", "binary"):
  393. kwords = None
  394. if "ko" in type_mods:
  395. kwords = 'Id|Header'
  396. elif "k" in type_mods:
  397. kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
  398. else:
  399. return None
  400. pattern = r"""
  401. \$ # Starts with a dollar, followed by...
  402. (%s) # one of the keywords, followed by...
  403. (:[^$\n]+)? # possibly an old expansion, followed by...
  404. \$ # another dollar
  405. """ % kwords
  406. return pattern
  407. else:
  408. return None
  409. #
  410. # Given a file, return a regexp matching the possible
  411. # RCS keywords that will be expanded, or None for files
  412. # with kw expansion turned off.
  413. #
  414. def p4_keywords_regexp_for_file(file):
  415. if not os.path.exists(file):
  416. return None
  417. else:
  418. (type_base, type_mods) = split_p4_type(p4_type(file))
  419. return p4_keywords_regexp_for_type(type_base, type_mods)
  420. def setP4ExecBit(file, mode):
  421. # Reopens an already open file and changes the execute bit to match
  422. # the execute bit setting in the passed in mode.
  423. p4Type = "+x"
  424. if not isModeExec(mode):
  425. p4Type = getP4OpenedType(file)
  426. p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
  427. p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
  428. if p4Type[-1] == "+":
  429. p4Type = p4Type[0:-1]
  430. p4_reopen(p4Type, file)
  431. def getP4OpenedType(file):
  432. # Returns the perforce file type for the given file.
  433. result = p4_read_pipe(["opened", wildcard_encode(file)])
  434. match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
  435. if match:
  436. return match.group(1)
  437. else:
  438. die("Could not determine file type for %s (result: '%s')" % (file, result))
  439. # Return the set of all p4 labels
  440. def getP4Labels(depotPaths):
  441. labels = set()
  442. if isinstance(depotPaths,basestring):
  443. depotPaths = [depotPaths]
  444. for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
  445. label = l['label']
  446. labels.add(label)
  447. return labels
  448. # Return the set of all git tags
  449. def getGitTags():
  450. gitTags = set()
  451. for line in read_pipe_lines(["git", "tag"]):
  452. tag = line.strip()
  453. gitTags.add(tag)
  454. return gitTags
  455. def diffTreePattern():
  456. # This is a simple generator for the diff tree regex pattern. This could be
  457. # a class variable if this and parseDiffTreeEntry were a part of a class.
  458. pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
  459. while True:
  460. yield pattern
  461. def parseDiffTreeEntry(entry):
  462. """Parses a single diff tree entry into its component elements.
  463. See git-diff-tree(1) manpage for details about the format of the diff
  464. output. This method returns a dictionary with the following elements:
  465. src_mode - The mode of the source file
  466. dst_mode - The mode of the destination file
  467. src_sha1 - The sha1 for the source file
  468. dst_sha1 - The sha1 fr the destination file
  469. status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
  470. status_score - The score for the status (applicable for 'C' and 'R'
  471. statuses). This is None if there is no score.
  472. src - The path for the source file.
  473. dst - The path for the destination file. This is only present for
  474. copy or renames. If it is not present, this is None.
  475. If the pattern is not matched, None is returned."""
  476. match = diffTreePattern().next().match(entry)
  477. if match:
  478. return {
  479. 'src_mode': match.group(1),
  480. 'dst_mode': match.group(2),
  481. 'src_sha1': match.group(3),
  482. 'dst_sha1': match.group(4),
  483. 'status': match.group(5),
  484. 'status_score': match.group(6),
  485. 'src': match.group(7),
  486. 'dst': match.group(10)
  487. }
  488. return None
  489. def isModeExec(mode):
  490. # Returns True if the given git mode represents an executable file,
  491. # otherwise False.
  492. return mode[-3:] == "755"
  493. class P4Exception(Exception):
  494. """ Base class for exceptions from the p4 client """
  495. def __init__(self, exit_code):
  496. self.p4ExitCode = exit_code
  497. class P4ServerException(P4Exception):
  498. """ Base class for exceptions where we get some kind of marshalled up result from the server """
  499. def __init__(self, exit_code, p4_result):
  500. super(P4ServerException, self).__init__(exit_code)
  501. self.p4_result = p4_result
  502. self.code = p4_result[0]['code']
  503. self.data = p4_result[0]['data']
  504. class P4RequestSizeException(P4ServerException):
  505. """ One of the maxresults or maxscanrows errors """
  506. def __init__(self, exit_code, p4_result, limit):
  507. super(P4RequestSizeException, self).__init__(exit_code, p4_result)
  508. self.limit = limit
  509. def isModeExecChanged(src_mode, dst_mode):
  510. return isModeExec(src_mode) != isModeExec(dst_mode)
  511. def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
  512. errors_as_exceptions=False):
  513. if isinstance(cmd,basestring):
  514. cmd = "-G " + cmd
  515. expand = True
  516. else:
  517. cmd = ["-G"] + cmd
  518. expand = False
  519. cmd = p4_build_cmd(cmd)
  520. if verbose:
  521. sys.stderr.write("Opening pipe: %s\n" % str(cmd))
  522. # Use a temporary file to avoid deadlocks without
  523. # subprocess.communicate(), which would put another copy
  524. # of stdout into memory.
  525. stdin_file = None
  526. if stdin is not None:
  527. stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
  528. if isinstance(stdin,basestring):
  529. stdin_file.write(stdin)
  530. else:
  531. for i in stdin:
  532. stdin_file.write(i + '\n')
  533. stdin_file.flush()
  534. stdin_file.seek(0)
  535. p4 = subprocess.Popen(cmd,
  536. shell=expand,
  537. stdin=stdin_file,
  538. stdout=subprocess.PIPE)
  539. result = []
  540. try:
  541. while True:
  542. entry = marshal.load(p4.stdout)
  543. if skip_info:
  544. if 'code' in entry and entry['code'] == 'info':
  545. continue
  546. if cb is not None:
  547. cb(entry)
  548. else:
  549. result.append(entry)
  550. except EOFError:
  551. pass
  552. exitCode = p4.wait()
  553. if exitCode != 0:
  554. if errors_as_exceptions:
  555. if len(result) > 0:
  556. data = result[0].get('data')
  557. if data:
  558. m = re.search('Too many rows scanned \(over (\d+)\)', data)
  559. if not m:
  560. m = re.search('Request too large \(over (\d+)\)', data)
  561. if m:
  562. limit = int(m.group(1))
  563. raise P4RequestSizeException(exitCode, result, limit)
  564. raise P4ServerException(exitCode, result)
  565. else:
  566. raise P4Exception(exitCode)
  567. else:
  568. entry = {}
  569. entry["p4ExitCode"] = exitCode
  570. result.append(entry)
  571. return result
  572. def p4Cmd(cmd):
  573. list = p4CmdList(cmd)
  574. result = {}
  575. for entry in list:
  576. result.update(entry)
  577. return result;
  578. def p4Where(depotPath):
  579. if not depotPath.endswith("/"):
  580. depotPath += "/"
  581. depotPathLong = depotPath + "..."
  582. outputList = p4CmdList(["where", depotPathLong])
  583. output = None
  584. for entry in outputList:
  585. if "depotFile" in entry:
  586. # Search for the base client side depot path, as long as it starts with the branch's P4 path.
  587. # The base path always ends with "/...".
  588. if entry["depotFile"].find(depotPath) == 0 and entry["depotFile"][-4:] == "/...":
  589. output = entry
  590. break
  591. elif "data" in entry:
  592. data = entry.get("data")
  593. space = data.find(" ")
  594. if data[:space] == depotPath:
  595. output = entry
  596. break
  597. if output == None:
  598. return ""
  599. if output["code"] == "error":
  600. return ""
  601. clientPath = ""
  602. if "path" in output:
  603. clientPath = output.get("path")
  604. elif "data" in output:
  605. data = output.get("data")
  606. lastSpace = data.rfind(" ")
  607. clientPath = data[lastSpace + 1:]
  608. if clientPath.endswith("..."):
  609. clientPath = clientPath[:-3]
  610. return clientPath
  611. def currentGitBranch():
  612. return read_pipe_text(["git", "symbolic-ref", "--short", "-q", "HEAD"])
  613. def isValidGitDir(path):
  614. return git_dir(path) != None
  615. def parseRevision(ref):
  616. return read_pipe("git rev-parse %s" % ref).strip()
  617. def branchExists(ref):
  618. rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
  619. ignore_error=True)
  620. return len(rev) > 0
  621. def extractLogMessageFromGitCommit(commit):
  622. logMessage = ""
  623. ## fixme: title is first line of commit, not 1st paragraph.
  624. foundTitle = False
  625. for log in read_pipe_lines(["git", "cat-file", "commit", commit]):
  626. if not foundTitle:
  627. if len(log) == 1:
  628. foundTitle = True
  629. continue
  630. logMessage += log
  631. return logMessage
  632. def extractSettingsGitLog(log):
  633. values = {}
  634. for line in log.split("\n"):
  635. line = line.strip()
  636. m = re.search (r"^ *\[git-p4: (.*)\]$", line)
  637. if not m:
  638. continue
  639. assignments = m.group(1).split (':')
  640. for a in assignments:
  641. vals = a.split ('=')
  642. key = vals[0].strip()
  643. val = ('='.join (vals[1:])).strip()
  644. if val.endswith ('\"') and val.startswith('"'):
  645. val = val[1:-1]
  646. values[key] = val
  647. paths = values.get("depot-paths")
  648. if not paths:
  649. paths = values.get("depot-path")
  650. if paths:
  651. values['depot-paths'] = paths.split(',')
  652. return values
  653. def gitBranchExists(branch):
  654. proc = subprocess.Popen(["git", "rev-parse", branch],
  655. stderr=subprocess.PIPE, stdout=subprocess.PIPE);
  656. return proc.wait() == 0;
  657. def gitUpdateRef(ref, newvalue):
  658. subprocess.check_call(["git", "update-ref", ref, newvalue])
  659. def gitDeleteRef(ref):
  660. subprocess.check_call(["git", "update-ref", "-d", ref])
  661. _gitConfig = {}
  662. def gitConfig(key, typeSpecifier=None):
  663. if key not in _gitConfig:
  664. cmd = [ "git", "config" ]
  665. if typeSpecifier:
  666. cmd += [ typeSpecifier ]
  667. cmd += [ key ]
  668. s = read_pipe(cmd, ignore_error=True)
  669. _gitConfig[key] = s.strip()
  670. return _gitConfig[key]
  671. def gitConfigBool(key):
  672. """Return a bool, using git config --bool. It is True only if the
  673. variable is set to true, and False if set to false or not present
  674. in the config."""
  675. if key not in _gitConfig:
  676. _gitConfig[key] = gitConfig(key, '--bool') == "true"
  677. return _gitConfig[key]
  678. def gitConfigInt(key):
  679. if key not in _gitConfig:
  680. cmd = [ "git", "config", "--int", key ]
  681. s = read_pipe(cmd, ignore_error=True)
  682. v = s.strip()
  683. try:
  684. _gitConfig[key] = int(gitConfig(key, '--int'))
  685. except ValueError:
  686. _gitConfig[key] = None
  687. return _gitConfig[key]
  688. def gitConfigList(key):
  689. if key not in _gitConfig:
  690. s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
  691. _gitConfig[key] = s.strip().splitlines()
  692. if _gitConfig[key] == ['']:
  693. _gitConfig[key] = []
  694. return _gitConfig[key]
  695. def p4BranchesInGit(branchesAreInRemotes=True):
  696. """Find all the branches whose names start with "p4/", looking
  697. in remotes or heads as specified by the argument. Return
  698. a dictionary of { branch: revision } for each one found.
  699. The branch names are the short names, without any
  700. "p4/" prefix."""
  701. branches = {}
  702. cmdline = "git rev-parse --symbolic "
  703. if branchesAreInRemotes:
  704. cmdline += "--remotes"
  705. else:
  706. cmdline += "--branches"
  707. for line in read_pipe_lines(cmdline):
  708. line = line.strip()
  709. # only import to p4/
  710. if not line.startswith('p4/'):
  711. continue
  712. # special symbolic ref to p4/master
  713. if line == "p4/HEAD":
  714. continue
  715. # strip off p4/ prefix
  716. branch = line[len("p4/"):]
  717. branches[branch] = parseRevision(line)
  718. return branches
  719. def branch_exists(branch):
  720. """Make sure that the given ref name really exists."""
  721. cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
  722. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  723. out, _ = p.communicate()
  724. if p.returncode:
  725. return False
  726. # expect exactly one line of output: the branch name
  727. return out.rstrip() == branch
  728. def findUpstreamBranchPoint(head = "HEAD"):
  729. branches = p4BranchesInGit()
  730. # map from depot-path to branch name
  731. branchByDepotPath = {}
  732. for branch in branches.keys():
  733. tip = branches[branch]
  734. log = extractLogMessageFromGitCommit(tip)
  735. settings = extractSettingsGitLog(log)
  736. if "depot-paths" in settings:
  737. paths = ",".join(settings["depot-paths"])
  738. branchByDepotPath[paths] = "remotes/p4/" + branch
  739. settings = None
  740. parent = 0
  741. while parent < 65535:
  742. commit = head + "~%s" % parent
  743. log = extractLogMessageFromGitCommit(commit)
  744. settings = extractSettingsGitLog(log)
  745. if "depot-paths" in settings:
  746. paths = ",".join(settings["depot-paths"])
  747. if paths in branchByDepotPath:
  748. return [branchByDepotPath[paths], settings]
  749. parent = parent + 1
  750. return ["", settings]
  751. def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
  752. if not silent:
  753. print("Creating/updating branch(es) in %s based on origin branch(es)"
  754. % localRefPrefix)
  755. originPrefix = "origin/p4/"
  756. for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
  757. line = line.strip()
  758. if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
  759. continue
  760. headName = line[len(originPrefix):]
  761. remoteHead = localRefPrefix + headName
  762. originHead = line
  763. original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
  764. if ('depot-paths' not in original
  765. or 'change' not in original):
  766. continue
  767. update = False
  768. if not gitBranchExists(remoteHead):
  769. if verbose:
  770. print("creating %s" % remoteHead)
  771. update = True
  772. else:
  773. settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
  774. if 'change' in settings:
  775. if settings['depot-paths'] == original['depot-paths']:
  776. originP4Change = int(original['change'])
  777. p4Change = int(settings['change'])
  778. if originP4Change > p4Change:
  779. print("%s (%s) is newer than %s (%s). "
  780. "Updating p4 branch from origin."
  781. % (originHead, originP4Change,
  782. remoteHead, p4Change))
  783. update = True
  784. else:
  785. print("Ignoring: %s was imported from %s while "
  786. "%s was imported from %s"
  787. % (originHead, ','.join(original['depot-paths']),
  788. remoteHead, ','.join(settings['depot-paths'])))
  789. if update:
  790. system("git update-ref %s %s" % (remoteHead, originHead))
  791. def originP4BranchesExist():
  792. return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
  793. def p4ParseNumericChangeRange(parts):
  794. changeStart = int(parts[0][1:])
  795. if parts[1] == '#head':
  796. changeEnd = p4_last_change()
  797. else:
  798. changeEnd = int(parts[1])
  799. return (changeStart, changeEnd)
  800. def chooseBlockSize(blockSize):
  801. if blockSize:
  802. return blockSize
  803. else:
  804. return defaultBlockSize
  805. def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
  806. assert depotPaths
  807. # Parse the change range into start and end. Try to find integer
  808. # revision ranges as these can be broken up into blocks to avoid
  809. # hitting server-side limits (maxrows, maxscanresults). But if
  810. # that doesn't work, fall back to using the raw revision specifier
  811. # strings, without using block mode.
  812. if changeRange is None or changeRange == '':
  813. changeStart = 1
  814. changeEnd = p4_last_change()
  815. block_size = chooseBlockSize(requestedBlockSize)
  816. else:
  817. parts = changeRange.split(',')
  818. assert len(parts) == 2
  819. try:
  820. (changeStart, changeEnd) = p4ParseNumericChangeRange(parts)
  821. block_size = chooseBlockSize(requestedBlockSize)
  822. except ValueError:
  823. changeStart = parts[0][1:]
  824. changeEnd = parts[1]
  825. if requestedBlockSize:
  826. die("cannot use --changes-block-size with non-numeric revisions")
  827. block_size = None
  828. changes = set()
  829. # Retrieve changes a block at a time, to prevent running
  830. # into a MaxResults/MaxScanRows error from the server. If
  831. # we _do_ hit one of those errors, turn down the block size
  832. while True:
  833. cmd = ['changes']
  834. if block_size:
  835. end = min(changeEnd, changeStart + block_size)
  836. revisionRange = "%d,%d" % (changeStart, end)
  837. else:
  838. revisionRange = "%s,%s" % (changeStart, changeEnd)
  839. for p in depotPaths:
  840. cmd += ["%s...@%s" % (p, revisionRange)]
  841. # fetch the changes
  842. try:
  843. result = p4CmdList(cmd, errors_as_exceptions=True)
  844. except P4RequestSizeException as e:
  845. if not block_size:
  846. block_size = e.limit
  847. elif block_size > e.limit:
  848. block_size = e.limit
  849. else:
  850. block_size = max(2, block_size // 2)
  851. if verbose: print("block size error, retrying with block size {0}".format(block_size))
  852. continue
  853. except P4Exception as e:
  854. die('Error retrieving changes description ({0})'.format(e.p4ExitCode))
  855. # Insert changes in chronological order
  856. for entry in reversed(result):
  857. if 'change' not in entry:
  858. continue
  859. changes.add(int(entry['change']))
  860. if not block_size:
  861. break
  862. if end >= changeEnd:
  863. break
  864. changeStart = end + 1
  865. changes = sorted(changes)
  866. return changes
  867. def p4PathStartsWith(path, prefix):
  868. # This method tries to remedy a potential mixed-case issue:
  869. #
  870. # If UserA adds //depot/DirA/file1
  871. # and UserB adds //depot/dira/file2
  872. #
  873. # we may or may not have a problem. If you have core.ignorecase=true,
  874. # we treat DirA and dira as the same directory
  875. if gitConfigBool("core.ignorecase"):
  876. return path.lower().startswith(prefix.lower())
  877. return path.startswith(prefix)
  878. def getClientSpec():
  879. """Look at the p4 client spec, create a View() object that contains
  880. all the mappings, and return it."""
  881. specList = p4CmdList("client -o")
  882. if len(specList) != 1:
  883. die('Output from "client -o" is %d lines, expecting 1' %
  884. len(specList))
  885. # dictionary of all client parameters
  886. entry = specList[0]
  887. # the //client/ name
  888. client_name = entry["Client"]
  889. # just the keys that start with "View"
  890. view_keys = [ k for k in entry.keys() if k.startswith("View") ]
  891. # hold this new View
  892. view = View(client_name)
  893. # append the lines, in order, to the view
  894. for view_num in range(len(view_keys)):
  895. k = "View%d" % view_num
  896. if k not in view_keys:
  897. die("Expected view key %s missing" % k)
  898. view.append(entry[k])
  899. return view
  900. def getClientRoot():
  901. """Grab the client directory."""
  902. output = p4CmdList("client -o")
  903. if len(output) != 1:
  904. die('Output from "client -o" is %d lines, expecting 1' % len(output))
  905. entry = output[0]
  906. if "Root" not in entry:
  907. die('Client has no "Root"')
  908. return entry["Root"]
  909. #
  910. # P4 wildcards are not allowed in filenames. P4 complains
  911. # if you simply add them, but you can force it with "-f", in
  912. # which case it translates them into %xx encoding internally.
  913. #
  914. def wildcard_decode(path):
  915. # Search for and fix just these four characters. Do % last so
  916. # that fixing it does not inadvertently create new %-escapes.
  917. # Cannot have * in a filename in windows; untested as to
  918. # what p4 would do in such a case.
  919. if not platform.system() == "Windows":
  920. path = path.replace("%2A", "*")
  921. path = path.replace("%23", "#") \
  922. .replace("%40", "@") \
  923. .replace("%25", "%")
  924. return path
  925. def wildcard_encode(path):
  926. # do % first to avoid double-encoding the %s introduced here
  927. path = path.replace("%", "%25") \
  928. .replace("*", "%2A") \
  929. .replace("#", "%23") \
  930. .replace("@", "%40")
  931. return path
  932. def wildcard_present(path):
  933. m = re.search("[*#@%]", path)
  934. return m is not None
  935. class LargeFileSystem(object):
  936. """Base class for large file system support."""
  937. def __init__(self, writeToGitStream):
  938. self.largeFiles = set()
  939. self.writeToGitStream = writeToGitStream
  940. def generatePointer(self, cloneDestination, contentFile):
  941. """Return the content of a pointer file that is stored in Git instead of
  942. the actual content."""
  943. assert False, "Method 'generatePointer' required in " + self.__class__.__name__
  944. def pushFile(self, localLargeFile):
  945. """Push the actual content which is not stored in the Git repository to
  946. a server."""
  947. assert False, "Method 'pushFile' required in " + self.__class__.__name__
  948. def hasLargeFileExtension(self, relPath):
  949. return reduce(
  950. lambda a, b: a or b,
  951. [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')],
  952. False
  953. )
  954. def generateTempFile(self, contents):
  955. contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)
  956. for d in contents:
  957. contentFile.write(d)
  958. contentFile.close()
  959. return contentFile.name
  960. def exceedsLargeFileThreshold(self, relPath, contents):
  961. if gitConfigInt('git-p4.largeFileThreshold'):
  962. contentsSize = sum(len(d) for d in contents)
  963. if contentsSize > gitConfigInt('git-p4.largeFileThreshold'):
  964. return True
  965. if gitConfigInt('git-p4.largeFileCompressedThreshold'):
  966. contentsSize = sum(len(d) for d in contents)
  967. if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'):
  968. return False
  969. contentTempFile = self.generateTempFile(contents)
  970. compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=True)
  971. with zipfile.ZipFile(compressedContentFile, mode='w') as zf:
  972. zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
  973. compressedContentsSize = zf.infolist()[0].compress_size
  974. os.remove(contentTempFile)
  975. if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
  976. return True
  977. return False
  978. def addLargeFile(self, relPath):
  979. self.largeFiles.add(relPath)
  980. def removeLargeFile(self, relPath):
  981. self.largeFiles.remove(relPath)
  982. def isLargeFile(self, relPath):
  983. return relPath in self.largeFiles
  984. def processContent(self, git_mode, relPath, contents):
  985. """Processes the content of git fast import. This method decides if a
  986. file is stored in the large file system and handles all necessary
  987. steps."""
  988. if self.exceedsLargeFileThreshold(relPath, contents) or self.hasLargeFileExtension(relPath):
  989. contentTempFile = self.generateTempFile(contents)
  990. (pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)
  991. if pointer_git_mode:
  992. git_mode = pointer_git_mode
  993. if localLargeFile:
  994. # Move temp file to final location in large file system
  995. largeFileDir = os.path.dirname(localLargeFile)
  996. if not os.path.isdir(largeFileDir):
  997. os.makedirs(largeFileDir)
  998. shutil.move(contentTempFile, localLargeFile)
  999. self.addLargeFile(relPath)
  1000. if gitConfigBool('git-p4.largeFilePush'):
  1001. self.pushFile(localLargeFile)
  1002. if verbose:
  1003. sys.stderr.write("%s moved to large file system (%s)\n" % (relPath, localLargeFile))
  1004. return (git_mode, contents)
  1005. class MockLFS(LargeFileSystem):
  1006. """Mock large file system for testing."""
  1007. def generatePointer(self, contentFile):
  1008. """The pointer content is the original content prefixed with "pointer-".
  1009. The local filename of the large file storage is derived from the file content.
  1010. """
  1011. with open(contentFile, 'r') as f:
  1012. content = next(f)
  1013. gitMode = '100644'
  1014. pointerContents = 'pointer-' + content
  1015. localLargeFile = os.path.join(os.getcwd(), '.git', 'mock-storage', 'local', content[:-1])
  1016. return (gitMode, pointerContents, localLargeFile)
  1017. def pushFile(self, localLargeFile):
  1018. """The remote filename of the large file storage is the same as the local
  1019. one but in a different directory.
  1020. """
  1021. remotePath = os.path.join(os.path.dirname(localLargeFile), '..', 'remote')
  1022. if not os.path.exists(remotePath):
  1023. os.makedirs(remotePath)
  1024. shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))
  1025. class GitLFS(LargeFileSystem):
  1026. """Git LFS as backend for the git-p4 large file system.
  1027. See https://git-lfs.github.com/ for details."""
  1028. def __init__(self, *args):
  1029. LargeFileSystem.__init__(self, *args)
  1030. self.baseGitAttributes = []
  1031. def generatePointer(self, contentFile):
  1032. """Generate a Git LFS pointer for the content. Return LFS Pointer file
  1033. mode and content which is stored in the Git repository instead of
  1034. the actual content. Return also the new location of the actual
  1035. content.
  1036. """
  1037. if os.path.getsize(contentFile) == 0:
  1038. return (None, '', None)
  1039. pointerProcess = subprocess.Popen(
  1040. ['git', 'lfs', 'pointer', '--file=' + contentFile],
  1041. stdout=subprocess.PIPE
  1042. )
  1043. pointerFile = pointerProcess.stdout.read()
  1044. if pointerProcess.wait():
  1045. os.remove(contentFile)
  1046. die('git-lfs pointer command failed. Did you install the extension?')
  1047. # Git LFS removed the preamble in the output of the 'pointer' command
  1048. # starting from version 1.2.0. Check for the preamble here to support
  1049. # earlier versions.
  1050. # c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b43
  1051. if pointerFile.startswith('Git LFS pointer for'):
  1052. pointerFile = re.sub(r'Git LFS pointer for.*\n\n', '', pointerFile)
  1053. oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)
  1054. localLargeFile = os.path.join(
  1055. os.getcwd(),
  1056. '.git', 'lfs', 'objects', oid[:2], oid[2:4],
  1057. oid,
  1058. )
  1059. # LFS Spec states that pointer files should not have the executable bit set.
  1060. gitMode = '100644'
  1061. return (gitMode, pointerFile, localLargeFile)
  1062. def pushFile(self, localLargeFile):
  1063. uploadProcess = subprocess.Popen(
  1064. ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
  1065. )
  1066. if uploadProcess.wait():
  1067. die('git-lfs push command failed. Did you define a remote?')
  1068. def generateGitAttributes(self):
  1069. return (
  1070. self.baseGitAttributes +
  1071. [
  1072. '\n',
  1073. '#\n',
  1074. '# Git LFS (see https://git-lfs.github.com/)\n',
  1075. '#\n',
  1076. ] +
  1077. ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
  1078. for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
  1079. ] +
  1080. ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
  1081. for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
  1082. ]
  1083. )
  1084. def addLargeFile(self, relPath):
  1085. LargeFileSystem.addLargeFile(self, relPath)
  1086. self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
  1087. def removeLargeFile(self, relPath):
  1088. LargeFileSystem.removeLargeFile(self, relPath)
  1089. self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
  1090. def processContent(self, git_mode, relPath, contents):
  1091. if relPath == '.gitattributes':
  1092. self.baseGitAttributes = contents
  1093. return (git_mode, self.generateGitAttributes())
  1094. else:
  1095. return LargeFileSystem.processContent(self, git_mode, relPath, contents)
  1096. class Command:
  1097. delete_actions = ( "delete", "move/delete", "purge" )
  1098. add_actions = ( "add", "branch", "move/add" )
  1099. def __init__(self):
  1100. self.usage = "usage: %prog [options]"
  1101. self.needsGit = True
  1102. self.verbose = False
  1103. # This is required for the "append" update_shelve action
  1104. def ensure_value(self, attr, value):
  1105. if not hasattr(self, attr) or getattr(self, attr) is None:
  1106. setattr(self, attr, value)
  1107. return getattr(self, attr)
  1108. class P4UserMap:
  1109. def __init__(self):
  1110. self.userMapFromPerforceServer = False
  1111. self.myP4UserId = None
  1112. def p4UserId(self):
  1113. if self.myP4UserId:
  1114. return self.myP4UserId
  1115. results = p4CmdList("user -o")
  1116. for r in results:
  1117. if 'User' in r:
  1118. self.myP4UserId = r['User']
  1119. return r['User']
  1120. die("Could not find your p4 user id")
  1121. def p4UserIsMe(self, p4User):
  1122. # return True if the given p4 user is actually me
  1123. me = self.p4UserId()
  1124. if not p4User or p4User != me:
  1125. return False
  1126. else:
  1127. return True
  1128. def getUserCacheFilename(self):
  1129. home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
  1130. return home + "/.gitp4-usercache.txt"
  1131. def getUserMapFromPerforceServer(self):
  1132. if self.userMapFromPerforceServer:
  1133. return
  1134. self.users = {}
  1135. self.emails = {}
  1136. for output in p4CmdList("users"):
  1137. if "User" not in output:
  1138. continue
  1139. self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
  1140. self.emails[output["Email"]] = output["User"]
  1141. mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)
  1142. for mapUserConfig in gitConfigList("git-p4.mapUser"):
  1143. mapUser = mapUserConfigRegex.findall(mapUserConfig)
  1144. if mapUser and len(mapUser[0]) == 3:
  1145. user = mapUser[0][0]
  1146. fullname = mapUser[0][1]
  1147. email = mapUser[0][2]
  1148. self.users[user] = fullname + " <" + email + ">"
  1149. self.emails[email] = user
  1150. s = ''
  1151. for (key, val) in self.users.items():
  1152. s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
  1153. open(self.getUserCacheFilename(), "wb").write(s)
  1154. self.userMapFromPerforceServer = True
  1155. def loadUserMapFromCache(self):
  1156. self.users = {}
  1157. self.userMapFromPerforceServer = False
  1158. try:
  1159. cache = open(self.getUserCacheFilename(), "rb")
  1160. lines = cache.readlines()
  1161. cache.close()
  1162. for line in lines:
  1163. entry = line.strip().split("\t")
  1164. self.users[entry[0]] = entry[1]
  1165. except IOError:
  1166. self.getUserMapFromPerforceServer()
  1167. class P4Debug(Command):
  1168. def __init__(self):
  1169. Command.__init__(self)
  1170. self.options = []
  1171. self.description = "A tool to debug the output of p4 -G."
  1172. self.needsGit = False
  1173. def run(self, args):
  1174. j = 0
  1175. for output in p4CmdList(args):
  1176. print('Element: %d' % j)
  1177. j += 1
  1178. print(output)
  1179. return True
  1180. class P4RollBack(Command):
  1181. def __init__(self):
  1182. Command.__init__(self)
  1183. self.options = [
  1184. optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
  1185. ]
  1186. self.description = "A tool to debug the multi-branch import. Don't use :)"
  1187. self.rollbackLocalBranches = False
  1188. def run(self, args):
  1189. if len(args) != 1:
  1190. return False
  1191. maxChange = int(args[0])
  1192. if "p4ExitCode" in p4Cmd("changes -m 1"):
  1193. die("Problems executing p4");
  1194. if self.rollbackLocalBranches:
  1195. refPrefix = "refs/heads/"
  1196. lines = read_pipe_lines("git rev-parse --symbolic --branches")
  1197. else:
  1198. refPrefix = "refs/remotes/"
  1199. lines = read_pipe_lines("git rev-parse --symbolic --remotes")
  1200. for line in lines:
  1201. if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
  1202. line = line.strip()
  1203. ref = refPrefix + line
  1204. log = extractLogMessageFromGitCommit(ref)
  1205. settings = extractSettingsGitLog(log)
  1206. depotPaths = settings['depot-paths']
  1207. change = settings['change']
  1208. changed = False
  1209. if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
  1210. for p in depotPaths]))) == 0:
  1211. print("Branch %s did not exist at change %s, deleting." % (ref, maxChange))
  1212. system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
  1213. continue
  1214. while change and int(change) > maxChange:
  1215. changed = True
  1216. if self.verbose:
  1217. print("%s is at %s ; rewinding towards %s" % (ref, change, maxChange))
  1218. system("git update-ref %s \"%s^\"" % (ref, ref))
  1219. log = extractLogMessageFromGitCommit(ref)
  1220. settings = extractSettingsGitLog(log)
  1221. depotPaths = settings['depot-paths']
  1222. change = settings['change']
  1223. if changed:
  1224. print("%s rewound to %s" % (ref, change))
  1225. return True
  1226. class P4Submit(Command, P4UserMap):
  1227. conflict_behavior_choices = ("ask", "skip", "quit")
  1228. def __init__(self):
  1229. Command.__init__(self)
  1230. P4UserMap.__init__(self)
  1231. self.options = [
  1232. optparse.make_option("--origin", dest="origin"),
  1233. optparse.make_option("-M", dest="detectRenames", action="store_true"),
  1234. # preserve the user, requires relevant p4 permissions
  1235. optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
  1236. optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
  1237. optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
  1238. optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
  1239. optparse.make_option("--conflict", dest="conflict_behavior",
  1240. choices=self.conflict_behavior_choices),
  1241. optparse.make_option("--branch", dest="branch"),
  1242. optparse.make_option("--shelve", dest="shelve", action="store_true",
  1243. help="Shelve instead of submit. Shelved files are reverted, "
  1244. "restoring the workspace to the state before the shelve"),
  1245. optparse.make_option("--update-shelve", dest="update_shelve", action="append", type="int",
  1246. metavar="CHANGELIST",
  1247. help="update an existing shelved changelist, implies --shelve, "
  1248. "repeat in-order for multiple shelved changelists"),
  1249. optparse.make_option("--commit", dest="commit", metavar="COMMIT",
  1250. help="submit only the specified commit(s), one commit or xxx..xxx"),
  1251. optparse.make_option("--disable-rebase", dest="disable_rebase", action="store_true",
  1252. help="Disable rebase after submit is completed. Can be useful if you "
  1253. "work from a local git branch that is not master"),
  1254. optparse.make_option("--disable-p4sync", dest="disable_p4sync", action="store_true",
  1255. help="Skip Perforce sync of p4/master after submit or shelve"),
  1256. ]
  1257. self.description = """Submit changes from git to the perforce depot.\n
  1258. The `p4-pre-submit` hook is executed if it exists and is executable.
  1259. The hook takes no parameters and nothing from standard input. Exiting with
  1260. non-zero status from this script prevents `git-p4 submit` from launching.
  1261. One usage scenario is to run unit tests in the hook."""
  1262. self.usage += " [name of git branch to submit into perforce depot]"
  1263. self.origin = ""
  1264. self.detectRenames = False
  1265. self.preserveUser = gitConfigBool("git-p4.preserveUser")
  1266. self.dry_run = False
  1267. self.shelve = False
  1268. self.update_shelve = list()
  1269. self.commit = ""
  1270. self.disable_rebase = gitConfigBool("git-p4.disableRebase")
  1271. self.disable_p4sync = gitConfigBool("git-p4.disableP4Sync")
  1272. self.prepare_p4_only = False
  1273. self.conflict_behavior = None
  1274. self.isWindows = (platform.system() == "Windows")
  1275. self.exportLabels = False
  1276. self.p4HasMoveCommand = p4_has_move_command()
  1277. self.branch = None
  1278. if gitConfig('git-p4.largeFileSystem'):
  1279. die("Large file system not supported for git-p4 submit command. Please remove it from config.")
  1280. def check(self):
  1281. if len(p4CmdList("opened ...")) > 0:
  1282. die("You have files opened with perforce! Close them before starting the sync.")
  1283. def separate_jobs_from_description(self, message):
  1284. """Extract and return a possible Jobs field in the commit
  1285. message. It goes into a separate section in the p4 change
  1286. specification.
  1287. A jobs line starts with "Jobs:" and looks like a new field
  1288. in a form. Values are white-space separated on the same
  1289. line or on following lines that start with a tab.
  1290. This does not parse and extract the full git commit message
  1291. like a p4 form. It just sees the Jobs: line as a marker
  1292. to pass everything from then on directly into the p4 form,
  1293. but outside the description section.
  1294. Return a tuple (stripped log message, jobs string)."""
  1295. m = re.search(r'^Jobs:', message, re.MULTILINE)
  1296. if m is None:
  1297. return (message, None)
  1298. jobtext = message[m.start():]
  1299. stripped_message = message[:m.start()].rstrip()
  1300. return (stripped_message, jobtext)
  1301. def prepareLogMessage(self, template, message, jobs):
  1302. """Edits the template returned from "p4 change -o" to insert
  1303. the message in the Description field, and the jobs text in
  1304. the Jobs field."""
  1305. result = ""
  1306. inDescriptionSection = False
  1307. for line in template.split("\n"):
  1308. if line.startswith("#"):
  1309. result += line + "\n"
  1310. continue
  1311. if inDescriptionSection:
  1312. if line.startswith("Files:") or line.startswith("Jobs:"):
  1313. inDescriptionSection = False
  1314. # insert Jobs section
  1315. if jobs:
  1316. result += jobs + "\n"
  1317. else:
  1318. continue
  1319. else:
  1320. if line.startswith("Description:"):
  1321. inDescriptionSection = True
  1322. line += "\n"
  1323. for messageLine in message.split("\n"):
  1324. line += "\t" + messageLine + "\n"
  1325. result += line + "\n"
  1326. return result
  1327. def patchRCSKeywords(self, file, pattern):
  1328. # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
  1329. (handle, outFileName) = tempfile.mkstemp(dir='.')
  1330. try:
  1331. outFile = os.fdopen(handle, "w+")
  1332. inFile = open(file, "r")
  1333. regexp = re.compile(pattern, re.VERBOSE)
  1334. for line in inFile.readlines():
  1335. line = regexp.sub(r'$\1$', line)
  1336. outFile.write(line)
  1337. inFile.close()
  1338. outFile.close()
  1339. # Forcibly overwrite the original file
  1340. os.unlink(file)
  1341. shutil.move(outFileName, file)
  1342. except:
  1343. # cleanup our temporary file
  1344. os.unlink(outFileName)
  1345. print("Failed to strip RCS keywords in %s" % file)
  1346. raise
  1347. print("Patched up RCS keywords in %s" % file)
  1348. def p4UserForCommit(self,id):
  1349. # Return the tuple (perforce user,git email) for a given git commit id
  1350. self.getUserMapFromPerforceServer()
  1351. gitEmail = read_pipe(["git", "log", "--max-count=1",
  1352. "--format=%ae", id])
  1353. gitEmail = gitEmail.strip()
  1354. if gitEmail not in self.emails:
  1355. return (None,gitEmail)
  1356. else:
  1357. return (self.emails[gitEmail],gitEmail)
  1358. def checkValidP4Users(self,commits):
  1359. # check if any git authors cannot be mapped to p4 users
  1360. for id in commits:
  1361. (user,email) = self.p4UserForCommit(id)
  1362. if not user:
  1363. msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
  1364. if gitConfigBool("git-p4.allowMissingP4Users"):
  1365. print("%s" % msg)
  1366. else:
  1367. die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
  1368. def lastP4Changelist(self):
  1369. # Get back the last changelist number submitted in this client spec. This
  1370. # then gets used to patch up the username in the change. If the same
  1371. # client spec is being used by multiple processes then this might go
  1372. # wrong.
  1373. results = p4CmdList("client -o") # find the current client
  1374. client = None
  1375. for r in results:
  1376. if 'Client' in r:
  1377. client = r['Client']
  1378. break
  1379. if not client:
  1380. die("could not get client spec")
  1381. results = p4CmdList(["changes", "-c", client, "-m", "1"])
  1382. for r in results:
  1383. if 'change' in r:
  1384. return r['change']
  1385. die("Could not get changelist number for last submit - cannot patch up user details")
  1386. def modifyChangelistUser(self, changelist, newUser):
  1387. # fixup the user field of a changelist after it has been submitted.
  1388. changes = p4CmdList("change -o %s" % changelist)
  1389. if len(changes) != 1:
  1390. die("Bad output from p4 change modifying %s to user %s" %
  1391. (changelist, newUser))
  1392. c = changes[0]
  1393. if c['User'] == newUser: return # nothing to do
  1394. c['User'] = newUser
  1395. input = marshal.dumps(c)
  1396. result = p4CmdList("change -f -i", stdin=input)
  1397. for r in result:
  1398. if 'code' in r:
  1399. if r['code'] == 'error':
  1400. die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
  1401. if 'data' in r:
  1402. print("Updated user field for changelist %s to %s" % (changelist, newUser))
  1403. return
  1404. die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
  1405. def canChangeChangelists(self):
  1406. # check to see if we have p4 admin or super-user permissions, either of
  1407. # which are required to modify changelists.
  1408. results = p4CmdList(["protects", self.depotPath])
  1409. for r in results:
  1410. if 'perm' in r:
  1411. if r['perm'] == 'admin':
  1412. return 1
  1413. if r['perm'] == 'super':
  1414. return 1
  1415. return 0
  1416. def prepareSubmitTemplate(self, changelist=None):
  1417. """Run "p4 change -o" to grab a change specification template.
  1418. This does not use "p4 -G", as it is nice to keep the submission
  1419. template in original order, since a human might edit it.
  1420. Remove lines in the Files section that show changes to files
  1421. outside the depot path we're committing into."""
  1422. [upstream, settings] = findUpstreamBranchPoint()
  1423. template = """\
  1424. # A Perforce Change Specification.
  1425. #
  1426. # Change: The change number. 'new' on a new changelist.
  1427. # Date: The date this specification was last modified.
  1428. # Client: The client on which the changelist was created. Read-only.
  1429. # User: The user who created the changelist.
  1430. # Status: Either 'pending' or 'submitted'. Read-only.
  1431. # Type: Either 'public' or 'restricted'. Default is 'public'.
  1432. # Description: Comments about the changelist. Required.
  1433. # Jobs: What opened jobs are to be closed by this changelist.
  1434. # You may delete jobs from this list. (New changelists only.)
  1435. # Files: What opened files from the default changelist are to be added
  1436. # to this changelist. You may delete files from this list.
  1437. # (New changelists only.)
  1438. """
  1439. files_list = []
  1440. inFilesSection = False
  1441. change_entry = None
  1442. args = ['change', '-o']
  1443. if changelist:
  1444. args.append(str(changelist))
  1445. for entry in p4CmdList(args):
  1446. if 'code' not in entry:
  1447. continue
  1448. if entry['code'] == 'stat':
  1449. change_entry = entry
  1450. break
  1451. if not change_entry:
  1452. die('Failed to decode output of p4 change -o')
  1453. for key, value in change_entry.iteritems():
  1454. if key.startswith('File'):
  1455. if 'depot-paths' in settings:
  1456. if not [p for p in settings['depot-paths']
  1457. if p4PathStartsWith(value, p)]:
  1458. continue
  1459. else:
  1460. if not p4PathStartsWith(value, self.depotPath):
  1461. continue
  1462. files_list.append(value)
  1463. continue
  1464. # Output in the order expected by prepareLogMessage
  1465. for key in ['Change', 'Client', 'User', 'Status', 'Description', 'Jobs']:
  1466. if key not in change_entry:
  1467. continue
  1468. template += '\n'
  1469. template += key + ':'
  1470. if key == 'Description':
  1471. template += '\n'
  1472. for field_line in change_entry[key].splitlines():
  1473. template += '\t'+field_line+'\n'
  1474. if len(files_list) > 0:
  1475. template += '\n'
  1476. template += 'Files:\n'
  1477. for path in files_list:
  1478. template += '\t'+path+'\n'
  1479. return template
  1480. def edit_template(self, template_file):
  1481. """Invoke the editor to let the user change the submission
  1482. message. Return true if okay to continue with the submit."""
  1483. # if configured to skip the editing part, just submit
  1484. if gitConfigBool("git-p4.skipSubmitEdit"):
  1485. return True
  1486. # look at the modification time, to check later if the user saved
  1487. # the file
  1488. mtime = os.stat(template_file).st_mtime
  1489. # invoke the editor
  1490. if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
  1491. editor = os.environ.get("P4EDITOR")
  1492. else:
  1493. editor = read_pipe("git var GIT_EDITOR").strip()
  1494. system(["sh", "-c", ('%s "$@"' % editor), editor, template_file])
  1495. # If the file was not saved, prompt to see if this patch should
  1496. # be skipped. But skip this verification step if configured so.
  1497. if gitConfigBool("git-p4.skipSubmitEditCheck"):
  1498. return True
  1499. # modification time updated means user saved the file
  1500. if os.stat(template_file).st_mtime > mtime:
  1501. return True
  1502. while True:
  1503. response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
  1504. if response == 'y':
  1505. return True
  1506. if response == 'n':
  1507. return False
  1508. def get_diff_description(self, editedFiles, filesToAdd, symlinks):
  1509. # diff
  1510. if "P4DIFF" in os.environ:
  1511. del(os.environ["P4DIFF"])
  1512. diff = ""
  1513. for editedFile in editedFiles:
  1514. diff += p4_read_pipe(['diff', '-du',
  1515. wildcard_encode(editedFile)])
  1516. # new file diff
  1517. newdiff = ""
  1518. for newFile in filesToAdd:
  1519. newdiff += "==== new file ====\n"
  1520. newdiff += "--- /dev/null\n"
  1521. newdiff += "+++ %s\n" % newFile
  1522. is_link = os.path.islink(newFile)
  1523. expect_link = newFile in symlinks
  1524. if is_link and expect_link:
  1525. newdiff += "+%s\n" % os.readlink(newFile)
  1526. else:
  1527. f = open(newFile, "r")
  1528. for line in f.readlines():
  1529. newdiff += "+" + line
  1530. f.close()
  1531. return (diff + newdiff).replace('\r\n', '\n')
  1532. def applyCommit(self, id):
  1533. """Apply one commit, return True if it succeeded."""
  1534. print("Applying", read_pipe(["git", "show", "-s",
  1535. "--format=format:%h %s", id]))
  1536. (p4User, gitEmail) = self.p4UserForCommit(id)
  1537. diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
  1538. filesToAdd = set()
  1539. filesToChangeType = set()
  1540. filesToDelete = set()
  1541. editedFiles = set()
  1542. pureRenameCopy = set()
  1543. symlinks = set()
  1544. filesToChangeExecBit = {}
  1545. all_files = list()
  1546. for line in diff:
  1547. diff = parseDiffTreeEntry(line)
  1548. modifier = diff['status']
  1549. path = diff['src']
  1550. all_files.append(path)
  1551. if modifier == "M":
  1552. p4_edit(path)
  1553. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1554. filesToChangeExecBit[path] = diff['dst_mode']
  1555. editedFiles.add(path)
  1556. elif modifier == "A":
  1557. filesToAdd.add(path)
  1558. filesToChangeExecBit[path] = diff['dst_mode']
  1559. if path in filesToDelete:
  1560. filesToDelete.remove(path)
  1561. dst_mode = int(diff['dst_mode'], 8)
  1562. if dst_mode == 0o120000:
  1563. symlinks.add(path)
  1564. elif modifier == "D":
  1565. filesToDelete.add(path)
  1566. if path in filesToAdd:
  1567. filesToAdd.remove(path)
  1568. elif modifier == "C":
  1569. src, dest = diff['src'], diff['dst']
  1570. all_files.append(dest)
  1571. p4_integrate(src, dest)
  1572. pureRenameCopy.add(dest)
  1573. if diff['src_sha1'] != diff['dst_sha1']:
  1574. p4_edit(dest)
  1575. pureRenameCopy.discard(dest)
  1576. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1577. p4_edit(dest)
  1578. pureRenameCopy.discard(dest)
  1579. filesToChangeExecBit[dest] = diff['dst_mode']
  1580. if self.isWindows:
  1581. # turn off read-only attribute
  1582. os.chmod(dest, stat.S_IWRITE)
  1583. os.unlink(dest)
  1584. editedFiles.add(dest)
  1585. elif modifier == "R":
  1586. src, dest = diff['src'], diff['dst']
  1587. all_files.append(dest)
  1588. if self.p4HasMoveCommand:
  1589. p4_edit(src) # src must be open before move
  1590. p4_move(src, dest) # opens for (move/delete, move/add)
  1591. else:
  1592. p4_integrate(src, dest)
  1593. if diff['src_sha1'] != diff['dst_sha1']:
  1594. p4_edit(dest)
  1595. else:
  1596. pureRenameCopy.add(dest)
  1597. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1598. if not self.p4HasMoveCommand:
  1599. p4_edit(dest) # with move: already open, writable
  1600. filesToChangeExecBit[dest] = diff['dst_mode']
  1601. if not self.p4HasMoveCommand:
  1602. if self.isWindows:
  1603. os.chmod(dest, stat.S_IWRITE)
  1604. os.unlink(dest)
  1605. filesToDelete.add(src)
  1606. editedFiles.add(dest)
  1607. elif modifier == "T":
  1608. filesToChangeType.add(path)
  1609. else:
  1610. die("unknown modifier %s for %s" % (modifier, path))
  1611. diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
  1612. patchcmd = diffcmd + " | git apply "
  1613. tryPatchCmd = patchcmd + "--check -"
  1614. applyPatchCmd = patchcmd + "--check --apply -"
  1615. patch_succeeded = True
  1616. if os.system(tryPatchCmd) != 0:
  1617. fixed_rcs_keywords = False
  1618. patch_succeeded = False
  1619. print("Unfortunately applying the change failed!")
  1620. # Patch failed, maybe it's just RCS keyword woes. Look through
  1621. # the patch to see if that's possible.
  1622. if gitConfigBool("git-p4.attemptRCSCleanup"):
  1623. file = None
  1624. pattern = None
  1625. kwfiles = {}
  1626. for file in editedFiles | filesToDelete:
  1627. # did this file's delta contain RCS keywords?
  1628. pattern = p4_keywords_regexp_for_file(file)
  1629. if pattern:
  1630. # this file is a possibility...look for RCS keywords.
  1631. regexp = re.compile(pattern, re.VERBOSE)
  1632. for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
  1633. if regexp.search(line):
  1634. if verbose:
  1635. print("got keyword match on %s in %s in %s" % (pattern, line, file))
  1636. kwfiles[file] = pattern
  1637. break
  1638. for file in kwfiles:
  1639. if verbose:
  1640. print("zapping %s with %s" % (line,pattern))
  1641. # File is being deleted, so not open in p4. Must
  1642. # disable the read-only bit on windows.
  1643. if self.isWindows and file not in editedFiles:
  1644. os.chmod(file, stat.S_IWRITE)
  1645. self.patchRCSKeywords(file, kwfiles[file])
  1646. fixed_rcs_keywords = True
  1647. if fixed_rcs_keywords:
  1648. print("Retrying the patch with RCS keywords cleaned up")
  1649. if os.system(tryPatchCmd) == 0:
  1650. patch_succeeded = True
  1651. if not patch_succeeded:
  1652. for f in editedFiles:
  1653. p4_revert(f)
  1654. return False
  1655. #
  1656. # Apply the patch for real, and do add/delete/+x handling.
  1657. #
  1658. system(applyPatchCmd)
  1659. for f in filesToChangeType:
  1660. p4_edit(f, "-t", "auto")
  1661. for f in filesToAdd:
  1662. p4_add(f)
  1663. for f in filesToDelete:
  1664. p4_revert(f)
  1665. p4_delete(f)
  1666. # Set/clear executable bits
  1667. for f in filesToChangeExecBit.keys():
  1668. mode = filesToChangeExecBit[f]
  1669. setP4ExecBit(f, mode)
  1670. update_shelve = 0
  1671. if len(self.update_shelve) > 0:
  1672. update_shelve = self.update_shelve.pop(0)
  1673. p4_reopen_in_change(update_shelve, all_files)
  1674. #
  1675. # Build p4 change description, starting with the contents
  1676. # of the git commit message.
  1677. #
  1678. logMessage = extractLogMessageFromGitCommit(id)
  1679. logMessage = logMessage.strip()
  1680. (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
  1681. template = self.prepareSubmitTemplate(update_shelve)
  1682. submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
  1683. if self.preserveUser:
  1684. submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
  1685. if self.checkAuthorship and not self.p4UserIsMe(p4User):
  1686. submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
  1687. submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
  1688. submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
  1689. separatorLine = "######## everything below this line is just the diff #######\n"
  1690. if not self.prepare_p4_only:
  1691. submitTemplate += separatorLine
  1692. submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)
  1693. (handle, fileName) = tempfile.mkstemp()
  1694. tmpFile = os.fdopen(handle, "w+b")
  1695. if self.isWindows:
  1696. submitTemplate = submitTemplate.replace("\n", "\r\n")
  1697. tmpFile.write(submitTemplate)
  1698. tmpFile.close()
  1699. if self.prepare_p4_only:
  1700. #
  1701. # Leave the p4 tree prepared, and the submit template around
  1702. # and let the user decide what to do next
  1703. #
  1704. print()
  1705. print("P4 workspace prepared for submission.")
  1706. print("To submit or revert, go to client workspace")
  1707. print(" " + self.clientPath)
  1708. print()
  1709. print("To submit, use \"p4 submit\" to write a new description,")
  1710. print("or \"p4 submit -i <%s\" to use the one prepared by" \
  1711. " \"git p4\"." % fileName)
  1712. print("You can delete the file \"%s\" when finished." % fileName)
  1713. if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
  1714. print("To preserve change ownership by user %s, you must\n" \
  1715. "do \"p4 change -f <change>\" after submitting and\n" \
  1716. "edit the User field.")
  1717. if pureRenameCopy:
  1718. print("After submitting, renamed files must be re-synced.")
  1719. print("Invoke \"p4 sync -f\" on each of these files:")
  1720. for f in pureRenameCopy:
  1721. print(" " + f)
  1722. print()
  1723. print("To revert the changes, use \"p4 revert ...\", and delete")
  1724. print("the submit template file \"%s\"" % fileName)
  1725. if filesToAdd:
  1726. print("Since the commit adds new files, they must be deleted:")
  1727. for f in filesToAdd:
  1728. print(" " + f)
  1729. print()
  1730. return True
  1731. #
  1732. # Let the user edit the change description, then submit it.
  1733. #
  1734. submitted = False
  1735. try:
  1736. if self.edit_template(fileName):
  1737. # read the edited message and submit
  1738. tmpFile = open(fileName, "rb")
  1739. message = tmpFile.read()
  1740. tmpFile.close()
  1741. if self.isWindows:
  1742. message = message.replace("\r\n", "\n")
  1743. submitTemplate = message[:message.index(separatorLine)]
  1744. if update_shelve:
  1745. p4_write_pipe(['shelve', '-r', '-i'], submitTemplate)
  1746. elif self.shelve:
  1747. p4_write_pipe(['shelve', '-i'], submitTemplate)
  1748. else:
  1749. p4_write_pipe(['submit', '-i'], submitTemplate)
  1750. # The rename/copy happened by applying a patch that created a
  1751. # new file. This leaves it writable, which confuses p4.
  1752. for f in pureRenameCopy:
  1753. p4_sync(f, "-f")
  1754. if self.preserveUser:
  1755. if p4User:
  1756. # Get last changelist number. Cannot easily get it from
  1757. # the submit command output as the output is
  1758. # unmarshalled.
  1759. changelist = self.lastP4Changelist()
  1760. self.modifyChangelistUser(changelist, p4User)
  1761. submitted = True
  1762. finally:
  1763. # skip this patch
  1764. if not submitted or self.shelve:
  1765. if self.shelve:
  1766. print ("Reverting shelved files.")
  1767. else:
  1768. print ("Submission cancelled, undoing p4 changes.")
  1769. for f in editedFiles | filesToDelete:
  1770. p4_revert(f)
  1771. for f in filesToAdd:
  1772. p4_revert(f)
  1773. os.remove(f)
  1774. os.remove(fileName)
  1775. return submitted
  1776. # Export git tags as p4 labels. Create a p4 label and then tag
  1777. # with that.
  1778. def exportGitTags(self, gitTags):
  1779. validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
  1780. if len(validLabelRegexp) == 0:
  1781. validLabelRegexp = defaultLabelRegexp
  1782. m = re.compile(validLabelRegexp)
  1783. for name in gitTags:
  1784. if not m.match(name):
  1785. if verbose:
  1786. print("tag %s does not match regexp %s" % (name, validLabelRegexp))
  1787. continue
  1788. # Get the p4 commit this corresponds to
  1789. logMessage = extractLogMessageFromGitCommit(name)
  1790. values = extractSettingsGitLog(logMessage)
  1791. if 'change' not in values:
  1792. # a tag pointing to something not sent to p4; ignore
  1793. if verbose:
  1794. print("git tag %s does not give a p4 commit" % name)
  1795. continue
  1796. else:
  1797. changelist = values['change']
  1798. # Get the tag details.
  1799. inHeader = True
  1800. isAnnotated = False
  1801. body = []
  1802. for l in read_pipe_lines(["git", "cat-file", "-p", name]):
  1803. l = l.strip()
  1804. if inHeader:
  1805. if re.match(r'tag\s+', l):
  1806. isAnnotated = True
  1807. elif re.match(r'\s*$', l):
  1808. inHeader = False
  1809. continue
  1810. else:
  1811. body.append(l)
  1812. if not isAnnotated:
  1813. body = ["lightweight tag imported by git p4\n"]
  1814. # Create the label - use the same view as the client spec we are using
  1815. clientSpec = getClientSpec()
  1816. labelTemplate = "Label: %s\n" % name
  1817. labelTemplate += "Description:\n"
  1818. for b in body:
  1819. labelTemplate += "\t" + b + "\n"
  1820. labelTemplate += "View:\n"
  1821. for depot_side in clientSpec.mappings:
  1822. labelTemplate += "\t%s\n" % depot_side
  1823. if self.dry_run:
  1824. print("Would create p4 label %s for tag" % name)
  1825. elif self.prepare_p4_only:
  1826. print("Not creating p4 label %s for tag due to option" \
  1827. " --prepare-p4-only" % name)
  1828. else:
  1829. p4_write_pipe(["label", "-i"], labelTemplate)
  1830. # Use the label
  1831. p4_system(["tag", "-l", name] +
  1832. ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
  1833. if verbose:
  1834. print("created p4 label for tag %s" % name)
  1835. def run(self, args):
  1836. if len(args) == 0:
  1837. self.master = currentGitBranch()
  1838. elif len(args) == 1:
  1839. self.master = args[0]
  1840. if not branchExists(self.master):
  1841. die("Branch %s does not exist" % self.master)
  1842. else:
  1843. return False
  1844. for i in self.update_shelve:
  1845. if i <= 0:
  1846. sys.exit("invalid changelist %d" % i)
  1847. if self.master:
  1848. allowSubmit = gitConfig("git-p4.allowSubmit")
  1849. if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
  1850. die("%s is not in git-p4.allowSubmit" % self.master)
  1851. [upstream, settings] = findUpstreamBranchPoint()
  1852. self.depotPath = settings['depot-paths'][0]
  1853. if len(self.origin) == 0:
  1854. self.origin = upstream
  1855. if len(self.update_shelve) > 0:
  1856. self.shelve = True
  1857. if self.preserveUser:
  1858. if not self.canChangeChangelists():
  1859. die("Cannot preserve user names without p4 super-user or admin permissions")
  1860. # if not set from the command line, try the config file
  1861. if self.conflict_behavior is None:
  1862. val = gitConfig("git-p4.conflict")
  1863. if val:
  1864. if val not in self.conflict_behavior_choices:
  1865. die("Invalid value '%s' for config git-p4.conflict" % val)
  1866. else:
  1867. val = "ask"
  1868. self.conflict_behavior = val
  1869. if self.verbose:
  1870. print("Origin branch is " + self.origin)
  1871. if len(self.depotPath) == 0:
  1872. print("Internal error: cannot locate perforce depot path from existing branches")
  1873. sys.exit(128)
  1874. self.useClientSpec = False
  1875. if gitConfigBool("git-p4.useclientspec"):
  1876. self.useClientSpec = True
  1877. if self.useClientSpec:
  1878. self.clientSpecDirs = getClientSpec()
  1879. # Check for the existence of P4 branches
  1880. branchesDetected = (len(p4BranchesInGit().keys()) > 1)
  1881. if self.useClientSpec and not branchesDetected:
  1882. # all files are relative to the client spec
  1883. self.clientPath = getClientRoot()
  1884. else:
  1885. self.clientPath = p4Where(self.depotPath)
  1886. if self.clientPath == "":
  1887. die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
  1888. print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
  1889. self.oldWorkingDirectory = os.getcwd()
  1890. # ensure the clientPath exists
  1891. new_client_dir = False
  1892. if not os.path.exists(self.clientPath):
  1893. new_client_dir = True
  1894. os.makedirs(self.clientPath)
  1895. chdir(self.clientPath, is_client_path=True)
  1896. if self.dry_run:
  1897. print("Would synchronize p4 checkout in %s" % self.clientPath)
  1898. else:
  1899. print("Synchronizing p4 checkout...")
  1900. if new_client_dir:
  1901. # old one was destroyed, and maybe nobody told p4
  1902. p4_sync("...", "-f")
  1903. else:
  1904. p4_sync("...")
  1905. self.check()
  1906. commits = []
  1907. if self.master:
  1908. committish = self.master
  1909. else:
  1910. committish = 'HEAD'
  1911. if self.commit != "":
  1912. if self.commit.find("..") != -1:
  1913. limits_ish = self.commit.split("..")
  1914. for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (limits_ish[0], limits_ish[1])]):
  1915. commits.append(line.strip())
  1916. commits.reverse()
  1917. else:
  1918. commits.append(self.commit)
  1919. else:
  1920. for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
  1921. commits.append(line.strip())
  1922. commits.reverse()
  1923. if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
  1924. self.checkAuthorship = False
  1925. else:
  1926. self.checkAuthorship = True
  1927. if self.preserveUser:
  1928. self.checkValidP4Users(commits)
  1929. #
  1930. # Build up a set of options to be passed to diff when
  1931. # submitting each commit to p4.
  1932. #
  1933. if self.detectRenames:
  1934. # command-line -M arg
  1935. self.diffOpts = "-M"
  1936. else:
  1937. # If not explicitly set check the config variable
  1938. detectRenames = gitConfig("git-p4.detectRenames")
  1939. if detectRenames.lower() == "false" or detectRenames == "":
  1940. self.diffOpts = ""
  1941. elif detectRenames.lower() == "true":
  1942. self.diffOpts = "-M"
  1943. else:
  1944. self.diffOpts = "-M%s" % detectRenames
  1945. # no command-line arg for -C or --find-copies-harder, just
  1946. # config variables
  1947. detectCopies = gitConfig("git-p4.detectCopies")
  1948. if detectCopies.lower() == "false" or detectCopies == "":
  1949. pass
  1950. elif detectCopies.lower() == "true":
  1951. self.diffOpts += " -C"
  1952. else:
  1953. self.diffOpts += " -C%s" % detectCopies
  1954. if gitConfigBool("git-p4.detectCopiesHarder"):
  1955. self.diffOpts += " --find-copies-harder"
  1956. num_shelves = len(self.update_shelve)
  1957. if num_shelves > 0 and num_shelves != len(commits):
  1958. sys.exit("number of commits (%d) must match number of shelved changelist (%d)" %
  1959. (len(commits), num_shelves))
  1960. hooks_path = gitConfig("core.hooksPath")
  1961. if len(hooks_path) <= 0:
  1962. hooks_path = os.path.join(os.environ.get("GIT_DIR", ".git"), "hooks")
  1963. hook_file = os.path.join(hooks_path, "p4-pre-submit")
  1964. if os.path.isfile(hook_file) and os.access(hook_file, os.X_OK) and subprocess.call([hook_file]) != 0:
  1965. sys.exit(1)
  1966. #
  1967. # Apply the commits, one at a time. On failure, ask if should
  1968. # continue to try the rest of the patches, or quit.
  1969. #
  1970. if self.dry_run:
  1971. print("Would apply")
  1972. applied = []
  1973. last = len(commits) - 1
  1974. for i, commit in enumerate(commits):
  1975. if self.dry_run:
  1976. print(" ", read_pipe(["git", "show", "-s",
  1977. "--format=format:%h %s", commit]))
  1978. ok = True
  1979. else:
  1980. ok = self.applyCommit(commit)
  1981. if ok:
  1982. applied.append(commit)
  1983. else:
  1984. if self.prepare_p4_only and i < last:
  1985. print("Processing only the first commit due to option" \
  1986. " --prepare-p4-only")
  1987. break
  1988. if i < last:
  1989. quit = False
  1990. while True:
  1991. # prompt for what to do, or use the option/variable
  1992. if self.conflict_behavior == "ask":
  1993. print("What do you want to do?")
  1994. response = raw_input("[s]kip this commit but apply"
  1995. " the rest, or [q]uit? ")
  1996. if not response:
  1997. continue
  1998. elif self.conflict_behavior == "skip":
  1999. response = "s"
  2000. elif self.conflict_behavior == "quit":
  2001. response = "q"
  2002. else:
  2003. die("Unknown conflict_behavior '%s'" %
  2004. self.conflict_behavior)
  2005. if response[0] == "s":
  2006. print("Skipping this commit, but applying the rest")
  2007. break
  2008. if response[0] == "q":
  2009. print("Quitting")
  2010. quit = True
  2011. break
  2012. if quit:
  2013. break
  2014. chdir(self.oldWorkingDirectory)
  2015. shelved_applied = "shelved" if self.shelve else "applied"
  2016. if self.dry_run:
  2017. pass
  2018. elif self.prepare_p4_only:
  2019. pass
  2020. elif len(commits) == len(applied):
  2021. print("All commits {0}!".format(shelved_applied))
  2022. sync = P4Sync()
  2023. if self.branch:
  2024. sync.branch = self.branch
  2025. if self.disable_p4sync:
  2026. sync.sync_origin_only()
  2027. else:
  2028. sync.run([])
  2029. if not self.disable_rebase:
  2030. rebase = P4Rebase()
  2031. rebase.rebase()
  2032. else:
  2033. if len(applied) == 0:
  2034. print("No commits {0}.".format(shelved_applied))
  2035. else:
  2036. print("{0} only the commits marked with '*':".format(shelved_applied.capitalize()))
  2037. for c in commits:
  2038. if c in applied:
  2039. star = "*"
  2040. else:
  2041. star = " "
  2042. print(star, read_pipe(["git", "show", "-s",
  2043. "--format=format:%h %s", c]))
  2044. print("You will have to do 'git p4 sync' and rebase.")
  2045. if gitConfigBool("git-p4.exportLabels"):
  2046. self.exportLabels = True
  2047. if self.exportLabels:
  2048. p4Labels = getP4Labels(self.depotPath)
  2049. gitTags = getGitTags()
  2050. missingGitTags = gitTags - p4Labels
  2051. self.exportGitTags(missingGitTags)
  2052. # exit with error unless everything applied perfectly
  2053. if len(commits) != len(applied):
  2054. sys.exit(1)
  2055. return True
  2056. class View(object):
  2057. """Represent a p4 view ("p4 help views"), and map files in a
  2058. repo according to the view."""
  2059. def __init__(self, client_name):
  2060. self.mappings = []
  2061. self.client_prefix = "//%s/" % client_name
  2062. # cache results of "p4 where" to lookup client file locations
  2063. self.client_spec_path_cache = {}
  2064. def append(self, view_line):
  2065. """Parse a view line, splitting it into depot and client
  2066. sides. Append to self.mappings, preserving order. This
  2067. is only needed for tag creation."""
  2068. # Split the view line into exactly two words. P4 enforces
  2069. # structure on these lines that simplifies this quite a bit.
  2070. #
  2071. # Either or both words may be double-quoted.
  2072. # Single quotes do not matter.
  2073. # Double-quote marks cannot occur inside the words.
  2074. # A + or - prefix is also inside the quotes.
  2075. # There are no quotes unless they contain a space.
  2076. # The line is already white-space stripped.
  2077. # The two words are separated by a single space.
  2078. #
  2079. if view_line[0] == '"':
  2080. # First word is double quoted. Find its end.
  2081. close_quote_index = view_line.find('"', 1)
  2082. if close_quote_index <= 0:
  2083. die("No first-word closing quote found: %s" % view_line)
  2084. depot_side = view_line[1:close_quote_index]
  2085. # skip closing quote and space
  2086. rhs_index = close_quote_index + 1 + 1
  2087. else:
  2088. space_index = view_line.find(" ")
  2089. if space_index <= 0:
  2090. die("No word-splitting space found: %s" % view_line)
  2091. depot_side = view_line[0:space_index]
  2092. rhs_index = space_index + 1
  2093. # prefix + means overlay on previous mapping
  2094. if depot_side.startswith("+"):
  2095. depot_side = depot_side[1:]
  2096. # prefix - means exclude this path, leave out of mappings
  2097. exclude = False
  2098. if depot_side.startswith("-"):
  2099. exclude = True
  2100. depot_side = depot_side[1:]
  2101. if not exclude:
  2102. self.mappings.append(depot_side)
  2103. def convert_client_path(self, clientFile):
  2104. # chop off //client/ part to make it relative
  2105. if not clientFile.startswith(self.client_prefix):
  2106. die("No prefix '%s' on clientFile '%s'" %
  2107. (self.client_prefix, clientFile))
  2108. return clientFile[len(self.client_prefix):]
  2109. def update_client_spec_path_cache(self, files):
  2110. """ Caching file paths by "p4 where" batch query """
  2111. # List depot file paths exclude that already cached
  2112. fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache]
  2113. if len(fileArgs) == 0:
  2114. return # All files in cache
  2115. where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
  2116. for res in where_result:
  2117. if "code" in res and res["code"] == "error":
  2118. # assume error is "... file(s) not in client view"
  2119. continue
  2120. if "clientFile" not in res:
  2121. die("No clientFile in 'p4 where' output")
  2122. if "unmap" in res:
  2123. # it will list all of them, but only one not unmap-ped
  2124. continue
  2125. if gitConfigBool("core.ignorecase"):
  2126. res['depotFile'] = res['depotFile'].lower()
  2127. self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])
  2128. # not found files or unmap files set to ""
  2129. for depotFile in fileArgs:
  2130. if gitConfigBool("core.ignorecase"):
  2131. depotFile = depotFile.lower()
  2132. if depotFile not in self.client_spec_path_cache:
  2133. self.client_spec_path_cache[depotFile] = ""
  2134. def map_in_client(self, depot_path):
  2135. """Return the relative location in the client where this
  2136. depot file should live. Returns "" if the file should
  2137. not be mapped in the client."""
  2138. if gitConfigBool("core.ignorecase"):
  2139. depot_path = depot_path.lower()
  2140. if depot_path in self.client_spec_path_cache:
  2141. return self.client_spec_path_cache[depot_path]
  2142. die( "Error: %s is not found in client spec path" % depot_path )
  2143. return ""
  2144. def cloneExcludeCallback(option, opt_str, value, parser):
  2145. # prepend "/" because the first "/" was consumed as part of the option itself.
  2146. # ("-//depot/A/..." becomes "/depot/A/..." after option parsing)
  2147. parser.values.cloneExclude += ["/" + re.sub(r"\.\.\.$", "", value)]
  2148. class P4Sync(Command, P4UserMap):
  2149. def __init__(self):
  2150. Command.__init__(self)
  2151. P4UserMap.__init__(self)
  2152. self.options = [
  2153. optparse.make_option("--branch", dest="branch"),
  2154. optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
  2155. optparse.make_option("--changesfile", dest="changesFile"),
  2156. optparse.make_option("--silent", dest="silent", action="store_true"),
  2157. optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
  2158. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  2159. optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
  2160. help="Import into refs/heads/ , not refs/remotes"),
  2161. optparse.make_option("--max-changes", dest="maxChanges",
  2162. help="Maximum number of changes to import"),
  2163. optparse.make_option("--changes-block-size", dest="changes_block_size", type="int",
  2164. help="Internal block size to use when iteratively calling p4 changes"),
  2165. optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
  2166. help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
  2167. optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
  2168. help="Only sync files that are included in the Perforce Client Spec"),
  2169. optparse.make_option("-/", dest="cloneExclude",
  2170. action="callback", callback=cloneExcludeCallback, type="string",
  2171. help="exclude depot path"),
  2172. ]
  2173. self.description = """Imports from Perforce into a git repository.\n
  2174. example:
  2175. //depot/my/project/ -- to import the current head
  2176. //depot/my/project/@all -- to import everything
  2177. //depot/my/project/@1,6 -- to import only from revision 1 to 6
  2178. (a ... is not needed in the path p4 specification, it's added implicitly)"""
  2179. self.usage += " //depot/path[@revRange]"
  2180. self.silent = False
  2181. self.createdBranches = set()
  2182. self.committedChanges = set()
  2183. self.branch = ""
  2184. self.detectBranches = False
  2185. self.detectLabels = False
  2186. self.importLabels = False
  2187. self.changesFile = ""
  2188. self.syncWithOrigin = True
  2189. self.importIntoRemotes = True
  2190. self.maxChanges = ""
  2191. self.changes_block_size = None
  2192. self.keepRepoPath = False
  2193. self.depotPaths = None
  2194. self.p4BranchesInGit = []
  2195. self.cloneExclude = []
  2196. self.useClientSpec = False
  2197. self.useClientSpec_from_options = False
  2198. self.clientSpecDirs = None
  2199. self.tempBranches = []
  2200. self.tempBranchLocation = "refs/git-p4-tmp"
  2201. self.largeFileSystem = None
  2202. self.suppress_meta_comment = False
  2203. if gitConfig('git-p4.largeFileSystem'):
  2204. largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')]
  2205. self.largeFileSystem = largeFileSystemConstructor(
  2206. lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)
  2207. )
  2208. if gitConfig("git-p4.syncFromOrigin") == "false":
  2209. self.syncWithOrigin = False
  2210. self.depotPaths = []
  2211. self.changeRange = ""
  2212. self.previousDepotPaths = []
  2213. self.hasOrigin = False
  2214. # map from branch depot path to parent branch
  2215. self.knownBranches = {}
  2216. self.initialParents = {}
  2217. self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
  2218. self.labels = {}
  2219. # Force a checkpoint in fast-import and wait for it to finish
  2220. def checkpoint(self):
  2221. self.gitStream.write("checkpoint\n\n")
  2222. self.gitStream.write("progress checkpoint\n\n")
  2223. out = self.gitOutput.readline()
  2224. if self.verbose:
  2225. print("checkpoint finished: " + out)
  2226. def isPathWanted(self, path):
  2227. for p in self.cloneExclude:
  2228. if p.endswith("/"):
  2229. if p4PathStartsWith(path, p):
  2230. return False
  2231. # "-//depot/file1" without a trailing "/" should only exclude "file1", but not "file111" or "file1_dir/file2"
  2232. elif path.lower() == p.lower():
  2233. return False
  2234. for p in self.depotPaths:
  2235. if p4PathStartsWith(path, p):
  2236. return True
  2237. return False
  2238. def extractFilesFromCommit(self, commit, shelved=False, shelved_cl = 0):
  2239. files = []
  2240. fnum = 0
  2241. while "depotFile%s" % fnum in commit:
  2242. path = commit["depotFile%s" % fnum]
  2243. found = self.isPathWanted(path)
  2244. if not found:
  2245. fnum = fnum + 1
  2246. continue
  2247. file = {}
  2248. file["path"] = path
  2249. file["rev"] = commit["rev%s" % fnum]
  2250. file["action"] = commit["action%s" % fnum]
  2251. file["type"] = commit["type%s" % fnum]
  2252. if shelved:
  2253. file["shelved_cl"] = int(shelved_cl)
  2254. files.append(file)
  2255. fnum = fnum + 1
  2256. return files
  2257. def extractJobsFromCommit(self, commit):
  2258. jobs = []
  2259. jnum = 0
  2260. while "job%s" % jnum in commit:
  2261. job = commit["job%s" % jnum]
  2262. jobs.append(job)
  2263. jnum = jnum + 1
  2264. return jobs
  2265. def stripRepoPath(self, path, prefixes):
  2266. """When streaming files, this is called to map a p4 depot path
  2267. to where it should go in git. The prefixes are either
  2268. self.depotPaths, or self.branchPrefixes in the case of
  2269. branch detection."""
  2270. if self.useClientSpec:
  2271. # branch detection moves files up a level (the branch name)
  2272. # from what client spec interpretation gives
  2273. path = self.clientSpecDirs.map_in_client(path)
  2274. if self.detectBranches:
  2275. for b in self.knownBranches:
  2276. if p4PathStartsWith(path, b + "/"):
  2277. path = path[len(b)+1:]
  2278. elif self.keepRepoPath:
  2279. # Preserve everything in relative path name except leading
  2280. # //depot/; just look at first prefix as they all should
  2281. # be in the same depot.
  2282. depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
  2283. if p4PathStartsWith(path, depot):
  2284. path = path[len(depot):]
  2285. else:
  2286. for p in prefixes:
  2287. if p4PathStartsWith(path, p):
  2288. path = path[len(p):]
  2289. break
  2290. path = wildcard_decode(path)
  2291. return path
  2292. def splitFilesIntoBranches(self, commit):
  2293. """Look at each depotFile in the commit to figure out to what
  2294. branch it belongs."""
  2295. if self.clientSpecDirs:
  2296. files = self.extractFilesFromCommit(commit)
  2297. self.clientSpecDirs.update_client_spec_path_cache(files)
  2298. branches = {}
  2299. fnum = 0
  2300. while "depotFile%s" % fnum in commit:
  2301. path = commit["depotFile%s" % fnum]
  2302. found = self.isPathWanted(path)
  2303. if not found:
  2304. fnum = fnum + 1
  2305. continue
  2306. file = {}
  2307. file["path"] = path
  2308. file["rev"] = commit["rev%s" % fnum]
  2309. file["action"] = commit["action%s" % fnum]
  2310. file["type"] = commit["type%s" % fnum]
  2311. fnum = fnum + 1
  2312. # start with the full relative path where this file would
  2313. # go in a p4 client
  2314. if self.useClientSpec:
  2315. relPath = self.clientSpecDirs.map_in_client(path)
  2316. else:
  2317. relPath = self.stripRepoPath(path, self.depotPaths)
  2318. for branch in self.knownBranches.keys():
  2319. # add a trailing slash so that a commit into qt/4.2foo
  2320. # doesn't end up in qt/4.2, e.g.
  2321. if p4PathStartsWith(relPath, branch + "/"):
  2322. if branch not in branches:
  2323. branches[branch] = []
  2324. branches[branch].append(file)
  2325. break
  2326. return branches
  2327. def writeToGitStream(self, gitMode, relPath, contents):
  2328. self.gitStream.write('M %s inline %s\n' % (gitMode, relPath))
  2329. self.gitStream.write('data %d\n' % sum(len(d) for d in contents))
  2330. for d in contents:
  2331. self.gitStream.write(d)
  2332. self.gitStream.write('\n')
  2333. def encodeWithUTF8(self, path):
  2334. try:
  2335. path.decode('ascii')
  2336. except:
  2337. encoding = 'utf8'
  2338. if gitConfig('git-p4.pathEncoding'):
  2339. encoding = gitConfig('git-p4.pathEncoding')
  2340. path = path.decode(encoding, 'replace').encode('utf8', 'replace')
  2341. if self.verbose:
  2342. print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
  2343. return path
  2344. # output one file from the P4 stream
  2345. # - helper for streamP4Files
  2346. def streamOneP4File(self, file, contents):
  2347. relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
  2348. relPath = self.encodeWithUTF8(relPath)
  2349. if verbose:
  2350. if 'fileSize' in self.stream_file:
  2351. size = int(self.stream_file['fileSize'])
  2352. else:
  2353. size = 0 # deleted files don't get a fileSize apparently
  2354. sys.stdout.write('\r%s --> %s (%i MB)\n' % (file['depotFile'], relPath, size/1024/1024))
  2355. sys.stdout.flush()
  2356. (type_base, type_mods) = split_p4_type(file["type"])
  2357. git_mode = "100644"
  2358. if "x" in type_mods:
  2359. git_mode = "100755"
  2360. if type_base == "symlink":
  2361. git_mode = "120000"
  2362. # p4 print on a symlink sometimes contains "target\n";
  2363. # if it does, remove the newline
  2364. data = ''.join(contents)
  2365. if not data:
  2366. # Some version of p4 allowed creating a symlink that pointed
  2367. # to nothing. This causes p4 errors when checking out such
  2368. # a change, and errors here too. Work around it by ignoring
  2369. # the bad symlink; hopefully a future change fixes it.
  2370. print("\nIgnoring empty symlink in %s" % file['depotFile'])
  2371. return
  2372. elif data[-1] == '\n':
  2373. contents = [data[:-1]]
  2374. else:
  2375. contents = [data]
  2376. if type_base == "utf16":
  2377. # p4 delivers different text in the python output to -G
  2378. # than it does when using "print -o", or normal p4 client
  2379. # operations. utf16 is converted to ascii or utf8, perhaps.
  2380. # But ascii text saved as -t utf16 is completely mangled.
  2381. # Invoke print -o to get the real contents.
  2382. #
  2383. # On windows, the newlines will always be mangled by print, so put
  2384. # them back too. This is not needed to the cygwin windows version,
  2385. # just the native "NT" type.
  2386. #
  2387. try:
  2388. text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (file['depotFile'], file['change'])])
  2389. except Exception as e:
  2390. if 'Translation of file content failed' in str(e):
  2391. type_base = 'binary'
  2392. else:
  2393. raise e
  2394. else:
  2395. if p4_version_string().find('/NT') >= 0:
  2396. text = text.replace('\r\n', '\n')
  2397. contents = [ text ]
  2398. if type_base == "apple":
  2399. # Apple filetype files will be streamed as a concatenation of
  2400. # its appledouble header and the contents. This is useless
  2401. # on both macs and non-macs. If using "print -q -o xx", it
  2402. # will create "xx" with the data, and "%xx" with the header.
  2403. # This is also not very useful.
  2404. #
  2405. # Ideally, someday, this script can learn how to generate
  2406. # appledouble files directly and import those to git, but
  2407. # non-mac machines can never find a use for apple filetype.
  2408. print("\nIgnoring apple filetype file %s" % file['depotFile'])
  2409. return
  2410. # Note that we do not try to de-mangle keywords on utf16 files,
  2411. # even though in theory somebody may want that.
  2412. pattern = p4_keywords_regexp_for_type(type_base, type_mods)
  2413. if pattern:
  2414. regexp = re.compile(pattern, re.VERBOSE)
  2415. text = ''.join(contents)
  2416. text = regexp.sub(r'$\1$', text)
  2417. contents = [ text ]
  2418. if self.largeFileSystem:
  2419. (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)
  2420. self.writeToGitStream(git_mode, relPath, contents)
  2421. def streamOneP4Deletion(self, file):
  2422. relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
  2423. relPath = self.encodeWithUTF8(relPath)
  2424. if verbose:
  2425. sys.stdout.write("delete %s\n" % relPath)
  2426. sys.stdout.flush()
  2427. self.gitStream.write("D %s\n" % relPath)
  2428. if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
  2429. self.largeFileSystem.removeLargeFile(relPath)
  2430. # handle another chunk of streaming data
  2431. def streamP4FilesCb(self, marshalled):
  2432. # catch p4 errors and complain
  2433. err = None
  2434. if "code" in marshalled:
  2435. if marshalled["code"] == "error":
  2436. if "data" in marshalled:
  2437. err = marshalled["data"].rstrip()
  2438. if not err and 'fileSize' in self.stream_file:
  2439. required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree())
  2440. if required_bytes > 0:
  2441. err = 'Not enough space left on %s! Free at least %i MB.' % (
  2442. os.getcwd(), required_bytes/1024/1024
  2443. )
  2444. if err:
  2445. f = None
  2446. if self.stream_have_file_info:
  2447. if "depotFile" in self.stream_file:
  2448. f = self.stream_file["depotFile"]
  2449. # force a failure in fast-import, else an empty
  2450. # commit will be made
  2451. self.gitStream.write("\n")
  2452. self.gitStream.write("die-now\n")
  2453. self.gitStream.close()
  2454. # ignore errors, but make sure it exits first
  2455. self.importProcess.wait()
  2456. if f:
  2457. die("Error from p4 print for %s: %s" % (f, err))
  2458. else:
  2459. die("Error from p4 print: %s" % err)
  2460. if 'depotFile' in marshalled and self.stream_have_file_info:
  2461. # start of a new file - output the old one first
  2462. self.streamOneP4File(self.stream_file, self.stream_contents)
  2463. self.stream_file = {}
  2464. self.stream_contents = []
  2465. self.stream_have_file_info = False
  2466. # pick up the new file information... for the
  2467. # 'data' field we need to append to our array
  2468. for k in marshalled.keys():
  2469. if k == 'data':
  2470. if 'streamContentSize' not in self.stream_file:
  2471. self.stream_file['streamContentSize'] = 0
  2472. self.stream_file['streamContentSize'] += len(marshalled['data'])
  2473. self.stream_contents.append(marshalled['data'])
  2474. else:
  2475. self.stream_file[k] = marshalled[k]
  2476. if (verbose and
  2477. 'streamContentSize' in self.stream_file and
  2478. 'fileSize' in self.stream_file and
  2479. 'depotFile' in self.stream_file):
  2480. size = int(self.stream_file["fileSize"])
  2481. if size > 0:
  2482. progress = 100*self.stream_file['streamContentSize']/size
  2483. sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024)))
  2484. sys.stdout.flush()
  2485. self.stream_have_file_info = True
  2486. # Stream directly from "p4 files" into "git fast-import"
  2487. def streamP4Files(self, files):
  2488. filesForCommit = []
  2489. filesToRead = []
  2490. filesToDelete = []
  2491. for f in files:
  2492. filesForCommit.append(f)
  2493. if f['action'] in self.delete_actions:
  2494. filesToDelete.append(f)
  2495. else:
  2496. filesToRead.append(f)
  2497. # deleted files...
  2498. for f in filesToDelete:
  2499. self.streamOneP4Deletion(f)
  2500. if len(filesToRead) > 0:
  2501. self.stream_file = {}
  2502. self.stream_contents = []
  2503. self.stream_have_file_info = False
  2504. # curry self argument
  2505. def streamP4FilesCbSelf(entry):
  2506. self.streamP4FilesCb(entry)
  2507. fileArgs = []
  2508. for f in filesToRead:
  2509. if 'shelved_cl' in f:
  2510. # Handle shelved CLs using the "p4 print file@=N" syntax to print
  2511. # the contents
  2512. fileArg = '%s@=%d' % (f['path'], f['shelved_cl'])
  2513. else:
  2514. fileArg = '%s#%s' % (f['path'], f['rev'])
  2515. fileArgs.append(fileArg)
  2516. p4CmdList(["-x", "-", "print"],
  2517. stdin=fileArgs,
  2518. cb=streamP4FilesCbSelf)
  2519. # do the last chunk
  2520. if 'depotFile' in self.stream_file:
  2521. self.streamOneP4File(self.stream_file, self.stream_contents)
  2522. def make_email(self, userid):
  2523. if userid in self.users:
  2524. return self.users[userid]
  2525. else:
  2526. return "%s <a@b>" % userid
  2527. def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
  2528. """ Stream a p4 tag.
  2529. commit is either a git commit, or a fast-import mark, ":<p4commit>"
  2530. """
  2531. if verbose:
  2532. print("writing tag %s for commit %s" % (labelName, commit))
  2533. gitStream.write("tag %s\n" % labelName)
  2534. gitStream.write("from %s\n" % commit)
  2535. if 'Owner' in labelDetails:
  2536. owner = labelDetails["Owner"]
  2537. else:
  2538. owner = None
  2539. # Try to use the owner of the p4 label, or failing that,
  2540. # the current p4 user id.
  2541. if owner:
  2542. email = self.make_email(owner)
  2543. else:
  2544. email = self.make_email(self.p4UserId())
  2545. tagger = "%s %s %s" % (email, epoch, self.tz)
  2546. gitStream.write("tagger %s\n" % tagger)
  2547. print("labelDetails=",labelDetails)
  2548. if 'Description' in labelDetails:
  2549. description = labelDetails['Description']
  2550. else:
  2551. description = 'Label from git p4'
  2552. gitStream.write("data %d\n" % len(description))
  2553. gitStream.write(description)
  2554. gitStream.write("\n")
  2555. def inClientSpec(self, path):
  2556. if not self.clientSpecDirs:
  2557. return True
  2558. inClientSpec = self.clientSpecDirs.map_in_client(path)
  2559. if not inClientSpec and self.verbose:
  2560. print('Ignoring file outside of client spec: {0}'.format(path))
  2561. return inClientSpec
  2562. def hasBranchPrefix(self, path):
  2563. if not self.branchPrefixes:
  2564. return True
  2565. hasPrefix = [p for p in self.branchPrefixes
  2566. if p4PathStartsWith(path, p)]
  2567. if not hasPrefix and self.verbose:
  2568. print('Ignoring file outside of prefix: {0}'.format(path))
  2569. return hasPrefix
  2570. def commit(self, details, files, branch, parent = "", allow_empty=False):
  2571. epoch = details["time"]
  2572. author = details["user"]
  2573. jobs = self.extractJobsFromCommit(details)
  2574. if self.verbose:
  2575. print('commit into {0}'.format(branch))
  2576. if self.clientSpecDirs:
  2577. self.clientSpecDirs.update_client_spec_path_cache(files)
  2578. files = [f for f in files
  2579. if self.inClientSpec(f['path']) and self.hasBranchPrefix(f['path'])]
  2580. if gitConfigBool('git-p4.keepEmptyCommits'):
  2581. allow_empty = True
  2582. if not files and not allow_empty:
  2583. print('Ignoring revision {0} as it would produce an empty commit.'
  2584. .format(details['change']))
  2585. return
  2586. self.gitStream.write("commit %s\n" % branch)
  2587. self.gitStream.write("mark :%s\n" % details["change"])
  2588. self.committedChanges.add(int(details["change"]))
  2589. committer = ""
  2590. if author not in self.users:
  2591. self.getUserMapFromPerforceServer()
  2592. committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
  2593. self.gitStream.write("committer %s\n" % committer)
  2594. self.gitStream.write("data <<EOT\n")
  2595. self.gitStream.write(details["desc"])
  2596. if len(jobs) > 0:
  2597. self.gitStream.write("\nJobs: %s" % (' '.join(jobs)))
  2598. if not self.suppress_meta_comment:
  2599. self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
  2600. (','.join(self.branchPrefixes), details["change"]))
  2601. if len(details['options']) > 0:
  2602. self.gitStream.write(": options = %s" % details['options'])
  2603. self.gitStream.write("]\n")
  2604. self.gitStream.write("EOT\n\n")
  2605. if len(parent) > 0:
  2606. if self.verbose:
  2607. print("parent %s" % parent)
  2608. self.gitStream.write("from %s\n" % parent)
  2609. self.streamP4Files(files)
  2610. self.gitStream.write("\n")
  2611. change = int(details["change"])
  2612. if change in self.labels:
  2613. label = self.labels[change]
  2614. labelDetails = label[0]
  2615. labelRevisions = label[1]
  2616. if self.verbose:
  2617. print("Change %s is labelled %s" % (change, labelDetails))
  2618. files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
  2619. for p in self.branchPrefixes])
  2620. if len(files) == len(labelRevisions):
  2621. cleanedFiles = {}
  2622. for info in files:
  2623. if info["action"] in self.delete_actions:
  2624. continue
  2625. cleanedFiles[info["depotFile"]] = info["rev"]
  2626. if cleanedFiles == labelRevisions:
  2627. self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
  2628. else:
  2629. if not self.silent:
  2630. print("Tag %s does not match with change %s: files do not match."
  2631. % (labelDetails["label"], change))
  2632. else:
  2633. if not self.silent:
  2634. print("Tag %s does not match with change %s: file count is different."
  2635. % (labelDetails["label"], change))
  2636. # Build a dictionary of changelists and labels, for "detect-labels" option.
  2637. def getLabels(self):
  2638. self.labels = {}
  2639. l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
  2640. if len(l) > 0 and not self.silent:
  2641. print("Finding files belonging to labels in %s" % self.depotPaths)
  2642. for output in l:
  2643. label = output["label"]
  2644. revisions = {}
  2645. newestChange = 0
  2646. if self.verbose:
  2647. print("Querying files for label %s" % label)
  2648. for file in p4CmdList(["files"] +
  2649. ["%s...@%s" % (p, label)
  2650. for p in self.depotPaths]):
  2651. revisions[file["depotFile"]] = file["rev"]
  2652. change = int(file["change"])
  2653. if change > newestChange:
  2654. newestChange = change
  2655. self.labels[newestChange] = [output, revisions]
  2656. if self.verbose:
  2657. print("Label changes: %s" % self.labels.keys())
  2658. # Import p4 labels as git tags. A direct mapping does not
  2659. # exist, so assume that if all the files are at the same revision
  2660. # then we can use that, or it's something more complicated we should
  2661. # just ignore.
  2662. def importP4Labels(self, stream, p4Labels):
  2663. if verbose:
  2664. print("import p4 labels: " + ' '.join(p4Labels))
  2665. ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
  2666. validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
  2667. if len(validLabelRegexp) == 0:
  2668. validLabelRegexp = defaultLabelRegexp
  2669. m = re.compile(validLabelRegexp)
  2670. for name in p4Labels:
  2671. commitFound = False
  2672. if not m.match(name):
  2673. if verbose:
  2674. print("label %s does not match regexp %s" % (name,validLabelRegexp))
  2675. continue
  2676. if name in ignoredP4Labels:
  2677. continue
  2678. labelDetails = p4CmdList(['label', "-o", name])[0]
  2679. # get the most recent changelist for each file in this label
  2680. change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
  2681. for p in self.depotPaths])
  2682. if 'change' in change:
  2683. # find the corresponding git commit; take the oldest commit
  2684. changelist = int(change['change'])
  2685. if changelist in self.committedChanges:
  2686. gitCommit = ":%d" % changelist # use a fast-import mark
  2687. commitFound = True
  2688. else:
  2689. gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
  2690. "--reverse", ":/\[git-p4:.*change = %d\]" % changelist], ignore_error=True)
  2691. if len(gitCommit) == 0:
  2692. print("importing label %s: could not find git commit for changelist %d" % (name, changelist))
  2693. else:
  2694. commitFound = True
  2695. gitCommit = gitCommit.strip()
  2696. if commitFound:
  2697. # Convert from p4 time format
  2698. try:
  2699. tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
  2700. except ValueError:
  2701. print("Could not convert label time %s" % labelDetails['Update'])
  2702. tmwhen = 1
  2703. when = int(time.mktime(tmwhen))
  2704. self.streamTag(stream, name, labelDetails, gitCommit, when)
  2705. if verbose:
  2706. print("p4 label %s mapped to git commit %s" % (name, gitCommit))
  2707. else:
  2708. if verbose:
  2709. print("Label %s has no changelists - possibly deleted?" % name)
  2710. if not commitFound:
  2711. # We can't import this label; don't try again as it will get very
  2712. # expensive repeatedly fetching all the files for labels that will
  2713. # never be imported. If the label is moved in the future, the
  2714. # ignore will need to be removed manually.
  2715. system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
  2716. def guessProjectName(self):
  2717. for p in self.depotPaths:
  2718. if p.endswith("/"):
  2719. p = p[:-1]
  2720. p = p[p.strip().rfind("/") + 1:]
  2721. if not p.endswith("/"):
  2722. p += "/"
  2723. return p
  2724. def getBranchMapping(self):
  2725. lostAndFoundBranches = set()
  2726. user = gitConfig("git-p4.branchUser")
  2727. if len(user) > 0:
  2728. command = "branches -u %s" % user
  2729. else:
  2730. command = "branches"
  2731. for info in p4CmdList(command):
  2732. details = p4Cmd(["branch", "-o", info["branch"]])
  2733. viewIdx = 0
  2734. while "View%s" % viewIdx in details:
  2735. paths = details["View%s" % viewIdx].split(" ")
  2736. viewIdx = viewIdx + 1
  2737. # require standard //depot/foo/... //depot/bar/... mapping
  2738. if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
  2739. continue
  2740. source = paths[0]
  2741. destination = paths[1]
  2742. ## HACK
  2743. if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
  2744. source = source[len(self.depotPaths[0]):-4]
  2745. destination = destination[len(self.depotPaths[0]):-4]
  2746. if destination in self.knownBranches:
  2747. if not self.silent:
  2748. print("p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination))
  2749. print("but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination))
  2750. continue
  2751. self.knownBranches[destination] = source
  2752. lostAndFoundBranches.discard(destination)
  2753. if source not in self.knownBranches:
  2754. lostAndFoundBranches.add(source)
  2755. # Perforce does not strictly require branches to be defined, so we also
  2756. # check git config for a branch list.
  2757. #
  2758. # Example of branch definition in git config file:
  2759. # [git-p4]
  2760. # branchList=main:branchA
  2761. # branchList=main:branchB
  2762. # branchList=branchA:branchC
  2763. configBranches = gitConfigList("git-p4.branchList")
  2764. for branch in configBranches:
  2765. if branch:
  2766. (source, destination) = branch.split(":")
  2767. self.knownBranches[destination] = source
  2768. lostAndFoundBranches.discard(destination)
  2769. if source not in self.knownBranches:
  2770. lostAndFoundBranches.add(source)
  2771. for branch in lostAndFoundBranches:
  2772. self.knownBranches[branch] = branch
  2773. def getBranchMappingFromGitBranches(self):
  2774. branches = p4BranchesInGit(self.importIntoRemotes)
  2775. for branch in branches.keys():
  2776. if branch == "master":
  2777. branch = "main"
  2778. else:
  2779. branch = branch[len(self.projectName):]
  2780. self.knownBranches[branch] = branch
  2781. def updateOptionDict(self, d):
  2782. option_keys = {}
  2783. if self.keepRepoPath:
  2784. option_keys['keepRepoPath'] = 1
  2785. d["options"] = ' '.join(sorted(option_keys.keys()))
  2786. def readOptions(self, d):
  2787. self.keepRepoPath = ('options' in d
  2788. and ('keepRepoPath' in d['options']))
  2789. def gitRefForBranch(self, branch):
  2790. if branch == "main":
  2791. return self.refPrefix + "master"
  2792. if len(branch) <= 0:
  2793. return branch
  2794. return self.refPrefix + self.projectName + branch
  2795. def gitCommitByP4Change(self, ref, change):
  2796. if self.verbose:
  2797. print("looking in ref " + ref + " for change %s using bisect..." % change)
  2798. earliestCommit = ""
  2799. latestCommit = parseRevision(ref)
  2800. while True:
  2801. if self.verbose:
  2802. print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
  2803. next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
  2804. if len(next) == 0:
  2805. if self.verbose:
  2806. print("argh")
  2807. return ""
  2808. log = extractLogMessageFromGitCommit(next)
  2809. settings = extractSettingsGitLog(log)
  2810. currentChange = int(settings['change'])
  2811. if self.verbose:
  2812. print("current change %s" % currentChange)
  2813. if currentChange == change:
  2814. if self.verbose:
  2815. print("found %s" % next)
  2816. return next
  2817. if currentChange < change:
  2818. earliestCommit = "^%s" % next
  2819. else:
  2820. if next == latestCommit:
  2821. die("Infinite loop while looking in ref %s for change %s. Check your branch mappings" % (ref, change))
  2822. latestCommit = "%s^@" % next
  2823. return ""
  2824. def importNewBranch(self, branch, maxChange):
  2825. # make fast-import flush all changes to disk and update the refs using the checkpoint
  2826. # command so that we can try to find the branch parent in the git history
  2827. self.gitStream.write("checkpoint\n\n");
  2828. self.gitStream.flush();
  2829. branchPrefix = self.depotPaths[0] + branch + "/"
  2830. range = "@1,%s" % maxChange
  2831. #print "prefix" + branchPrefix
  2832. changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size)
  2833. if len(changes) <= 0:
  2834. return False
  2835. firstChange = changes[0]
  2836. #print "first change in branch: %s" % firstChange
  2837. sourceBranch = self.knownBranches[branch]
  2838. sourceDepotPath = self.depotPaths[0] + sourceBranch
  2839. sourceRef = self.gitRefForBranch(sourceBranch)
  2840. #print "source " + sourceBranch
  2841. branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
  2842. #print "branch parent: %s" % branchParentChange
  2843. gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
  2844. if len(gitParent) > 0:
  2845. self.initialParents[self.gitRefForBranch(branch)] = gitParent
  2846. #print "parent git commit: %s" % gitParent
  2847. self.importChanges(changes)
  2848. return True
  2849. def searchParent(self, parent, branch, target):
  2850. parentFound = False
  2851. for blob in read_pipe_lines(["git", "rev-list", "--reverse",
  2852. "--no-merges", parent]):
  2853. blob = blob.strip()
  2854. if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
  2855. parentFound = True
  2856. if self.verbose:
  2857. print("Found parent of %s in commit %s" % (branch, blob))
  2858. break
  2859. if parentFound:
  2860. return blob
  2861. else:
  2862. return None
  2863. def importChanges(self, changes, origin_revision=0):
  2864. cnt = 1
  2865. for change in changes:
  2866. description = p4_describe(change)
  2867. self.updateOptionDict(description)
  2868. if not self.silent:
  2869. sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
  2870. sys.stdout.flush()
  2871. cnt = cnt + 1
  2872. try:
  2873. if self.detectBranches:
  2874. branches = self.splitFilesIntoBranches(description)
  2875. for branch in branches.keys():
  2876. ## HACK --hwn
  2877. branchPrefix = self.depotPaths[0] + branch + "/"
  2878. self.branchPrefixes = [ branchPrefix ]
  2879. parent = ""
  2880. filesForCommit = branches[branch]
  2881. if self.verbose:
  2882. print("branch is %s" % branch)
  2883. self.updatedBranches.add(branch)
  2884. if branch not in self.createdBranches:
  2885. self.createdBranches.add(branch)
  2886. parent = self.knownBranches[branch]
  2887. if parent == branch:
  2888. parent = ""
  2889. else:
  2890. fullBranch = self.projectName + branch
  2891. if fullBranch not in self.p4BranchesInGit:
  2892. if not self.silent:
  2893. print("\n Importing new branch %s" % fullBranch);
  2894. if self.importNewBranch(branch, change - 1):
  2895. parent = ""
  2896. self.p4BranchesInGit.append(fullBranch)
  2897. if not self.silent:
  2898. print("\n Resuming with change %s" % change);
  2899. if self.verbose:
  2900. print("parent determined through known branches: %s" % parent)
  2901. branch = self.gitRefForBranch(branch)
  2902. parent = self.gitRefForBranch(parent)
  2903. if self.verbose:
  2904. print("looking for initial parent for %s; current parent is %s" % (branch, parent))
  2905. if len(parent) == 0 and branch in self.initialParents:
  2906. parent = self.initialParents[branch]
  2907. del self.initialParents[branch]
  2908. blob = None
  2909. if len(parent) > 0:
  2910. tempBranch = "%s/%d" % (self.tempBranchLocation, change)
  2911. if self.verbose:
  2912. print("Creating temporary branch: " + tempBranch)
  2913. self.commit(description, filesForCommit, tempBranch)
  2914. self.tempBranches.append(tempBranch)
  2915. self.checkpoint()
  2916. blob = self.searchParent(parent, branch, tempBranch)
  2917. if blob:
  2918. self.commit(description, filesForCommit, branch, blob)
  2919. else:
  2920. if self.verbose:
  2921. print("Parent of %s not found. Committing into head of %s" % (branch, parent))
  2922. self.commit(description, filesForCommit, branch, parent)
  2923. else:
  2924. files = self.extractFilesFromCommit(description)
  2925. self.commit(description, files, self.branch,
  2926. self.initialParent)
  2927. # only needed once, to connect to the previous commit
  2928. self.initialParent = ""
  2929. except IOError:
  2930. print(self.gitError.read())
  2931. sys.exit(1)
  2932. def sync_origin_only(self):
  2933. if self.syncWithOrigin:
  2934. self.hasOrigin = originP4BranchesExist()
  2935. if self.hasOrigin:
  2936. if not self.silent:
  2937. print('Syncing with origin first, using "git fetch origin"')
  2938. system("git fetch origin")
  2939. def importHeadRevision(self, revision):
  2940. print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
  2941. details = {}
  2942. details["user"] = "git perforce import user"
  2943. details["desc"] = ("Initial import of %s from the state at revision %s\n"
  2944. % (' '.join(self.depotPaths), revision))
  2945. details["change"] = revision
  2946. newestRevision = 0
  2947. fileCnt = 0
  2948. fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
  2949. for info in p4CmdList(["files"] + fileArgs):
  2950. if 'code' in info and info['code'] == 'error':
  2951. sys.stderr.write("p4 returned an error: %s\n"
  2952. % info['data'])
  2953. if info['data'].find("must refer to client") >= 0:
  2954. sys.stderr.write("This particular p4 error is misleading.\n")
  2955. sys.stderr.write("Perhaps the depot path was misspelled.\n");
  2956. sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
  2957. sys.exit(1)
  2958. if 'p4ExitCode' in info:
  2959. sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
  2960. sys.exit(1)
  2961. change = int(info["change"])
  2962. if change > newestRevision:
  2963. newestRevision = change
  2964. if info["action"] in self.delete_actions:
  2965. # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
  2966. #fileCnt = fileCnt + 1
  2967. continue
  2968. for prop in ["depotFile", "rev", "action", "type" ]:
  2969. details["%s%s" % (prop, fileCnt)] = info[prop]
  2970. fileCnt = fileCnt + 1
  2971. details["change"] = newestRevision
  2972. # Use time from top-most change so that all git p4 clones of
  2973. # the same p4 repo have the same commit SHA1s.
  2974. res = p4_describe(newestRevision)
  2975. details["time"] = res["time"]
  2976. self.updateOptionDict(details)
  2977. try:
  2978. self.commit(details, self.extractFilesFromCommit(details), self.branch)
  2979. except IOError as err:
  2980. print("IO error with git fast-import. Is your git version recent enough?")
  2981. print("IO error details: {}".format(err))
  2982. print(self.gitError.read())
  2983. def openStreams(self):
  2984. self.importProcess = subprocess.Popen(["git", "fast-import"],
  2985. stdin=subprocess.PIPE,
  2986. stdout=subprocess.PIPE,
  2987. stderr=subprocess.PIPE);
  2988. self.gitOutput = self.importProcess.stdout
  2989. self.gitStream = self.importProcess.stdin
  2990. self.gitError = self.importProcess.stderr
  2991. def closeStreams(self):
  2992. self.gitStream.close()
  2993. if self.importProcess.wait() != 0:
  2994. die("fast-import failed: %s" % self.gitError.read())
  2995. self.gitOutput.close()
  2996. self.gitError.close()
  2997. def run(self, args):
  2998. if self.importIntoRemotes:
  2999. self.refPrefix = "refs/remotes/p4/"
  3000. else:
  3001. self.refPrefix = "refs/heads/p4/"
  3002. self.sync_origin_only()
  3003. branch_arg_given = bool(self.branch)
  3004. if len(self.branch) == 0:
  3005. self.branch = self.refPrefix + "master"
  3006. if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
  3007. system("git update-ref %s refs/heads/p4" % self.branch)
  3008. system("git branch -D p4")
  3009. # accept either the command-line option, or the configuration variable
  3010. if self.useClientSpec:
  3011. # will use this after clone to set the variable
  3012. self.useClientSpec_from_options = True
  3013. else:
  3014. if gitConfigBool("git-p4.useclientspec"):
  3015. self.useClientSpec = True
  3016. if self.useClientSpec:
  3017. self.clientSpecDirs = getClientSpec()
  3018. # TODO: should always look at previous commits,
  3019. # merge with previous imports, if possible.
  3020. if args == []:
  3021. if self.hasOrigin:
  3022. createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
  3023. # branches holds mapping from branch name to sha1
  3024. branches = p4BranchesInGit(self.importIntoRemotes)
  3025. # restrict to just this one, disabling detect-branches
  3026. if branch_arg_given:
  3027. short = self.branch.split("/")[-1]
  3028. if short in branches:
  3029. self.p4BranchesInGit = [ short ]
  3030. else:
  3031. self.p4BranchesInGit = branches.keys()
  3032. if len(self.p4BranchesInGit) > 1:
  3033. if not self.silent:
  3034. print("Importing from/into multiple branches")
  3035. self.detectBranches = True
  3036. for branch in branches.keys():
  3037. self.initialParents[self.refPrefix + branch] = \
  3038. branches[branch]
  3039. if self.verbose:
  3040. print("branches: %s" % self.p4BranchesInGit)
  3041. p4Change = 0
  3042. for branch in self.p4BranchesInGit:
  3043. logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
  3044. settings = extractSettingsGitLog(logMsg)
  3045. self.readOptions(settings)
  3046. if ('depot-paths' in settings
  3047. and 'change' in settings):
  3048. change = int(settings['change']) + 1
  3049. p4Change = max(p4Change, change)
  3050. depotPaths = sorted(settings['depot-paths'])
  3051. if self.previousDepotPaths == []:
  3052. self.previousDepotPaths = depotPaths
  3053. else:
  3054. paths = []
  3055. for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
  3056. prev_list = prev.split("/")
  3057. cur_list = cur.split("/")
  3058. for i in range(0, min(len(cur_list), len(prev_list))):
  3059. if cur_list[i] != prev_list[i]:
  3060. i = i - 1
  3061. break
  3062. paths.append ("/".join(cur_list[:i + 1]))
  3063. self.previousDepotPaths = paths
  3064. if p4Change > 0:
  3065. self.depotPaths = sorted(self.previousDepotPaths)
  3066. self.changeRange = "@%s,#head" % p4Change
  3067. if not self.silent and not self.detectBranches:
  3068. print("Performing incremental import into %s git branch" % self.branch)
  3069. # accept multiple ref name abbreviations:
  3070. # refs/foo/bar/branch -> use it exactly
  3071. # p4/branch -> prepend refs/remotes/ or refs/heads/
  3072. # branch -> prepend refs/remotes/p4/ or refs/heads/p4/
  3073. if not self.branch.startswith("refs/"):
  3074. if self.importIntoRemotes:
  3075. prepend = "refs/remotes/"
  3076. else:
  3077. prepend = "refs/heads/"
  3078. if not self.branch.startswith("p4/"):
  3079. prepend += "p4/"
  3080. self.branch = prepend + self.branch
  3081. if len(args) == 0 and self.depotPaths:
  3082. if not self.silent:
  3083. print("Depot paths: %s" % ' '.join(self.depotPaths))
  3084. else:
  3085. if self.depotPaths and self.depotPaths != args:
  3086. print("previous import used depot path %s and now %s was specified. "
  3087. "This doesn't work!" % (' '.join (self.depotPaths),
  3088. ' '.join (args)))
  3089. sys.exit(1)
  3090. self.depotPaths = sorted(args)
  3091. revision = ""
  3092. self.users = {}
  3093. # Make sure no revision specifiers are used when --changesfile
  3094. # is specified.
  3095. bad_changesfile = False
  3096. if len(self.changesFile) > 0:
  3097. for p in self.depotPaths:
  3098. if p.find("@") >= 0 or p.find("#") >= 0:
  3099. bad_changesfile = True
  3100. break
  3101. if bad_changesfile:
  3102. die("Option --changesfile is incompatible with revision specifiers")
  3103. newPaths = []
  3104. for p in self.depotPaths:
  3105. if p.find("@") != -1:
  3106. atIdx = p.index("@")
  3107. self.changeRange = p[atIdx:]
  3108. if self.changeRange == "@all":
  3109. self.changeRange = ""
  3110. elif ',' not in self.changeRange:
  3111. revision = self.changeRange
  3112. self.changeRange = ""
  3113. p = p[:atIdx]
  3114. elif p.find("#") != -1:
  3115. hashIdx = p.index("#")
  3116. revision = p[hashIdx:]
  3117. p = p[:hashIdx]
  3118. elif self.previousDepotPaths == []:
  3119. # pay attention to changesfile, if given, else import
  3120. # the entire p4 tree at the head revision
  3121. if len(self.changesFile) == 0:
  3122. revision = "#head"
  3123. p = re.sub ("\.\.\.$", "", p)
  3124. if not p.endswith("/"):
  3125. p += "/"
  3126. newPaths.append(p)
  3127. self.depotPaths = newPaths
  3128. # --detect-branches may change this for each branch
  3129. self.branchPrefixes = self.depotPaths
  3130. self.loadUserMapFromCache()
  3131. self.labels = {}
  3132. if self.detectLabels:
  3133. self.getLabels();
  3134. if self.detectBranches:
  3135. ## FIXME - what's a P4 projectName ?
  3136. self.projectName = self.guessProjectName()
  3137. if self.hasOrigin:
  3138. self.getBranchMappingFromGitBranches()
  3139. else:
  3140. self.getBranchMapping()
  3141. if self.verbose:
  3142. print("p4-git branches: %s" % self.p4BranchesInGit)
  3143. print("initial parents: %s" % self.initialParents)
  3144. for b in self.p4BranchesInGit:
  3145. if b != "master":
  3146. ## FIXME
  3147. b = b[len(self.projectName):]
  3148. self.createdBranches.add(b)
  3149. self.openStreams()
  3150. if revision:
  3151. self.importHeadRevision(revision)
  3152. else:
  3153. changes = []
  3154. if len(self.changesFile) > 0:
  3155. output = open(self.changesFile).readlines()
  3156. changeSet = set()
  3157. for line in output:
  3158. changeSet.add(int(line))
  3159. for change in changeSet:
  3160. changes.append(change)
  3161. changes.sort()
  3162. else:
  3163. # catch "git p4 sync" with no new branches, in a repo that
  3164. # does not have any existing p4 branches
  3165. if len(args) == 0:
  3166. if not self.p4BranchesInGit:
  3167. die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
  3168. # The default branch is master, unless --branch is used to
  3169. # specify something else. Make sure it exists, or complain
  3170. # nicely about how to use --branch.
  3171. if not self.detectBranches:
  3172. if not branch_exists(self.branch):
  3173. if branch_arg_given:
  3174. die("Error: branch %s does not exist." % self.branch)
  3175. else:
  3176. die("Error: no branch %s; perhaps specify one with --branch." %
  3177. self.branch)
  3178. if self.verbose:
  3179. print("Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
  3180. self.changeRange))
  3181. changes = p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)
  3182. if len(self.maxChanges) > 0:
  3183. changes = changes[:min(int(self.maxChanges), len(changes))]
  3184. if len(changes) == 0:
  3185. if not self.silent:
  3186. print("No changes to import!")
  3187. else:
  3188. if not self.silent and not self.detectBranches:
  3189. print("Import destination: %s" % self.branch)
  3190. self.updatedBranches = set()
  3191. if not self.detectBranches:
  3192. if args:
  3193. # start a new branch
  3194. self.initialParent = ""
  3195. else:
  3196. # build on a previous revision
  3197. self.initialParent = parseRevision(self.branch)
  3198. self.importChanges(changes)
  3199. if not self.silent:
  3200. print("")
  3201. if len(self.updatedBranches) > 0:
  3202. sys.stdout.write("Updated branches: ")
  3203. for b in self.updatedBranches:
  3204. sys.stdout.write("%s " % b)
  3205. sys.stdout.write("\n")
  3206. if gitConfigBool("git-p4.importLabels"):
  3207. self.importLabels = True
  3208. if self.importLabels:
  3209. p4Labels = getP4Labels(self.depotPaths)
  3210. gitTags = getGitTags()
  3211. missingP4Labels = p4Labels - gitTags
  3212. self.importP4Labels(self.gitStream, missingP4Labels)
  3213. self.closeStreams()
  3214. # Cleanup temporary branches created during import
  3215. if self.tempBranches != []:
  3216. for branch in self.tempBranches:
  3217. read_pipe("git update-ref -d %s" % branch)
  3218. os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
  3219. # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
  3220. # a convenient shortcut refname "p4".
  3221. if self.importIntoRemotes:
  3222. head_ref = self.refPrefix + "HEAD"
  3223. if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
  3224. system(["git", "symbolic-ref", head_ref, self.branch])
  3225. return True
  3226. class P4Rebase(Command):
  3227. def __init__(self):
  3228. Command.__init__(self)
  3229. self.options = [
  3230. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  3231. ]
  3232. self.importLabels = False
  3233. self.description = ("Fetches the latest revision from perforce and "
  3234. + "rebases the current work (branch) against it")
  3235. def run(self, args):
  3236. sync = P4Sync()
  3237. sync.importLabels = self.importLabels
  3238. sync.run([])
  3239. return self.rebase()
  3240. def rebase(self):
  3241. if os.system("git update-index --refresh") != 0:
  3242. 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.");
  3243. if len(read_pipe("git diff-index HEAD --")) > 0:
  3244. die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
  3245. [upstream, settings] = findUpstreamBranchPoint()
  3246. if len(upstream) == 0:
  3247. die("Cannot find upstream branchpoint for rebase")
  3248. # the branchpoint may be p4/foo~3, so strip off the parent
  3249. upstream = re.sub("~[0-9]+$", "", upstream)
  3250. print("Rebasing the current branch onto %s" % upstream)
  3251. oldHead = read_pipe("git rev-parse HEAD").strip()
  3252. system("git rebase %s" % upstream)
  3253. system("git diff-tree --stat --summary -M %s HEAD --" % oldHead)
  3254. return True
  3255. class P4Clone(P4Sync):
  3256. def __init__(self):
  3257. P4Sync.__init__(self)
  3258. self.description = "Creates a new git repository and imports from Perforce into it"
  3259. self.usage = "usage: %prog [options] //depot/path[@revRange]"
  3260. self.options += [
  3261. optparse.make_option("--destination", dest="cloneDestination",
  3262. action='store', default=None,
  3263. help="where to leave result of the clone"),
  3264. optparse.make_option("--bare", dest="cloneBare",
  3265. action="store_true", default=False),
  3266. ]
  3267. self.cloneDestination = None
  3268. self.needsGit = False
  3269. self.cloneBare = False
  3270. def defaultDestination(self, args):
  3271. ## TODO: use common prefix of args?
  3272. depotPath = args[0]
  3273. depotDir = re.sub("(@[^@]*)$", "", depotPath)
  3274. depotDir = re.sub("(#[^#]*)$", "", depotDir)
  3275. depotDir = re.sub(r"\.\.\.$", "", depotDir)
  3276. depotDir = re.sub(r"/$", "", depotDir)
  3277. return os.path.split(depotDir)[1]
  3278. def run(self, args):
  3279. if len(args) < 1:
  3280. return False
  3281. if self.keepRepoPath and not self.cloneDestination:
  3282. sys.stderr.write("Must specify destination for --keep-path\n")
  3283. sys.exit(1)
  3284. depotPaths = args
  3285. if not self.cloneDestination and len(depotPaths) > 1:
  3286. self.cloneDestination = depotPaths[-1]
  3287. depotPaths = depotPaths[:-1]
  3288. for p in depotPaths:
  3289. if not p.startswith("//"):
  3290. sys.stderr.write('Depot paths must start with "//": %s\n' % p)
  3291. return False
  3292. if not self.cloneDestination:
  3293. self.cloneDestination = self.defaultDestination(args)
  3294. print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
  3295. if not os.path.exists(self.cloneDestination):
  3296. os.makedirs(self.cloneDestination)
  3297. chdir(self.cloneDestination)
  3298. init_cmd = [ "git", "init" ]
  3299. if self.cloneBare:
  3300. init_cmd.append("--bare")
  3301. retcode = subprocess.call(init_cmd)
  3302. if retcode:
  3303. raise CalledProcessError(retcode, init_cmd)
  3304. if not P4Sync.run(self, depotPaths):
  3305. return False
  3306. # create a master branch and check out a work tree
  3307. if gitBranchExists(self.branch):
  3308. system([ "git", "branch", "master", self.branch ])
  3309. if not self.cloneBare:
  3310. system([ "git", "checkout", "-f" ])
  3311. else:
  3312. print('Not checking out any branch, use ' \
  3313. '"git checkout -q -b master <branch>"')
  3314. # auto-set this variable if invoked with --use-client-spec
  3315. if self.useClientSpec_from_options:
  3316. system("git config --bool git-p4.useclientspec true")
  3317. return True
  3318. class P4Unshelve(Command):
  3319. def __init__(self):
  3320. Command.__init__(self)
  3321. self.options = []
  3322. self.origin = "HEAD"
  3323. self.description = "Unshelve a P4 changelist into a git commit"
  3324. self.usage = "usage: %prog [options] changelist"
  3325. self.options += [
  3326. optparse.make_option("--origin", dest="origin",
  3327. help="Use this base revision instead of the default (%s)" % self.origin),
  3328. ]
  3329. self.verbose = False
  3330. self.noCommit = False
  3331. self.destbranch = "refs/remotes/p4-unshelved"
  3332. def renameBranch(self, branch_name):
  3333. """ Rename the existing branch to branch_name.N
  3334. """
  3335. found = True
  3336. for i in range(0,1000):
  3337. backup_branch_name = "{0}.{1}".format(branch_name, i)
  3338. if not gitBranchExists(backup_branch_name):
  3339. gitUpdateRef(backup_branch_name, branch_name) # copy ref to backup
  3340. gitDeleteRef(branch_name)
  3341. found = True
  3342. print("renamed old unshelve branch to {0}".format(backup_branch_name))
  3343. break
  3344. if not found:
  3345. sys.exit("gave up trying to rename existing branch {0}".format(sync.branch))
  3346. def findLastP4Revision(self, starting_point):
  3347. """ Look back from starting_point for the first commit created by git-p4
  3348. to find the P4 commit we are based on, and the depot-paths.
  3349. """
  3350. for parent in (range(65535)):
  3351. log = extractLogMessageFromGitCommit("{0}^{1}".format(starting_point, parent))
  3352. settings = extractSettingsGitLog(log)
  3353. if 'change' in settings:
  3354. return settings
  3355. sys.exit("could not find git-p4 commits in {0}".format(self.origin))
  3356. def createShelveParent(self, change, branch_name, sync, origin):
  3357. """ Create a commit matching the parent of the shelved changelist 'change'
  3358. """
  3359. parent_description = p4_describe(change, shelved=True)
  3360. parent_description['desc'] = 'parent for shelved changelist {}\n'.format(change)
  3361. files = sync.extractFilesFromCommit(parent_description, shelved=False, shelved_cl=change)
  3362. parent_files = []
  3363. for f in files:
  3364. # if it was added in the shelved changelist, it won't exist in the parent
  3365. if f['action'] in self.add_actions:
  3366. continue
  3367. # if it was deleted in the shelved changelist it must not be deleted
  3368. # in the parent - we might even need to create it if the origin branch
  3369. # does not have it
  3370. if f['action'] in self.delete_actions:
  3371. f['action'] = 'add'
  3372. parent_files.append(f)
  3373. sync.commit(parent_description, parent_files, branch_name,
  3374. parent=origin, allow_empty=True)
  3375. print("created parent commit for {0} based on {1} in {2}".format(
  3376. change, self.origin, branch_name))
  3377. def run(self, args):
  3378. if len(args) != 1:
  3379. return False
  3380. if not gitBranchExists(self.origin):
  3381. sys.exit("origin branch {0} does not exist".format(self.origin))
  3382. sync = P4Sync()
  3383. changes = args
  3384. # only one change at a time
  3385. change = changes[0]
  3386. # if the target branch already exists, rename it
  3387. branch_name = "{0}/{1}".format(self.destbranch, change)
  3388. if gitBranchExists(branch_name):
  3389. self.renameBranch(branch_name)
  3390. sync.branch = branch_name
  3391. sync.verbose = self.verbose
  3392. sync.suppress_meta_comment = True
  3393. settings = self.findLastP4Revision(self.origin)
  3394. sync.depotPaths = settings['depot-paths']
  3395. sync.branchPrefixes = sync.depotPaths
  3396. sync.openStreams()
  3397. sync.loadUserMapFromCache()
  3398. sync.silent = True
  3399. # create a commit for the parent of the shelved changelist
  3400. self.createShelveParent(change, branch_name, sync, self.origin)
  3401. # create the commit for the shelved changelist itself
  3402. description = p4_describe(change, True)
  3403. files = sync.extractFilesFromCommit(description, True, change)
  3404. sync.commit(description, files, branch_name, "")
  3405. sync.closeStreams()
  3406. print("unshelved changelist {0} into {1}".format(change, branch_name))
  3407. return True
  3408. class P4Branches(Command):
  3409. def __init__(self):
  3410. Command.__init__(self)
  3411. self.options = [ ]
  3412. self.description = ("Shows the git branches that hold imports and their "
  3413. + "corresponding perforce depot paths")
  3414. self.verbose = False
  3415. def run(self, args):
  3416. if originP4BranchesExist():
  3417. createOrUpdateBranchesFromOrigin()
  3418. cmdline = "git rev-parse --symbolic "
  3419. cmdline += " --remotes"
  3420. for line in read_pipe_lines(cmdline):
  3421. line = line.strip()
  3422. if not line.startswith('p4/') or line == "p4/HEAD":
  3423. continue
  3424. branch = line
  3425. log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
  3426. settings = extractSettingsGitLog(log)
  3427. print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
  3428. return True
  3429. class HelpFormatter(optparse.IndentedHelpFormatter):
  3430. def __init__(self):
  3431. optparse.IndentedHelpFormatter.__init__(self)
  3432. def format_description(self, description):
  3433. if description:
  3434. return description + "\n"
  3435. else:
  3436. return ""
  3437. def printUsage(commands):
  3438. print("usage: %s <command> [options]" % sys.argv[0])
  3439. print("")
  3440. print("valid commands: %s" % ", ".join(commands))
  3441. print("")
  3442. print("Try %s <command> --help for command specific help." % sys.argv[0])
  3443. print("")
  3444. commands = {
  3445. "debug" : P4Debug,
  3446. "submit" : P4Submit,
  3447. "commit" : P4Submit,
  3448. "sync" : P4Sync,
  3449. "rebase" : P4Rebase,
  3450. "clone" : P4Clone,
  3451. "rollback" : P4RollBack,
  3452. "branches" : P4Branches,
  3453. "unshelve" : P4Unshelve,
  3454. }
  3455. def main():
  3456. if len(sys.argv[1:]) == 0:
  3457. printUsage(commands.keys())
  3458. sys.exit(2)
  3459. cmdName = sys.argv[1]
  3460. try:
  3461. klass = commands[cmdName]
  3462. cmd = klass()
  3463. except KeyError:
  3464. print("unknown command %s" % cmdName)
  3465. print("")
  3466. printUsage(commands.keys())
  3467. sys.exit(2)
  3468. options = cmd.options
  3469. cmd.gitdir = os.environ.get("GIT_DIR", None)
  3470. args = sys.argv[2:]
  3471. options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
  3472. if cmd.needsGit:
  3473. options.append(optparse.make_option("--git-dir", dest="gitdir"))
  3474. parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
  3475. options,
  3476. description = cmd.description,
  3477. formatter = HelpFormatter())
  3478. (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
  3479. global verbose
  3480. verbose = cmd.verbose
  3481. if cmd.needsGit:
  3482. if cmd.gitdir == None:
  3483. cmd.gitdir = os.path.abspath(".git")
  3484. if not isValidGitDir(cmd.gitdir):
  3485. # "rev-parse --git-dir" without arguments will try $PWD/.git
  3486. cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
  3487. if os.path.exists(cmd.gitdir):
  3488. cdup = read_pipe("git rev-parse --show-cdup").strip()
  3489. if len(cdup) > 0:
  3490. chdir(cdup);
  3491. if not isValidGitDir(cmd.gitdir):
  3492. if isValidGitDir(cmd.gitdir + "/.git"):
  3493. cmd.gitdir += "/.git"
  3494. else:
  3495. die("fatal: cannot locate git repository at %s" % cmd.gitdir)
  3496. # so git commands invoked from the P4 workspace will succeed
  3497. os.environ["GIT_DIR"] = cmd.gitdir
  3498. if not cmd.run(args):
  3499. parser.print_help()
  3500. sys.exit(2)
  3501. if __name__ == '__main__':
  3502. main()