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# 10import sys 11if 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) 15import os 16import optparse 17import marshal 18import subprocess 19import tempfile 20import time 21import platform 22import re 23import shutil 24import stat 25import zipfile 26import zlib 27import ctypes 28import errno 29 30try: 31from subprocess import CalledProcessError 32exceptImportError: 33# from python2.7:subprocess.py 34# Exception classes used by this module. 35classCalledProcessError(Exception): 36"""This exception is raised when a process run by check_call() returns 37 a non-zero exit status. The exit status will be stored in the 38 returncode attribute.""" 39def__init__(self, returncode, cmd): 40 self.returncode = returncode 41 self.cmd = cmd 42def__str__(self): 43return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 44 45verbose =False 46 47# Only labels/tags matching this will be imported/exported 48defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 49 50# Grab changes in blocks of this many revisions, unless otherwise requested 51defaultBlockSize =512 52 53defp4_build_cmd(cmd): 54"""Build a suitable p4 command line. 55 56 This consolidates building and returning a p4 command line into one 57 location. It means that hooking into the environment, or other configuration 58 can be done more easily. 59 """ 60 real_cmd = ["p4"] 61 62 user =gitConfig("git-p4.user") 63iflen(user) >0: 64 real_cmd += ["-u",user] 65 66 password =gitConfig("git-p4.password") 67iflen(password) >0: 68 real_cmd += ["-P", password] 69 70 port =gitConfig("git-p4.port") 71iflen(port) >0: 72 real_cmd += ["-p", port] 73 74 host =gitConfig("git-p4.host") 75iflen(host) >0: 76 real_cmd += ["-H", host] 77 78 client =gitConfig("git-p4.client") 79iflen(client) >0: 80 real_cmd += ["-c", client] 81 82 retries =gitConfigInt("git-p4.retries") 83if retries is None: 84# Perform 3 retries by default 85 retries =3 86if retries >0: 87# Provide a way to not pass this option by setting git-p4.retries to 0 88 real_cmd += ["-r",str(retries)] 89 90ifisinstance(cmd,basestring): 91 real_cmd =' '.join(real_cmd) +' '+ cmd 92else: 93 real_cmd += cmd 94return real_cmd 95 96defgit_dir(path): 97""" Return TRUE if the given path is a git directory (/path/to/dir/.git). 98 This won't automatically add ".git" to a directory. 99 """ 100 d =read_pipe(["git","--git-dir", path,"rev-parse","--git-dir"],True).strip() 101if not d orlen(d) ==0: 102return None 103else: 104return d 105 106defchdir(path, is_client_path=False): 107"""Do chdir to the given path, and set the PWD environment 108 variable for use by P4. It does not look at getcwd() output. 109 Since we're not using the shell, it is necessary to set the 110 PWD environment variable explicitly. 111 112 Normally, expand the path to force it to be absolute. This 113 addresses the use of relative path names inside P4 settings, 114 e.g. P4CONFIG=.p4config. P4 does not simply open the filename 115 as given; it looks for .p4config using PWD. 116 117 If is_client_path, the path was handed to us directly by p4, 118 and may be a symbolic link. Do not call os.getcwd() in this 119 case, because it will cause p4 to think that PWD is not inside 120 the client path. 121 """ 122 123 os.chdir(path) 124if not is_client_path: 125 path = os.getcwd() 126 os.environ['PWD'] = path 127 128defcalcDiskFree(): 129"""Return free space in bytes on the disk of the given dirname.""" 130if platform.system() =='Windows': 131 free_bytes = ctypes.c_ulonglong(0) 132 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()),None,None, ctypes.pointer(free_bytes)) 133return free_bytes.value 134else: 135 st = os.statvfs(os.getcwd()) 136return st.f_bavail * st.f_frsize 137 138defdie(msg): 139if verbose: 140raiseException(msg) 141else: 142 sys.stderr.write(msg +"\n") 143 sys.exit(1) 144 145defwrite_pipe(c, stdin): 146if verbose: 147 sys.stderr.write('Writing pipe:%s\n'%str(c)) 148 149 expand =isinstance(c,basestring) 150 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 151 pipe = p.stdin 152 val = pipe.write(stdin) 153 pipe.close() 154if p.wait(): 155die('Command failed:%s'%str(c)) 156 157return val 158 159defp4_write_pipe(c, stdin): 160 real_cmd =p4_build_cmd(c) 161returnwrite_pipe(real_cmd, stdin) 162 163defread_pipe_full(c): 164""" Read output from command. Returns a tuple 165 of the return status, stdout text and stderr 166 text. 167 """ 168if verbose: 169 sys.stderr.write('Reading pipe:%s\n'%str(c)) 170 171 expand =isinstance(c,basestring) 172 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand) 173(out, err) = p.communicate() 174return(p.returncode, out, err) 175 176defread_pipe(c, ignore_error=False): 177""" Read output from command. Returns the output text on 178 success. On failure, terminates execution, unless 179 ignore_error is True, when it returns an empty string. 180 """ 181(retcode, out, err) =read_pipe_full(c) 182if retcode !=0: 183if ignore_error: 184 out ="" 185else: 186die('Command failed:%s\nError:%s'% (str(c), err)) 187return out 188 189defread_pipe_text(c): 190""" Read output from a command with trailing whitespace stripped. 191 On error, returns None. 192 """ 193(retcode, out, err) =read_pipe_full(c) 194if retcode !=0: 195return None 196else: 197return out.rstrip() 198 199defp4_read_pipe(c, ignore_error=False): 200 real_cmd =p4_build_cmd(c) 201returnread_pipe(real_cmd, ignore_error) 202 203defread_pipe_lines(c): 204if verbose: 205 sys.stderr.write('Reading pipe:%s\n'%str(c)) 206 207 expand =isinstance(c, basestring) 208 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 209 pipe = p.stdout 210 val = pipe.readlines() 211if pipe.close()or p.wait(): 212die('Command failed:%s'%str(c)) 213 214return val 215 216defp4_read_pipe_lines(c): 217"""Specifically invoke p4 on the command supplied. """ 218 real_cmd =p4_build_cmd(c) 219returnread_pipe_lines(real_cmd) 220 221defp4_has_command(cmd): 222"""Ask p4 for help on this command. If it returns an error, the 223 command does not exist in this version of p4.""" 224 real_cmd =p4_build_cmd(["help", cmd]) 225 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 226 stderr=subprocess.PIPE) 227 p.communicate() 228return p.returncode ==0 229 230defp4_has_move_command(): 231"""See if the move command exists, that it supports -k, and that 232 it has not been administratively disabled. The arguments 233 must be correct, but the filenames do not have to exist. Use 234 ones with wildcards so even if they exist, it will fail.""" 235 236if notp4_has_command("move"): 237return False 238 cmd =p4_build_cmd(["move","-k","@from","@to"]) 239 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 240(out, err) = p.communicate() 241# return code will be 1 in either case 242if err.find("Invalid option") >=0: 243return False 244if err.find("disabled") >=0: 245return False 246# assume it failed because @... was invalid changelist 247return True 248 249defsystem(cmd, ignore_error=False): 250 expand =isinstance(cmd,basestring) 251if verbose: 252 sys.stderr.write("executing%s\n"%str(cmd)) 253 retcode = subprocess.call(cmd, shell=expand) 254if retcode and not ignore_error: 255raiseCalledProcessError(retcode, cmd) 256 257return retcode 258 259defp4_system(cmd): 260"""Specifically invoke p4 as the system command. """ 261 real_cmd =p4_build_cmd(cmd) 262 expand =isinstance(real_cmd, basestring) 263 retcode = subprocess.call(real_cmd, shell=expand) 264if retcode: 265raiseCalledProcessError(retcode, real_cmd) 266 267_p4_version_string =None 268defp4_version_string(): 269"""Read the version string, showing just the last line, which 270 hopefully is the interesting version bit. 271 272 $ p4 -V 273 Perforce - The Fast Software Configuration Management System. 274 Copyright 1995-2011 Perforce Software. All rights reserved. 275 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 276 """ 277global _p4_version_string 278if not _p4_version_string: 279 a =p4_read_pipe_lines(["-V"]) 280 _p4_version_string = a[-1].rstrip() 281return _p4_version_string 282 283defp4_integrate(src, dest): 284p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 285 286defp4_sync(f, *options): 287p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 288 289defp4_add(f): 290# forcibly add file names with wildcards 291ifwildcard_present(f): 292p4_system(["add","-f", f]) 293else: 294p4_system(["add", f]) 295 296defp4_delete(f): 297p4_system(["delete",wildcard_encode(f)]) 298 299defp4_edit(f, *options): 300p4_system(["edit"] +list(options) + [wildcard_encode(f)]) 301 302defp4_revert(f): 303p4_system(["revert",wildcard_encode(f)]) 304 305defp4_reopen(type, f): 306p4_system(["reopen","-t",type,wildcard_encode(f)]) 307 308defp4_reopen_in_change(changelist, files): 309 cmd = ["reopen","-c",str(changelist)] + files 310p4_system(cmd) 311 312defp4_move(src, dest): 313p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 314 315defp4_last_change(): 316 results =p4CmdList(["changes","-m","1"], skip_info=True) 317returnint(results[0]['change']) 318 319defp4_describe(change): 320"""Make sure it returns a valid result by checking for 321 the presence of field "time". Return a dict of the 322 results.""" 323 324 ds =p4CmdList(["describe","-s",str(change)], skip_info=True) 325iflen(ds) !=1: 326die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 327 328 d = ds[0] 329 330if"p4ExitCode"in d: 331die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 332str(d))) 333if"code"in d: 334if d["code"] =="error": 335die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 336 337if"time"not in d: 338die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 339 340return d 341 342# 343# Canonicalize the p4 type and return a tuple of the 344# base type, plus any modifiers. See "p4 help filetypes" 345# for a list and explanation. 346# 347defsplit_p4_type(p4type): 348 349 p4_filetypes_historical = { 350"ctempobj":"binary+Sw", 351"ctext":"text+C", 352"cxtext":"text+Cx", 353"ktext":"text+k", 354"kxtext":"text+kx", 355"ltext":"text+F", 356"tempobj":"binary+FSw", 357"ubinary":"binary+F", 358"uresource":"resource+F", 359"uxbinary":"binary+Fx", 360"xbinary":"binary+x", 361"xltext":"text+Fx", 362"xtempobj":"binary+Swx", 363"xtext":"text+x", 364"xunicode":"unicode+x", 365"xutf16":"utf16+x", 366} 367if p4type in p4_filetypes_historical: 368 p4type = p4_filetypes_historical[p4type] 369 mods ="" 370 s = p4type.split("+") 371 base = s[0] 372 mods ="" 373iflen(s) >1: 374 mods = s[1] 375return(base, mods) 376 377# 378# return the raw p4 type of a file (text, text+ko, etc) 379# 380defp4_type(f): 381 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 382return results[0]['headType'] 383 384# 385# Given a type base and modifier, return a regexp matching 386# the keywords that can be expanded in the file 387# 388defp4_keywords_regexp_for_type(base, type_mods): 389if base in("text","unicode","binary"): 390 kwords =None 391if"ko"in type_mods: 392 kwords ='Id|Header' 393elif"k"in type_mods: 394 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 395else: 396return None 397 pattern = r""" 398 \$ # Starts with a dollar, followed by... 399 (%s) # one of the keywords, followed by... 400 (:[^$\n]+)? # possibly an old expansion, followed by... 401 \$ # another dollar 402 """% kwords 403return pattern 404else: 405return None 406 407# 408# Given a file, return a regexp matching the possible 409# RCS keywords that will be expanded, or None for files 410# with kw expansion turned off. 411# 412defp4_keywords_regexp_for_file(file): 413if not os.path.exists(file): 414return None 415else: 416(type_base, type_mods) =split_p4_type(p4_type(file)) 417returnp4_keywords_regexp_for_type(type_base, type_mods) 418 419defsetP4ExecBit(file, mode): 420# Reopens an already open file and changes the execute bit to match 421# the execute bit setting in the passed in mode. 422 423 p4Type ="+x" 424 425if notisModeExec(mode): 426 p4Type =getP4OpenedType(file) 427 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 428 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 429if p4Type[-1] =="+": 430 p4Type = p4Type[0:-1] 431 432p4_reopen(p4Type,file) 433 434defgetP4OpenedType(file): 435# Returns the perforce file type for the given file. 436 437 result =p4_read_pipe(["opened",wildcard_encode(file)]) 438 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 439if match: 440return match.group(1) 441else: 442die("Could not determine file type for%s(result: '%s')"% (file, result)) 443 444# Return the set of all p4 labels 445defgetP4Labels(depotPaths): 446 labels =set() 447ifisinstance(depotPaths,basestring): 448 depotPaths = [depotPaths] 449 450for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 451 label = l['label'] 452 labels.add(label) 453 454return labels 455 456# Return the set of all git tags 457defgetGitTags(): 458 gitTags =set() 459for line inread_pipe_lines(["git","tag"]): 460 tag = line.strip() 461 gitTags.add(tag) 462return gitTags 463 464defdiffTreePattern(): 465# This is a simple generator for the diff tree regex pattern. This could be 466# a class variable if this and parseDiffTreeEntry were a part of a class. 467 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 468while True: 469yield pattern 470 471defparseDiffTreeEntry(entry): 472"""Parses a single diff tree entry into its component elements. 473 474 See git-diff-tree(1) manpage for details about the format of the diff 475 output. This method returns a dictionary with the following elements: 476 477 src_mode - The mode of the source file 478 dst_mode - The mode of the destination file 479 src_sha1 - The sha1 for the source file 480 dst_sha1 - The sha1 fr the destination file 481 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 482 status_score - The score for the status (applicable for 'C' and 'R' 483 statuses). This is None if there is no score. 484 src - The path for the source file. 485 dst - The path for the destination file. This is only present for 486 copy or renames. If it is not present, this is None. 487 488 If the pattern is not matched, None is returned.""" 489 490 match =diffTreePattern().next().match(entry) 491if match: 492return{ 493'src_mode': match.group(1), 494'dst_mode': match.group(2), 495'src_sha1': match.group(3), 496'dst_sha1': match.group(4), 497'status': match.group(5), 498'status_score': match.group(6), 499'src': match.group(7), 500'dst': match.group(10) 501} 502return None 503 504defisModeExec(mode): 505# Returns True if the given git mode represents an executable file, 506# otherwise False. 507return mode[-3:] =="755" 508 509defisModeExecChanged(src_mode, dst_mode): 510returnisModeExec(src_mode) !=isModeExec(dst_mode) 511 512defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False): 513 514ifisinstance(cmd,basestring): 515 cmd ="-G "+ cmd 516 expand =True 517else: 518 cmd = ["-G"] + cmd 519 expand =False 520 521 cmd =p4_build_cmd(cmd) 522if verbose: 523 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 524 525# Use a temporary file to avoid deadlocks without 526# subprocess.communicate(), which would put another copy 527# of stdout into memory. 528 stdin_file =None 529if stdin is not None: 530 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 531ifisinstance(stdin,basestring): 532 stdin_file.write(stdin) 533else: 534for i in stdin: 535 stdin_file.write(i +'\n') 536 stdin_file.flush() 537 stdin_file.seek(0) 538 539 p4 = subprocess.Popen(cmd, 540 shell=expand, 541 stdin=stdin_file, 542 stdout=subprocess.PIPE) 543 544 result = [] 545try: 546while True: 547 entry = marshal.load(p4.stdout) 548if skip_info: 549if'code'in entry and entry['code'] =='info': 550continue 551if cb is not None: 552cb(entry) 553else: 554 result.append(entry) 555exceptEOFError: 556pass 557 exitCode = p4.wait() 558if exitCode !=0: 559 entry = {} 560 entry["p4ExitCode"] = exitCode 561 result.append(entry) 562 563return result 564 565defp4Cmd(cmd): 566list=p4CmdList(cmd) 567 result = {} 568for entry inlist: 569 result.update(entry) 570return result; 571 572defp4Where(depotPath): 573if not depotPath.endswith("/"): 574 depotPath +="/" 575 depotPathLong = depotPath +"..." 576 outputList =p4CmdList(["where", depotPathLong]) 577 output =None 578for entry in outputList: 579if"depotFile"in entry: 580# Search for the base client side depot path, as long as it starts with the branch's P4 path. 581# The base path always ends with "/...". 582if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 583 output = entry 584break 585elif"data"in entry: 586 data = entry.get("data") 587 space = data.find(" ") 588if data[:space] == depotPath: 589 output = entry 590break 591if output ==None: 592return"" 593if output["code"] =="error": 594return"" 595 clientPath ="" 596if"path"in output: 597 clientPath = output.get("path") 598elif"data"in output: 599 data = output.get("data") 600 lastSpace = data.rfind(" ") 601 clientPath = data[lastSpace +1:] 602 603if clientPath.endswith("..."): 604 clientPath = clientPath[:-3] 605return clientPath 606 607defcurrentGitBranch(): 608returnread_pipe_text(["git","symbolic-ref","--short","-q","HEAD"]) 609 610defisValidGitDir(path): 611returngit_dir(path) !=None 612 613defparseRevision(ref): 614returnread_pipe("git rev-parse%s"% ref).strip() 615 616defbranchExists(ref): 617 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 618 ignore_error=True) 619returnlen(rev) >0 620 621defextractLogMessageFromGitCommit(commit): 622 logMessage ="" 623 624## fixme: title is first line of commit, not 1st paragraph. 625 foundTitle =False 626for log inread_pipe_lines("git cat-file commit%s"% commit): 627if not foundTitle: 628iflen(log) ==1: 629 foundTitle =True 630continue 631 632 logMessage += log 633return logMessage 634 635defextractSettingsGitLog(log): 636 values = {} 637for line in log.split("\n"): 638 line = line.strip() 639 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 640if not m: 641continue 642 643 assignments = m.group(1).split(':') 644for a in assignments: 645 vals = a.split('=') 646 key = vals[0].strip() 647 val = ('='.join(vals[1:])).strip() 648if val.endswith('\"')and val.startswith('"'): 649 val = val[1:-1] 650 651 values[key] = val 652 653 paths = values.get("depot-paths") 654if not paths: 655 paths = values.get("depot-path") 656if paths: 657 values['depot-paths'] = paths.split(',') 658return values 659 660defgitBranchExists(branch): 661 proc = subprocess.Popen(["git","rev-parse", branch], 662 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 663return proc.wait() ==0; 664 665_gitConfig = {} 666 667defgitConfig(key, typeSpecifier=None): 668if not _gitConfig.has_key(key): 669 cmd = ["git","config"] 670if typeSpecifier: 671 cmd += [ typeSpecifier ] 672 cmd += [ key ] 673 s =read_pipe(cmd, ignore_error=True) 674 _gitConfig[key] = s.strip() 675return _gitConfig[key] 676 677defgitConfigBool(key): 678"""Return a bool, using git config --bool. It is True only if the 679 variable is set to true, and False if set to false or not present 680 in the config.""" 681 682if not _gitConfig.has_key(key): 683 _gitConfig[key] =gitConfig(key,'--bool') =="true" 684return _gitConfig[key] 685 686defgitConfigInt(key): 687if not _gitConfig.has_key(key): 688 cmd = ["git","config","--int", key ] 689 s =read_pipe(cmd, ignore_error=True) 690 v = s.strip() 691try: 692 _gitConfig[key] =int(gitConfig(key,'--int')) 693exceptValueError: 694 _gitConfig[key] =None 695return _gitConfig[key] 696 697defgitConfigList(key): 698if not _gitConfig.has_key(key): 699 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 700 _gitConfig[key] = s.strip().splitlines() 701if _gitConfig[key] == ['']: 702 _gitConfig[key] = [] 703return _gitConfig[key] 704 705defp4BranchesInGit(branchesAreInRemotes=True): 706"""Find all the branches whose names start with "p4/", looking 707 in remotes or heads as specified by the argument. Return 708 a dictionary of{ branch: revision }for each one found. 709 The branch names are the short names, without any 710 "p4/" prefix.""" 711 712 branches = {} 713 714 cmdline ="git rev-parse --symbolic " 715if branchesAreInRemotes: 716 cmdline +="--remotes" 717else: 718 cmdline +="--branches" 719 720for line inread_pipe_lines(cmdline): 721 line = line.strip() 722 723# only import to p4/ 724if not line.startswith('p4/'): 725continue 726# special symbolic ref to p4/master 727if line =="p4/HEAD": 728continue 729 730# strip off p4/ prefix 731 branch = line[len("p4/"):] 732 733 branches[branch] =parseRevision(line) 734 735return branches 736 737defbranch_exists(branch): 738"""Make sure that the given ref name really exists.""" 739 740 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 741 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 742 out, _ = p.communicate() 743if p.returncode: 744return False 745# expect exactly one line of output: the branch name 746return out.rstrip() == branch 747 748deffindUpstreamBranchPoint(head ="HEAD"): 749 branches =p4BranchesInGit() 750# map from depot-path to branch name 751 branchByDepotPath = {} 752for branch in branches.keys(): 753 tip = branches[branch] 754 log =extractLogMessageFromGitCommit(tip) 755 settings =extractSettingsGitLog(log) 756if settings.has_key("depot-paths"): 757 paths =",".join(settings["depot-paths"]) 758 branchByDepotPath[paths] ="remotes/p4/"+ branch 759 760 settings =None 761 parent =0 762while parent <65535: 763 commit = head +"~%s"% parent 764 log =extractLogMessageFromGitCommit(commit) 765 settings =extractSettingsGitLog(log) 766if settings.has_key("depot-paths"): 767 paths =",".join(settings["depot-paths"]) 768if branchByDepotPath.has_key(paths): 769return[branchByDepotPath[paths], settings] 770 771 parent = parent +1 772 773return["", settings] 774 775defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 776if not silent: 777print("Creating/updating branch(es) in%sbased on origin branch(es)" 778% localRefPrefix) 779 780 originPrefix ="origin/p4/" 781 782for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 783 line = line.strip() 784if(not line.startswith(originPrefix))or line.endswith("HEAD"): 785continue 786 787 headName = line[len(originPrefix):] 788 remoteHead = localRefPrefix + headName 789 originHead = line 790 791 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 792if(not original.has_key('depot-paths') 793or not original.has_key('change')): 794continue 795 796 update =False 797if notgitBranchExists(remoteHead): 798if verbose: 799print"creating%s"% remoteHead 800 update =True 801else: 802 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 803if settings.has_key('change') >0: 804if settings['depot-paths'] == original['depot-paths']: 805 originP4Change =int(original['change']) 806 p4Change =int(settings['change']) 807if originP4Change > p4Change: 808print("%s(%s) is newer than%s(%s). " 809"Updating p4 branch from origin." 810% (originHead, originP4Change, 811 remoteHead, p4Change)) 812 update =True 813else: 814print("Ignoring:%swas imported from%swhile " 815"%swas imported from%s" 816% (originHead,','.join(original['depot-paths']), 817 remoteHead,','.join(settings['depot-paths']))) 818 819if update: 820system("git update-ref%s %s"% (remoteHead, originHead)) 821 822deforiginP4BranchesExist(): 823returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 824 825 826defp4ParseNumericChangeRange(parts): 827 changeStart =int(parts[0][1:]) 828if parts[1] =='#head': 829 changeEnd =p4_last_change() 830else: 831 changeEnd =int(parts[1]) 832 833return(changeStart, changeEnd) 834 835defchooseBlockSize(blockSize): 836if blockSize: 837return blockSize 838else: 839return defaultBlockSize 840 841defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 842assert depotPaths 843 844# Parse the change range into start and end. Try to find integer 845# revision ranges as these can be broken up into blocks to avoid 846# hitting server-side limits (maxrows, maxscanresults). But if 847# that doesn't work, fall back to using the raw revision specifier 848# strings, without using block mode. 849 850if changeRange is None or changeRange =='': 851 changeStart =1 852 changeEnd =p4_last_change() 853 block_size =chooseBlockSize(requestedBlockSize) 854else: 855 parts = changeRange.split(',') 856assertlen(parts) ==2 857try: 858(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 859 block_size =chooseBlockSize(requestedBlockSize) 860except: 861 changeStart = parts[0][1:] 862 changeEnd = parts[1] 863if requestedBlockSize: 864die("cannot use --changes-block-size with non-numeric revisions") 865 block_size =None 866 867 changes =set() 868 869# Retrieve changes a block at a time, to prevent running 870# into a MaxResults/MaxScanRows error from the server. 871 872while True: 873 cmd = ['changes'] 874 875if block_size: 876 end =min(changeEnd, changeStart + block_size) 877 revisionRange ="%d,%d"% (changeStart, end) 878else: 879 revisionRange ="%s,%s"% (changeStart, changeEnd) 880 881for p in depotPaths: 882 cmd += ["%s...@%s"% (p, revisionRange)] 883 884# Insert changes in chronological order 885for entry inreversed(p4CmdList(cmd)): 886if entry.has_key('p4ExitCode'): 887die('Error retrieving changes descriptions ({})'.format(entry['p4ExitCode'])) 888if not entry.has_key('change'): 889continue 890 changes.add(int(entry['change'])) 891 892if not block_size: 893break 894 895if end >= changeEnd: 896break 897 898 changeStart = end +1 899 900 changes =sorted(changes) 901return changes 902 903defp4PathStartsWith(path, prefix): 904# This method tries to remedy a potential mixed-case issue: 905# 906# If UserA adds //depot/DirA/file1 907# and UserB adds //depot/dira/file2 908# 909# we may or may not have a problem. If you have core.ignorecase=true, 910# we treat DirA and dira as the same directory 911ifgitConfigBool("core.ignorecase"): 912return path.lower().startswith(prefix.lower()) 913return path.startswith(prefix) 914 915defgetClientSpec(): 916"""Look at the p4 client spec, create a View() object that contains 917 all the mappings, and return it.""" 918 919 specList =p4CmdList("client -o") 920iflen(specList) !=1: 921die('Output from "client -o" is%dlines, expecting 1'% 922len(specList)) 923 924# dictionary of all client parameters 925 entry = specList[0] 926 927# the //client/ name 928 client_name = entry["Client"] 929 930# just the keys that start with "View" 931 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 932 933# hold this new View 934 view =View(client_name) 935 936# append the lines, in order, to the view 937for view_num inrange(len(view_keys)): 938 k ="View%d"% view_num 939if k not in view_keys: 940die("Expected view key%smissing"% k) 941 view.append(entry[k]) 942 943return view 944 945defgetClientRoot(): 946"""Grab the client directory.""" 947 948 output =p4CmdList("client -o") 949iflen(output) !=1: 950die('Output from "client -o" is%dlines, expecting 1'%len(output)) 951 952 entry = output[0] 953if"Root"not in entry: 954die('Client has no "Root"') 955 956return entry["Root"] 957 958# 959# P4 wildcards are not allowed in filenames. P4 complains 960# if you simply add them, but you can force it with "-f", in 961# which case it translates them into %xx encoding internally. 962# 963defwildcard_decode(path): 964# Search for and fix just these four characters. Do % last so 965# that fixing it does not inadvertently create new %-escapes. 966# Cannot have * in a filename in windows; untested as to 967# what p4 would do in such a case. 968if not platform.system() =="Windows": 969 path = path.replace("%2A","*") 970 path = path.replace("%23","#") \ 971.replace("%40","@") \ 972.replace("%25","%") 973return path 974 975defwildcard_encode(path): 976# do % first to avoid double-encoding the %s introduced here 977 path = path.replace("%","%25") \ 978.replace("*","%2A") \ 979.replace("#","%23") \ 980.replace("@","%40") 981return path 982 983defwildcard_present(path): 984 m = re.search("[*#@%]", path) 985return m is not None 986 987classLargeFileSystem(object): 988"""Base class for large file system support.""" 989 990def__init__(self, writeToGitStream): 991 self.largeFiles =set() 992 self.writeToGitStream = writeToGitStream 993 994defgeneratePointer(self, cloneDestination, contentFile): 995"""Return the content of a pointer file that is stored in Git instead of 996 the actual content.""" 997assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 998 999defpushFile(self, localLargeFile):1000"""Push the actual content which is not stored in the Git repository to1001 a server."""1002assert False,"Method 'pushFile' required in "+ self.__class__.__name__10031004defhasLargeFileExtension(self, relPath):1005returnreduce(1006lambda a, b: a or b,1007[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')],1008False1009)10101011defgenerateTempFile(self, contents):1012 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)1013for d in contents:1014 contentFile.write(d)1015 contentFile.close()1016return contentFile.name10171018defexceedsLargeFileThreshold(self, relPath, contents):1019ifgitConfigInt('git-p4.largeFileThreshold'):1020 contentsSize =sum(len(d)for d in contents)1021if contentsSize >gitConfigInt('git-p4.largeFileThreshold'):1022return True1023ifgitConfigInt('git-p4.largeFileCompressedThreshold'):1024 contentsSize =sum(len(d)for d in contents)1025if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'):1026return False1027 contentTempFile = self.generateTempFile(contents)1028 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)1029 zf = zipfile.ZipFile(compressedContentFile.name, mode='w')1030 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)1031 zf.close()1032 compressedContentsSize = zf.infolist()[0].compress_size1033 os.remove(contentTempFile)1034 os.remove(compressedContentFile.name)1035if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'):1036return True1037return False10381039defaddLargeFile(self, relPath):1040 self.largeFiles.add(relPath)10411042defremoveLargeFile(self, relPath):1043 self.largeFiles.remove(relPath)10441045defisLargeFile(self, relPath):1046return relPath in self.largeFiles10471048defprocessContent(self, git_mode, relPath, contents):1049"""Processes the content of git fast import. This method decides if a1050 file is stored in the large file system and handles all necessary1051 steps."""1052if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1053 contentTempFile = self.generateTempFile(contents)1054(pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)1055if pointer_git_mode:1056 git_mode = pointer_git_mode1057if localLargeFile:1058# Move temp file to final location in large file system1059 largeFileDir = os.path.dirname(localLargeFile)1060if not os.path.isdir(largeFileDir):1061 os.makedirs(largeFileDir)1062 shutil.move(contentTempFile, localLargeFile)1063 self.addLargeFile(relPath)1064ifgitConfigBool('git-p4.largeFilePush'):1065 self.pushFile(localLargeFile)1066if verbose:1067 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1068return(git_mode, contents)10691070classMockLFS(LargeFileSystem):1071"""Mock large file system for testing."""10721073defgeneratePointer(self, contentFile):1074"""The pointer content is the original content prefixed with "pointer-".1075 The local filename of the large file storage is derived from the file content.1076 """1077withopen(contentFile,'r')as f:1078 content =next(f)1079 gitMode ='100644'1080 pointerContents ='pointer-'+ content1081 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1082return(gitMode, pointerContents, localLargeFile)10831084defpushFile(self, localLargeFile):1085"""The remote filename of the large file storage is the same as the local1086 one but in a different directory.1087 """1088 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1089if not os.path.exists(remotePath):1090 os.makedirs(remotePath)1091 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10921093classGitLFS(LargeFileSystem):1094"""Git LFS as backend for the git-p4 large file system.1095 See https://git-lfs.github.com/ for details."""10961097def__init__(self, *args):1098 LargeFileSystem.__init__(self, *args)1099 self.baseGitAttributes = []11001101defgeneratePointer(self, contentFile):1102"""Generate a Git LFS pointer for the content. Return LFS Pointer file1103 mode and content which is stored in the Git repository instead of1104 the actual content. Return also the new location of the actual1105 content.1106 """1107if os.path.getsize(contentFile) ==0:1108return(None,'',None)11091110 pointerProcess = subprocess.Popen(1111['git','lfs','pointer','--file='+ contentFile],1112 stdout=subprocess.PIPE1113)1114 pointerFile = pointerProcess.stdout.read()1115if pointerProcess.wait():1116 os.remove(contentFile)1117die('git-lfs pointer command failed. Did you install the extension?')11181119# Git LFS removed the preamble in the output of the 'pointer' command1120# starting from version 1.2.0. Check for the preamble here to support1121# earlier versions.1122# c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b431123if pointerFile.startswith('Git LFS pointer for'):1124 pointerFile = re.sub(r'Git LFS pointer for.*\n\n','', pointerFile)11251126 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)1127 localLargeFile = os.path.join(1128 os.getcwd(),1129'.git','lfs','objects', oid[:2], oid[2:4],1130 oid,1131)1132# LFS Spec states that pointer files should not have the executable bit set.1133 gitMode ='100644'1134return(gitMode, pointerFile, localLargeFile)11351136defpushFile(self, localLargeFile):1137 uploadProcess = subprocess.Popen(1138['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1139)1140if uploadProcess.wait():1141die('git-lfs push command failed. Did you define a remote?')11421143defgenerateGitAttributes(self):1144return(1145 self.baseGitAttributes +1146[1147'\n',1148'#\n',1149'# Git LFS (see https://git-lfs.github.com/)\n',1150'#\n',1151] +1152['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs diff=lfs merge=lfs -text\n'1153for f insorted(gitConfigList('git-p4.largeFileExtensions'))1154] +1155['/'+ f.replace(' ','[[:space:]]') +' filter=lfs diff=lfs merge=lfs -text\n'1156for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1157]1158)11591160defaddLargeFile(self, relPath):1161 LargeFileSystem.addLargeFile(self, relPath)1162 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11631164defremoveLargeFile(self, relPath):1165 LargeFileSystem.removeLargeFile(self, relPath)1166 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11671168defprocessContent(self, git_mode, relPath, contents):1169if relPath =='.gitattributes':1170 self.baseGitAttributes = contents1171return(git_mode, self.generateGitAttributes())1172else:1173return LargeFileSystem.processContent(self, git_mode, relPath, contents)11741175class Command:1176def__init__(self):1177 self.usage ="usage: %prog [options]"1178 self.needsGit =True1179 self.verbose =False11801181class P4UserMap:1182def__init__(self):1183 self.userMapFromPerforceServer =False1184 self.myP4UserId =None11851186defp4UserId(self):1187if self.myP4UserId:1188return self.myP4UserId11891190 results =p4CmdList("user -o")1191for r in results:1192if r.has_key('User'):1193 self.myP4UserId = r['User']1194return r['User']1195die("Could not find your p4 user id")11961197defp4UserIsMe(self, p4User):1198# return True if the given p4 user is actually me1199 me = self.p4UserId()1200if not p4User or p4User != me:1201return False1202else:1203return True12041205defgetUserCacheFilename(self):1206 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1207return home +"/.gitp4-usercache.txt"12081209defgetUserMapFromPerforceServer(self):1210if self.userMapFromPerforceServer:1211return1212 self.users = {}1213 self.emails = {}12141215for output inp4CmdList("users"):1216if not output.has_key("User"):1217continue1218 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1219 self.emails[output["Email"]] = output["User"]12201221 mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)1222for mapUserConfig ingitConfigList("git-p4.mapUser"):1223 mapUser = mapUserConfigRegex.findall(mapUserConfig)1224if mapUser andlen(mapUser[0]) ==3:1225 user = mapUser[0][0]1226 fullname = mapUser[0][1]1227 email = mapUser[0][2]1228 self.users[user] = fullname +" <"+ email +">"1229 self.emails[email] = user12301231 s =''1232for(key, val)in self.users.items():1233 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))12341235open(self.getUserCacheFilename(),"wb").write(s)1236 self.userMapFromPerforceServer =True12371238defloadUserMapFromCache(self):1239 self.users = {}1240 self.userMapFromPerforceServer =False1241try:1242 cache =open(self.getUserCacheFilename(),"rb")1243 lines = cache.readlines()1244 cache.close()1245for line in lines:1246 entry = line.strip().split("\t")1247 self.users[entry[0]] = entry[1]1248exceptIOError:1249 self.getUserMapFromPerforceServer()12501251classP4Debug(Command):1252def__init__(self):1253 Command.__init__(self)1254 self.options = []1255 self.description ="A tool to debug the output of p4 -G."1256 self.needsGit =False12571258defrun(self, args):1259 j =01260for output inp4CmdList(args):1261print'Element:%d'% j1262 j +=11263print output1264return True12651266classP4RollBack(Command):1267def__init__(self):1268 Command.__init__(self)1269 self.options = [1270 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1271]1272 self.description ="A tool to debug the multi-branch import. Don't use :)"1273 self.rollbackLocalBranches =False12741275defrun(self, args):1276iflen(args) !=1:1277return False1278 maxChange =int(args[0])12791280if"p4ExitCode"inp4Cmd("changes -m 1"):1281die("Problems executing p4");12821283if self.rollbackLocalBranches:1284 refPrefix ="refs/heads/"1285 lines =read_pipe_lines("git rev-parse --symbolic --branches")1286else:1287 refPrefix ="refs/remotes/"1288 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12891290for line in lines:1291if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1292 line = line.strip()1293 ref = refPrefix + line1294 log =extractLogMessageFromGitCommit(ref)1295 settings =extractSettingsGitLog(log)12961297 depotPaths = settings['depot-paths']1298 change = settings['change']12991300 changed =False13011302iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1303for p in depotPaths]))) ==0:1304print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1305system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1306continue13071308while change andint(change) > maxChange:1309 changed =True1310if self.verbose:1311print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1312system("git update-ref%s\"%s^\""% (ref, ref))1313 log =extractLogMessageFromGitCommit(ref)1314 settings =extractSettingsGitLog(log)131513161317 depotPaths = settings['depot-paths']1318 change = settings['change']13191320if changed:1321print"%srewound to%s"% (ref, change)13221323return True13241325classP4Submit(Command, P4UserMap):13261327 conflict_behavior_choices = ("ask","skip","quit")13281329def__init__(self):1330 Command.__init__(self)1331 P4UserMap.__init__(self)1332 self.options = [1333 optparse.make_option("--origin", dest="origin"),1334 optparse.make_option("-M", dest="detectRenames", action="store_true"),1335# preserve the user, requires relevant p4 permissions1336 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1337 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1338 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1339 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1340 optparse.make_option("--conflict", dest="conflict_behavior",1341 choices=self.conflict_behavior_choices),1342 optparse.make_option("--branch", dest="branch"),1343 optparse.make_option("--shelve", dest="shelve", action="store_true",1344help="Shelve instead of submit. Shelved files are reverted, "1345"restoring the workspace to the state before the shelve"),1346 optparse.make_option("--update-shelve", dest="update_shelve", action="store",type="int",1347 metavar="CHANGELIST",1348help="update an existing shelved changelist, implies --shelve")1349]1350 self.description ="Submit changes from git to the perforce depot."1351 self.usage +=" [name of git branch to submit into perforce depot]"1352 self.origin =""1353 self.detectRenames =False1354 self.preserveUser =gitConfigBool("git-p4.preserveUser")1355 self.dry_run =False1356 self.shelve =False1357 self.update_shelve =None1358 self.prepare_p4_only =False1359 self.conflict_behavior =None1360 self.isWindows = (platform.system() =="Windows")1361 self.exportLabels =False1362 self.p4HasMoveCommand =p4_has_move_command()1363 self.branch =None13641365ifgitConfig('git-p4.largeFileSystem'):1366die("Large file system not supported for git-p4 submit command. Please remove it from config.")13671368defcheck(self):1369iflen(p4CmdList("opened ...")) >0:1370die("You have files opened with perforce! Close them before starting the sync.")13711372defseparate_jobs_from_description(self, message):1373"""Extract and return a possible Jobs field in the commit1374 message. It goes into a separate section in the p4 change1375 specification.13761377 A jobs line starts with "Jobs:" and looks like a new field1378 in a form. Values are white-space separated on the same1379 line or on following lines that start with a tab.13801381 This does not parse and extract the full git commit message1382 like a p4 form. It just sees the Jobs: line as a marker1383 to pass everything from then on directly into the p4 form,1384 but outside the description section.13851386 Return a tuple (stripped log message, jobs string)."""13871388 m = re.search(r'^Jobs:', message, re.MULTILINE)1389if m is None:1390return(message,None)13911392 jobtext = message[m.start():]1393 stripped_message = message[:m.start()].rstrip()1394return(stripped_message, jobtext)13951396defprepareLogMessage(self, template, message, jobs):1397"""Edits the template returned from "p4 change -o" to insert1398 the message in the Description field, and the jobs text in1399 the Jobs field."""1400 result =""14011402 inDescriptionSection =False14031404for line in template.split("\n"):1405if line.startswith("#"):1406 result += line +"\n"1407continue14081409if inDescriptionSection:1410if line.startswith("Files:")or line.startswith("Jobs:"):1411 inDescriptionSection =False1412# insert Jobs section1413if jobs:1414 result += jobs +"\n"1415else:1416continue1417else:1418if line.startswith("Description:"):1419 inDescriptionSection =True1420 line +="\n"1421for messageLine in message.split("\n"):1422 line +="\t"+ messageLine +"\n"14231424 result += line +"\n"14251426return result14271428defpatchRCSKeywords(self,file, pattern):1429# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1430(handle, outFileName) = tempfile.mkstemp(dir='.')1431try:1432 outFile = os.fdopen(handle,"w+")1433 inFile =open(file,"r")1434 regexp = re.compile(pattern, re.VERBOSE)1435for line in inFile.readlines():1436 line = regexp.sub(r'$\1$', line)1437 outFile.write(line)1438 inFile.close()1439 outFile.close()1440# Forcibly overwrite the original file1441 os.unlink(file)1442 shutil.move(outFileName,file)1443except:1444# cleanup our temporary file1445 os.unlink(outFileName)1446print"Failed to strip RCS keywords in%s"%file1447raise14481449print"Patched up RCS keywords in%s"%file14501451defp4UserForCommit(self,id):1452# Return the tuple (perforce user,git email) for a given git commit id1453 self.getUserMapFromPerforceServer()1454 gitEmail =read_pipe(["git","log","--max-count=1",1455"--format=%ae",id])1456 gitEmail = gitEmail.strip()1457if not self.emails.has_key(gitEmail):1458return(None,gitEmail)1459else:1460return(self.emails[gitEmail],gitEmail)14611462defcheckValidP4Users(self,commits):1463# check if any git authors cannot be mapped to p4 users1464foridin commits:1465(user,email) = self.p4UserForCommit(id)1466if not user:1467 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1468ifgitConfigBool("git-p4.allowMissingP4Users"):1469print"%s"% msg1470else:1471die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)14721473deflastP4Changelist(self):1474# Get back the last changelist number submitted in this client spec. This1475# then gets used to patch up the username in the change. If the same1476# client spec is being used by multiple processes then this might go1477# wrong.1478 results =p4CmdList("client -o")# find the current client1479 client =None1480for r in results:1481if r.has_key('Client'):1482 client = r['Client']1483break1484if not client:1485die("could not get client spec")1486 results =p4CmdList(["changes","-c", client,"-m","1"])1487for r in results:1488if r.has_key('change'):1489return r['change']1490die("Could not get changelist number for last submit - cannot patch up user details")14911492defmodifyChangelistUser(self, changelist, newUser):1493# fixup the user field of a changelist after it has been submitted.1494 changes =p4CmdList("change -o%s"% changelist)1495iflen(changes) !=1:1496die("Bad output from p4 change modifying%sto user%s"%1497(changelist, newUser))14981499 c = changes[0]1500if c['User'] == newUser:return# nothing to do1501 c['User'] = newUser1502input= marshal.dumps(c)15031504 result =p4CmdList("change -f -i", stdin=input)1505for r in result:1506if r.has_key('code'):1507if r['code'] =='error':1508die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1509if r.has_key('data'):1510print("Updated user field for changelist%sto%s"% (changelist, newUser))1511return1512die("Could not modify user field of changelist%sto%s"% (changelist, newUser))15131514defcanChangeChangelists(self):1515# check to see if we have p4 admin or super-user permissions, either of1516# which are required to modify changelists.1517 results =p4CmdList(["protects", self.depotPath])1518for r in results:1519if r.has_key('perm'):1520if r['perm'] =='admin':1521return11522if r['perm'] =='super':1523return11524return015251526defprepareSubmitTemplate(self, changelist=None):1527"""Run "p4 change -o" to grab a change specification template.1528 This does not use "p4 -G", as it is nice to keep the submission1529 template in original order, since a human might edit it.15301531 Remove lines in the Files section that show changes to files1532 outside the depot path we're committing into."""15331534[upstream, settings] =findUpstreamBranchPoint()15351536 template ="""\1537# A Perforce Change Specification.1538#1539# Change: The change number. 'new' on a new changelist.1540# Date: The date this specification was last modified.1541# Client: The client on which the changelist was created. Read-only.1542# User: The user who created the changelist.1543# Status: Either 'pending' or 'submitted'. Read-only.1544# Type: Either 'public' or 'restricted'. Default is 'public'.1545# Description: Comments about the changelist. Required.1546# Jobs: What opened jobs are to be closed by this changelist.1547# You may delete jobs from this list. (New changelists only.)1548# Files: What opened files from the default changelist are to be added1549# to this changelist. You may delete files from this list.1550# (New changelists only.)1551"""1552 files_list = []1553 inFilesSection =False1554 change_entry =None1555 args = ['change','-o']1556if changelist:1557 args.append(str(changelist))1558for entry inp4CmdList(args):1559if not entry.has_key('code'):1560continue1561if entry['code'] =='stat':1562 change_entry = entry1563break1564if not change_entry:1565die('Failed to decode output of p4 change -o')1566for key, value in change_entry.iteritems():1567if key.startswith('File'):1568if settings.has_key('depot-paths'):1569if not[p for p in settings['depot-paths']1570ifp4PathStartsWith(value, p)]:1571continue1572else:1573if notp4PathStartsWith(value, self.depotPath):1574continue1575 files_list.append(value)1576continue1577# Output in the order expected by prepareLogMessage1578for key in['Change','Client','User','Status','Description','Jobs']:1579if not change_entry.has_key(key):1580continue1581 template +='\n'1582 template += key +':'1583if key =='Description':1584 template +='\n'1585for field_line in change_entry[key].splitlines():1586 template +='\t'+field_line+'\n'1587iflen(files_list) >0:1588 template +='\n'1589 template +='Files:\n'1590for path in files_list:1591 template +='\t'+path+'\n'1592return template15931594defedit_template(self, template_file):1595"""Invoke the editor to let the user change the submission1596 message. Return true if okay to continue with the submit."""15971598# if configured to skip the editing part, just submit1599ifgitConfigBool("git-p4.skipSubmitEdit"):1600return True16011602# look at the modification time, to check later if the user saved1603# the file1604 mtime = os.stat(template_file).st_mtime16051606# invoke the editor1607if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1608 editor = os.environ.get("P4EDITOR")1609else:1610 editor =read_pipe("git var GIT_EDITOR").strip()1611system(["sh","-c", ('%s"$@"'% editor), editor, template_file])16121613# If the file was not saved, prompt to see if this patch should1614# be skipped. But skip this verification step if configured so.1615ifgitConfigBool("git-p4.skipSubmitEditCheck"):1616return True16171618# modification time updated means user saved the file1619if os.stat(template_file).st_mtime > mtime:1620return True16211622while True:1623 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1624if response =='y':1625return True1626if response =='n':1627return False16281629defget_diff_description(self, editedFiles, filesToAdd, symlinks):1630# diff1631if os.environ.has_key("P4DIFF"):1632del(os.environ["P4DIFF"])1633 diff =""1634for editedFile in editedFiles:1635 diff +=p4_read_pipe(['diff','-du',1636wildcard_encode(editedFile)])16371638# new file diff1639 newdiff =""1640for newFile in filesToAdd:1641 newdiff +="==== new file ====\n"1642 newdiff +="--- /dev/null\n"1643 newdiff +="+++%s\n"% newFile16441645 is_link = os.path.islink(newFile)1646 expect_link = newFile in symlinks16471648if is_link and expect_link:1649 newdiff +="+%s\n"% os.readlink(newFile)1650else:1651 f =open(newFile,"r")1652for line in f.readlines():1653 newdiff +="+"+ line1654 f.close()16551656return(diff + newdiff).replace('\r\n','\n')16571658defapplyCommit(self,id):1659"""Apply one commit, return True if it succeeded."""16601661print"Applying",read_pipe(["git","show","-s",1662"--format=format:%h%s",id])16631664(p4User, gitEmail) = self.p4UserForCommit(id)16651666 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1667 filesToAdd =set()1668 filesToChangeType =set()1669 filesToDelete =set()1670 editedFiles =set()1671 pureRenameCopy =set()1672 symlinks =set()1673 filesToChangeExecBit = {}1674 all_files =list()16751676for line in diff:1677 diff =parseDiffTreeEntry(line)1678 modifier = diff['status']1679 path = diff['src']1680 all_files.append(path)16811682if modifier =="M":1683p4_edit(path)1684ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1685 filesToChangeExecBit[path] = diff['dst_mode']1686 editedFiles.add(path)1687elif modifier =="A":1688 filesToAdd.add(path)1689 filesToChangeExecBit[path] = diff['dst_mode']1690if path in filesToDelete:1691 filesToDelete.remove(path)16921693 dst_mode =int(diff['dst_mode'],8)1694if dst_mode ==0120000:1695 symlinks.add(path)16961697elif modifier =="D":1698 filesToDelete.add(path)1699if path in filesToAdd:1700 filesToAdd.remove(path)1701elif modifier =="C":1702 src, dest = diff['src'], diff['dst']1703p4_integrate(src, dest)1704 pureRenameCopy.add(dest)1705if diff['src_sha1'] != diff['dst_sha1']:1706p4_edit(dest)1707 pureRenameCopy.discard(dest)1708ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1709p4_edit(dest)1710 pureRenameCopy.discard(dest)1711 filesToChangeExecBit[dest] = diff['dst_mode']1712if self.isWindows:1713# turn off read-only attribute1714 os.chmod(dest, stat.S_IWRITE)1715 os.unlink(dest)1716 editedFiles.add(dest)1717elif modifier =="R":1718 src, dest = diff['src'], diff['dst']1719if self.p4HasMoveCommand:1720p4_edit(src)# src must be open before move1721p4_move(src, dest)# opens for (move/delete, move/add)1722else:1723p4_integrate(src, dest)1724if diff['src_sha1'] != diff['dst_sha1']:1725p4_edit(dest)1726else:1727 pureRenameCopy.add(dest)1728ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1729if not self.p4HasMoveCommand:1730p4_edit(dest)# with move: already open, writable1731 filesToChangeExecBit[dest] = diff['dst_mode']1732if not self.p4HasMoveCommand:1733if self.isWindows:1734 os.chmod(dest, stat.S_IWRITE)1735 os.unlink(dest)1736 filesToDelete.add(src)1737 editedFiles.add(dest)1738elif modifier =="T":1739 filesToChangeType.add(path)1740else:1741die("unknown modifier%sfor%s"% (modifier, path))17421743 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1744 patchcmd = diffcmd +" | git apply "1745 tryPatchCmd = patchcmd +"--check -"1746 applyPatchCmd = patchcmd +"--check --apply -"1747 patch_succeeded =True17481749if os.system(tryPatchCmd) !=0:1750 fixed_rcs_keywords =False1751 patch_succeeded =False1752print"Unfortunately applying the change failed!"17531754# Patch failed, maybe it's just RCS keyword woes. Look through1755# the patch to see if that's possible.1756ifgitConfigBool("git-p4.attemptRCSCleanup"):1757file=None1758 pattern =None1759 kwfiles = {}1760forfilein editedFiles | filesToDelete:1761# did this file's delta contain RCS keywords?1762 pattern =p4_keywords_regexp_for_file(file)17631764if pattern:1765# this file is a possibility...look for RCS keywords.1766 regexp = re.compile(pattern, re.VERBOSE)1767for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1768if regexp.search(line):1769if verbose:1770print"got keyword match on%sin%sin%s"% (pattern, line,file)1771 kwfiles[file] = pattern1772break17731774forfilein kwfiles:1775if verbose:1776print"zapping%swith%s"% (line,pattern)1777# File is being deleted, so not open in p4. Must1778# disable the read-only bit on windows.1779if self.isWindows andfilenot in editedFiles:1780 os.chmod(file, stat.S_IWRITE)1781 self.patchRCSKeywords(file, kwfiles[file])1782 fixed_rcs_keywords =True17831784if fixed_rcs_keywords:1785print"Retrying the patch with RCS keywords cleaned up"1786if os.system(tryPatchCmd) ==0:1787 patch_succeeded =True17881789if not patch_succeeded:1790for f in editedFiles:1791p4_revert(f)1792return False17931794#1795# Apply the patch for real, and do add/delete/+x handling.1796#1797system(applyPatchCmd)17981799for f in filesToChangeType:1800p4_edit(f,"-t","auto")1801for f in filesToAdd:1802p4_add(f)1803for f in filesToDelete:1804p4_revert(f)1805p4_delete(f)18061807# Set/clear executable bits1808for f in filesToChangeExecBit.keys():1809 mode = filesToChangeExecBit[f]1810setP4ExecBit(f, mode)18111812if self.update_shelve:1813print("all_files =%s"%str(all_files))1814p4_reopen_in_change(self.update_shelve, all_files)18151816#1817# Build p4 change description, starting with the contents1818# of the git commit message.1819#1820 logMessage =extractLogMessageFromGitCommit(id)1821 logMessage = logMessage.strip()1822(logMessage, jobs) = self.separate_jobs_from_description(logMessage)18231824 template = self.prepareSubmitTemplate(self.update_shelve)1825 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)18261827if self.preserveUser:1828 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User18291830if self.checkAuthorship and not self.p4UserIsMe(p4User):1831 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1832 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1833 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"18341835 separatorLine ="######## everything below this line is just the diff #######\n"1836if not self.prepare_p4_only:1837 submitTemplate += separatorLine1838 submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)18391840(handle, fileName) = tempfile.mkstemp()1841 tmpFile = os.fdopen(handle,"w+b")1842if self.isWindows:1843 submitTemplate = submitTemplate.replace("\n","\r\n")1844 tmpFile.write(submitTemplate)1845 tmpFile.close()18461847if self.prepare_p4_only:1848#1849# Leave the p4 tree prepared, and the submit template around1850# and let the user decide what to do next1851#1852print1853print"P4 workspace prepared for submission."1854print"To submit or revert, go to client workspace"1855print" "+ self.clientPath1856print1857print"To submit, use\"p4 submit\"to write a new description,"1858print"or\"p4 submit -i <%s\"to use the one prepared by" \1859"\"git p4\"."% fileName1860print"You can delete the file\"%s\"when finished."% fileName18611862if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1863print"To preserve change ownership by user%s, you must\n" \1864"do\"p4 change -f <change>\"after submitting and\n" \1865"edit the User field."1866if pureRenameCopy:1867print"After submitting, renamed files must be re-synced."1868print"Invoke\"p4 sync -f\"on each of these files:"1869for f in pureRenameCopy:1870print" "+ f18711872print1873print"To revert the changes, use\"p4 revert ...\", and delete"1874print"the submit template file\"%s\""% fileName1875if filesToAdd:1876print"Since the commit adds new files, they must be deleted:"1877for f in filesToAdd:1878print" "+ f1879print1880return True18811882#1883# Let the user edit the change description, then submit it.1884#1885 submitted =False18861887try:1888if self.edit_template(fileName):1889# read the edited message and submit1890 tmpFile =open(fileName,"rb")1891 message = tmpFile.read()1892 tmpFile.close()1893if self.isWindows:1894 message = message.replace("\r\n","\n")1895 submitTemplate = message[:message.index(separatorLine)]18961897if self.update_shelve:1898p4_write_pipe(['shelve','-r','-i'], submitTemplate)1899elif self.shelve:1900p4_write_pipe(['shelve','-i'], submitTemplate)1901else:1902p4_write_pipe(['submit','-i'], submitTemplate)1903# The rename/copy happened by applying a patch that created a1904# new file. This leaves it writable, which confuses p4.1905for f in pureRenameCopy:1906p4_sync(f,"-f")19071908if self.preserveUser:1909if p4User:1910# Get last changelist number. Cannot easily get it from1911# the submit command output as the output is1912# unmarshalled.1913 changelist = self.lastP4Changelist()1914 self.modifyChangelistUser(changelist, p4User)19151916 submitted =True19171918finally:1919# skip this patch1920if not submitted or self.shelve:1921if self.shelve:1922print("Reverting shelved files.")1923else:1924print("Submission cancelled, undoing p4 changes.")1925for f in editedFiles | filesToDelete:1926p4_revert(f)1927for f in filesToAdd:1928p4_revert(f)1929 os.remove(f)19301931 os.remove(fileName)1932return submitted19331934# Export git tags as p4 labels. Create a p4 label and then tag1935# with that.1936defexportGitTags(self, gitTags):1937 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1938iflen(validLabelRegexp) ==0:1939 validLabelRegexp = defaultLabelRegexp1940 m = re.compile(validLabelRegexp)19411942for name in gitTags:19431944if not m.match(name):1945if verbose:1946print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1947continue19481949# Get the p4 commit this corresponds to1950 logMessage =extractLogMessageFromGitCommit(name)1951 values =extractSettingsGitLog(logMessage)19521953if not values.has_key('change'):1954# a tag pointing to something not sent to p4; ignore1955if verbose:1956print"git tag%sdoes not give a p4 commit"% name1957continue1958else:1959 changelist = values['change']19601961# Get the tag details.1962 inHeader =True1963 isAnnotated =False1964 body = []1965for l inread_pipe_lines(["git","cat-file","-p", name]):1966 l = l.strip()1967if inHeader:1968if re.match(r'tag\s+', l):1969 isAnnotated =True1970elif re.match(r'\s*$', l):1971 inHeader =False1972continue1973else:1974 body.append(l)19751976if not isAnnotated:1977 body = ["lightweight tag imported by git p4\n"]19781979# Create the label - use the same view as the client spec we are using1980 clientSpec =getClientSpec()19811982 labelTemplate ="Label:%s\n"% name1983 labelTemplate +="Description:\n"1984for b in body:1985 labelTemplate +="\t"+ b +"\n"1986 labelTemplate +="View:\n"1987for depot_side in clientSpec.mappings:1988 labelTemplate +="\t%s\n"% depot_side19891990if self.dry_run:1991print"Would create p4 label%sfor tag"% name1992elif self.prepare_p4_only:1993print"Not creating p4 label%sfor tag due to option" \1994" --prepare-p4-only"% name1995else:1996p4_write_pipe(["label","-i"], labelTemplate)19971998# Use the label1999p4_system(["tag","-l", name] +2000["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])20012002if verbose:2003print"created p4 label for tag%s"% name20042005defrun(self, args):2006iflen(args) ==0:2007 self.master =currentGitBranch()2008eliflen(args) ==1:2009 self.master = args[0]2010if notbranchExists(self.master):2011die("Branch%sdoes not exist"% self.master)2012else:2013return False20142015if self.master:2016 allowSubmit =gitConfig("git-p4.allowSubmit")2017iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):2018die("%sis not in git-p4.allowSubmit"% self.master)20192020[upstream, settings] =findUpstreamBranchPoint()2021 self.depotPath = settings['depot-paths'][0]2022iflen(self.origin) ==0:2023 self.origin = upstream20242025if self.update_shelve:2026 self.shelve =True20272028if self.preserveUser:2029if not self.canChangeChangelists():2030die("Cannot preserve user names without p4 super-user or admin permissions")20312032# if not set from the command line, try the config file2033if self.conflict_behavior is None:2034 val =gitConfig("git-p4.conflict")2035if val:2036if val not in self.conflict_behavior_choices:2037die("Invalid value '%s' for config git-p4.conflict"% val)2038else:2039 val ="ask"2040 self.conflict_behavior = val20412042if self.verbose:2043print"Origin branch is "+ self.origin20442045iflen(self.depotPath) ==0:2046print"Internal error: cannot locate perforce depot path from existing branches"2047 sys.exit(128)20482049 self.useClientSpec =False2050ifgitConfigBool("git-p4.useclientspec"):2051 self.useClientSpec =True2052if self.useClientSpec:2053 self.clientSpecDirs =getClientSpec()20542055# Check for the existence of P4 branches2056 branchesDetected = (len(p4BranchesInGit().keys()) >1)20572058if self.useClientSpec and not branchesDetected:2059# all files are relative to the client spec2060 self.clientPath =getClientRoot()2061else:2062 self.clientPath =p4Where(self.depotPath)20632064if self.clientPath =="":2065die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)20662067print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)2068 self.oldWorkingDirectory = os.getcwd()20692070# ensure the clientPath exists2071 new_client_dir =False2072if not os.path.exists(self.clientPath):2073 new_client_dir =True2074 os.makedirs(self.clientPath)20752076chdir(self.clientPath, is_client_path=True)2077if self.dry_run:2078print"Would synchronize p4 checkout in%s"% self.clientPath2079else:2080print"Synchronizing p4 checkout..."2081if new_client_dir:2082# old one was destroyed, and maybe nobody told p42083p4_sync("...","-f")2084else:2085p4_sync("...")2086 self.check()20872088 commits = []2089if self.master:2090 commitish = self.master2091else:2092 commitish ='HEAD'20932094for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):2095 commits.append(line.strip())2096 commits.reverse()20972098if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):2099 self.checkAuthorship =False2100else:2101 self.checkAuthorship =True21022103if self.preserveUser:2104 self.checkValidP4Users(commits)21052106#2107# Build up a set of options to be passed to diff when2108# submitting each commit to p4.2109#2110if self.detectRenames:2111# command-line -M arg2112 self.diffOpts ="-M"2113else:2114# If not explicitly set check the config variable2115 detectRenames =gitConfig("git-p4.detectRenames")21162117if detectRenames.lower() =="false"or detectRenames =="":2118 self.diffOpts =""2119elif detectRenames.lower() =="true":2120 self.diffOpts ="-M"2121else:2122 self.diffOpts ="-M%s"% detectRenames21232124# no command-line arg for -C or --find-copies-harder, just2125# config variables2126 detectCopies =gitConfig("git-p4.detectCopies")2127if detectCopies.lower() =="false"or detectCopies =="":2128pass2129elif detectCopies.lower() =="true":2130 self.diffOpts +=" -C"2131else:2132 self.diffOpts +=" -C%s"% detectCopies21332134ifgitConfigBool("git-p4.detectCopiesHarder"):2135 self.diffOpts +=" --find-copies-harder"21362137#2138# Apply the commits, one at a time. On failure, ask if should2139# continue to try the rest of the patches, or quit.2140#2141if self.dry_run:2142print"Would apply"2143 applied = []2144 last =len(commits) -12145for i, commit inenumerate(commits):2146if self.dry_run:2147print" ",read_pipe(["git","show","-s",2148"--format=format:%h%s", commit])2149 ok =True2150else:2151 ok = self.applyCommit(commit)2152if ok:2153 applied.append(commit)2154else:2155if self.prepare_p4_only and i < last:2156print"Processing only the first commit due to option" \2157" --prepare-p4-only"2158break2159if i < last:2160 quit =False2161while True:2162# prompt for what to do, or use the option/variable2163if self.conflict_behavior =="ask":2164print"What do you want to do?"2165 response =raw_input("[s]kip this commit but apply"2166" the rest, or [q]uit? ")2167if not response:2168continue2169elif self.conflict_behavior =="skip":2170 response ="s"2171elif self.conflict_behavior =="quit":2172 response ="q"2173else:2174die("Unknown conflict_behavior '%s'"%2175 self.conflict_behavior)21762177if response[0] =="s":2178print"Skipping this commit, but applying the rest"2179break2180if response[0] =="q":2181print"Quitting"2182 quit =True2183break2184if quit:2185break21862187chdir(self.oldWorkingDirectory)2188 shelved_applied ="shelved"if self.shelve else"applied"2189if self.dry_run:2190pass2191elif self.prepare_p4_only:2192pass2193eliflen(commits) ==len(applied):2194print("All commits{0}!".format(shelved_applied))21952196 sync =P4Sync()2197if self.branch:2198 sync.branch = self.branch2199 sync.run([])22002201 rebase =P4Rebase()2202 rebase.rebase()22032204else:2205iflen(applied) ==0:2206print("No commits{0}.".format(shelved_applied))2207else:2208print("{0}only the commits marked with '*':".format(shelved_applied.capitalize()))2209for c in commits:2210if c in applied:2211 star ="*"2212else:2213 star =" "2214print star,read_pipe(["git","show","-s",2215"--format=format:%h%s", c])2216print"You will have to do 'git p4 sync' and rebase."22172218ifgitConfigBool("git-p4.exportLabels"):2219 self.exportLabels =True22202221if self.exportLabels:2222 p4Labels =getP4Labels(self.depotPath)2223 gitTags =getGitTags()22242225 missingGitTags = gitTags - p4Labels2226 self.exportGitTags(missingGitTags)22272228# exit with error unless everything applied perfectly2229iflen(commits) !=len(applied):2230 sys.exit(1)22312232return True22332234classView(object):2235"""Represent a p4 view ("p4 help views"), and map files in a2236 repo according to the view."""22372238def__init__(self, client_name):2239 self.mappings = []2240 self.client_prefix ="//%s/"% client_name2241# cache results of "p4 where" to lookup client file locations2242 self.client_spec_path_cache = {}22432244defappend(self, view_line):2245"""Parse a view line, splitting it into depot and client2246 sides. Append to self.mappings, preserving order. This2247 is only needed for tag creation."""22482249# Split the view line into exactly two words. P4 enforces2250# structure on these lines that simplifies this quite a bit.2251#2252# Either or both words may be double-quoted.2253# Single quotes do not matter.2254# Double-quote marks cannot occur inside the words.2255# A + or - prefix is also inside the quotes.2256# There are no quotes unless they contain a space.2257# The line is already white-space stripped.2258# The two words are separated by a single space.2259#2260if view_line[0] =='"':2261# First word is double quoted. Find its end.2262 close_quote_index = view_line.find('"',1)2263if close_quote_index <=0:2264die("No first-word closing quote found:%s"% view_line)2265 depot_side = view_line[1:close_quote_index]2266# skip closing quote and space2267 rhs_index = close_quote_index +1+12268else:2269 space_index = view_line.find(" ")2270if space_index <=0:2271die("No word-splitting space found:%s"% view_line)2272 depot_side = view_line[0:space_index]2273 rhs_index = space_index +122742275# prefix + means overlay on previous mapping2276if depot_side.startswith("+"):2277 depot_side = depot_side[1:]22782279# prefix - means exclude this path, leave out of mappings2280 exclude =False2281if depot_side.startswith("-"):2282 exclude =True2283 depot_side = depot_side[1:]22842285if not exclude:2286 self.mappings.append(depot_side)22872288defconvert_client_path(self, clientFile):2289# chop off //client/ part to make it relative2290if not clientFile.startswith(self.client_prefix):2291die("No prefix '%s' on clientFile '%s'"%2292(self.client_prefix, clientFile))2293return clientFile[len(self.client_prefix):]22942295defupdate_client_spec_path_cache(self, files):2296""" Caching file paths by "p4 where" batch query """22972298# List depot file paths exclude that already cached2299 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]23002301iflen(fileArgs) ==0:2302return# All files in cache23032304 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2305for res in where_result:2306if"code"in res and res["code"] =="error":2307# assume error is "... file(s) not in client view"2308continue2309if"clientFile"not in res:2310die("No clientFile in 'p4 where' output")2311if"unmap"in res:2312# it will list all of them, but only one not unmap-ped2313continue2314ifgitConfigBool("core.ignorecase"):2315 res['depotFile'] = res['depotFile'].lower()2316 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])23172318# not found files or unmap files set to ""2319for depotFile in fileArgs:2320ifgitConfigBool("core.ignorecase"):2321 depotFile = depotFile.lower()2322if depotFile not in self.client_spec_path_cache:2323 self.client_spec_path_cache[depotFile] =""23242325defmap_in_client(self, depot_path):2326"""Return the relative location in the client where this2327 depot file should live. Returns "" if the file should2328 not be mapped in the client."""23292330ifgitConfigBool("core.ignorecase"):2331 depot_path = depot_path.lower()23322333if depot_path in self.client_spec_path_cache:2334return self.client_spec_path_cache[depot_path]23352336die("Error:%sis not found in client spec path"% depot_path )2337return""23382339classP4Sync(Command, P4UserMap):2340 delete_actions = ("delete","move/delete","purge")23412342def__init__(self):2343 Command.__init__(self)2344 P4UserMap.__init__(self)2345 self.options = [2346 optparse.make_option("--branch", dest="branch"),2347 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2348 optparse.make_option("--changesfile", dest="changesFile"),2349 optparse.make_option("--silent", dest="silent", action="store_true"),2350 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2351 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2352 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2353help="Import into refs/heads/ , not refs/remotes"),2354 optparse.make_option("--max-changes", dest="maxChanges",2355help="Maximum number of changes to import"),2356 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2357help="Internal block size to use when iteratively calling p4 changes"),2358 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2359help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2360 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2361help="Only sync files that are included in the Perforce Client Spec"),2362 optparse.make_option("-/", dest="cloneExclude",2363 action="append",type="string",2364help="exclude depot path"),2365]2366 self.description ="""Imports from Perforce into a git repository.\n2367 example:2368 //depot/my/project/ -- to import the current head2369 //depot/my/project/@all -- to import everything2370 //depot/my/project/@1,6 -- to import only from revision 1 to 623712372 (a ... is not needed in the path p4 specification, it's added implicitly)"""23732374 self.usage +=" //depot/path[@revRange]"2375 self.silent =False2376 self.createdBranches =set()2377 self.committedChanges =set()2378 self.branch =""2379 self.detectBranches =False2380 self.detectLabels =False2381 self.importLabels =False2382 self.changesFile =""2383 self.syncWithOrigin =True2384 self.importIntoRemotes =True2385 self.maxChanges =""2386 self.changes_block_size =None2387 self.keepRepoPath =False2388 self.depotPaths =None2389 self.p4BranchesInGit = []2390 self.cloneExclude = []2391 self.useClientSpec =False2392 self.useClientSpec_from_options =False2393 self.clientSpecDirs =None2394 self.tempBranches = []2395 self.tempBranchLocation ="refs/git-p4-tmp"2396 self.largeFileSystem =None23972398ifgitConfig('git-p4.largeFileSystem'):2399 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2400 self.largeFileSystem =largeFileSystemConstructor(2401lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2402)24032404ifgitConfig("git-p4.syncFromOrigin") =="false":2405 self.syncWithOrigin =False24062407# This is required for the "append" cloneExclude action2408defensure_value(self, attr, value):2409if nothasattr(self, attr)orgetattr(self, attr)is None:2410setattr(self, attr, value)2411returngetattr(self, attr)24122413# Force a checkpoint in fast-import and wait for it to finish2414defcheckpoint(self):2415 self.gitStream.write("checkpoint\n\n")2416 self.gitStream.write("progress checkpoint\n\n")2417 out = self.gitOutput.readline()2418if self.verbose:2419print"checkpoint finished: "+ out24202421defextractFilesFromCommit(self, commit):2422 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2423for path in self.cloneExclude]2424 files = []2425 fnum =02426while commit.has_key("depotFile%s"% fnum):2427 path = commit["depotFile%s"% fnum]24282429if[p for p in self.cloneExclude2430ifp4PathStartsWith(path, p)]:2431 found =False2432else:2433 found = [p for p in self.depotPaths2434ifp4PathStartsWith(path, p)]2435if not found:2436 fnum = fnum +12437continue24382439file= {}2440file["path"] = path2441file["rev"] = commit["rev%s"% fnum]2442file["action"] = commit["action%s"% fnum]2443file["type"] = commit["type%s"% fnum]2444 files.append(file)2445 fnum = fnum +12446return files24472448defextractJobsFromCommit(self, commit):2449 jobs = []2450 jnum =02451while commit.has_key("job%s"% jnum):2452 job = commit["job%s"% jnum]2453 jobs.append(job)2454 jnum = jnum +12455return jobs24562457defstripRepoPath(self, path, prefixes):2458"""When streaming files, this is called to map a p4 depot path2459 to where it should go in git. The prefixes are either2460 self.depotPaths, or self.branchPrefixes in the case of2461 branch detection."""24622463if self.useClientSpec:2464# branch detection moves files up a level (the branch name)2465# from what client spec interpretation gives2466 path = self.clientSpecDirs.map_in_client(path)2467if self.detectBranches:2468for b in self.knownBranches:2469if path.startswith(b +"/"):2470 path = path[len(b)+1:]24712472elif self.keepRepoPath:2473# Preserve everything in relative path name except leading2474# //depot/; just look at first prefix as they all should2475# be in the same depot.2476 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2477ifp4PathStartsWith(path, depot):2478 path = path[len(depot):]24792480else:2481for p in prefixes:2482ifp4PathStartsWith(path, p):2483 path = path[len(p):]2484break24852486 path =wildcard_decode(path)2487return path24882489defsplitFilesIntoBranches(self, commit):2490"""Look at each depotFile in the commit to figure out to what2491 branch it belongs."""24922493if self.clientSpecDirs:2494 files = self.extractFilesFromCommit(commit)2495 self.clientSpecDirs.update_client_spec_path_cache(files)24962497 branches = {}2498 fnum =02499while commit.has_key("depotFile%s"% fnum):2500 path = commit["depotFile%s"% fnum]2501 found = [p for p in self.depotPaths2502ifp4PathStartsWith(path, p)]2503if not found:2504 fnum = fnum +12505continue25062507file= {}2508file["path"] = path2509file["rev"] = commit["rev%s"% fnum]2510file["action"] = commit["action%s"% fnum]2511file["type"] = commit["type%s"% fnum]2512 fnum = fnum +125132514# start with the full relative path where this file would2515# go in a p4 client2516if self.useClientSpec:2517 relPath = self.clientSpecDirs.map_in_client(path)2518else:2519 relPath = self.stripRepoPath(path, self.depotPaths)25202521for branch in self.knownBranches.keys():2522# add a trailing slash so that a commit into qt/4.2foo2523# doesn't end up in qt/4.2, e.g.2524if relPath.startswith(branch +"/"):2525if branch not in branches:2526 branches[branch] = []2527 branches[branch].append(file)2528break25292530return branches25312532defwriteToGitStream(self, gitMode, relPath, contents):2533 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2534 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2535for d in contents:2536 self.gitStream.write(d)2537 self.gitStream.write('\n')25382539defencodeWithUTF8(self, path):2540try:2541 path.decode('ascii')2542except:2543 encoding ='utf8'2544ifgitConfig('git-p4.pathEncoding'):2545 encoding =gitConfig('git-p4.pathEncoding')2546 path = path.decode(encoding,'replace').encode('utf8','replace')2547if self.verbose:2548print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, path)2549return path25502551# output one file from the P4 stream2552# - helper for streamP4Files25532554defstreamOneP4File(self,file, contents):2555 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2556 relPath = self.encodeWithUTF8(relPath)2557if verbose:2558 size =int(self.stream_file['fileSize'])2559 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2560 sys.stdout.flush()25612562(type_base, type_mods) =split_p4_type(file["type"])25632564 git_mode ="100644"2565if"x"in type_mods:2566 git_mode ="100755"2567if type_base =="symlink":2568 git_mode ="120000"2569# p4 print on a symlink sometimes contains "target\n";2570# if it does, remove the newline2571 data =''.join(contents)2572if not data:2573# Some version of p4 allowed creating a symlink that pointed2574# to nothing. This causes p4 errors when checking out such2575# a change, and errors here too. Work around it by ignoring2576# the bad symlink; hopefully a future change fixes it.2577print"\nIgnoring empty symlink in%s"%file['depotFile']2578return2579elif data[-1] =='\n':2580 contents = [data[:-1]]2581else:2582 contents = [data]25832584if type_base =="utf16":2585# p4 delivers different text in the python output to -G2586# than it does when using "print -o", or normal p4 client2587# operations. utf16 is converted to ascii or utf8, perhaps.2588# But ascii text saved as -t utf16 is completely mangled.2589# Invoke print -o to get the real contents.2590#2591# On windows, the newlines will always be mangled by print, so put2592# them back too. This is not needed to the cygwin windows version,2593# just the native "NT" type.2594#2595try:2596 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2597exceptExceptionas e:2598if'Translation of file content failed'instr(e):2599 type_base ='binary'2600else:2601raise e2602else:2603ifp4_version_string().find('/NT') >=0:2604 text = text.replace('\r\n','\n')2605 contents = [ text ]26062607if type_base =="apple":2608# Apple filetype files will be streamed as a concatenation of2609# its appledouble header and the contents. This is useless2610# on both macs and non-macs. If using "print -q -o xx", it2611# will create "xx" with the data, and "%xx" with the header.2612# This is also not very useful.2613#2614# Ideally, someday, this script can learn how to generate2615# appledouble files directly and import those to git, but2616# non-mac machines can never find a use for apple filetype.2617print"\nIgnoring apple filetype file%s"%file['depotFile']2618return26192620# Note that we do not try to de-mangle keywords on utf16 files,2621# even though in theory somebody may want that.2622 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2623if pattern:2624 regexp = re.compile(pattern, re.VERBOSE)2625 text =''.join(contents)2626 text = regexp.sub(r'$\1$', text)2627 contents = [ text ]26282629if self.largeFileSystem:2630(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)26312632 self.writeToGitStream(git_mode, relPath, contents)26332634defstreamOneP4Deletion(self,file):2635 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2636 relPath = self.encodeWithUTF8(relPath)2637if verbose:2638 sys.stdout.write("delete%s\n"% relPath)2639 sys.stdout.flush()2640 self.gitStream.write("D%s\n"% relPath)26412642if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2643 self.largeFileSystem.removeLargeFile(relPath)26442645# handle another chunk of streaming data2646defstreamP4FilesCb(self, marshalled):26472648# catch p4 errors and complain2649 err =None2650if"code"in marshalled:2651if marshalled["code"] =="error":2652if"data"in marshalled:2653 err = marshalled["data"].rstrip()26542655if not err and'fileSize'in self.stream_file:2656 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2657if required_bytes >0:2658 err ='Not enough space left on%s! Free at least%iMB.'% (2659 os.getcwd(), required_bytes/1024/10242660)26612662if err:2663 f =None2664if self.stream_have_file_info:2665if"depotFile"in self.stream_file:2666 f = self.stream_file["depotFile"]2667# force a failure in fast-import, else an empty2668# commit will be made2669 self.gitStream.write("\n")2670 self.gitStream.write("die-now\n")2671 self.gitStream.close()2672# ignore errors, but make sure it exits first2673 self.importProcess.wait()2674if f:2675die("Error from p4 print for%s:%s"% (f, err))2676else:2677die("Error from p4 print:%s"% err)26782679if marshalled.has_key('depotFile')and self.stream_have_file_info:2680# start of a new file - output the old one first2681 self.streamOneP4File(self.stream_file, self.stream_contents)2682 self.stream_file = {}2683 self.stream_contents = []2684 self.stream_have_file_info =False26852686# pick up the new file information... for the2687# 'data' field we need to append to our array2688for k in marshalled.keys():2689if k =='data':2690if'streamContentSize'not in self.stream_file:2691 self.stream_file['streamContentSize'] =02692 self.stream_file['streamContentSize'] +=len(marshalled['data'])2693 self.stream_contents.append(marshalled['data'])2694else:2695 self.stream_file[k] = marshalled[k]26962697if(verbose and2698'streamContentSize'in self.stream_file and2699'fileSize'in self.stream_file and2700'depotFile'in self.stream_file):2701 size =int(self.stream_file["fileSize"])2702if size >0:2703 progress =100*self.stream_file['streamContentSize']/size2704 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2705 sys.stdout.flush()27062707 self.stream_have_file_info =True27082709# Stream directly from "p4 files" into "git fast-import"2710defstreamP4Files(self, files):2711 filesForCommit = []2712 filesToRead = []2713 filesToDelete = []27142715for f in files:2716 filesForCommit.append(f)2717if f['action']in self.delete_actions:2718 filesToDelete.append(f)2719else:2720 filesToRead.append(f)27212722# deleted files...2723for f in filesToDelete:2724 self.streamOneP4Deletion(f)27252726iflen(filesToRead) >0:2727 self.stream_file = {}2728 self.stream_contents = []2729 self.stream_have_file_info =False27302731# curry self argument2732defstreamP4FilesCbSelf(entry):2733 self.streamP4FilesCb(entry)27342735 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]27362737p4CmdList(["-x","-","print"],2738 stdin=fileArgs,2739 cb=streamP4FilesCbSelf)27402741# do the last chunk2742if self.stream_file.has_key('depotFile'):2743 self.streamOneP4File(self.stream_file, self.stream_contents)27442745defmake_email(self, userid):2746if userid in self.users:2747return self.users[userid]2748else:2749return"%s<a@b>"% userid27502751defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2752""" Stream a p4 tag.2753 commit is either a git commit, or a fast-import mark, ":<p4commit>"2754 """27552756if verbose:2757print"writing tag%sfor commit%s"% (labelName, commit)2758 gitStream.write("tag%s\n"% labelName)2759 gitStream.write("from%s\n"% commit)27602761if labelDetails.has_key('Owner'):2762 owner = labelDetails["Owner"]2763else:2764 owner =None27652766# Try to use the owner of the p4 label, or failing that,2767# the current p4 user id.2768if owner:2769 email = self.make_email(owner)2770else:2771 email = self.make_email(self.p4UserId())2772 tagger ="%s %s %s"% (email, epoch, self.tz)27732774 gitStream.write("tagger%s\n"% tagger)27752776print"labelDetails=",labelDetails2777if labelDetails.has_key('Description'):2778 description = labelDetails['Description']2779else:2780 description ='Label from git p4'27812782 gitStream.write("data%d\n"%len(description))2783 gitStream.write(description)2784 gitStream.write("\n")27852786definClientSpec(self, path):2787if not self.clientSpecDirs:2788return True2789 inClientSpec = self.clientSpecDirs.map_in_client(path)2790if not inClientSpec and self.verbose:2791print('Ignoring file outside of client spec:{0}'.format(path))2792return inClientSpec27932794defhasBranchPrefix(self, path):2795if not self.branchPrefixes:2796return True2797 hasPrefix = [p for p in self.branchPrefixes2798ifp4PathStartsWith(path, p)]2799if not hasPrefix and self.verbose:2800print('Ignoring file outside of prefix:{0}'.format(path))2801return hasPrefix28022803defcommit(self, details, files, branch, parent =""):2804 epoch = details["time"]2805 author = details["user"]2806 jobs = self.extractJobsFromCommit(details)28072808if self.verbose:2809print('commit into{0}'.format(branch))28102811if self.clientSpecDirs:2812 self.clientSpecDirs.update_client_spec_path_cache(files)28132814 files = [f for f in files2815if self.inClientSpec(f['path'])and self.hasBranchPrefix(f['path'])]28162817if not files and notgitConfigBool('git-p4.keepEmptyCommits'):2818print('Ignoring revision{0}as it would produce an empty commit.'2819.format(details['change']))2820return28212822 self.gitStream.write("commit%s\n"% branch)2823 self.gitStream.write("mark :%s\n"% details["change"])2824 self.committedChanges.add(int(details["change"]))2825 committer =""2826if author not in self.users:2827 self.getUserMapFromPerforceServer()2828 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)28292830 self.gitStream.write("committer%s\n"% committer)28312832 self.gitStream.write("data <<EOT\n")2833 self.gitStream.write(details["desc"])2834iflen(jobs) >0:2835 self.gitStream.write("\nJobs:%s"% (' '.join(jobs)))2836 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2837(','.join(self.branchPrefixes), details["change"]))2838iflen(details['options']) >0:2839 self.gitStream.write(": options =%s"% details['options'])2840 self.gitStream.write("]\nEOT\n\n")28412842iflen(parent) >0:2843if self.verbose:2844print"parent%s"% parent2845 self.gitStream.write("from%s\n"% parent)28462847 self.streamP4Files(files)2848 self.gitStream.write("\n")28492850 change =int(details["change"])28512852if self.labels.has_key(change):2853 label = self.labels[change]2854 labelDetails = label[0]2855 labelRevisions = label[1]2856if self.verbose:2857print"Change%sis labelled%s"% (change, labelDetails)28582859 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2860for p in self.branchPrefixes])28612862iflen(files) ==len(labelRevisions):28632864 cleanedFiles = {}2865for info in files:2866if info["action"]in self.delete_actions:2867continue2868 cleanedFiles[info["depotFile"]] = info["rev"]28692870if cleanedFiles == labelRevisions:2871 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)28722873else:2874if not self.silent:2875print("Tag%sdoes not match with change%s: files do not match."2876% (labelDetails["label"], change))28772878else:2879if not self.silent:2880print("Tag%sdoes not match with change%s: file count is different."2881% (labelDetails["label"], change))28822883# Build a dictionary of changelists and labels, for "detect-labels" option.2884defgetLabels(self):2885 self.labels = {}28862887 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2888iflen(l) >0and not self.silent:2889print"Finding files belonging to labels in%s"% `self.depotPaths`28902891for output in l:2892 label = output["label"]2893 revisions = {}2894 newestChange =02895if self.verbose:2896print"Querying files for label%s"% label2897forfileinp4CmdList(["files"] +2898["%s...@%s"% (p, label)2899for p in self.depotPaths]):2900 revisions[file["depotFile"]] =file["rev"]2901 change =int(file["change"])2902if change > newestChange:2903 newestChange = change29042905 self.labels[newestChange] = [output, revisions]29062907if self.verbose:2908print"Label changes:%s"% self.labels.keys()29092910# Import p4 labels as git tags. A direct mapping does not2911# exist, so assume that if all the files are at the same revision2912# then we can use that, or it's something more complicated we should2913# just ignore.2914defimportP4Labels(self, stream, p4Labels):2915if verbose:2916print"import p4 labels: "+' '.join(p4Labels)29172918 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2919 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2920iflen(validLabelRegexp) ==0:2921 validLabelRegexp = defaultLabelRegexp2922 m = re.compile(validLabelRegexp)29232924for name in p4Labels:2925 commitFound =False29262927if not m.match(name):2928if verbose:2929print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2930continue29312932if name in ignoredP4Labels:2933continue29342935 labelDetails =p4CmdList(['label',"-o", name])[0]29362937# get the most recent changelist for each file in this label2938 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2939for p in self.depotPaths])29402941if change.has_key('change'):2942# find the corresponding git commit; take the oldest commit2943 changelist =int(change['change'])2944if changelist in self.committedChanges:2945 gitCommit =":%d"% changelist # use a fast-import mark2946 commitFound =True2947else:2948 gitCommit =read_pipe(["git","rev-list","--max-count=1",2949"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2950iflen(gitCommit) ==0:2951print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2952else:2953 commitFound =True2954 gitCommit = gitCommit.strip()29552956if commitFound:2957# Convert from p4 time format2958try:2959 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2960exceptValueError:2961print"Could not convert label time%s"% labelDetails['Update']2962 tmwhen =129632964 when =int(time.mktime(tmwhen))2965 self.streamTag(stream, name, labelDetails, gitCommit, when)2966if verbose:2967print"p4 label%smapped to git commit%s"% (name, gitCommit)2968else:2969if verbose:2970print"Label%shas no changelists - possibly deleted?"% name29712972if not commitFound:2973# We can't import this label; don't try again as it will get very2974# expensive repeatedly fetching all the files for labels that will2975# never be imported. If the label is moved in the future, the2976# ignore will need to be removed manually.2977system(["git","config","--add","git-p4.ignoredP4Labels", name])29782979defguessProjectName(self):2980for p in self.depotPaths:2981if p.endswith("/"):2982 p = p[:-1]2983 p = p[p.strip().rfind("/") +1:]2984if not p.endswith("/"):2985 p +="/"2986return p29872988defgetBranchMapping(self):2989 lostAndFoundBranches =set()29902991 user =gitConfig("git-p4.branchUser")2992iflen(user) >0:2993 command ="branches -u%s"% user2994else:2995 command ="branches"29962997for info inp4CmdList(command):2998 details =p4Cmd(["branch","-o", info["branch"]])2999 viewIdx =03000while details.has_key("View%s"% viewIdx):3001 paths = details["View%s"% viewIdx].split(" ")3002 viewIdx = viewIdx +13003# require standard //depot/foo/... //depot/bar/... mapping3004iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):3005continue3006 source = paths[0]3007 destination = paths[1]3008## HACK3009ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):3010 source = source[len(self.depotPaths[0]):-4]3011 destination = destination[len(self.depotPaths[0]):-4]30123013if destination in self.knownBranches:3014if not self.silent:3015print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)3016print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)3017continue30183019 self.knownBranches[destination] = source30203021 lostAndFoundBranches.discard(destination)30223023if source not in self.knownBranches:3024 lostAndFoundBranches.add(source)30253026# Perforce does not strictly require branches to be defined, so we also3027# check git config for a branch list.3028#3029# Example of branch definition in git config file:3030# [git-p4]3031# branchList=main:branchA3032# branchList=main:branchB3033# branchList=branchA:branchC3034 configBranches =gitConfigList("git-p4.branchList")3035for branch in configBranches:3036if branch:3037(source, destination) = branch.split(":")3038 self.knownBranches[destination] = source30393040 lostAndFoundBranches.discard(destination)30413042if source not in self.knownBranches:3043 lostAndFoundBranches.add(source)304430453046for branch in lostAndFoundBranches:3047 self.knownBranches[branch] = branch30483049defgetBranchMappingFromGitBranches(self):3050 branches =p4BranchesInGit(self.importIntoRemotes)3051for branch in branches.keys():3052if branch =="master":3053 branch ="main"3054else:3055 branch = branch[len(self.projectName):]3056 self.knownBranches[branch] = branch30573058defupdateOptionDict(self, d):3059 option_keys = {}3060if self.keepRepoPath:3061 option_keys['keepRepoPath'] =130623063 d["options"] =' '.join(sorted(option_keys.keys()))30643065defreadOptions(self, d):3066 self.keepRepoPath = (d.has_key('options')3067and('keepRepoPath'in d['options']))30683069defgitRefForBranch(self, branch):3070if branch =="main":3071return self.refPrefix +"master"30723073iflen(branch) <=0:3074return branch30753076return self.refPrefix + self.projectName + branch30773078defgitCommitByP4Change(self, ref, change):3079if self.verbose:3080print"looking in ref "+ ref +" for change%susing bisect..."% change30813082 earliestCommit =""3083 latestCommit =parseRevision(ref)30843085while True:3086if self.verbose:3087print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)3088 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()3089iflen(next) ==0:3090if self.verbose:3091print"argh"3092return""3093 log =extractLogMessageFromGitCommit(next)3094 settings =extractSettingsGitLog(log)3095 currentChange =int(settings['change'])3096if self.verbose:3097print"current change%s"% currentChange30983099if currentChange == change:3100if self.verbose:3101print"found%s"% next3102return next31033104if currentChange < change:3105 earliestCommit ="^%s"% next3106else:3107 latestCommit ="%s"% next31083109return""31103111defimportNewBranch(self, branch, maxChange):3112# make fast-import flush all changes to disk and update the refs using the checkpoint3113# command so that we can try to find the branch parent in the git history3114 self.gitStream.write("checkpoint\n\n");3115 self.gitStream.flush();3116 branchPrefix = self.depotPaths[0] + branch +"/"3117range="@1,%s"% maxChange3118#print "prefix" + branchPrefix3119 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)3120iflen(changes) <=0:3121return False3122 firstChange = changes[0]3123#print "first change in branch: %s" % firstChange3124 sourceBranch = self.knownBranches[branch]3125 sourceDepotPath = self.depotPaths[0] + sourceBranch3126 sourceRef = self.gitRefForBranch(sourceBranch)3127#print "source " + sourceBranch31283129 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])3130#print "branch parent: %s" % branchParentChange3131 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)3132iflen(gitParent) >0:3133 self.initialParents[self.gitRefForBranch(branch)] = gitParent3134#print "parent git commit: %s" % gitParent31353136 self.importChanges(changes)3137return True31383139defsearchParent(self, parent, branch, target):3140 parentFound =False3141for blob inread_pipe_lines(["git","rev-list","--reverse",3142"--no-merges", parent]):3143 blob = blob.strip()3144iflen(read_pipe(["git","diff-tree", blob, target])) ==0:3145 parentFound =True3146if self.verbose:3147print"Found parent of%sin commit%s"% (branch, blob)3148break3149if parentFound:3150return blob3151else:3152return None31533154defimportChanges(self, changes):3155 cnt =13156for change in changes:3157 description =p4_describe(change)3158 self.updateOptionDict(description)31593160if not self.silent:3161 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))3162 sys.stdout.flush()3163 cnt = cnt +131643165try:3166if self.detectBranches:3167 branches = self.splitFilesIntoBranches(description)3168for branch in branches.keys():3169## HACK --hwn3170 branchPrefix = self.depotPaths[0] + branch +"/"3171 self.branchPrefixes = [ branchPrefix ]31723173 parent =""31743175 filesForCommit = branches[branch]31763177if self.verbose:3178print"branch is%s"% branch31793180 self.updatedBranches.add(branch)31813182if branch not in self.createdBranches:3183 self.createdBranches.add(branch)3184 parent = self.knownBranches[branch]3185if parent == branch:3186 parent =""3187else:3188 fullBranch = self.projectName + branch3189if fullBranch not in self.p4BranchesInGit:3190if not self.silent:3191print("\nImporting new branch%s"% fullBranch);3192if self.importNewBranch(branch, change -1):3193 parent =""3194 self.p4BranchesInGit.append(fullBranch)3195if not self.silent:3196print("\nResuming with change%s"% change);31973198if self.verbose:3199print"parent determined through known branches:%s"% parent32003201 branch = self.gitRefForBranch(branch)3202 parent = self.gitRefForBranch(parent)32033204if self.verbose:3205print"looking for initial parent for%s; current parent is%s"% (branch, parent)32063207iflen(parent) ==0and branch in self.initialParents:3208 parent = self.initialParents[branch]3209del self.initialParents[branch]32103211 blob =None3212iflen(parent) >0:3213 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3214if self.verbose:3215print"Creating temporary branch: "+ tempBranch3216 self.commit(description, filesForCommit, tempBranch)3217 self.tempBranches.append(tempBranch)3218 self.checkpoint()3219 blob = self.searchParent(parent, branch, tempBranch)3220if blob:3221 self.commit(description, filesForCommit, branch, blob)3222else:3223if self.verbose:3224print"Parent of%snot found. Committing into head of%s"% (branch, parent)3225 self.commit(description, filesForCommit, branch, parent)3226else:3227 files = self.extractFilesFromCommit(description)3228 self.commit(description, files, self.branch,3229 self.initialParent)3230# only needed once, to connect to the previous commit3231 self.initialParent =""3232exceptIOError:3233print self.gitError.read()3234 sys.exit(1)32353236defimportHeadRevision(self, revision):3237print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)32383239 details = {}3240 details["user"] ="git perforce import user"3241 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3242% (' '.join(self.depotPaths), revision))3243 details["change"] = revision3244 newestRevision =032453246 fileCnt =03247 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]32483249for info inp4CmdList(["files"] + fileArgs):32503251if'code'in info and info['code'] =='error':3252 sys.stderr.write("p4 returned an error:%s\n"3253% info['data'])3254if info['data'].find("must refer to client") >=0:3255 sys.stderr.write("This particular p4 error is misleading.\n")3256 sys.stderr.write("Perhaps the depot path was misspelled.\n");3257 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3258 sys.exit(1)3259if'p4ExitCode'in info:3260 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3261 sys.exit(1)326232633264 change =int(info["change"])3265if change > newestRevision:3266 newestRevision = change32673268if info["action"]in self.delete_actions:3269# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3270#fileCnt = fileCnt + 13271continue32723273for prop in["depotFile","rev","action","type"]:3274 details["%s%s"% (prop, fileCnt)] = info[prop]32753276 fileCnt = fileCnt +132773278 details["change"] = newestRevision32793280# Use time from top-most change so that all git p4 clones of3281# the same p4 repo have the same commit SHA1s.3282 res =p4_describe(newestRevision)3283 details["time"] = res["time"]32843285 self.updateOptionDict(details)3286try:3287 self.commit(details, self.extractFilesFromCommit(details), self.branch)3288exceptIOError:3289print"IO error with git fast-import. Is your git version recent enough?"3290print self.gitError.read()329132923293defrun(self, args):3294 self.depotPaths = []3295 self.changeRange =""3296 self.previousDepotPaths = []3297 self.hasOrigin =False32983299# map from branch depot path to parent branch3300 self.knownBranches = {}3301 self.initialParents = {}33023303if self.importIntoRemotes:3304 self.refPrefix ="refs/remotes/p4/"3305else:3306 self.refPrefix ="refs/heads/p4/"33073308if self.syncWithOrigin:3309 self.hasOrigin =originP4BranchesExist()3310if self.hasOrigin:3311if not self.silent:3312print'Syncing with origin first, using "git fetch origin"'3313system("git fetch origin")33143315 branch_arg_given =bool(self.branch)3316iflen(self.branch) ==0:3317 self.branch = self.refPrefix +"master"3318ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3319system("git update-ref%srefs/heads/p4"% self.branch)3320system("git branch -D p4")33213322# accept either the command-line option, or the configuration variable3323if self.useClientSpec:3324# will use this after clone to set the variable3325 self.useClientSpec_from_options =True3326else:3327ifgitConfigBool("git-p4.useclientspec"):3328 self.useClientSpec =True3329if self.useClientSpec:3330 self.clientSpecDirs =getClientSpec()33313332# TODO: should always look at previous commits,3333# merge with previous imports, if possible.3334if args == []:3335if self.hasOrigin:3336createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)33373338# branches holds mapping from branch name to sha13339 branches =p4BranchesInGit(self.importIntoRemotes)33403341# restrict to just this one, disabling detect-branches3342if branch_arg_given:3343 short = self.branch.split("/")[-1]3344if short in branches:3345 self.p4BranchesInGit = [ short ]3346else:3347 self.p4BranchesInGit = branches.keys()33483349iflen(self.p4BranchesInGit) >1:3350if not self.silent:3351print"Importing from/into multiple branches"3352 self.detectBranches =True3353for branch in branches.keys():3354 self.initialParents[self.refPrefix + branch] = \3355 branches[branch]33563357if self.verbose:3358print"branches:%s"% self.p4BranchesInGit33593360 p4Change =03361for branch in self.p4BranchesInGit:3362 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)33633364 settings =extractSettingsGitLog(logMsg)33653366 self.readOptions(settings)3367if(settings.has_key('depot-paths')3368and settings.has_key('change')):3369 change =int(settings['change']) +13370 p4Change =max(p4Change, change)33713372 depotPaths =sorted(settings['depot-paths'])3373if self.previousDepotPaths == []:3374 self.previousDepotPaths = depotPaths3375else:3376 paths = []3377for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3378 prev_list = prev.split("/")3379 cur_list = cur.split("/")3380for i inrange(0,min(len(cur_list),len(prev_list))):3381if cur_list[i] <> prev_list[i]:3382 i = i -13383break33843385 paths.append("/".join(cur_list[:i +1]))33863387 self.previousDepotPaths = paths33883389if p4Change >0:3390 self.depotPaths =sorted(self.previousDepotPaths)3391 self.changeRange ="@%s,#head"% p4Change3392if not self.silent and not self.detectBranches:3393print"Performing incremental import into%sgit branch"% self.branch33943395# accept multiple ref name abbreviations:3396# refs/foo/bar/branch -> use it exactly3397# p4/branch -> prepend refs/remotes/ or refs/heads/3398# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3399if not self.branch.startswith("refs/"):3400if self.importIntoRemotes:3401 prepend ="refs/remotes/"3402else:3403 prepend ="refs/heads/"3404if not self.branch.startswith("p4/"):3405 prepend +="p4/"3406 self.branch = prepend + self.branch34073408iflen(args) ==0and self.depotPaths:3409if not self.silent:3410print"Depot paths:%s"%' '.join(self.depotPaths)3411else:3412if self.depotPaths and self.depotPaths != args:3413print("previous import used depot path%sand now%swas specified. "3414"This doesn't work!"% (' '.join(self.depotPaths),3415' '.join(args)))3416 sys.exit(1)34173418 self.depotPaths =sorted(args)34193420 revision =""3421 self.users = {}34223423# Make sure no revision specifiers are used when --changesfile3424# is specified.3425 bad_changesfile =False3426iflen(self.changesFile) >0:3427for p in self.depotPaths:3428if p.find("@") >=0or p.find("#") >=0:3429 bad_changesfile =True3430break3431if bad_changesfile:3432die("Option --changesfile is incompatible with revision specifiers")34333434 newPaths = []3435for p in self.depotPaths:3436if p.find("@") != -1:3437 atIdx = p.index("@")3438 self.changeRange = p[atIdx:]3439if self.changeRange =="@all":3440 self.changeRange =""3441elif','not in self.changeRange:3442 revision = self.changeRange3443 self.changeRange =""3444 p = p[:atIdx]3445elif p.find("#") != -1:3446 hashIdx = p.index("#")3447 revision = p[hashIdx:]3448 p = p[:hashIdx]3449elif self.previousDepotPaths == []:3450# pay attention to changesfile, if given, else import3451# the entire p4 tree at the head revision3452iflen(self.changesFile) ==0:3453 revision ="#head"34543455 p = re.sub("\.\.\.$","", p)3456if not p.endswith("/"):3457 p +="/"34583459 newPaths.append(p)34603461 self.depotPaths = newPaths34623463# --detect-branches may change this for each branch3464 self.branchPrefixes = self.depotPaths34653466 self.loadUserMapFromCache()3467 self.labels = {}3468if self.detectLabels:3469 self.getLabels();34703471if self.detectBranches:3472## FIXME - what's a P4 projectName ?3473 self.projectName = self.guessProjectName()34743475if self.hasOrigin:3476 self.getBranchMappingFromGitBranches()3477else:3478 self.getBranchMapping()3479if self.verbose:3480print"p4-git branches:%s"% self.p4BranchesInGit3481print"initial parents:%s"% self.initialParents3482for b in self.p4BranchesInGit:3483if b !="master":34843485## FIXME3486 b = b[len(self.projectName):]3487 self.createdBranches.add(b)34883489 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))34903491 self.importProcess = subprocess.Popen(["git","fast-import"],3492 stdin=subprocess.PIPE,3493 stdout=subprocess.PIPE,3494 stderr=subprocess.PIPE);3495 self.gitOutput = self.importProcess.stdout3496 self.gitStream = self.importProcess.stdin3497 self.gitError = self.importProcess.stderr34983499if revision:3500 self.importHeadRevision(revision)3501else:3502 changes = []35033504iflen(self.changesFile) >0:3505 output =open(self.changesFile).readlines()3506 changeSet =set()3507for line in output:3508 changeSet.add(int(line))35093510for change in changeSet:3511 changes.append(change)35123513 changes.sort()3514else:3515# catch "git p4 sync" with no new branches, in a repo that3516# does not have any existing p4 branches3517iflen(args) ==0:3518if not self.p4BranchesInGit:3519die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")35203521# The default branch is master, unless --branch is used to3522# specify something else. Make sure it exists, or complain3523# nicely about how to use --branch.3524if not self.detectBranches:3525if notbranch_exists(self.branch):3526if branch_arg_given:3527die("Error: branch%sdoes not exist."% self.branch)3528else:3529die("Error: no branch%s; perhaps specify one with --branch."%3530 self.branch)35313532if self.verbose:3533print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3534 self.changeRange)3535 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)35363537iflen(self.maxChanges) >0:3538 changes = changes[:min(int(self.maxChanges),len(changes))]35393540iflen(changes) ==0:3541if not self.silent:3542print"No changes to import!"3543else:3544if not self.silent and not self.detectBranches:3545print"Import destination:%s"% self.branch35463547 self.updatedBranches =set()35483549if not self.detectBranches:3550if args:3551# start a new branch3552 self.initialParent =""3553else:3554# build on a previous revision3555 self.initialParent =parseRevision(self.branch)35563557 self.importChanges(changes)35583559if not self.silent:3560print""3561iflen(self.updatedBranches) >0:3562 sys.stdout.write("Updated branches: ")3563for b in self.updatedBranches:3564 sys.stdout.write("%s"% b)3565 sys.stdout.write("\n")35663567ifgitConfigBool("git-p4.importLabels"):3568 self.importLabels =True35693570if self.importLabels:3571 p4Labels =getP4Labels(self.depotPaths)3572 gitTags =getGitTags()35733574 missingP4Labels = p4Labels - gitTags3575 self.importP4Labels(self.gitStream, missingP4Labels)35763577 self.gitStream.close()3578if self.importProcess.wait() !=0:3579die("fast-import failed:%s"% self.gitError.read())3580 self.gitOutput.close()3581 self.gitError.close()35823583# Cleanup temporary branches created during import3584if self.tempBranches != []:3585for branch in self.tempBranches:3586read_pipe("git update-ref -d%s"% branch)3587 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))35883589# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3590# a convenient shortcut refname "p4".3591if self.importIntoRemotes:3592 head_ref = self.refPrefix +"HEAD"3593if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3594system(["git","symbolic-ref", head_ref, self.branch])35953596return True35973598classP4Rebase(Command):3599def__init__(self):3600 Command.__init__(self)3601 self.options = [3602 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3603]3604 self.importLabels =False3605 self.description = ("Fetches the latest revision from perforce and "3606+"rebases the current work (branch) against it")36073608defrun(self, args):3609 sync =P4Sync()3610 sync.importLabels = self.importLabels3611 sync.run([])36123613return self.rebase()36143615defrebase(self):3616if os.system("git update-index --refresh") !=0:3617die("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.");3618iflen(read_pipe("git diff-index HEAD --")) >0:3619die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");36203621[upstream, settings] =findUpstreamBranchPoint()3622iflen(upstream) ==0:3623die("Cannot find upstream branchpoint for rebase")36243625# the branchpoint may be p4/foo~3, so strip off the parent3626 upstream = re.sub("~[0-9]+$","", upstream)36273628print"Rebasing the current branch onto%s"% upstream3629 oldHead =read_pipe("git rev-parse HEAD").strip()3630system("git rebase%s"% upstream)3631system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3632return True36333634classP4Clone(P4Sync):3635def__init__(self):3636 P4Sync.__init__(self)3637 self.description ="Creates a new git repository and imports from Perforce into it"3638 self.usage ="usage: %prog [options] //depot/path[@revRange]"3639 self.options += [3640 optparse.make_option("--destination", dest="cloneDestination",3641 action='store', default=None,3642help="where to leave result of the clone"),3643 optparse.make_option("--bare", dest="cloneBare",3644 action="store_true", default=False),3645]3646 self.cloneDestination =None3647 self.needsGit =False3648 self.cloneBare =False36493650defdefaultDestination(self, args):3651## TODO: use common prefix of args?3652 depotPath = args[0]3653 depotDir = re.sub("(@[^@]*)$","", depotPath)3654 depotDir = re.sub("(#[^#]*)$","", depotDir)3655 depotDir = re.sub(r"\.\.\.$","", depotDir)3656 depotDir = re.sub(r"/$","", depotDir)3657return os.path.split(depotDir)[1]36583659defrun(self, args):3660iflen(args) <1:3661return False36623663if self.keepRepoPath and not self.cloneDestination:3664 sys.stderr.write("Must specify destination for --keep-path\n")3665 sys.exit(1)36663667 depotPaths = args36683669if not self.cloneDestination andlen(depotPaths) >1:3670 self.cloneDestination = depotPaths[-1]3671 depotPaths = depotPaths[:-1]36723673 self.cloneExclude = ["/"+p for p in self.cloneExclude]3674for p in depotPaths:3675if not p.startswith("//"):3676 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3677return False36783679if not self.cloneDestination:3680 self.cloneDestination = self.defaultDestination(args)36813682print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)36833684if not os.path.exists(self.cloneDestination):3685 os.makedirs(self.cloneDestination)3686chdir(self.cloneDestination)36873688 init_cmd = ["git","init"]3689if self.cloneBare:3690 init_cmd.append("--bare")3691 retcode = subprocess.call(init_cmd)3692if retcode:3693raiseCalledProcessError(retcode, init_cmd)36943695if not P4Sync.run(self, depotPaths):3696return False36973698# create a master branch and check out a work tree3699ifgitBranchExists(self.branch):3700system(["git","branch","master", self.branch ])3701if not self.cloneBare:3702system(["git","checkout","-f"])3703else:3704print'Not checking out any branch, use ' \3705'"git checkout -q -b master <branch>"'37063707# auto-set this variable if invoked with --use-client-spec3708if self.useClientSpec_from_options:3709system("git config --bool git-p4.useclientspec true")37103711return True37123713classP4Branches(Command):3714def__init__(self):3715 Command.__init__(self)3716 self.options = [ ]3717 self.description = ("Shows the git branches that hold imports and their "3718+"corresponding perforce depot paths")3719 self.verbose =False37203721defrun(self, args):3722iforiginP4BranchesExist():3723createOrUpdateBranchesFromOrigin()37243725 cmdline ="git rev-parse --symbolic "3726 cmdline +=" --remotes"37273728for line inread_pipe_lines(cmdline):3729 line = line.strip()37303731if not line.startswith('p4/')or line =="p4/HEAD":3732continue3733 branch = line37343735 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3736 settings =extractSettingsGitLog(log)37373738print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3739return True37403741classHelpFormatter(optparse.IndentedHelpFormatter):3742def__init__(self):3743 optparse.IndentedHelpFormatter.__init__(self)37443745defformat_description(self, description):3746if description:3747return description +"\n"3748else:3749return""37503751defprintUsage(commands):3752print"usage:%s<command> [options]"% sys.argv[0]3753print""3754print"valid commands:%s"%", ".join(commands)3755print""3756print"Try%s<command> --help for command specific help."% sys.argv[0]3757print""37583759commands = {3760"debug": P4Debug,3761"submit": P4Submit,3762"commit": P4Submit,3763"sync": P4Sync,3764"rebase": P4Rebase,3765"clone": P4Clone,3766"rollback": P4RollBack,3767"branches": P4Branches3768}376937703771defmain():3772iflen(sys.argv[1:]) ==0:3773printUsage(commands.keys())3774 sys.exit(2)37753776 cmdName = sys.argv[1]3777try:3778 klass = commands[cmdName]3779 cmd =klass()3780exceptKeyError:3781print"unknown command%s"% cmdName3782print""3783printUsage(commands.keys())3784 sys.exit(2)37853786 options = cmd.options3787 cmd.gitdir = os.environ.get("GIT_DIR",None)37883789 args = sys.argv[2:]37903791 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3792if cmd.needsGit:3793 options.append(optparse.make_option("--git-dir", dest="gitdir"))37943795 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3796 options,3797 description = cmd.description,3798 formatter =HelpFormatter())37993800(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3801global verbose3802 verbose = cmd.verbose3803if cmd.needsGit:3804if cmd.gitdir ==None:3805 cmd.gitdir = os.path.abspath(".git")3806if notisValidGitDir(cmd.gitdir):3807# "rev-parse --git-dir" without arguments will try $PWD/.git3808 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3809if os.path.exists(cmd.gitdir):3810 cdup =read_pipe("git rev-parse --show-cdup").strip()3811iflen(cdup) >0:3812chdir(cdup);38133814if notisValidGitDir(cmd.gitdir):3815ifisValidGitDir(cmd.gitdir +"/.git"):3816 cmd.gitdir +="/.git"3817else:3818die("fatal: cannot locate git repository at%s"% cmd.gitdir)38193820# so git commands invoked from the P4 workspace will succeed3821 os.environ["GIT_DIR"] = cmd.gitdir38223823if not cmd.run(args):3824 parser.print_help()3825 sys.exit(2)382638273828if __name__ =='__main__':3829main()