PageRenderTime 55ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/git-p4.py

https://github.com/skybound/git
Python | 3183 lines | 3078 code | 60 blank | 45 comment | 121 complexity | 0d7d915faa00c7e4fe1645cd28246436 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  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 optparse, sys, os, marshal, subprocess, shelve
  11. import tempfile, getopt, os.path, time, platform
  12. import re, shutil
  13. verbose = False
  14. # Only labels/tags matching this will be imported/exported
  15. defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
  16. def p4_build_cmd(cmd):
  17. """Build a suitable p4 command line.
  18. This consolidates building and returning a p4 command line into one
  19. location. It means that hooking into the environment, or other configuration
  20. can be done more easily.
  21. """
  22. real_cmd = ["p4"]
  23. user = gitConfig("git-p4.user")
  24. if len(user) > 0:
  25. real_cmd += ["-u",user]
  26. password = gitConfig("git-p4.password")
  27. if len(password) > 0:
  28. real_cmd += ["-P", password]
  29. port = gitConfig("git-p4.port")
  30. if len(port) > 0:
  31. real_cmd += ["-p", port]
  32. host = gitConfig("git-p4.host")
  33. if len(host) > 0:
  34. real_cmd += ["-H", host]
  35. client = gitConfig("git-p4.client")
  36. if len(client) > 0:
  37. real_cmd += ["-c", client]
  38. if isinstance(cmd,basestring):
  39. real_cmd = ' '.join(real_cmd) + ' ' + cmd
  40. else:
  41. real_cmd += cmd
  42. return real_cmd
  43. def chdir(dir):
  44. # P4 uses the PWD environment variable rather than getcwd(). Since we're
  45. # not using the shell, we have to set it ourselves. This path could
  46. # be relative, so go there first, then figure out where we ended up.
  47. os.chdir(dir)
  48. os.environ['PWD'] = os.getcwd()
  49. def die(msg):
  50. if verbose:
  51. raise Exception(msg)
  52. else:
  53. sys.stderr.write(msg + "\n")
  54. sys.exit(1)
  55. def write_pipe(c, stdin):
  56. if verbose:
  57. sys.stderr.write('Writing pipe: %s\n' % str(c))
  58. expand = isinstance(c,basestring)
  59. p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
  60. pipe = p.stdin
  61. val = pipe.write(stdin)
  62. pipe.close()
  63. if p.wait():
  64. die('Command failed: %s' % str(c))
  65. return val
  66. def p4_write_pipe(c, stdin):
  67. real_cmd = p4_build_cmd(c)
  68. return write_pipe(real_cmd, stdin)
  69. def read_pipe(c, ignore_error=False):
  70. if verbose:
  71. sys.stderr.write('Reading pipe: %s\n' % str(c))
  72. expand = isinstance(c,basestring)
  73. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  74. pipe = p.stdout
  75. val = pipe.read()
  76. if p.wait() and not ignore_error:
  77. die('Command failed: %s' % str(c))
  78. return val
  79. def p4_read_pipe(c, ignore_error=False):
  80. real_cmd = p4_build_cmd(c)
  81. return read_pipe(real_cmd, ignore_error)
  82. def read_pipe_lines(c):
  83. if verbose:
  84. sys.stderr.write('Reading pipe: %s\n' % str(c))
  85. expand = isinstance(c, basestring)
  86. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  87. pipe = p.stdout
  88. val = pipe.readlines()
  89. if pipe.close() or p.wait():
  90. die('Command failed: %s' % str(c))
  91. return val
  92. def p4_read_pipe_lines(c):
  93. """Specifically invoke p4 on the command supplied. """
  94. real_cmd = p4_build_cmd(c)
  95. return read_pipe_lines(real_cmd)
  96. def p4_has_command(cmd):
  97. """Ask p4 for help on this command. If it returns an error, the
  98. command does not exist in this version of p4."""
  99. real_cmd = p4_build_cmd(["help", cmd])
  100. p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
  101. stderr=subprocess.PIPE)
  102. p.communicate()
  103. return p.returncode == 0
  104. def system(cmd):
  105. expand = isinstance(cmd,basestring)
  106. if verbose:
  107. sys.stderr.write("executing %s\n" % str(cmd))
  108. subprocess.check_call(cmd, shell=expand)
  109. def p4_system(cmd):
  110. """Specifically invoke p4 as the system command. """
  111. real_cmd = p4_build_cmd(cmd)
  112. expand = isinstance(real_cmd, basestring)
  113. subprocess.check_call(real_cmd, shell=expand)
  114. def p4_integrate(src, dest):
  115. p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
  116. def p4_sync(f, *options):
  117. p4_system(["sync"] + list(options) + [wildcard_encode(f)])
  118. def p4_add(f):
  119. # forcibly add file names with wildcards
  120. if wildcard_present(f):
  121. p4_system(["add", "-f", f])
  122. else:
  123. p4_system(["add", f])
  124. def p4_delete(f):
  125. p4_system(["delete", wildcard_encode(f)])
  126. def p4_edit(f):
  127. p4_system(["edit", wildcard_encode(f)])
  128. def p4_revert(f):
  129. p4_system(["revert", wildcard_encode(f)])
  130. def p4_reopen(type, f):
  131. p4_system(["reopen", "-t", type, wildcard_encode(f)])
  132. def p4_move(src, dest):
  133. p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
  134. #
  135. # Canonicalize the p4 type and return a tuple of the
  136. # base type, plus any modifiers. See "p4 help filetypes"
  137. # for a list and explanation.
  138. #
  139. def split_p4_type(p4type):
  140. p4_filetypes_historical = {
  141. "ctempobj": "binary+Sw",
  142. "ctext": "text+C",
  143. "cxtext": "text+Cx",
  144. "ktext": "text+k",
  145. "kxtext": "text+kx",
  146. "ltext": "text+F",
  147. "tempobj": "binary+FSw",
  148. "ubinary": "binary+F",
  149. "uresource": "resource+F",
  150. "uxbinary": "binary+Fx",
  151. "xbinary": "binary+x",
  152. "xltext": "text+Fx",
  153. "xtempobj": "binary+Swx",
  154. "xtext": "text+x",
  155. "xunicode": "unicode+x",
  156. "xutf16": "utf16+x",
  157. }
  158. if p4type in p4_filetypes_historical:
  159. p4type = p4_filetypes_historical[p4type]
  160. mods = ""
  161. s = p4type.split("+")
  162. base = s[0]
  163. mods = ""
  164. if len(s) > 1:
  165. mods = s[1]
  166. return (base, mods)
  167. #
  168. # return the raw p4 type of a file (text, text+ko, etc)
  169. #
  170. def p4_type(file):
  171. results = p4CmdList(["fstat", "-T", "headType", file])
  172. return results[0]['headType']
  173. #
  174. # Given a type base and modifier, return a regexp matching
  175. # the keywords that can be expanded in the file
  176. #
  177. def p4_keywords_regexp_for_type(base, type_mods):
  178. if base in ("text", "unicode", "binary"):
  179. kwords = None
  180. if "ko" in type_mods:
  181. kwords = 'Id|Header'
  182. elif "k" in type_mods:
  183. kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
  184. else:
  185. return None
  186. pattern = r"""
  187. \$ # Starts with a dollar, followed by...
  188. (%s) # one of the keywords, followed by...
  189. (:[^$]+)? # possibly an old expansion, followed by...
  190. \$ # another dollar
  191. """ % kwords
  192. return pattern
  193. else:
  194. return None
  195. #
  196. # Given a file, return a regexp matching the possible
  197. # RCS keywords that will be expanded, or None for files
  198. # with kw expansion turned off.
  199. #
  200. def p4_keywords_regexp_for_file(file):
  201. if not os.path.exists(file):
  202. return None
  203. else:
  204. (type_base, type_mods) = split_p4_type(p4_type(file))
  205. return p4_keywords_regexp_for_type(type_base, type_mods)
  206. def setP4ExecBit(file, mode):
  207. # Reopens an already open file and changes the execute bit to match
  208. # the execute bit setting in the passed in mode.
  209. p4Type = "+x"
  210. if not isModeExec(mode):
  211. p4Type = getP4OpenedType(file)
  212. p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
  213. p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
  214. if p4Type[-1] == "+":
  215. p4Type = p4Type[0:-1]
  216. p4_reopen(p4Type, file)
  217. def getP4OpenedType(file):
  218. # Returns the perforce file type for the given file.
  219. result = p4_read_pipe(["opened", wildcard_encode(file)])
  220. match = re.match(".*\((.+)\)\r?$", result)
  221. if match:
  222. return match.group(1)
  223. else:
  224. die("Could not determine file type for %s (result: '%s')" % (file, result))
  225. # Return the set of all p4 labels
  226. def getP4Labels(depotPaths):
  227. labels = set()
  228. if isinstance(depotPaths,basestring):
  229. depotPaths = [depotPaths]
  230. for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
  231. label = l['label']
  232. labels.add(label)
  233. return labels
  234. # Return the set of all git tags
  235. def getGitTags():
  236. gitTags = set()
  237. for line in read_pipe_lines(["git", "tag"]):
  238. tag = line.strip()
  239. gitTags.add(tag)
  240. return gitTags
  241. def diffTreePattern():
  242. # This is a simple generator for the diff tree regex pattern. This could be
  243. # a class variable if this and parseDiffTreeEntry were a part of a class.
  244. pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
  245. while True:
  246. yield pattern
  247. def parseDiffTreeEntry(entry):
  248. """Parses a single diff tree entry into its component elements.
  249. See git-diff-tree(1) manpage for details about the format of the diff
  250. output. This method returns a dictionary with the following elements:
  251. src_mode - The mode of the source file
  252. dst_mode - The mode of the destination file
  253. src_sha1 - The sha1 for the source file
  254. dst_sha1 - The sha1 fr the destination file
  255. status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
  256. status_score - The score for the status (applicable for 'C' and 'R'
  257. statuses). This is None if there is no score.
  258. src - The path for the source file.
  259. dst - The path for the destination file. This is only present for
  260. copy or renames. If it is not present, this is None.
  261. If the pattern is not matched, None is returned."""
  262. match = diffTreePattern().next().match(entry)
  263. if match:
  264. return {
  265. 'src_mode': match.group(1),
  266. 'dst_mode': match.group(2),
  267. 'src_sha1': match.group(3),
  268. 'dst_sha1': match.group(4),
  269. 'status': match.group(5),
  270. 'status_score': match.group(6),
  271. 'src': match.group(7),
  272. 'dst': match.group(10)
  273. }
  274. return None
  275. def isModeExec(mode):
  276. # Returns True if the given git mode represents an executable file,
  277. # otherwise False.
  278. return mode[-3:] == "755"
  279. def isModeExecChanged(src_mode, dst_mode):
  280. return isModeExec(src_mode) != isModeExec(dst_mode)
  281. def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
  282. if isinstance(cmd,basestring):
  283. cmd = "-G " + cmd
  284. expand = True
  285. else:
  286. cmd = ["-G"] + cmd
  287. expand = False
  288. cmd = p4_build_cmd(cmd)
  289. if verbose:
  290. sys.stderr.write("Opening pipe: %s\n" % str(cmd))
  291. # Use a temporary file to avoid deadlocks without
  292. # subprocess.communicate(), which would put another copy
  293. # of stdout into memory.
  294. stdin_file = None
  295. if stdin is not None:
  296. stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
  297. if isinstance(stdin,basestring):
  298. stdin_file.write(stdin)
  299. else:
  300. for i in stdin:
  301. stdin_file.write(i + '\n')
  302. stdin_file.flush()
  303. stdin_file.seek(0)
  304. p4 = subprocess.Popen(cmd,
  305. shell=expand,
  306. stdin=stdin_file,
  307. stdout=subprocess.PIPE)
  308. result = []
  309. try:
  310. while True:
  311. entry = marshal.load(p4.stdout)
  312. if cb is not None:
  313. cb(entry)
  314. else:
  315. result.append(entry)
  316. except EOFError:
  317. pass
  318. exitCode = p4.wait()
  319. if exitCode != 0:
  320. entry = {}
  321. entry["p4ExitCode"] = exitCode
  322. result.append(entry)
  323. return result
  324. def p4Cmd(cmd):
  325. list = p4CmdList(cmd)
  326. result = {}
  327. for entry in list:
  328. result.update(entry)
  329. return result;
  330. def p4Where(depotPath):
  331. if not depotPath.endswith("/"):
  332. depotPath += "/"
  333. depotPath = depotPath + "..."
  334. outputList = p4CmdList(["where", depotPath])
  335. output = None
  336. for entry in outputList:
  337. if "depotFile" in entry:
  338. if entry["depotFile"] == depotPath:
  339. output = entry
  340. break
  341. elif "data" in entry:
  342. data = entry.get("data")
  343. space = data.find(" ")
  344. if data[:space] == depotPath:
  345. output = entry
  346. break
  347. if output == None:
  348. return ""
  349. if output["code"] == "error":
  350. return ""
  351. clientPath = ""
  352. if "path" in output:
  353. clientPath = output.get("path")
  354. elif "data" in output:
  355. data = output.get("data")
  356. lastSpace = data.rfind(" ")
  357. clientPath = data[lastSpace + 1:]
  358. if clientPath.endswith("..."):
  359. clientPath = clientPath[:-3]
  360. return clientPath
  361. def currentGitBranch():
  362. return read_pipe("git name-rev HEAD").split(" ")[1].strip()
  363. def isValidGitDir(path):
  364. if (os.path.exists(path + "/HEAD")
  365. and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
  366. return True;
  367. return False
  368. def parseRevision(ref):
  369. return read_pipe("git rev-parse %s" % ref).strip()
  370. def branchExists(ref):
  371. rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
  372. ignore_error=True)
  373. return len(rev) > 0
  374. def extractLogMessageFromGitCommit(commit):
  375. logMessage = ""
  376. ## fixme: title is first line of commit, not 1st paragraph.
  377. foundTitle = False
  378. for log in read_pipe_lines("git cat-file commit %s" % commit):
  379. if not foundTitle:
  380. if len(log) == 1:
  381. foundTitle = True
  382. continue
  383. logMessage += log
  384. return logMessage
  385. def extractSettingsGitLog(log):
  386. values = {}
  387. for line in log.split("\n"):
  388. line = line.strip()
  389. m = re.search (r"^ *\[git-p4: (.*)\]$", line)
  390. if not m:
  391. continue
  392. assignments = m.group(1).split (':')
  393. for a in assignments:
  394. vals = a.split ('=')
  395. key = vals[0].strip()
  396. val = ('='.join (vals[1:])).strip()
  397. if val.endswith ('\"') and val.startswith('"'):
  398. val = val[1:-1]
  399. values[key] = val
  400. paths = values.get("depot-paths")
  401. if not paths:
  402. paths = values.get("depot-path")
  403. if paths:
  404. values['depot-paths'] = paths.split(',')
  405. return values
  406. def gitBranchExists(branch):
  407. proc = subprocess.Popen(["git", "rev-parse", branch],
  408. stderr=subprocess.PIPE, stdout=subprocess.PIPE);
  409. return proc.wait() == 0;
  410. _gitConfig = {}
  411. def gitConfig(key, args = None): # set args to "--bool", for instance
  412. if not _gitConfig.has_key(key):
  413. argsFilter = ""
  414. if args != None:
  415. argsFilter = "%s " % args
  416. cmd = "git config %s%s" % (argsFilter, key)
  417. _gitConfig[key] = read_pipe(cmd, ignore_error=True).strip()
  418. return _gitConfig[key]
  419. def gitConfigList(key):
  420. if not _gitConfig.has_key(key):
  421. _gitConfig[key] = read_pipe("git config --get-all %s" % key, ignore_error=True).strip().split(os.linesep)
  422. return _gitConfig[key]
  423. def p4BranchesInGit(branchesAreInRemotes = True):
  424. branches = {}
  425. cmdline = "git rev-parse --symbolic "
  426. if branchesAreInRemotes:
  427. cmdline += " --remotes"
  428. else:
  429. cmdline += " --branches"
  430. for line in read_pipe_lines(cmdline):
  431. line = line.strip()
  432. ## only import to p4/
  433. if not line.startswith('p4/') or line == "p4/HEAD":
  434. continue
  435. branch = line
  436. # strip off p4
  437. branch = re.sub ("^p4/", "", line)
  438. branches[branch] = parseRevision(line)
  439. return branches
  440. def findUpstreamBranchPoint(head = "HEAD"):
  441. branches = p4BranchesInGit()
  442. # map from depot-path to branch name
  443. branchByDepotPath = {}
  444. for branch in branches.keys():
  445. tip = branches[branch]
  446. log = extractLogMessageFromGitCommit(tip)
  447. settings = extractSettingsGitLog(log)
  448. if settings.has_key("depot-paths"):
  449. paths = ",".join(settings["depot-paths"])
  450. branchByDepotPath[paths] = "remotes/p4/" + branch
  451. settings = None
  452. parent = 0
  453. while parent < 65535:
  454. commit = head + "~%s" % parent
  455. log = extractLogMessageFromGitCommit(commit)
  456. settings = extractSettingsGitLog(log)
  457. if settings.has_key("depot-paths"):
  458. paths = ",".join(settings["depot-paths"])
  459. if branchByDepotPath.has_key(paths):
  460. return [branchByDepotPath[paths], settings]
  461. parent = parent + 1
  462. return ["", settings]
  463. def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
  464. if not silent:
  465. print ("Creating/updating branch(es) in %s based on origin branch(es)"
  466. % localRefPrefix)
  467. originPrefix = "origin/p4/"
  468. for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
  469. line = line.strip()
  470. if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
  471. continue
  472. headName = line[len(originPrefix):]
  473. remoteHead = localRefPrefix + headName
  474. originHead = line
  475. original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
  476. if (not original.has_key('depot-paths')
  477. or not original.has_key('change')):
  478. continue
  479. update = False
  480. if not gitBranchExists(remoteHead):
  481. if verbose:
  482. print "creating %s" % remoteHead
  483. update = True
  484. else:
  485. settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
  486. if settings.has_key('change') > 0:
  487. if settings['depot-paths'] == original['depot-paths']:
  488. originP4Change = int(original['change'])
  489. p4Change = int(settings['change'])
  490. if originP4Change > p4Change:
  491. print ("%s (%s) is newer than %s (%s). "
  492. "Updating p4 branch from origin."
  493. % (originHead, originP4Change,
  494. remoteHead, p4Change))
  495. update = True
  496. else:
  497. print ("Ignoring: %s was imported from %s while "
  498. "%s was imported from %s"
  499. % (originHead, ','.join(original['depot-paths']),
  500. remoteHead, ','.join(settings['depot-paths'])))
  501. if update:
  502. system("git update-ref %s %s" % (remoteHead, originHead))
  503. def originP4BranchesExist():
  504. return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
  505. def p4ChangesForPaths(depotPaths, changeRange):
  506. assert depotPaths
  507. cmd = ['changes']
  508. for p in depotPaths:
  509. cmd += ["%s...%s" % (p, changeRange)]
  510. output = p4_read_pipe_lines(cmd)
  511. changes = {}
  512. for line in output:
  513. changeNum = int(line.split(" ")[1])
  514. changes[changeNum] = True
  515. changelist = changes.keys()
  516. changelist.sort()
  517. return changelist
  518. def p4PathStartsWith(path, prefix):
  519. # This method tries to remedy a potential mixed-case issue:
  520. #
  521. # If UserA adds //depot/DirA/file1
  522. # and UserB adds //depot/dira/file2
  523. #
  524. # we may or may not have a problem. If you have core.ignorecase=true,
  525. # we treat DirA and dira as the same directory
  526. ignorecase = gitConfig("core.ignorecase", "--bool") == "true"
  527. if ignorecase:
  528. return path.lower().startswith(prefix.lower())
  529. return path.startswith(prefix)
  530. def getClientSpec():
  531. """Look at the p4 client spec, create a View() object that contains
  532. all the mappings, and return it."""
  533. specList = p4CmdList("client -o")
  534. if len(specList) != 1:
  535. die('Output from "client -o" is %d lines, expecting 1' %
  536. len(specList))
  537. # dictionary of all client parameters
  538. entry = specList[0]
  539. # just the keys that start with "View"
  540. view_keys = [ k for k in entry.keys() if k.startswith("View") ]
  541. # hold this new View
  542. view = View()
  543. # append the lines, in order, to the view
  544. for view_num in range(len(view_keys)):
  545. k = "View%d" % view_num
  546. if k not in view_keys:
  547. die("Expected view key %s missing" % k)
  548. view.append(entry[k])
  549. return view
  550. def getClientRoot():
  551. """Grab the client directory."""
  552. output = p4CmdList("client -o")
  553. if len(output) != 1:
  554. die('Output from "client -o" is %d lines, expecting 1' % len(output))
  555. entry = output[0]
  556. if "Root" not in entry:
  557. die('Client has no "Root"')
  558. return entry["Root"]
  559. #
  560. # P4 wildcards are not allowed in filenames. P4 complains
  561. # if you simply add them, but you can force it with "-f", in
  562. # which case it translates them into %xx encoding internally.
  563. #
  564. def wildcard_decode(path):
  565. # Search for and fix just these four characters. Do % last so
  566. # that fixing it does not inadvertently create new %-escapes.
  567. # Cannot have * in a filename in windows; untested as to
  568. # what p4 would do in such a case.
  569. if not platform.system() == "Windows":
  570. path = path.replace("%2A", "*")
  571. path = path.replace("%23", "#") \
  572. .replace("%40", "@") \
  573. .replace("%25", "%")
  574. return path
  575. def wildcard_encode(path):
  576. # do % first to avoid double-encoding the %s introduced here
  577. path = path.replace("%", "%25") \
  578. .replace("*", "%2A") \
  579. .replace("#", "%23") \
  580. .replace("@", "%40")
  581. return path
  582. def wildcard_present(path):
  583. return path.translate(None, "*#@%") != path
  584. class Command:
  585. def __init__(self):
  586. self.usage = "usage: %prog [options]"
  587. self.needsGit = True
  588. self.verbose = False
  589. class P4UserMap:
  590. def __init__(self):
  591. self.userMapFromPerforceServer = False
  592. self.myP4UserId = None
  593. def p4UserId(self):
  594. if self.myP4UserId:
  595. return self.myP4UserId
  596. results = p4CmdList("user -o")
  597. for r in results:
  598. if r.has_key('User'):
  599. self.myP4UserId = r['User']
  600. return r['User']
  601. die("Could not find your p4 user id")
  602. def p4UserIsMe(self, p4User):
  603. # return True if the given p4 user is actually me
  604. me = self.p4UserId()
  605. if not p4User or p4User != me:
  606. return False
  607. else:
  608. return True
  609. def getUserCacheFilename(self):
  610. home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
  611. return home + "/.gitp4-usercache.txt"
  612. def getUserMapFromPerforceServer(self):
  613. if self.userMapFromPerforceServer:
  614. return
  615. self.users = {}
  616. self.emails = {}
  617. for output in p4CmdList("users"):
  618. if not output.has_key("User"):
  619. continue
  620. self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
  621. self.emails[output["Email"]] = output["User"]
  622. s = ''
  623. for (key, val) in self.users.items():
  624. s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
  625. open(self.getUserCacheFilename(), "wb").write(s)
  626. self.userMapFromPerforceServer = True
  627. def loadUserMapFromCache(self):
  628. self.users = {}
  629. self.userMapFromPerforceServer = False
  630. try:
  631. cache = open(self.getUserCacheFilename(), "rb")
  632. lines = cache.readlines()
  633. cache.close()
  634. for line in lines:
  635. entry = line.strip().split("\t")
  636. self.users[entry[0]] = entry[1]
  637. except IOError:
  638. self.getUserMapFromPerforceServer()
  639. class P4Debug(Command):
  640. def __init__(self):
  641. Command.__init__(self)
  642. self.options = []
  643. self.description = "A tool to debug the output of p4 -G."
  644. self.needsGit = False
  645. def run(self, args):
  646. j = 0
  647. for output in p4CmdList(args):
  648. print 'Element: %d' % j
  649. j += 1
  650. print output
  651. return True
  652. class P4RollBack(Command):
  653. def __init__(self):
  654. Command.__init__(self)
  655. self.options = [
  656. optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
  657. ]
  658. self.description = "A tool to debug the multi-branch import. Don't use :)"
  659. self.rollbackLocalBranches = False
  660. def run(self, args):
  661. if len(args) != 1:
  662. return False
  663. maxChange = int(args[0])
  664. if "p4ExitCode" in p4Cmd("changes -m 1"):
  665. die("Problems executing p4");
  666. if self.rollbackLocalBranches:
  667. refPrefix = "refs/heads/"
  668. lines = read_pipe_lines("git rev-parse --symbolic --branches")
  669. else:
  670. refPrefix = "refs/remotes/"
  671. lines = read_pipe_lines("git rev-parse --symbolic --remotes")
  672. for line in lines:
  673. if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
  674. line = line.strip()
  675. ref = refPrefix + line
  676. log = extractLogMessageFromGitCommit(ref)
  677. settings = extractSettingsGitLog(log)
  678. depotPaths = settings['depot-paths']
  679. change = settings['change']
  680. changed = False
  681. if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
  682. for p in depotPaths]))) == 0:
  683. print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
  684. system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
  685. continue
  686. while change and int(change) > maxChange:
  687. changed = True
  688. if self.verbose:
  689. print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
  690. system("git update-ref %s \"%s^\"" % (ref, ref))
  691. log = extractLogMessageFromGitCommit(ref)
  692. settings = extractSettingsGitLog(log)
  693. depotPaths = settings['depot-paths']
  694. change = settings['change']
  695. if changed:
  696. print "%s rewound to %s" % (ref, change)
  697. return True
  698. class P4Submit(Command, P4UserMap):
  699. conflict_behavior_choices = ("ask", "skip", "quit")
  700. def __init__(self):
  701. Command.__init__(self)
  702. P4UserMap.__init__(self)
  703. self.options = [
  704. optparse.make_option("--origin", dest="origin"),
  705. optparse.make_option("-M", dest="detectRenames", action="store_true"),
  706. # preserve the user, requires relevant p4 permissions
  707. optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
  708. optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
  709. optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
  710. optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
  711. optparse.make_option("--conflict", dest="conflict_behavior",
  712. choices=self.conflict_behavior_choices)
  713. ]
  714. self.description = "Submit changes from git to the perforce depot."
  715. self.usage += " [name of git branch to submit into perforce depot]"
  716. self.origin = ""
  717. self.detectRenames = False
  718. self.preserveUser = gitConfig("git-p4.preserveUser").lower() == "true"
  719. self.dry_run = False
  720. self.prepare_p4_only = False
  721. self.conflict_behavior = None
  722. self.isWindows = (platform.system() == "Windows")
  723. self.exportLabels = False
  724. self.p4HasMoveCommand = p4_has_command("move")
  725. def check(self):
  726. if len(p4CmdList("opened ...")) > 0:
  727. die("You have files opened with perforce! Close them before starting the sync.")
  728. def separate_jobs_from_description(self, message):
  729. """Extract and return a possible Jobs field in the commit
  730. message. It goes into a separate section in the p4 change
  731. specification.
  732. A jobs line starts with "Jobs:" and looks like a new field
  733. in a form. Values are white-space separated on the same
  734. line or on following lines that start with a tab.
  735. This does not parse and extract the full git commit message
  736. like a p4 form. It just sees the Jobs: line as a marker
  737. to pass everything from then on directly into the p4 form,
  738. but outside the description section.
  739. Return a tuple (stripped log message, jobs string)."""
  740. m = re.search(r'^Jobs:', message, re.MULTILINE)
  741. if m is None:
  742. return (message, None)
  743. jobtext = message[m.start():]
  744. stripped_message = message[:m.start()].rstrip()
  745. return (stripped_message, jobtext)
  746. def prepareLogMessage(self, template, message, jobs):
  747. """Edits the template returned from "p4 change -o" to insert
  748. the message in the Description field, and the jobs text in
  749. the Jobs field."""
  750. result = ""
  751. inDescriptionSection = False
  752. for line in template.split("\n"):
  753. if line.startswith("#"):
  754. result += line + "\n"
  755. continue
  756. if inDescriptionSection:
  757. if line.startswith("Files:") or line.startswith("Jobs:"):
  758. inDescriptionSection = False
  759. # insert Jobs section
  760. if jobs:
  761. result += jobs + "\n"
  762. else:
  763. continue
  764. else:
  765. if line.startswith("Description:"):
  766. inDescriptionSection = True
  767. line += "\n"
  768. for messageLine in message.split("\n"):
  769. line += "\t" + messageLine + "\n"
  770. result += line + "\n"
  771. return result
  772. def patchRCSKeywords(self, file, pattern):
  773. # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
  774. (handle, outFileName) = tempfile.mkstemp(dir='.')
  775. try:
  776. outFile = os.fdopen(handle, "w+")
  777. inFile = open(file, "r")
  778. regexp = re.compile(pattern, re.VERBOSE)
  779. for line in inFile.readlines():
  780. line = regexp.sub(r'$\1$', line)
  781. outFile.write(line)
  782. inFile.close()
  783. outFile.close()
  784. # Forcibly overwrite the original file
  785. os.unlink(file)
  786. shutil.move(outFileName, file)
  787. except:
  788. # cleanup our temporary file
  789. os.unlink(outFileName)
  790. print "Failed to strip RCS keywords in %s" % file
  791. raise
  792. print "Patched up RCS keywords in %s" % file
  793. def p4UserForCommit(self,id):
  794. # Return the tuple (perforce user,git email) for a given git commit id
  795. self.getUserMapFromPerforceServer()
  796. gitEmail = read_pipe("git log --max-count=1 --format='%%ae' %s" % id)
  797. gitEmail = gitEmail.strip()
  798. if not self.emails.has_key(gitEmail):
  799. return (None,gitEmail)
  800. else:
  801. return (self.emails[gitEmail],gitEmail)
  802. def checkValidP4Users(self,commits):
  803. # check if any git authors cannot be mapped to p4 users
  804. for id in commits:
  805. (user,email) = self.p4UserForCommit(id)
  806. if not user:
  807. msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
  808. if gitConfig('git-p4.allowMissingP4Users').lower() == "true":
  809. print "%s" % msg
  810. else:
  811. die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
  812. def lastP4Changelist(self):
  813. # Get back the last changelist number submitted in this client spec. This
  814. # then gets used to patch up the username in the change. If the same
  815. # client spec is being used by multiple processes then this might go
  816. # wrong.
  817. results = p4CmdList("client -o") # find the current client
  818. client = None
  819. for r in results:
  820. if r.has_key('Client'):
  821. client = r['Client']
  822. break
  823. if not client:
  824. die("could not get client spec")
  825. results = p4CmdList(["changes", "-c", client, "-m", "1"])
  826. for r in results:
  827. if r.has_key('change'):
  828. return r['change']
  829. die("Could not get changelist number for last submit - cannot patch up user details")
  830. def modifyChangelistUser(self, changelist, newUser):
  831. # fixup the user field of a changelist after it has been submitted.
  832. changes = p4CmdList("change -o %s" % changelist)
  833. if len(changes) != 1:
  834. die("Bad output from p4 change modifying %s to user %s" %
  835. (changelist, newUser))
  836. c = changes[0]
  837. if c['User'] == newUser: return # nothing to do
  838. c['User'] = newUser
  839. input = marshal.dumps(c)
  840. result = p4CmdList("change -f -i", stdin=input)
  841. for r in result:
  842. if r.has_key('code'):
  843. if r['code'] == 'error':
  844. die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
  845. if r.has_key('data'):
  846. print("Updated user field for changelist %s to %s" % (changelist, newUser))
  847. return
  848. die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
  849. def canChangeChangelists(self):
  850. # check to see if we have p4 admin or super-user permissions, either of
  851. # which are required to modify changelists.
  852. results = p4CmdList(["protects", self.depotPath])
  853. for r in results:
  854. if r.has_key('perm'):
  855. if r['perm'] == 'admin':
  856. return 1
  857. if r['perm'] == 'super':
  858. return 1
  859. return 0
  860. def prepareSubmitTemplate(self):
  861. """Run "p4 change -o" to grab a change specification template.
  862. This does not use "p4 -G", as it is nice to keep the submission
  863. template in original order, since a human might edit it.
  864. Remove lines in the Files section that show changes to files
  865. outside the depot path we're committing into."""
  866. template = ""
  867. inFilesSection = False
  868. for line in p4_read_pipe_lines(['change', '-o']):
  869. if line.endswith("\r\n"):
  870. line = line[:-2] + "\n"
  871. if inFilesSection:
  872. if line.startswith("\t"):
  873. # path starts and ends with a tab
  874. path = line[1:]
  875. lastTab = path.rfind("\t")
  876. if lastTab != -1:
  877. path = path[:lastTab]
  878. if not p4PathStartsWith(path, self.depotPath):
  879. continue
  880. else:
  881. inFilesSection = False
  882. else:
  883. if line.startswith("Files:"):
  884. inFilesSection = True
  885. template += line
  886. return template
  887. def edit_template(self, template_file):
  888. """Invoke the editor to let the user change the submission
  889. message. Return true if okay to continue with the submit."""
  890. # if configured to skip the editing part, just submit
  891. if gitConfig("git-p4.skipSubmitEdit") == "true":
  892. return True
  893. # look at the modification time, to check later if the user saved
  894. # the file
  895. mtime = os.stat(template_file).st_mtime
  896. # invoke the editor
  897. if os.environ.has_key("P4EDITOR") and (os.environ.get("P4EDITOR") != ""):
  898. editor = os.environ.get("P4EDITOR")
  899. else:
  900. editor = read_pipe("git var GIT_EDITOR").strip()
  901. system(editor + " " + template_file)
  902. # If the file was not saved, prompt to see if this patch should
  903. # be skipped. But skip this verification step if configured so.
  904. if gitConfig("git-p4.skipSubmitEditCheck") == "true":
  905. return True
  906. # modification time updated means user saved the file
  907. if os.stat(template_file).st_mtime > mtime:
  908. return True
  909. while True:
  910. response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
  911. if response == 'y':
  912. return True
  913. if response == 'n':
  914. return False
  915. def applyCommit(self, id):
  916. """Apply one commit, return True if it succeeded."""
  917. print "Applying", read_pipe(["git", "show", "-s",
  918. "--format=format:%h %s", id])
  919. (p4User, gitEmail) = self.p4UserForCommit(id)
  920. diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
  921. filesToAdd = set()
  922. filesToDelete = set()
  923. editedFiles = set()
  924. pureRenameCopy = set()
  925. filesToChangeExecBit = {}
  926. for line in diff:
  927. diff = parseDiffTreeEntry(line)
  928. modifier = diff['status']
  929. path = diff['src']
  930. if modifier == "M":
  931. p4_edit(path)
  932. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  933. filesToChangeExecBit[path] = diff['dst_mode']
  934. editedFiles.add(path)
  935. elif modifier == "A":
  936. filesToAdd.add(path)
  937. filesToChangeExecBit[path] = diff['dst_mode']
  938. if path in filesToDelete:
  939. filesToDelete.remove(path)
  940. elif modifier == "D":
  941. filesToDelete.add(path)
  942. if path in filesToAdd:
  943. filesToAdd.remove(path)
  944. elif modifier == "C":
  945. src, dest = diff['src'], diff['dst']
  946. p4_integrate(src, dest)
  947. pureRenameCopy.add(dest)
  948. if diff['src_sha1'] != diff['dst_sha1']:
  949. p4_edit(dest)
  950. pureRenameCopy.discard(dest)
  951. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  952. p4_edit(dest)
  953. pureRenameCopy.discard(dest)
  954. filesToChangeExecBit[dest] = diff['dst_mode']
  955. os.unlink(dest)
  956. editedFiles.add(dest)
  957. elif modifier == "R":
  958. src, dest = diff['src'], diff['dst']
  959. if self.p4HasMoveCommand:
  960. p4_edit(src) # src must be open before move
  961. p4_move(src, dest) # opens for (move/delete, move/add)
  962. else:
  963. p4_integrate(src, dest)
  964. if diff['src_sha1'] != diff['dst_sha1']:
  965. p4_edit(dest)
  966. else:
  967. pureRenameCopy.add(dest)
  968. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  969. if not self.p4HasMoveCommand:
  970. p4_edit(dest) # with move: already open, writable
  971. filesToChangeExecBit[dest] = diff['dst_mode']
  972. if not self.p4HasMoveCommand:
  973. os.unlink(dest)
  974. filesToDelete.add(src)
  975. editedFiles.add(dest)
  976. else:
  977. die("unknown modifier %s for %s" % (modifier, path))
  978. diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
  979. patchcmd = diffcmd + " | git apply "
  980. tryPatchCmd = patchcmd + "--check -"
  981. applyPatchCmd = patchcmd + "--check --apply -"
  982. patch_succeeded = True
  983. if os.system(tryPatchCmd) != 0:
  984. fixed_rcs_keywords = False
  985. patch_succeeded = False
  986. print "Unfortunately applying the change failed!"
  987. # Patch failed, maybe it's just RCS keyword woes. Look through
  988. # the patch to see if that's possible.
  989. if gitConfig("git-p4.attemptRCSCleanup","--bool") == "true":
  990. file = None
  991. pattern = None
  992. kwfiles = {}
  993. for file in editedFiles | filesToDelete:
  994. # did this file's delta contain RCS keywords?
  995. pattern = p4_keywords_regexp_for_file(file)
  996. if pattern:
  997. # this file is a possibility...look for RCS keywords.
  998. regexp = re.compile(pattern, re.VERBOSE)
  999. for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
  1000. if regexp.search(line):
  1001. if verbose:
  1002. print "got keyword match on %s in %s in %s" % (pattern, line, file)
  1003. kwfiles[file] = pattern
  1004. break
  1005. for file in kwfiles:
  1006. if verbose:
  1007. print "zapping %s with %s" % (line,pattern)
  1008. self.patchRCSKeywords(file, kwfiles[file])
  1009. fixed_rcs_keywords = True
  1010. if fixed_rcs_keywords:
  1011. print "Retrying the patch with RCS keywords cleaned up"
  1012. if os.system(tryPatchCmd) == 0:
  1013. patch_succeeded = True
  1014. if not patch_succeeded:
  1015. for f in editedFiles:
  1016. p4_revert(f)
  1017. return False
  1018. #
  1019. # Apply the patch for real, and do add/delete/+x handling.
  1020. #
  1021. system(applyPatchCmd)
  1022. for f in filesToAdd:
  1023. p4_add(f)
  1024. for f in filesToDelete:
  1025. p4_revert(f)
  1026. p4_delete(f)
  1027. # Set/clear executable bits
  1028. for f in filesToChangeExecBit.keys():
  1029. mode = filesToChangeExecBit[f]
  1030. setP4ExecBit(f, mode)
  1031. #
  1032. # Build p4 change description, starting with the contents
  1033. # of the git commit message.
  1034. #
  1035. logMessage = extractLogMessageFromGitCommit(id)
  1036. logMessage = logMessage.strip()
  1037. (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
  1038. template = self.prepareSubmitTemplate()
  1039. submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
  1040. if self.preserveUser:
  1041. submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
  1042. if self.checkAuthorship and not self.p4UserIsMe(p4User):
  1043. submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
  1044. submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
  1045. submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
  1046. separatorLine = "######## everything below this line is just the diff #######\n"
  1047. # diff
  1048. if os.environ.has_key("P4DIFF"):
  1049. del(os.environ["P4DIFF"])
  1050. diff = ""
  1051. for editedFile in editedFiles:
  1052. diff += p4_read_pipe(['diff', '-du',
  1053. wildcard_encode(editedFile)])
  1054. # new file diff
  1055. newdiff = ""
  1056. for newFile in filesToAdd:
  1057. newdiff += "==== new file ====\n"
  1058. newdiff += "--- /dev/null\n"
  1059. newdiff += "+++ %s\n" % newFile
  1060. f = open(newFile, "r")
  1061. for line in f.readlines():
  1062. newdiff += "+" + line
  1063. f.close()
  1064. # change description file: submitTemplate, separatorLine, diff, newdiff
  1065. (handle, fileName) = tempfile.mkstemp()
  1066. tmpFile = os.fdopen(handle, "w+")
  1067. if self.isWindows:
  1068. submitTemplate = submitTemplate.replace("\n", "\r\n")
  1069. separatorLine = separatorLine.replace("\n", "\r\n")
  1070. newdiff = newdiff.replace("\n", "\r\n")
  1071. tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
  1072. tmpFile.close()
  1073. if self.prepare_p4_only:
  1074. #
  1075. # Leave the p4 tree prepared, and the submit template around
  1076. # and let the user decide what to do next
  1077. #
  1078. print
  1079. print "P4 workspace prepared for submission."
  1080. print "To submit or revert, go to client workspace"
  1081. print " " + self.clientPath
  1082. print
  1083. print "To submit, use \"p4 submit\" to write a new description,"
  1084. print "or \"p4 submit -i %s\" to use the one prepared by" \
  1085. " \"git p4\"." % fileName
  1086. print "You can delete the file \"%s\" when finished." % fileName
  1087. if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
  1088. print "To preserve change ownership by user %s, you must\n" \
  1089. "do \"p4 change -f <change>\" after submitting and\n" \
  1090. "edit the User field."
  1091. if pureRenameCopy:
  1092. print "After submitting, renamed files must be re-synced."
  1093. print "Invoke \"p4 sync -f\" on each of these files:"
  1094. for f in pureRenameCopy:
  1095. print " " + f
  1096. print
  1097. print "To revert the changes, use \"p4 revert ...\", and delete"
  1098. print "the submit template file \"%s\"" % fileName
  1099. if filesToAdd:
  1100. print "Since the commit adds new files, they must be deleted:"
  1101. for f in filesToAdd:
  1102. print " " + f
  1103. print
  1104. return True
  1105. #
  1106. # Let the user edit the change description, then submit it.
  1107. #
  1108. if self.edit_template(fileName):
  1109. # read the edited message and submit
  1110. ret = True
  1111. tmpFile = open(fileName, "rb")
  1112. message = tmpFile.read()
  1113. tmpFile.close()
  1114. submitTemplate = message[:message.index(separatorLine)]
  1115. if self.isWindows:
  1116. submitTemplate = submitTemplate.replace("\r\n", "\n")
  1117. p4_write_pipe(['submit', '-i'], submitTemplate)
  1118. if self.preserveUser:
  1119. if p4User:
  1120. # Get last changelist number. Cannot easily get it from
  1121. # the submit command output as the output is
  1122. # unmarshalled.
  1123. changelist = self.lastP4Changelist()
  1124. self.modifyChangelistUser(changelist, p4User)
  1125. # The rename/copy happened by applying a patch that created a
  1126. # new file. This leaves it writable, which confuses p4.
  1127. for f in pureRenameCopy:
  1128. p4_sync(f, "-f")
  1129. else:
  1130. # skip this patch
  1131. ret = False
  1132. print "Submission cancelled, undoing p4 changes."
  1133. for f in editedFiles:
  1134. p4_revert(f)
  1135. for f in filesToAdd:
  1136. p4_revert(f)
  1137. os.remove(f)
  1138. for f in filesToDelete:
  1139. p4_revert(f)
  1140. os.remove(fileName)
  1141. return ret
  1142. # Export git tags as p4 labels. Create a p4 label and then tag
  1143. # with that.
  1144. def exportGitTags(self, gitTags):
  1145. validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
  1146. if len(validLabelRegexp) == 0:
  1147. validLabelRegexp = defaultLabelRegexp
  1148. m = re.compile(validLabelRegexp)
  1149. for name in gitTags:
  1150. if not m.match(name):
  1151. if verbose:
  1152. print "tag %s does not match regexp %s" % (name, validLabelRegexp)
  1153. continue
  1154. # Get the p4 commit this corresponds to
  1155. logMessage = extractLogMessageFromGitCommit(name)
  1156. values = extractSettingsGitLog(logMessage)
  1157. if not values.has_key('change'):
  1158. # a tag pointing to something not sent to p4; ignore
  1159. if verbose:
  1160. print "git tag %s does not give a p4 commit" % name
  1161. continue
  1162. else:
  1163. changelist = values['change']
  1164. # Get the tag details.
  1165. inHeader = True
  1166. isAnnotated = False
  1167. body = []
  1168. for l in read_pipe_lines(["git", "cat-file", "-p", name]):
  1169. l = l.strip()
  1170. if inHeader:
  1171. if re.match(r'tag\s+', l):
  1172. isAnnotated = True
  1173. elif re.match(r'\s*$', l):
  1174. inHeader = False
  1175. continue
  1176. else:
  1177. body.append(l)
  1178. if not isAnnotated:
  1179. body = ["lightweight tag imported by git p4\n"]
  1180. # Create the label - use the same view as the client spec we are using
  1181. clientSpec = getClientSpec()
  1182. labelTemplate = "Label: %s\n" % name
  1183. labelTemplate += "Description:\n"
  1184. for b in body:
  1185. labelTemplate += "\t" + b + "\n"
  1186. labelTemplate += "View:\n"
  1187. for mapping in clientSpec.mappings:
  1188. labelTemplate += "\t%s\n" % mapping.depot_side.path
  1189. if self.dry_run:
  1190. print "Would create p4 label %s for tag" % name
  1191. elif self.prepare_p4_only:
  1192. print "Not creating p4 label %s for tag due to option" \
  1193. " --prepare-p4-only" % name
  1194. else:
  1195. p4_write_pipe(["label", "-i"], labelTemplate)
  1196. # Use the label
  1197. p4_system(["tag", "-l", name] +
  1198. ["%s@%s" % (mapping.depot_side.path, changelist) for mapping in clientSpec.mappings])
  1199. if verbose:
  1200. print "created p4 label for tag %s" % name
  1201. def run(self, args):
  1202. if len(args) == 0:
  1203. self.master = currentGitBranch()
  1204. if len(self.master) =

Large files files are truncated, but you can click here to view the full file