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 28 29try: 30from subprocess import CalledProcessError 31exceptImportError: 32# from python2.7:subprocess.py 33# Exception classes used by this module. 34classCalledProcessError(Exception): 35"""This exception is raised when a process run by check_call() returns 36 a non-zero exit status. The exit status will be stored in the 37 returncode attribute.""" 38def__init__(self, returncode, cmd): 39 self.returncode = returncode 40 self.cmd = cmd 41def__str__(self): 42return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 43 44verbose =False 45 46# Only labels/tags matching this will be imported/exported 47defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 48 49# Grab changes in blocks of this many revisions, unless otherwise requested 50defaultBlockSize =512 51 52defp4_build_cmd(cmd): 53"""Build a suitable p4 command line. 54 55 This consolidates building and returning a p4 command line into one 56 location. It means that hooking into the environment, or other configuration 57 can be done more easily. 58 """ 59 real_cmd = ["p4"] 60 61 user =gitConfig("git-p4.user") 62iflen(user) >0: 63 real_cmd += ["-u",user] 64 65 password =gitConfig("git-p4.password") 66iflen(password) >0: 67 real_cmd += ["-P", password] 68 69 port =gitConfig("git-p4.port") 70iflen(port) >0: 71 real_cmd += ["-p", port] 72 73 host =gitConfig("git-p4.host") 74iflen(host) >0: 75 real_cmd += ["-H", host] 76 77 client =gitConfig("git-p4.client") 78iflen(client) >0: 79 real_cmd += ["-c", client] 80 81 82ifisinstance(cmd,basestring): 83 real_cmd =' '.join(real_cmd) +' '+ cmd 84else: 85 real_cmd += cmd 86return real_cmd 87 88defchdir(path, is_client_path=False): 89"""Do chdir to the given path, and set the PWD environment 90 variable for use by P4. It does not look at getcwd() output. 91 Since we're not using the shell, it is necessary to set the 92 PWD environment variable explicitly. 93 94 Normally, expand the path to force it to be absolute. This 95 addresses the use of relative path names inside P4 settings, 96 e.g. P4CONFIG=.p4config. P4 does not simply open the filename 97 as given; it looks for .p4config using PWD. 98 99 If is_client_path, the path was handed to us directly by p4, 100 and may be a symbolic link. Do not call os.getcwd() in this 101 case, because it will cause p4 to think that PWD is not inside 102 the client path. 103 """ 104 105 os.chdir(path) 106if not is_client_path: 107 path = os.getcwd() 108 os.environ['PWD'] = path 109 110defcalcDiskFree(): 111"""Return free space in bytes on the disk of the given dirname.""" 112if platform.system() =='Windows': 113 free_bytes = ctypes.c_ulonglong(0) 114 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()),None,None, ctypes.pointer(free_bytes)) 115return free_bytes.value 116else: 117 st = os.statvfs(os.getcwd()) 118return st.f_bavail * st.f_frsize 119 120defdie(msg): 121if verbose: 122raiseException(msg) 123else: 124 sys.stderr.write(msg +"\n") 125 sys.exit(1) 126 127defwrite_pipe(c, stdin): 128if verbose: 129 sys.stderr.write('Writing pipe:%s\n'%str(c)) 130 131 expand =isinstance(c,basestring) 132 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 133 pipe = p.stdin 134 val = pipe.write(stdin) 135 pipe.close() 136if p.wait(): 137die('Command failed:%s'%str(c)) 138 139return val 140 141defp4_write_pipe(c, stdin): 142 real_cmd =p4_build_cmd(c) 143returnwrite_pipe(real_cmd, stdin) 144 145defread_pipe(c, ignore_error=False): 146if verbose: 147 sys.stderr.write('Reading pipe:%s\n'%str(c)) 148 149 expand =isinstance(c,basestring) 150 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand) 151(out, err) = p.communicate() 152if p.returncode !=0and not ignore_error: 153die('Command failed:%s\nError:%s'% (str(c), err)) 154return out 155 156defp4_read_pipe(c, ignore_error=False): 157 real_cmd =p4_build_cmd(c) 158returnread_pipe(real_cmd, ignore_error) 159 160defread_pipe_lines(c): 161if verbose: 162 sys.stderr.write('Reading pipe:%s\n'%str(c)) 163 164 expand =isinstance(c, basestring) 165 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 166 pipe = p.stdout 167 val = pipe.readlines() 168if pipe.close()or p.wait(): 169die('Command failed:%s'%str(c)) 170 171return val 172 173defp4_read_pipe_lines(c): 174"""Specifically invoke p4 on the command supplied. """ 175 real_cmd =p4_build_cmd(c) 176returnread_pipe_lines(real_cmd) 177 178defp4_has_command(cmd): 179"""Ask p4 for help on this command. If it returns an error, the 180 command does not exist in this version of p4.""" 181 real_cmd =p4_build_cmd(["help", cmd]) 182 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 183 stderr=subprocess.PIPE) 184 p.communicate() 185return p.returncode ==0 186 187defp4_has_move_command(): 188"""See if the move command exists, that it supports -k, and that 189 it has not been administratively disabled. The arguments 190 must be correct, but the filenames do not have to exist. Use 191 ones with wildcards so even if they exist, it will fail.""" 192 193if notp4_has_command("move"): 194return False 195 cmd =p4_build_cmd(["move","-k","@from","@to"]) 196 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 197(out, err) = p.communicate() 198# return code will be 1 in either case 199if err.find("Invalid option") >=0: 200return False 201if err.find("disabled") >=0: 202return False 203# assume it failed because @... was invalid changelist 204return True 205 206defsystem(cmd): 207 expand =isinstance(cmd,basestring) 208if verbose: 209 sys.stderr.write("executing%s\n"%str(cmd)) 210 retcode = subprocess.call(cmd, shell=expand) 211if retcode: 212raiseCalledProcessError(retcode, cmd) 213 214defp4_system(cmd): 215"""Specifically invoke p4 as the system command. """ 216 real_cmd =p4_build_cmd(cmd) 217 expand =isinstance(real_cmd, basestring) 218 retcode = subprocess.call(real_cmd, shell=expand) 219if retcode: 220raiseCalledProcessError(retcode, real_cmd) 221 222_p4_version_string =None 223defp4_version_string(): 224"""Read the version string, showing just the last line, which 225 hopefully is the interesting version bit. 226 227 $ p4 -V 228 Perforce - The Fast Software Configuration Management System. 229 Copyright 1995-2011 Perforce Software. All rights reserved. 230 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 231 """ 232global _p4_version_string 233if not _p4_version_string: 234 a =p4_read_pipe_lines(["-V"]) 235 _p4_version_string = a[-1].rstrip() 236return _p4_version_string 237 238defp4_integrate(src, dest): 239p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 240 241defp4_sync(f, *options): 242p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 243 244defp4_add(f): 245# forcibly add file names with wildcards 246ifwildcard_present(f): 247p4_system(["add","-f", f]) 248else: 249p4_system(["add", f]) 250 251defp4_delete(f): 252p4_system(["delete",wildcard_encode(f)]) 253 254defp4_edit(f): 255p4_system(["edit",wildcard_encode(f)]) 256 257defp4_revert(f): 258p4_system(["revert",wildcard_encode(f)]) 259 260defp4_reopen(type, f): 261p4_system(["reopen","-t",type,wildcard_encode(f)]) 262 263defp4_move(src, dest): 264p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 265 266defp4_last_change(): 267 results =p4CmdList(["changes","-m","1"]) 268returnint(results[0]['change']) 269 270defp4_describe(change): 271"""Make sure it returns a valid result by checking for 272 the presence of field "time". Return a dict of the 273 results.""" 274 275 ds =p4CmdList(["describe","-s",str(change)]) 276iflen(ds) !=1: 277die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 278 279 d = ds[0] 280 281if"p4ExitCode"in d: 282die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 283str(d))) 284if"code"in d: 285if d["code"] =="error": 286die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 287 288if"time"not in d: 289die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 290 291return d 292 293# 294# Canonicalize the p4 type and return a tuple of the 295# base type, plus any modifiers. See "p4 help filetypes" 296# for a list and explanation. 297# 298defsplit_p4_type(p4type): 299 300 p4_filetypes_historical = { 301"ctempobj":"binary+Sw", 302"ctext":"text+C", 303"cxtext":"text+Cx", 304"ktext":"text+k", 305"kxtext":"text+kx", 306"ltext":"text+F", 307"tempobj":"binary+FSw", 308"ubinary":"binary+F", 309"uresource":"resource+F", 310"uxbinary":"binary+Fx", 311"xbinary":"binary+x", 312"xltext":"text+Fx", 313"xtempobj":"binary+Swx", 314"xtext":"text+x", 315"xunicode":"unicode+x", 316"xutf16":"utf16+x", 317} 318if p4type in p4_filetypes_historical: 319 p4type = p4_filetypes_historical[p4type] 320 mods ="" 321 s = p4type.split("+") 322 base = s[0] 323 mods ="" 324iflen(s) >1: 325 mods = s[1] 326return(base, mods) 327 328# 329# return the raw p4 type of a file (text, text+ko, etc) 330# 331defp4_type(f): 332 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 333return results[0]['headType'] 334 335# 336# Given a type base and modifier, return a regexp matching 337# the keywords that can be expanded in the file 338# 339defp4_keywords_regexp_for_type(base, type_mods): 340if base in("text","unicode","binary"): 341 kwords =None 342if"ko"in type_mods: 343 kwords ='Id|Header' 344elif"k"in type_mods: 345 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 346else: 347return None 348 pattern = r""" 349 \$ # Starts with a dollar, followed by... 350 (%s) # one of the keywords, followed by... 351 (:[^$\n]+)? # possibly an old expansion, followed by... 352 \$ # another dollar 353 """% kwords 354return pattern 355else: 356return None 357 358# 359# Given a file, return a regexp matching the possible 360# RCS keywords that will be expanded, or None for files 361# with kw expansion turned off. 362# 363defp4_keywords_regexp_for_file(file): 364if not os.path.exists(file): 365return None 366else: 367(type_base, type_mods) =split_p4_type(p4_type(file)) 368returnp4_keywords_regexp_for_type(type_base, type_mods) 369 370defsetP4ExecBit(file, mode): 371# Reopens an already open file and changes the execute bit to match 372# the execute bit setting in the passed in mode. 373 374 p4Type ="+x" 375 376if notisModeExec(mode): 377 p4Type =getP4OpenedType(file) 378 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 379 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 380if p4Type[-1] =="+": 381 p4Type = p4Type[0:-1] 382 383p4_reopen(p4Type,file) 384 385defgetP4OpenedType(file): 386# Returns the perforce file type for the given file. 387 388 result =p4_read_pipe(["opened",wildcard_encode(file)]) 389 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 390if match: 391return match.group(1) 392else: 393die("Could not determine file type for%s(result: '%s')"% (file, result)) 394 395# Return the set of all p4 labels 396defgetP4Labels(depotPaths): 397 labels =set() 398ifisinstance(depotPaths,basestring): 399 depotPaths = [depotPaths] 400 401for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 402 label = l['label'] 403 labels.add(label) 404 405return labels 406 407# Return the set of all git tags 408defgetGitTags(): 409 gitTags =set() 410for line inread_pipe_lines(["git","tag"]): 411 tag = line.strip() 412 gitTags.add(tag) 413return gitTags 414 415defdiffTreePattern(): 416# This is a simple generator for the diff tree regex pattern. This could be 417# a class variable if this and parseDiffTreeEntry were a part of a class. 418 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 419while True: 420yield pattern 421 422defparseDiffTreeEntry(entry): 423"""Parses a single diff tree entry into its component elements. 424 425 See git-diff-tree(1) manpage for details about the format of the diff 426 output. This method returns a dictionary with the following elements: 427 428 src_mode - The mode of the source file 429 dst_mode - The mode of the destination file 430 src_sha1 - The sha1 for the source file 431 dst_sha1 - The sha1 fr the destination file 432 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 433 status_score - The score for the status (applicable for 'C' and 'R' 434 statuses). This is None if there is no score. 435 src - The path for the source file. 436 dst - The path for the destination file. This is only present for 437 copy or renames. If it is not present, this is None. 438 439 If the pattern is not matched, None is returned.""" 440 441 match =diffTreePattern().next().match(entry) 442if match: 443return{ 444'src_mode': match.group(1), 445'dst_mode': match.group(2), 446'src_sha1': match.group(3), 447'dst_sha1': match.group(4), 448'status': match.group(5), 449'status_score': match.group(6), 450'src': match.group(7), 451'dst': match.group(10) 452} 453return None 454 455defisModeExec(mode): 456# Returns True if the given git mode represents an executable file, 457# otherwise False. 458return mode[-3:] =="755" 459 460defisModeExecChanged(src_mode, dst_mode): 461returnisModeExec(src_mode) !=isModeExec(dst_mode) 462 463defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 464 465ifisinstance(cmd,basestring): 466 cmd ="-G "+ cmd 467 expand =True 468else: 469 cmd = ["-G"] + cmd 470 expand =False 471 472 cmd =p4_build_cmd(cmd) 473if verbose: 474 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 475 476# Use a temporary file to avoid deadlocks without 477# subprocess.communicate(), which would put another copy 478# of stdout into memory. 479 stdin_file =None 480if stdin is not None: 481 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 482ifisinstance(stdin,basestring): 483 stdin_file.write(stdin) 484else: 485for i in stdin: 486 stdin_file.write(i +'\n') 487 stdin_file.flush() 488 stdin_file.seek(0) 489 490 p4 = subprocess.Popen(cmd, 491 shell=expand, 492 stdin=stdin_file, 493 stdout=subprocess.PIPE) 494 495 result = [] 496try: 497while True: 498 entry = marshal.load(p4.stdout) 499if cb is not None: 500cb(entry) 501else: 502 result.append(entry) 503exceptEOFError: 504pass 505 exitCode = p4.wait() 506if exitCode !=0: 507 entry = {} 508 entry["p4ExitCode"] = exitCode 509 result.append(entry) 510 511return result 512 513defp4Cmd(cmd): 514list=p4CmdList(cmd) 515 result = {} 516for entry inlist: 517 result.update(entry) 518return result; 519 520defp4Where(depotPath): 521if not depotPath.endswith("/"): 522 depotPath +="/" 523 depotPathLong = depotPath +"..." 524 outputList =p4CmdList(["where", depotPathLong]) 525 output =None 526for entry in outputList: 527if"depotFile"in entry: 528# Search for the base client side depot path, as long as it starts with the branch's P4 path. 529# The base path always ends with "/...". 530if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 531 output = entry 532break 533elif"data"in entry: 534 data = entry.get("data") 535 space = data.find(" ") 536if data[:space] == depotPath: 537 output = entry 538break 539if output ==None: 540return"" 541if output["code"] =="error": 542return"" 543 clientPath ="" 544if"path"in output: 545 clientPath = output.get("path") 546elif"data"in output: 547 data = output.get("data") 548 lastSpace = data.rfind(" ") 549 clientPath = data[lastSpace +1:] 550 551if clientPath.endswith("..."): 552 clientPath = clientPath[:-3] 553return clientPath 554 555defcurrentGitBranch(): 556returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 557 558defisValidGitDir(path): 559if(os.path.exists(path +"/HEAD") 560and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 561return True; 562return False 563 564defparseRevision(ref): 565returnread_pipe("git rev-parse%s"% ref).strip() 566 567defbranchExists(ref): 568 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 569 ignore_error=True) 570returnlen(rev) >0 571 572defextractLogMessageFromGitCommit(commit): 573 logMessage ="" 574 575## fixme: title is first line of commit, not 1st paragraph. 576 foundTitle =False 577for log inread_pipe_lines("git cat-file commit%s"% commit): 578if not foundTitle: 579iflen(log) ==1: 580 foundTitle =True 581continue 582 583 logMessage += log 584return logMessage 585 586defextractSettingsGitLog(log): 587 values = {} 588for line in log.split("\n"): 589 line = line.strip() 590 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 591if not m: 592continue 593 594 assignments = m.group(1).split(':') 595for a in assignments: 596 vals = a.split('=') 597 key = vals[0].strip() 598 val = ('='.join(vals[1:])).strip() 599if val.endswith('\"')and val.startswith('"'): 600 val = val[1:-1] 601 602 values[key] = val 603 604 paths = values.get("depot-paths") 605if not paths: 606 paths = values.get("depot-path") 607if paths: 608 values['depot-paths'] = paths.split(',') 609return values 610 611defgitBranchExists(branch): 612 proc = subprocess.Popen(["git","rev-parse", branch], 613 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 614return proc.wait() ==0; 615 616_gitConfig = {} 617 618defgitConfig(key, typeSpecifier=None): 619if not _gitConfig.has_key(key): 620 cmd = ["git","config"] 621if typeSpecifier: 622 cmd += [ typeSpecifier ] 623 cmd += [ key ] 624 s =read_pipe(cmd, ignore_error=True) 625 _gitConfig[key] = s.strip() 626return _gitConfig[key] 627 628defgitConfigBool(key): 629"""Return a bool, using git config --bool. It is True only if the 630 variable is set to true, and False if set to false or not present 631 in the config.""" 632 633if not _gitConfig.has_key(key): 634 _gitConfig[key] =gitConfig(key,'--bool') =="true" 635return _gitConfig[key] 636 637defgitConfigInt(key): 638if not _gitConfig.has_key(key): 639 cmd = ["git","config","--int", key ] 640 s =read_pipe(cmd, ignore_error=True) 641 v = s.strip() 642try: 643 _gitConfig[key] =int(gitConfig(key,'--int')) 644exceptValueError: 645 _gitConfig[key] =None 646return _gitConfig[key] 647 648defgitConfigList(key): 649if not _gitConfig.has_key(key): 650 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 651 _gitConfig[key] = s.strip().split(os.linesep) 652if _gitConfig[key] == ['']: 653 _gitConfig[key] = [] 654return _gitConfig[key] 655 656defp4BranchesInGit(branchesAreInRemotes=True): 657"""Find all the branches whose names start with "p4/", looking 658 in remotes or heads as specified by the argument. Return 659 a dictionary of{ branch: revision }for each one found. 660 The branch names are the short names, without any 661 "p4/" prefix.""" 662 663 branches = {} 664 665 cmdline ="git rev-parse --symbolic " 666if branchesAreInRemotes: 667 cmdline +="--remotes" 668else: 669 cmdline +="--branches" 670 671for line inread_pipe_lines(cmdline): 672 line = line.strip() 673 674# only import to p4/ 675if not line.startswith('p4/'): 676continue 677# special symbolic ref to p4/master 678if line =="p4/HEAD": 679continue 680 681# strip off p4/ prefix 682 branch = line[len("p4/"):] 683 684 branches[branch] =parseRevision(line) 685 686return branches 687 688defbranch_exists(branch): 689"""Make sure that the given ref name really exists.""" 690 691 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 692 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 693 out, _ = p.communicate() 694if p.returncode: 695return False 696# expect exactly one line of output: the branch name 697return out.rstrip() == branch 698 699deffindUpstreamBranchPoint(head ="HEAD"): 700 branches =p4BranchesInGit() 701# map from depot-path to branch name 702 branchByDepotPath = {} 703for branch in branches.keys(): 704 tip = branches[branch] 705 log =extractLogMessageFromGitCommit(tip) 706 settings =extractSettingsGitLog(log) 707if settings.has_key("depot-paths"): 708 paths =",".join(settings["depot-paths"]) 709 branchByDepotPath[paths] ="remotes/p4/"+ branch 710 711 settings =None 712 parent =0 713while parent <65535: 714 commit = head +"~%s"% parent 715 log =extractLogMessageFromGitCommit(commit) 716 settings =extractSettingsGitLog(log) 717if settings.has_key("depot-paths"): 718 paths =",".join(settings["depot-paths"]) 719if branchByDepotPath.has_key(paths): 720return[branchByDepotPath[paths], settings] 721 722 parent = parent +1 723 724return["", settings] 725 726defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 727if not silent: 728print("Creating/updating branch(es) in%sbased on origin branch(es)" 729% localRefPrefix) 730 731 originPrefix ="origin/p4/" 732 733for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 734 line = line.strip() 735if(not line.startswith(originPrefix))or line.endswith("HEAD"): 736continue 737 738 headName = line[len(originPrefix):] 739 remoteHead = localRefPrefix + headName 740 originHead = line 741 742 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 743if(not original.has_key('depot-paths') 744or not original.has_key('change')): 745continue 746 747 update =False 748if notgitBranchExists(remoteHead): 749if verbose: 750print"creating%s"% remoteHead 751 update =True 752else: 753 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 754if settings.has_key('change') >0: 755if settings['depot-paths'] == original['depot-paths']: 756 originP4Change =int(original['change']) 757 p4Change =int(settings['change']) 758if originP4Change > p4Change: 759print("%s(%s) is newer than%s(%s). " 760"Updating p4 branch from origin." 761% (originHead, originP4Change, 762 remoteHead, p4Change)) 763 update =True 764else: 765print("Ignoring:%swas imported from%swhile " 766"%swas imported from%s" 767% (originHead,','.join(original['depot-paths']), 768 remoteHead,','.join(settings['depot-paths']))) 769 770if update: 771system("git update-ref%s %s"% (remoteHead, originHead)) 772 773deforiginP4BranchesExist(): 774returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 775 776 777defp4ParseNumericChangeRange(parts): 778 changeStart =int(parts[0][1:]) 779if parts[1] =='#head': 780 changeEnd =p4_last_change() 781else: 782 changeEnd =int(parts[1]) 783 784return(changeStart, changeEnd) 785 786defchooseBlockSize(blockSize): 787if blockSize: 788return blockSize 789else: 790return defaultBlockSize 791 792defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 793assert depotPaths 794 795# Parse the change range into start and end. Try to find integer 796# revision ranges as these can be broken up into blocks to avoid 797# hitting server-side limits (maxrows, maxscanresults). But if 798# that doesn't work, fall back to using the raw revision specifier 799# strings, without using block mode. 800 801if changeRange is None or changeRange =='': 802 changeStart =1 803 changeEnd =p4_last_change() 804 block_size =chooseBlockSize(requestedBlockSize) 805else: 806 parts = changeRange.split(',') 807assertlen(parts) ==2 808try: 809(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 810 block_size =chooseBlockSize(requestedBlockSize) 811except: 812 changeStart = parts[0][1:] 813 changeEnd = parts[1] 814if requestedBlockSize: 815die("cannot use --changes-block-size with non-numeric revisions") 816 block_size =None 817 818# Accumulate change numbers in a dictionary to avoid duplicates 819 changes = {} 820 821for p in depotPaths: 822# Retrieve changes a block at a time, to prevent running 823# into a MaxResults/MaxScanRows error from the server. 824 825while True: 826 cmd = ['changes'] 827 828if block_size: 829 end =min(changeEnd, changeStart + block_size) 830 revisionRange ="%d,%d"% (changeStart, end) 831else: 832 revisionRange ="%s,%s"% (changeStart, changeEnd) 833 834 cmd += ["%s...@%s"% (p, revisionRange)] 835 836for line inp4_read_pipe_lines(cmd): 837 changeNum =int(line.split(" ")[1]) 838 changes[changeNum] =True 839 840if not block_size: 841break 842 843if end >= changeEnd: 844break 845 846 changeStart = end +1 847 848 changelist = changes.keys() 849 changelist.sort() 850return changelist 851 852defp4PathStartsWith(path, prefix): 853# This method tries to remedy a potential mixed-case issue: 854# 855# If UserA adds //depot/DirA/file1 856# and UserB adds //depot/dira/file2 857# 858# we may or may not have a problem. If you have core.ignorecase=true, 859# we treat DirA and dira as the same directory 860ifgitConfigBool("core.ignorecase"): 861return path.lower().startswith(prefix.lower()) 862return path.startswith(prefix) 863 864defgetClientSpec(): 865"""Look at the p4 client spec, create a View() object that contains 866 all the mappings, and return it.""" 867 868 specList =p4CmdList("client -o") 869iflen(specList) !=1: 870die('Output from "client -o" is%dlines, expecting 1'% 871len(specList)) 872 873# dictionary of all client parameters 874 entry = specList[0] 875 876# the //client/ name 877 client_name = entry["Client"] 878 879# just the keys that start with "View" 880 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 881 882# hold this new View 883 view =View(client_name) 884 885# append the lines, in order, to the view 886for view_num inrange(len(view_keys)): 887 k ="View%d"% view_num 888if k not in view_keys: 889die("Expected view key%smissing"% k) 890 view.append(entry[k]) 891 892return view 893 894defgetClientRoot(): 895"""Grab the client directory.""" 896 897 output =p4CmdList("client -o") 898iflen(output) !=1: 899die('Output from "client -o" is%dlines, expecting 1'%len(output)) 900 901 entry = output[0] 902if"Root"not in entry: 903die('Client has no "Root"') 904 905return entry["Root"] 906 907# 908# P4 wildcards are not allowed in filenames. P4 complains 909# if you simply add them, but you can force it with "-f", in 910# which case it translates them into %xx encoding internally. 911# 912defwildcard_decode(path): 913# Search for and fix just these four characters. Do % last so 914# that fixing it does not inadvertently create new %-escapes. 915# Cannot have * in a filename in windows; untested as to 916# what p4 would do in such a case. 917if not platform.system() =="Windows": 918 path = path.replace("%2A","*") 919 path = path.replace("%23","#") \ 920.replace("%40","@") \ 921.replace("%25","%") 922return path 923 924defwildcard_encode(path): 925# do % first to avoid double-encoding the %s introduced here 926 path = path.replace("%","%25") \ 927.replace("*","%2A") \ 928.replace("#","%23") \ 929.replace("@","%40") 930return path 931 932defwildcard_present(path): 933 m = re.search("[*#@%]", path) 934return m is not None 935 936classLargeFileSystem(object): 937"""Base class for large file system support.""" 938 939def__init__(self, writeToGitStream): 940 self.largeFiles =set() 941 self.writeToGitStream = writeToGitStream 942 943defgeneratePointer(self, cloneDestination, contentFile): 944"""Return the content of a pointer file that is stored in Git instead of 945 the actual content.""" 946assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 947 948defpushFile(self, localLargeFile): 949"""Push the actual content which is not stored in the Git repository to 950 a server.""" 951assert False,"Method 'pushFile' required in "+ self.__class__.__name__ 952 953defhasLargeFileExtension(self, relPath): 954returnreduce( 955lambda a, b: a or b, 956[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')], 957False 958) 959 960defgenerateTempFile(self, contents): 961 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 962for d in contents: 963 contentFile.write(d) 964 contentFile.close() 965return contentFile.name 966 967defexceedsLargeFileThreshold(self, relPath, contents): 968ifgitConfigInt('git-p4.largeFileThreshold'): 969 contentsSize =sum(len(d)for d in contents) 970if contentsSize >gitConfigInt('git-p4.largeFileThreshold'): 971return True 972ifgitConfigInt('git-p4.largeFileCompressedThreshold'): 973 contentsSize =sum(len(d)for d in contents) 974if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'): 975return False 976 contentTempFile = self.generateTempFile(contents) 977 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 978 zf = zipfile.ZipFile(compressedContentFile.name, mode='w') 979 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) 980 zf.close() 981 compressedContentsSize = zf.infolist()[0].compress_size 982 os.remove(contentTempFile) 983 os.remove(compressedContentFile.name) 984if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'): 985return True 986return False 987 988defaddLargeFile(self, relPath): 989 self.largeFiles.add(relPath) 990 991defremoveLargeFile(self, relPath): 992 self.largeFiles.remove(relPath) 993 994defisLargeFile(self, relPath): 995return relPath in self.largeFiles 996 997defprocessContent(self, git_mode, relPath, contents): 998"""Processes the content of git fast import. This method decides if a 999 file is stored in the large file system and handles all necessary1000 steps."""1001if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1002 contentTempFile = self.generateTempFile(contents)1003(git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)10041005# Move temp file to final location in large file system1006 largeFileDir = os.path.dirname(localLargeFile)1007if not os.path.isdir(largeFileDir):1008 os.makedirs(largeFileDir)1009 shutil.move(contentTempFile, localLargeFile)1010 self.addLargeFile(relPath)1011ifgitConfigBool('git-p4.largeFilePush'):1012 self.pushFile(localLargeFile)1013if verbose:1014 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1015return(git_mode, contents)10161017classMockLFS(LargeFileSystem):1018"""Mock large file system for testing."""10191020defgeneratePointer(self, contentFile):1021"""The pointer content is the original content prefixed with "pointer-".1022 The local filename of the large file storage is derived from the file content.1023 """1024withopen(contentFile,'r')as f:1025 content =next(f)1026 gitMode ='100644'1027 pointerContents ='pointer-'+ content1028 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1029return(gitMode, pointerContents, localLargeFile)10301031defpushFile(self, localLargeFile):1032"""The remote filename of the large file storage is the same as the local1033 one but in a different directory.1034 """1035 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1036if not os.path.exists(remotePath):1037 os.makedirs(remotePath)1038 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10391040classGitLFS(LargeFileSystem):1041"""Git LFS as backend for the git-p4 large file system.1042 See https://git-lfs.github.com/ for details."""10431044def__init__(self, *args):1045 LargeFileSystem.__init__(self, *args)1046 self.baseGitAttributes = []10471048defgeneratePointer(self, contentFile):1049"""Generate a Git LFS pointer for the content. Return LFS Pointer file1050 mode and content which is stored in the Git repository instead of1051 the actual content. Return also the new location of the actual1052 content.1053 """1054 pointerProcess = subprocess.Popen(1055['git','lfs','pointer','--file='+ contentFile],1056 stdout=subprocess.PIPE1057)1058 pointerFile = pointerProcess.stdout.read()1059if pointerProcess.wait():1060 os.remove(contentFile)1061die('git-lfs pointer command failed. Did you install the extension?')1062 pointerContents = [i+'\n'for i in pointerFile.split('\n')[2:][:-1]]1063 oid = pointerContents[1].split(' ')[1].split(':')[1][:-1]1064 localLargeFile = os.path.join(1065 os.getcwd(),1066'.git','lfs','objects', oid[:2], oid[2:4],1067 oid,1068)1069# LFS Spec states that pointer files should not have the executable bit set.1070 gitMode ='100644'1071return(gitMode, pointerContents, localLargeFile)10721073defpushFile(self, localLargeFile):1074 uploadProcess = subprocess.Popen(1075['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1076)1077if uploadProcess.wait():1078die('git-lfs push command failed. Did you define a remote?')10791080defgenerateGitAttributes(self):1081return(1082 self.baseGitAttributes +1083[1084'\n',1085'#\n',1086'# Git LFS (see https://git-lfs.github.com/)\n',1087'#\n',1088] +1089['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1090for f insorted(gitConfigList('git-p4.largeFileExtensions'))1091] +1092['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1093for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1094]1095)10961097defaddLargeFile(self, relPath):1098 LargeFileSystem.addLargeFile(self, relPath)1099 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11001101defremoveLargeFile(self, relPath):1102 LargeFileSystem.removeLargeFile(self, relPath)1103 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11041105defprocessContent(self, git_mode, relPath, contents):1106if relPath =='.gitattributes':1107 self.baseGitAttributes = contents1108return(git_mode, self.generateGitAttributes())1109else:1110return LargeFileSystem.processContent(self, git_mode, relPath, contents)11111112class Command:1113def__init__(self):1114 self.usage ="usage: %prog [options]"1115 self.needsGit =True1116 self.verbose =False11171118class P4UserMap:1119def__init__(self):1120 self.userMapFromPerforceServer =False1121 self.myP4UserId =None11221123defp4UserId(self):1124if self.myP4UserId:1125return self.myP4UserId11261127 results =p4CmdList("user -o")1128for r in results:1129if r.has_key('User'):1130 self.myP4UserId = r['User']1131return r['User']1132die("Could not find your p4 user id")11331134defp4UserIsMe(self, p4User):1135# return True if the given p4 user is actually me1136 me = self.p4UserId()1137if not p4User or p4User != me:1138return False1139else:1140return True11411142defgetUserCacheFilename(self):1143 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1144return home +"/.gitp4-usercache.txt"11451146defgetUserMapFromPerforceServer(self):1147if self.userMapFromPerforceServer:1148return1149 self.users = {}1150 self.emails = {}11511152for output inp4CmdList("users"):1153if not output.has_key("User"):1154continue1155 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1156 self.emails[output["Email"]] = output["User"]115711581159 s =''1160for(key, val)in self.users.items():1161 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11621163open(self.getUserCacheFilename(),"wb").write(s)1164 self.userMapFromPerforceServer =True11651166defloadUserMapFromCache(self):1167 self.users = {}1168 self.userMapFromPerforceServer =False1169try:1170 cache =open(self.getUserCacheFilename(),"rb")1171 lines = cache.readlines()1172 cache.close()1173for line in lines:1174 entry = line.strip().split("\t")1175 self.users[entry[0]] = entry[1]1176exceptIOError:1177 self.getUserMapFromPerforceServer()11781179classP4Debug(Command):1180def__init__(self):1181 Command.__init__(self)1182 self.options = []1183 self.description ="A tool to debug the output of p4 -G."1184 self.needsGit =False11851186defrun(self, args):1187 j =01188for output inp4CmdList(args):1189print'Element:%d'% j1190 j +=11191print output1192return True11931194classP4RollBack(Command):1195def__init__(self):1196 Command.__init__(self)1197 self.options = [1198 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1199]1200 self.description ="A tool to debug the multi-branch import. Don't use :)"1201 self.rollbackLocalBranches =False12021203defrun(self, args):1204iflen(args) !=1:1205return False1206 maxChange =int(args[0])12071208if"p4ExitCode"inp4Cmd("changes -m 1"):1209die("Problems executing p4");12101211if self.rollbackLocalBranches:1212 refPrefix ="refs/heads/"1213 lines =read_pipe_lines("git rev-parse --symbolic --branches")1214else:1215 refPrefix ="refs/remotes/"1216 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12171218for line in lines:1219if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1220 line = line.strip()1221 ref = refPrefix + line1222 log =extractLogMessageFromGitCommit(ref)1223 settings =extractSettingsGitLog(log)12241225 depotPaths = settings['depot-paths']1226 change = settings['change']12271228 changed =False12291230iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1231for p in depotPaths]))) ==0:1232print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1233system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1234continue12351236while change andint(change) > maxChange:1237 changed =True1238if self.verbose:1239print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1240system("git update-ref%s\"%s^\""% (ref, ref))1241 log =extractLogMessageFromGitCommit(ref)1242 settings =extractSettingsGitLog(log)124312441245 depotPaths = settings['depot-paths']1246 change = settings['change']12471248if changed:1249print"%srewound to%s"% (ref, change)12501251return True12521253classP4Submit(Command, P4UserMap):12541255 conflict_behavior_choices = ("ask","skip","quit")12561257def__init__(self):1258 Command.__init__(self)1259 P4UserMap.__init__(self)1260 self.options = [1261 optparse.make_option("--origin", dest="origin"),1262 optparse.make_option("-M", dest="detectRenames", action="store_true"),1263# preserve the user, requires relevant p4 permissions1264 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1265 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1266 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1267 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1268 optparse.make_option("--conflict", dest="conflict_behavior",1269 choices=self.conflict_behavior_choices),1270 optparse.make_option("--branch", dest="branch"),1271]1272 self.description ="Submit changes from git to the perforce depot."1273 self.usage +=" [name of git branch to submit into perforce depot]"1274 self.origin =""1275 self.detectRenames =False1276 self.preserveUser =gitConfigBool("git-p4.preserveUser")1277 self.dry_run =False1278 self.prepare_p4_only =False1279 self.conflict_behavior =None1280 self.isWindows = (platform.system() =="Windows")1281 self.exportLabels =False1282 self.p4HasMoveCommand =p4_has_move_command()1283 self.branch =None12841285ifgitConfig('git-p4.largeFileSystem'):1286die("Large file system not supported for git-p4 submit command. Please remove it from config.")12871288defcheck(self):1289iflen(p4CmdList("opened ...")) >0:1290die("You have files opened with perforce! Close them before starting the sync.")12911292defseparate_jobs_from_description(self, message):1293"""Extract and return a possible Jobs field in the commit1294 message. It goes into a separate section in the p4 change1295 specification.12961297 A jobs line starts with "Jobs:" and looks like a new field1298 in a form. Values are white-space separated on the same1299 line or on following lines that start with a tab.13001301 This does not parse and extract the full git commit message1302 like a p4 form. It just sees the Jobs: line as a marker1303 to pass everything from then on directly into the p4 form,1304 but outside the description section.13051306 Return a tuple (stripped log message, jobs string)."""13071308 m = re.search(r'^Jobs:', message, re.MULTILINE)1309if m is None:1310return(message,None)13111312 jobtext = message[m.start():]1313 stripped_message = message[:m.start()].rstrip()1314return(stripped_message, jobtext)13151316defprepareLogMessage(self, template, message, jobs):1317"""Edits the template returned from "p4 change -o" to insert1318 the message in the Description field, and the jobs text in1319 the Jobs field."""1320 result =""13211322 inDescriptionSection =False13231324for line in template.split("\n"):1325if line.startswith("#"):1326 result += line +"\n"1327continue13281329if inDescriptionSection:1330if line.startswith("Files:")or line.startswith("Jobs:"):1331 inDescriptionSection =False1332# insert Jobs section1333if jobs:1334 result += jobs +"\n"1335else:1336continue1337else:1338if line.startswith("Description:"):1339 inDescriptionSection =True1340 line +="\n"1341for messageLine in message.split("\n"):1342 line +="\t"+ messageLine +"\n"13431344 result += line +"\n"13451346return result13471348defpatchRCSKeywords(self,file, pattern):1349# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1350(handle, outFileName) = tempfile.mkstemp(dir='.')1351try:1352 outFile = os.fdopen(handle,"w+")1353 inFile =open(file,"r")1354 regexp = re.compile(pattern, re.VERBOSE)1355for line in inFile.readlines():1356 line = regexp.sub(r'$\1$', line)1357 outFile.write(line)1358 inFile.close()1359 outFile.close()1360# Forcibly overwrite the original file1361 os.unlink(file)1362 shutil.move(outFileName,file)1363except:1364# cleanup our temporary file1365 os.unlink(outFileName)1366print"Failed to strip RCS keywords in%s"%file1367raise13681369print"Patched up RCS keywords in%s"%file13701371defp4UserForCommit(self,id):1372# Return the tuple (perforce user,git email) for a given git commit id1373 self.getUserMapFromPerforceServer()1374 gitEmail =read_pipe(["git","log","--max-count=1",1375"--format=%ae",id])1376 gitEmail = gitEmail.strip()1377if not self.emails.has_key(gitEmail):1378return(None,gitEmail)1379else:1380return(self.emails[gitEmail],gitEmail)13811382defcheckValidP4Users(self,commits):1383# check if any git authors cannot be mapped to p4 users1384foridin commits:1385(user,email) = self.p4UserForCommit(id)1386if not user:1387 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1388ifgitConfigBool("git-p4.allowMissingP4Users"):1389print"%s"% msg1390else:1391die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)13921393deflastP4Changelist(self):1394# Get back the last changelist number submitted in this client spec. This1395# then gets used to patch up the username in the change. If the same1396# client spec is being used by multiple processes then this might go1397# wrong.1398 results =p4CmdList("client -o")# find the current client1399 client =None1400for r in results:1401if r.has_key('Client'):1402 client = r['Client']1403break1404if not client:1405die("could not get client spec")1406 results =p4CmdList(["changes","-c", client,"-m","1"])1407for r in results:1408if r.has_key('change'):1409return r['change']1410die("Could not get changelist number for last submit - cannot patch up user details")14111412defmodifyChangelistUser(self, changelist, newUser):1413# fixup the user field of a changelist after it has been submitted.1414 changes =p4CmdList("change -o%s"% changelist)1415iflen(changes) !=1:1416die("Bad output from p4 change modifying%sto user%s"%1417(changelist, newUser))14181419 c = changes[0]1420if c['User'] == newUser:return# nothing to do1421 c['User'] = newUser1422input= marshal.dumps(c)14231424 result =p4CmdList("change -f -i", stdin=input)1425for r in result:1426if r.has_key('code'):1427if r['code'] =='error':1428die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1429if r.has_key('data'):1430print("Updated user field for changelist%sto%s"% (changelist, newUser))1431return1432die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14331434defcanChangeChangelists(self):1435# check to see if we have p4 admin or super-user permissions, either of1436# which are required to modify changelists.1437 results =p4CmdList(["protects", self.depotPath])1438for r in results:1439if r.has_key('perm'):1440if r['perm'] =='admin':1441return11442if r['perm'] =='super':1443return11444return014451446defprepareSubmitTemplate(self):1447"""Run "p4 change -o" to grab a change specification template.1448 This does not use "p4 -G", as it is nice to keep the submission1449 template in original order, since a human might edit it.14501451 Remove lines in the Files section that show changes to files1452 outside the depot path we're committing into."""14531454 template =""1455 inFilesSection =False1456for line inp4_read_pipe_lines(['change','-o']):1457if line.endswith("\r\n"):1458 line = line[:-2] +"\n"1459if inFilesSection:1460if line.startswith("\t"):1461# path starts and ends with a tab1462 path = line[1:]1463 lastTab = path.rfind("\t")1464if lastTab != -1:1465 path = path[:lastTab]1466if notp4PathStartsWith(path, self.depotPath):1467continue1468else:1469 inFilesSection =False1470else:1471if line.startswith("Files:"):1472 inFilesSection =True14731474 template += line14751476return template14771478defedit_template(self, template_file):1479"""Invoke the editor to let the user change the submission1480 message. Return true if okay to continue with the submit."""14811482# if configured to skip the editing part, just submit1483ifgitConfigBool("git-p4.skipSubmitEdit"):1484return True14851486# look at the modification time, to check later if the user saved1487# the file1488 mtime = os.stat(template_file).st_mtime14891490# invoke the editor1491if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1492 editor = os.environ.get("P4EDITOR")1493else:1494 editor =read_pipe("git var GIT_EDITOR").strip()1495system(["sh","-c", ('%s"$@"'% editor), editor, template_file])14961497# If the file was not saved, prompt to see if this patch should1498# be skipped. But skip this verification step if configured so.1499ifgitConfigBool("git-p4.skipSubmitEditCheck"):1500return True15011502# modification time updated means user saved the file1503if os.stat(template_file).st_mtime > mtime:1504return True15051506while True:1507 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1508if response =='y':1509return True1510if response =='n':1511return False15121513defget_diff_description(self, editedFiles, filesToAdd):1514# diff1515if os.environ.has_key("P4DIFF"):1516del(os.environ["P4DIFF"])1517 diff =""1518for editedFile in editedFiles:1519 diff +=p4_read_pipe(['diff','-du',1520wildcard_encode(editedFile)])15211522# new file diff1523 newdiff =""1524for newFile in filesToAdd:1525 newdiff +="==== new file ====\n"1526 newdiff +="--- /dev/null\n"1527 newdiff +="+++%s\n"% newFile1528 f =open(newFile,"r")1529for line in f.readlines():1530 newdiff +="+"+ line1531 f.close()15321533return(diff + newdiff).replace('\r\n','\n')15341535defapplyCommit(self,id):1536"""Apply one commit, return True if it succeeded."""15371538print"Applying",read_pipe(["git","show","-s",1539"--format=format:%h%s",id])15401541(p4User, gitEmail) = self.p4UserForCommit(id)15421543 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1544 filesToAdd =set()1545 filesToDelete =set()1546 editedFiles =set()1547 pureRenameCopy =set()1548 filesToChangeExecBit = {}15491550for line in diff:1551 diff =parseDiffTreeEntry(line)1552 modifier = diff['status']1553 path = diff['src']1554if modifier =="M":1555p4_edit(path)1556ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1557 filesToChangeExecBit[path] = diff['dst_mode']1558 editedFiles.add(path)1559elif modifier =="A":1560 filesToAdd.add(path)1561 filesToChangeExecBit[path] = diff['dst_mode']1562if path in filesToDelete:1563 filesToDelete.remove(path)1564elif modifier =="D":1565 filesToDelete.add(path)1566if path in filesToAdd:1567 filesToAdd.remove(path)1568elif modifier =="C":1569 src, dest = diff['src'], diff['dst']1570p4_integrate(src, dest)1571 pureRenameCopy.add(dest)1572if diff['src_sha1'] != diff['dst_sha1']:1573p4_edit(dest)1574 pureRenameCopy.discard(dest)1575ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1576p4_edit(dest)1577 pureRenameCopy.discard(dest)1578 filesToChangeExecBit[dest] = diff['dst_mode']1579if self.isWindows:1580# turn off read-only attribute1581 os.chmod(dest, stat.S_IWRITE)1582 os.unlink(dest)1583 editedFiles.add(dest)1584elif modifier =="R":1585 src, dest = diff['src'], diff['dst']1586if self.p4HasMoveCommand:1587p4_edit(src)# src must be open before move1588p4_move(src, dest)# opens for (move/delete, move/add)1589else:1590p4_integrate(src, dest)1591if diff['src_sha1'] != diff['dst_sha1']:1592p4_edit(dest)1593else:1594 pureRenameCopy.add(dest)1595ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1596if not self.p4HasMoveCommand:1597p4_edit(dest)# with move: already open, writable1598 filesToChangeExecBit[dest] = diff['dst_mode']1599if not self.p4HasMoveCommand:1600if self.isWindows:1601 os.chmod(dest, stat.S_IWRITE)1602 os.unlink(dest)1603 filesToDelete.add(src)1604 editedFiles.add(dest)1605else:1606die("unknown modifier%sfor%s"% (modifier, path))16071608 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1609 patchcmd = diffcmd +" | git apply "1610 tryPatchCmd = patchcmd +"--check -"1611 applyPatchCmd = patchcmd +"--check --apply -"1612 patch_succeeded =True16131614if os.system(tryPatchCmd) !=0:1615 fixed_rcs_keywords =False1616 patch_succeeded =False1617print"Unfortunately applying the change failed!"16181619# Patch failed, maybe it's just RCS keyword woes. Look through1620# the patch to see if that's possible.1621ifgitConfigBool("git-p4.attemptRCSCleanup"):1622file=None1623 pattern =None1624 kwfiles = {}1625forfilein editedFiles | filesToDelete:1626# did this file's delta contain RCS keywords?1627 pattern =p4_keywords_regexp_for_file(file)16281629if pattern:1630# this file is a possibility...look for RCS keywords.1631 regexp = re.compile(pattern, re.VERBOSE)1632for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1633if regexp.search(line):1634if verbose:1635print"got keyword match on%sin%sin%s"% (pattern, line,file)1636 kwfiles[file] = pattern1637break16381639forfilein kwfiles:1640if verbose:1641print"zapping%swith%s"% (line,pattern)1642# File is being deleted, so not open in p4. Must1643# disable the read-only bit on windows.1644if self.isWindows andfilenot in editedFiles:1645 os.chmod(file, stat.S_IWRITE)1646 self.patchRCSKeywords(file, kwfiles[file])1647 fixed_rcs_keywords =True16481649if fixed_rcs_keywords:1650print"Retrying the patch with RCS keywords cleaned up"1651if os.system(tryPatchCmd) ==0:1652 patch_succeeded =True16531654if not patch_succeeded:1655for f in editedFiles:1656p4_revert(f)1657return False16581659#1660# Apply the patch for real, and do add/delete/+x handling.1661#1662system(applyPatchCmd)16631664for f in filesToAdd:1665p4_add(f)1666for f in filesToDelete:1667p4_revert(f)1668p4_delete(f)16691670# Set/clear executable bits1671for f in filesToChangeExecBit.keys():1672 mode = filesToChangeExecBit[f]1673setP4ExecBit(f, mode)16741675#1676# Build p4 change description, starting with the contents1677# of the git commit message.1678#1679 logMessage =extractLogMessageFromGitCommit(id)1680 logMessage = logMessage.strip()1681(logMessage, jobs) = self.separate_jobs_from_description(logMessage)16821683 template = self.prepareSubmitTemplate()1684 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)16851686if self.preserveUser:1687 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User16881689if self.checkAuthorship and not self.p4UserIsMe(p4User):1690 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1691 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1692 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"16931694 separatorLine ="######## everything below this line is just the diff #######\n"1695if not self.prepare_p4_only:1696 submitTemplate += separatorLine1697 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)16981699(handle, fileName) = tempfile.mkstemp()1700 tmpFile = os.fdopen(handle,"w+b")1701if self.isWindows:1702 submitTemplate = submitTemplate.replace("\n","\r\n")1703 tmpFile.write(submitTemplate)1704 tmpFile.close()17051706if self.prepare_p4_only:1707#1708# Leave the p4 tree prepared, and the submit template around1709# and let the user decide what to do next1710#1711print1712print"P4 workspace prepared for submission."1713print"To submit or revert, go to client workspace"1714print" "+ self.clientPath1715print1716print"To submit, use\"p4 submit\"to write a new description,"1717print"or\"p4 submit -i <%s\"to use the one prepared by" \1718"\"git p4\"."% fileName1719print"You can delete the file\"%s\"when finished."% fileName17201721if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1722print"To preserve change ownership by user%s, you must\n" \1723"do\"p4 change -f <change>\"after submitting and\n" \1724"edit the User field."1725if pureRenameCopy:1726print"After submitting, renamed files must be re-synced."1727print"Invoke\"p4 sync -f\"on each of these files:"1728for f in pureRenameCopy:1729print" "+ f17301731print1732print"To revert the changes, use\"p4 revert ...\", and delete"1733print"the submit template file\"%s\""% fileName1734if filesToAdd:1735print"Since the commit adds new files, they must be deleted:"1736for f in filesToAdd:1737print" "+ f1738print1739return True17401741#1742# Let the user edit the change description, then submit it.1743#1744if self.edit_template(fileName):1745# read the edited message and submit1746 ret =True1747 tmpFile =open(fileName,"rb")1748 message = tmpFile.read()1749 tmpFile.close()1750if self.isWindows:1751 message = message.replace("\r\n","\n")1752 submitTemplate = message[:message.index(separatorLine)]1753p4_write_pipe(['submit','-i'], submitTemplate)17541755if self.preserveUser:1756if p4User:1757# Get last changelist number. Cannot easily get it from1758# the submit command output as the output is1759# unmarshalled.1760 changelist = self.lastP4Changelist()1761 self.modifyChangelistUser(changelist, p4User)17621763# The rename/copy happened by applying a patch that created a1764# new file. This leaves it writable, which confuses p4.1765for f in pureRenameCopy:1766p4_sync(f,"-f")17671768else:1769# skip this patch1770 ret =False1771print"Submission cancelled, undoing p4 changes."1772for f in editedFiles:1773p4_revert(f)1774for f in filesToAdd:1775p4_revert(f)1776 os.remove(f)1777for f in filesToDelete:1778p4_revert(f)17791780 os.remove(fileName)1781return ret17821783# Export git tags as p4 labels. Create a p4 label and then tag1784# with that.1785defexportGitTags(self, gitTags):1786 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1787iflen(validLabelRegexp) ==0:1788 validLabelRegexp = defaultLabelRegexp1789 m = re.compile(validLabelRegexp)17901791for name in gitTags:17921793if not m.match(name):1794if verbose:1795print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1796continue17971798# Get the p4 commit this corresponds to1799 logMessage =extractLogMessageFromGitCommit(name)1800 values =extractSettingsGitLog(logMessage)18011802if not values.has_key('change'):1803# a tag pointing to something not sent to p4; ignore1804if verbose:1805print"git tag%sdoes not give a p4 commit"% name1806continue1807else:1808 changelist = values['change']18091810# Get the tag details.1811 inHeader =True1812 isAnnotated =False1813 body = []1814for l inread_pipe_lines(["git","cat-file","-p", name]):1815 l = l.strip()1816if inHeader:1817if re.match(r'tag\s+', l):1818 isAnnotated =True1819elif re.match(r'\s*$', l):1820 inHeader =False1821continue1822else:1823 body.append(l)18241825if not isAnnotated:1826 body = ["lightweight tag imported by git p4\n"]18271828# Create the label - use the same view as the client spec we are using1829 clientSpec =getClientSpec()18301831 labelTemplate ="Label:%s\n"% name1832 labelTemplate +="Description:\n"1833for b in body:1834 labelTemplate +="\t"+ b +"\n"1835 labelTemplate +="View:\n"1836for depot_side in clientSpec.mappings:1837 labelTemplate +="\t%s\n"% depot_side18381839if self.dry_run:1840print"Would create p4 label%sfor tag"% name1841elif self.prepare_p4_only:1842print"Not creating p4 label%sfor tag due to option" \1843" --prepare-p4-only"% name1844else:1845p4_write_pipe(["label","-i"], labelTemplate)18461847# Use the label1848p4_system(["tag","-l", name] +1849["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18501851if verbose:1852print"created p4 label for tag%s"% name18531854defrun(self, args):1855iflen(args) ==0:1856 self.master =currentGitBranch()1857iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1858die("Detecting current git branch failed!")1859eliflen(args) ==1:1860 self.master = args[0]1861if notbranchExists(self.master):1862die("Branch%sdoes not exist"% self.master)1863else:1864return False18651866 allowSubmit =gitConfig("git-p4.allowSubmit")1867iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1868die("%sis not in git-p4.allowSubmit"% self.master)18691870[upstream, settings] =findUpstreamBranchPoint()1871 self.depotPath = settings['depot-paths'][0]1872iflen(self.origin) ==0:1873 self.origin = upstream18741875if self.preserveUser:1876if not self.canChangeChangelists():1877die("Cannot preserve user names without p4 super-user or admin permissions")18781879# if not set from the command line, try the config file1880if self.conflict_behavior is None:1881 val =gitConfig("git-p4.conflict")1882if val:1883if val not in self.conflict_behavior_choices:1884die("Invalid value '%s' for config git-p4.conflict"% val)1885else:1886 val ="ask"1887 self.conflict_behavior = val18881889if self.verbose:1890print"Origin branch is "+ self.origin18911892iflen(self.depotPath) ==0:1893print"Internal error: cannot locate perforce depot path from existing branches"1894 sys.exit(128)18951896 self.useClientSpec =False1897ifgitConfigBool("git-p4.useclientspec"):1898 self.useClientSpec =True1899if self.useClientSpec:1900 self.clientSpecDirs =getClientSpec()19011902# Check for the existance of P4 branches1903 branchesDetected = (len(p4BranchesInGit().keys()) >1)19041905if self.useClientSpec and not branchesDetected:1906# all files are relative to the client spec1907 self.clientPath =getClientRoot()1908else:1909 self.clientPath =p4Where(self.depotPath)19101911if self.clientPath =="":1912die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19131914print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1915 self.oldWorkingDirectory = os.getcwd()19161917# ensure the clientPath exists1918 new_client_dir =False1919if not os.path.exists(self.clientPath):1920 new_client_dir =True1921 os.makedirs(self.clientPath)19221923chdir(self.clientPath, is_client_path=True)1924if self.dry_run:1925print"Would synchronize p4 checkout in%s"% self.clientPath1926else:1927print"Synchronizing p4 checkout..."1928if new_client_dir:1929# old one was destroyed, and maybe nobody told p41930p4_sync("...","-f")1931else:1932p4_sync("...")1933 self.check()19341935 commits = []1936for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, self.master)]):1937 commits.append(line.strip())1938 commits.reverse()19391940if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1941 self.checkAuthorship =False1942else:1943 self.checkAuthorship =True19441945if self.preserveUser:1946 self.checkValidP4Users(commits)19471948#1949# Build up a set of options to be passed to diff when1950# submitting each commit to p4.1951#1952if self.detectRenames:1953# command-line -M arg1954 self.diffOpts ="-M"1955else:1956# If not explicitly set check the config variable1957 detectRenames =gitConfig("git-p4.detectRenames")19581959if detectRenames.lower() =="false"or detectRenames =="":1960 self.diffOpts =""1961elif detectRenames.lower() =="true":1962 self.diffOpts ="-M"1963else:1964 self.diffOpts ="-M%s"% detectRenames19651966# no command-line arg for -C or --find-copies-harder, just1967# config variables1968 detectCopies =gitConfig("git-p4.detectCopies")1969if detectCopies.lower() =="false"or detectCopies =="":1970pass1971elif detectCopies.lower() =="true":1972 self.diffOpts +=" -C"1973else:1974 self.diffOpts +=" -C%s"% detectCopies19751976ifgitConfigBool("git-p4.detectCopiesHarder"):1977 self.diffOpts +=" --find-copies-harder"19781979#1980# Apply the commits, one at a time. On failure, ask if should1981# continue to try the rest of the patches, or quit.1982#1983if self.dry_run:1984print"Would apply"1985 applied = []1986 last =len(commits) -11987for i, commit inenumerate(commits):1988if self.dry_run:1989print" ",read_pipe(["git","show","-s",1990"--format=format:%h%s", commit])1991 ok =True1992else:1993 ok = self.applyCommit(commit)1994if ok:1995 applied.append(commit)1996else:1997if self.prepare_p4_only and i < last:1998print"Processing only the first commit due to option" \1999" --prepare-p4-only"2000break2001if i < last:2002 quit =False2003while True:2004# prompt for what to do, or use the option/variable2005if self.conflict_behavior =="ask":2006print"What do you want to do?"2007 response =raw_input("[s]kip this commit but apply"2008" the rest, or [q]uit? ")2009if not response:2010continue2011elif self.conflict_behavior =="skip":2012 response ="s"2013elif self.conflict_behavior =="quit":2014 response ="q"2015else:2016die("Unknown conflict_behavior '%s'"%2017 self.conflict_behavior)20182019if response[0] =="s":2020print"Skipping this commit, but applying the rest"2021break2022if response[0] =="q":2023print"Quitting"2024 quit =True2025break2026if quit:2027break20282029chdir(self.oldWorkingDirectory)20302031if self.dry_run:2032pass2033elif self.prepare_p4_only:2034pass2035eliflen(commits) ==len(applied):2036print"All commits applied!"20372038 sync =P4Sync()2039if self.branch:2040 sync.branch = self.branch2041 sync.run([])20422043 rebase =P4Rebase()2044 rebase.rebase()20452046else:2047iflen(applied) ==0:2048print"No commits applied."2049else:2050print"Applied only the commits marked with '*':"2051for c in commits:2052if c in applied:2053 star ="*"2054else:2055 star =" "2056print star,read_pipe(["git","show","-s",2057"--format=format:%h%s", c])2058print"You will have to do 'git p4 sync' and rebase."20592060ifgitConfigBool("git-p4.exportLabels"):2061 self.exportLabels =True20622063if self.exportLabels:2064 p4Labels =getP4Labels(self.depotPath)2065 gitTags =getGitTags()20662067 missingGitTags = gitTags - p4Labels2068 self.exportGitTags(missingGitTags)20692070# exit with error unless everything applied perfectly2071iflen(commits) !=len(applied):2072 sys.exit(1)20732074return True20752076classView(object):2077"""Represent a p4 view ("p4 help views"), and map files in a2078 repo according to the view."""20792080def__init__(self, client_name):2081 self.mappings = []2082 self.client_prefix ="//%s/"% client_name2083# cache results of "p4 where" to lookup client file locations2084 self.client_spec_path_cache = {}20852086defappend(self, view_line):2087"""Parse a view line, splitting it into depot and client2088 sides. Append to self.mappings, preserving order. This2089 is only needed for tag creation."""20902091# Split the view line into exactly two words. P4 enforces2092# structure on these lines that simplifies this quite a bit.2093#2094# Either or both words may be double-quoted.2095# Single quotes do not matter.2096# Double-quote marks cannot occur inside the words.2097# A + or - prefix is also inside the quotes.2098# There are no quotes unless they contain a space.2099# The line is already white-space stripped.2100# The two words are separated by a single space.2101#2102if view_line[0] =='"':2103# First word is double quoted. Find its end.2104 close_quote_index = view_line.find('"',1)2105if close_quote_index <=0:2106die("No first-word closing quote found:%s"% view_line)2107 depot_side = view_line[1:close_quote_index]2108# skip closing quote and space2109 rhs_index = close_quote_index +1+12110else:2111 space_index = view_line.find(" ")2112if space_index <=0:2113die("No word-splitting space found:%s"% view_line)2114 depot_side = view_line[0:space_index]2115 rhs_index = space_index +121162117# prefix + means overlay on previous mapping2118if depot_side.startswith("+"):2119 depot_side = depot_side[1:]21202121# prefix - means exclude this path, leave out of mappings2122 exclude =False2123if depot_side.startswith("-"):2124 exclude =True2125 depot_side = depot_side[1:]21262127if not exclude:2128 self.mappings.append(depot_side)21292130defconvert_client_path(self, clientFile):2131# chop off //client/ part to make it relative2132if not clientFile.startswith(self.client_prefix):2133die("No prefix '%s' on clientFile '%s'"%2134(self.client_prefix, clientFile))2135return clientFile[len(self.client_prefix):]21362137defupdate_client_spec_path_cache(self, files):2138""" Caching file paths by "p4 where" batch query """21392140# List depot file paths exclude that already cached2141 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21422143iflen(fileArgs) ==0:2144return# All files in cache21452146 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2147for res in where_result:2148if"code"in res and res["code"] =="error":2149# assume error is "... file(s) not in client view"2150continue2151if"clientFile"not in res:2152die("No clientFile in 'p4 where' output")2153if"unmap"in res:2154# it will list all of them, but only one not unmap-ped2155continue2156ifgitConfigBool("core.ignorecase"):2157 res['depotFile'] = res['depotFile'].lower()2158 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])21592160# not found files or unmap files set to ""2161for depotFile in fileArgs:2162ifgitConfigBool("core.ignorecase"):2163 depotFile = depotFile.lower()2164if depotFile not in self.client_spec_path_cache:2165 self.client_spec_path_cache[depotFile] =""21662167defmap_in_client(self, depot_path):2168"""Return the relative location in the client where this2169 depot file should live. Returns "" if the file should2170 not be mapped in the client."""21712172ifgitConfigBool("core.ignorecase"):2173 depot_path = depot_path.lower()21742175if depot_path in self.client_spec_path_cache:2176return self.client_spec_path_cache[depot_path]21772178die("Error:%sis not found in client spec path"% depot_path )2179return""21802181classP4Sync(Command, P4UserMap):2182 delete_actions = ("delete","move/delete","purge")21832184def__init__(self):2185 Command.__init__(self)2186 P4UserMap.__init__(self)2187 self.options = [2188 optparse.make_option("--branch", dest="branch"),2189 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2190 optparse.make_option("--changesfile", dest="changesFile"),2191 optparse.make_option("--silent", dest="silent", action="store_true"),2192 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2193 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2194 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2195help="Import into refs/heads/ , not refs/remotes"),2196 optparse.make_option("--max-changes", dest="maxChanges",2197help="Maximum number of changes to import"),2198 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2199help="Internal block size to use when iteratively calling p4 changes"),2200 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2201help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2202 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2203help="Only sync files that are included in the Perforce Client Spec"),2204 optparse.make_option("-/", dest="cloneExclude",2205 action="append",type="string",2206help="exclude depot path"),2207]2208 self.description ="""Imports from Perforce into a git repository.\n2209 example:2210 //depot/my/project/ -- to import the current head2211 //depot/my/project/@all -- to import everything2212 //depot/my/project/@1,6 -- to import only from revision 1 to 622132214 (a ... is not needed in the path p4 specification, it's added implicitly)"""22152216 self.usage +=" //depot/path[@revRange]"2217 self.silent =False2218 self.createdBranches =set()2219 self.committedChanges =set()2220 self.branch =""2221 self.detectBranches =False2222 self.detectLabels =False2223 self.importLabels =False2224 self.changesFile =""2225 self.syncWithOrigin =True2226 self.importIntoRemotes =True2227 self.maxChanges =""2228 self.changes_block_size =None2229 self.keepRepoPath =False2230 self.depotPaths =None2231 self.p4BranchesInGit = []2232 self.cloneExclude = []2233 self.useClientSpec =False2234 self.useClientSpec_from_options =False2235 self.clientSpecDirs =None2236 self.tempBranches = []2237 self.tempBranchLocation ="git-p4-tmp"2238 self.largeFileSystem =None22392240ifgitConfig('git-p4.largeFileSystem'):2241 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2242 self.largeFileSystem =largeFileSystemConstructor(2243lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2244)22452246ifgitConfig("git-p4.syncFromOrigin") =="false":2247 self.syncWithOrigin =False22482249# This is required for the "append" cloneExclude action2250defensure_value(self, attr, value):2251if nothasattr(self, attr)orgetattr(self, attr)is None:2252setattr(self, attr, value)2253returngetattr(self, attr)22542255# Force a checkpoint in fast-import and wait for it to finish2256defcheckpoint(self):2257 self.gitStream.write("checkpoint\n\n")2258 self.gitStream.write("progress checkpoint\n\n")2259 out = self.gitOutput.readline()2260if self.verbose:2261print"checkpoint finished: "+ out22622263defextractFilesFromCommit(self, commit):2264 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2265for path in self.cloneExclude]2266 files = []2267 fnum =02268while commit.has_key("depotFile%s"% fnum):2269 path = commit["depotFile%s"% fnum]22702271if[p for p in self.cloneExclude2272ifp4PathStartsWith(path, p)]:2273 found =False2274else:2275 found = [p for p in self.depotPaths2276ifp4PathStartsWith(path, p)]2277if not found:2278 fnum = fnum +12279continue22802281file= {}2282file["path"] = path2283file["rev"] = commit["rev%s"% fnum]2284file["action"] = commit["action%s"% fnum]2285file["type"] = commit["type%s"% fnum]2286 files.append(file)2287 fnum = fnum +12288return files22892290defstripRepoPath(self, path, prefixes):2291"""When streaming files, this is called to map a p4 depot path2292 to where it should go in git. The prefixes are either2293 self.depotPaths, or self.branchPrefixes in the case of2294 branch detection."""22952296if self.useClientSpec:2297# branch detection moves files up a level (the branch name)2298# from what client spec interpretation gives2299 path = self.clientSpecDirs.map_in_client(path)2300if self.detectBranches:2301for b in self.knownBranches:2302if path.startswith(b +"/"):2303 path = path[len(b)+1:]23042305elif self.keepRepoPath:2306# Preserve everything in relative path name except leading2307# //depot/; just look at first prefix as they all should2308# be in the same depot.2309 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2310ifp4PathStartsWith(path, depot):2311 path = path[len(depot):]23122313else:2314for p in prefixes:2315ifp4PathStartsWith(path, p):2316 path = path[len(p):]2317break23182319 path =wildcard_decode(path)2320return path23212322defsplitFilesIntoBranches(self, commit):2323"""Look at each depotFile in the commit to figure out to what2324 branch it belongs."""23252326if self.clientSpecDirs:2327 files = self.extractFilesFromCommit(commit)2328 self.clientSpecDirs.update_client_spec_path_cache(files)23292330 branches = {}2331 fnum =02332while commit.has_key("depotFile%s"% fnum):2333 path = commit["depotFile%s"% fnum]2334 found = [p for p in self.depotPaths2335ifp4PathStartsWith(path, p)]2336if not found:2337 fnum = fnum +12338continue23392340file= {}2341file["path"] = path2342file["rev"] = commit["rev%s"% fnum]2343file["action"] = commit["action%s"% fnum]2344file["type"] = commit["type%s"% fnum]2345 fnum = fnum +123462347# start with the full relative path where this file would2348# go in a p4 client2349if self.useClientSpec:2350 relPath = self.clientSpecDirs.map_in_client(path)2351else:2352 relPath = self.stripRepoPath(path, self.depotPaths)23532354for branch in self.knownBranches.keys():2355# add a trailing slash so that a commit into qt/4.2foo2356# doesn't end up in qt/4.2, e.g.2357if relPath.startswith(branch +"/"):2358if branch not in branches:2359 branches[branch] = []2360 branches[branch].append(file)2361break23622363return branches23642365defwriteToGitStream(self, gitMode, relPath, contents):2366 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2367 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2368for d in contents:2369 self.gitStream.write(d)2370 self.gitStream.write('\n')23712372# output one file from the P4 stream2373# - helper for streamP4Files23742375defstreamOneP4File(self,file, contents):2376 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2377if verbose:2378 size =int(self.stream_file['fileSize'])2379 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2380 sys.stdout.flush()23812382(type_base, type_mods) =split_p4_type(file["type"])23832384 git_mode ="100644"2385if"x"in type_mods:2386 git_mode ="100755"2387if type_base =="symlink":2388 git_mode ="120000"2389# p4 print on a symlink sometimes contains "target\n";2390# if it does, remove the newline2391 data =''.join(contents)2392if not data:2393# Some version of p4 allowed creating a symlink that pointed2394# to nothing. This causes p4 errors when checking out such2395# a change, and errors here too. Work around it by ignoring2396# the bad symlink; hopefully a future change fixes it.2397print"\nIgnoring empty symlink in%s"%file['depotFile']2398return2399elif data[-1] =='\n':2400 contents = [data[:-1]]2401else:2402 contents = [data]24032404if type_base =="utf16":2405# p4 delivers different text in the python output to -G2406# than it does when using "print -o", or normal p4 client2407# operations. utf16 is converted to ascii or utf8, perhaps.2408# But ascii text saved as -t utf16 is completely mangled.2409# Invoke print -o to get the real contents.2410#2411# On windows, the newlines will always be mangled by print, so put2412# them back too. This is not needed to the cygwin windows version,2413# just the native "NT" type.2414#2415try:2416 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2417exceptExceptionas e:2418if'Translation of file content failed'instr(e):2419 type_base ='binary'2420else:2421raise e2422else:2423ifp4_version_string().find('/NT') >=0:2424 text = text.replace('\r\n','\n')2425 contents = [ text ]24262427if type_base =="apple":2428# Apple filetype files will be streamed as a concatenation of2429# its appledouble header and the contents. This is useless2430# on both macs and non-macs. If using "print -q -o xx", it2431# will create "xx" with the data, and "%xx" with the header.2432# This is also not very useful.2433#2434# Ideally, someday, this script can learn how to generate2435# appledouble files directly and import those to git, but2436# non-mac machines can never find a use for apple filetype.2437print"\nIgnoring apple filetype file%s"%file['depotFile']2438return24392440# Note that we do not try to de-mangle keywords on utf16 files,2441# even though in theory somebody may want that.2442 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2443if pattern:2444 regexp = re.compile(pattern, re.VERBOSE)2445 text =''.join(contents)2446 text = regexp.sub(r'$\1$', text)2447 contents = [ text ]24482449try:2450 relPath.decode('ascii')2451except:2452 encoding ='utf8'2453ifgitConfig('git-p4.pathEncoding'):2454 encoding =gitConfig('git-p4.pathEncoding')2455 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2456if self.verbose:2457print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)24582459if self.largeFileSystem:2460(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)24612462 self.writeToGitStream(git_mode, relPath, contents)24632464defstreamOneP4Deletion(self,file):2465 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2466if verbose:2467 sys.stdout.write("delete%s\n"% relPath)2468 sys.stdout.flush()2469 self.gitStream.write("D%s\n"% relPath)24702471if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2472 self.largeFileSystem.removeLargeFile(relPath)24732474# handle another chunk of streaming data2475defstreamP4FilesCb(self, marshalled):24762477# catch p4 errors and complain2478 err =None2479if"code"in marshalled:2480if marshalled["code"] =="error":2481if"data"in marshalled:2482 err = marshalled["data"].rstrip()24832484if not err and'fileSize'in self.stream_file:2485 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2486if required_bytes >0:2487 err ='Not enough space left on%s! Free at least%iMB.'% (2488 os.getcwd(), required_bytes/1024/10242489)24902491if err:2492 f =None2493if self.stream_have_file_info:2494if"depotFile"in self.stream_file:2495 f = self.stream_file["depotFile"]2496# force a failure in fast-import, else an empty2497# commit will be made2498 self.gitStream.write("\n")2499 self.gitStream.write("die-now\n")2500 self.gitStream.close()2501# ignore errors, but make sure it exits first2502 self.importProcess.wait()2503if f:2504die("Error from p4 print for%s:%s"% (f, err))2505else:2506die("Error from p4 print:%s"% err)25072508if marshalled.has_key('depotFile')and self.stream_have_file_info:2509# start of a new file - output the old one first2510 self.streamOneP4File(self.stream_file, self.stream_contents)2511 self.stream_file = {}2512 self.stream_contents = []2513 self.stream_have_file_info =False25142515# pick up the new file information... for the2516# 'data' field we need to append to our array2517for k in marshalled.keys():2518if k =='data':2519if'streamContentSize'not in self.stream_file:2520 self.stream_file['streamContentSize'] =02521 self.stream_file['streamContentSize'] +=len(marshalled['data'])2522 self.stream_contents.append(marshalled['data'])2523else:2524 self.stream_file[k] = marshalled[k]25252526if(verbose and2527'streamContentSize'in self.stream_file and2528'fileSize'in self.stream_file and2529'depotFile'in self.stream_file):2530 size =int(self.stream_file["fileSize"])2531if size >0:2532 progress =100*self.stream_file['streamContentSize']/size2533 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2534 sys.stdout.flush()25352536 self.stream_have_file_info =True25372538# Stream directly from "p4 files" into "git fast-import"2539defstreamP4Files(self, files):2540 filesForCommit = []2541 filesToRead = []2542 filesToDelete = []25432544for f in files:2545# if using a client spec, only add the files that have2546# a path in the client2547if self.clientSpecDirs:2548if self.clientSpecDirs.map_in_client(f['path']) =="":2549continue25502551 filesForCommit.append(f)2552if f['action']in self.delete_actions:2553 filesToDelete.append(f)2554else:2555 filesToRead.append(f)25562557# deleted files...2558for f in filesToDelete:2559 self.streamOneP4Deletion(f)25602561iflen(filesToRead) >0:2562 self.stream_file = {}2563 self.stream_contents = []2564 self.stream_have_file_info =False25652566# curry self argument2567defstreamP4FilesCbSelf(entry):2568 self.streamP4FilesCb(entry)25692570 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]25712572p4CmdList(["-x","-","print"],2573 stdin=fileArgs,2574 cb=streamP4FilesCbSelf)25752576# do the last chunk2577if self.stream_file.has_key('depotFile'):2578 self.streamOneP4File(self.stream_file, self.stream_contents)25792580defmake_email(self, userid):2581if userid in self.users:2582return self.users[userid]2583else:2584return"%s<a@b>"% userid25852586defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2587""" Stream a p4 tag.2588 commit is either a git commit, or a fast-import mark, ":<p4commit>"2589 """25902591if verbose:2592print"writing tag%sfor commit%s"% (labelName, commit)2593 gitStream.write("tag%s\n"% labelName)2594 gitStream.write("from%s\n"% commit)25952596if labelDetails.has_key('Owner'):2597 owner = labelDetails["Owner"]2598else:2599 owner =None26002601# Try to use the owner of the p4 label, or failing that,2602# the current p4 user id.2603if owner:2604 email = self.make_email(owner)2605else:2606 email = self.make_email(self.p4UserId())2607 tagger ="%s %s %s"% (email, epoch, self.tz)26082609 gitStream.write("tagger%s\n"% tagger)26102611print"labelDetails=",labelDetails2612if labelDetails.has_key('Description'):2613 description = labelDetails['Description']2614else:2615 description ='Label from git p4'26162617 gitStream.write("data%d\n"%len(description))2618 gitStream.write(description)2619 gitStream.write("\n")26202621defcommit(self, details, files, branch, parent =""):2622 epoch = details["time"]2623 author = details["user"]26242625if self.verbose:2626print"commit into%s"% branch26272628# start with reading files; if that fails, we should not2629# create a commit.2630 new_files = []2631for f in files:2632if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2633 new_files.append(f)2634else:2635 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])26362637if self.clientSpecDirs:2638 self.clientSpecDirs.update_client_spec_path_cache(files)26392640 self.gitStream.write("commit%s\n"% branch)2641 self.gitStream.write("mark :%s\n"% details["change"])2642 self.committedChanges.add(int(details["change"]))2643 committer =""2644if author not in self.users:2645 self.getUserMapFromPerforceServer()2646 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)26472648 self.gitStream.write("committer%s\n"% committer)26492650 self.gitStream.write("data <<EOT\n")2651 self.gitStream.write(details["desc"])2652 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2653(','.join(self.branchPrefixes), details["change"]))2654iflen(details['options']) >0:2655 self.gitStream.write(": options =%s"% details['options'])2656 self.gitStream.write("]\nEOT\n\n")26572658iflen(parent) >0:2659if self.verbose:2660print"parent%s"% parent2661 self.gitStream.write("from%s\n"% parent)26622663 self.streamP4Files(new_files)2664 self.gitStream.write("\n")26652666 change =int(details["change"])26672668if self.labels.has_key(change):2669 label = self.labels[change]2670 labelDetails = label[0]2671 labelRevisions = label[1]2672if self.verbose:2673print"Change%sis labelled%s"% (change, labelDetails)26742675 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2676for p in self.branchPrefixes])26772678iflen(files) ==len(labelRevisions):26792680 cleanedFiles = {}2681for info in files:2682if info["action"]in self.delete_actions:2683continue2684 cleanedFiles[info["depotFile"]] = info["rev"]26852686if cleanedFiles == labelRevisions:2687 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)26882689else:2690if not self.silent:2691print("Tag%sdoes not match with change%s: files do not match."2692% (labelDetails["label"], change))26932694else:2695if not self.silent:2696print("Tag%sdoes not match with change%s: file count is different."2697% (labelDetails["label"], change))26982699# Build a dictionary of changelists and labels, for "detect-labels" option.2700defgetLabels(self):2701 self.labels = {}27022703 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2704iflen(l) >0and not self.silent:2705print"Finding files belonging to labels in%s"% `self.depotPaths`27062707for output in l:2708 label = output["label"]2709 revisions = {}2710 newestChange =02711if self.verbose:2712print"Querying files for label%s"% label2713forfileinp4CmdList(["files"] +2714["%s...@%s"% (p, label)2715for p in self.depotPaths]):2716 revisions[file["depotFile"]] =file["rev"]2717 change =int(file["change"])2718if change > newestChange:2719 newestChange = change27202721 self.labels[newestChange] = [output, revisions]27222723if self.verbose:2724print"Label changes:%s"% self.labels.keys()27252726# Import p4 labels as git tags. A direct mapping does not2727# exist, so assume that if all the files are at the same revision2728# then we can use that, or it's something more complicated we should2729# just ignore.2730defimportP4Labels(self, stream, p4Labels):2731if verbose:2732print"import p4 labels: "+' '.join(p4Labels)27332734 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2735 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2736iflen(validLabelRegexp) ==0:2737 validLabelRegexp = defaultLabelRegexp2738 m = re.compile(validLabelRegexp)27392740for name in p4Labels:2741 commitFound =False27422743if not m.match(name):2744if verbose:2745print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2746continue27472748if name in ignoredP4Labels:2749continue27502751 labelDetails =p4CmdList(['label',"-o", name])[0]27522753# get the most recent changelist for each file in this label2754 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2755for p in self.depotPaths])27562757if change.has_key('change'):2758# find the corresponding git commit; take the oldest commit2759 changelist =int(change['change'])2760if changelist in self.committedChanges:2761 gitCommit =":%d"% changelist # use a fast-import mark2762 commitFound =True2763else:2764 gitCommit =read_pipe(["git","rev-list","--max-count=1",2765"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2766iflen(gitCommit) ==0:2767print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2768else:2769 commitFound =True2770 gitCommit = gitCommit.strip()27712772if commitFound:2773# Convert from p4 time format2774try:2775 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2776exceptValueError:2777print"Could not convert label time%s"% labelDetails['Update']2778 tmwhen =127792780 when =int(time.mktime(tmwhen))2781 self.streamTag(stream, name, labelDetails, gitCommit, when)2782if verbose:2783print"p4 label%smapped to git commit%s"% (name, gitCommit)2784else:2785if verbose:2786print"Label%shas no changelists - possibly deleted?"% name27872788if not commitFound:2789# We can't import this label; don't try again as it will get very2790# expensive repeatedly fetching all the files for labels that will2791# never be imported. If the label is moved in the future, the2792# ignore will need to be removed manually.2793system(["git","config","--add","git-p4.ignoredP4Labels", name])27942795defguessProjectName(self):2796for p in self.depotPaths:2797if p.endswith("/"):2798 p = p[:-1]2799 p = p[p.strip().rfind("/") +1:]2800if not p.endswith("/"):2801 p +="/"2802return p28032804defgetBranchMapping(self):2805 lostAndFoundBranches =set()28062807 user =gitConfig("git-p4.branchUser")2808iflen(user) >0:2809 command ="branches -u%s"% user2810else:2811 command ="branches"28122813for info inp4CmdList(command):2814 details =p4Cmd(["branch","-o", info["branch"]])2815 viewIdx =02816while details.has_key("View%s"% viewIdx):2817 paths = details["View%s"% viewIdx].split(" ")2818 viewIdx = viewIdx +12819# require standard //depot/foo/... //depot/bar/... mapping2820iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2821continue2822 source = paths[0]2823 destination = paths[1]2824## HACK2825ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2826 source = source[len(self.depotPaths[0]):-4]2827 destination = destination[len(self.depotPaths[0]):-4]28282829if destination in self.knownBranches:2830if not self.silent:2831print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2832print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2833continue28342835 self.knownBranches[destination] = source28362837 lostAndFoundBranches.discard(destination)28382839if source not in self.knownBranches:2840 lostAndFoundBranches.add(source)28412842# Perforce does not strictly require branches to be defined, so we also2843# check git config for a branch list.2844#2845# Example of branch definition in git config file:2846# [git-p4]2847# branchList=main:branchA2848# branchList=main:branchB2849# branchList=branchA:branchC2850 configBranches =gitConfigList("git-p4.branchList")2851for branch in configBranches:2852if branch:2853(source, destination) = branch.split(":")2854 self.knownBranches[destination] = source28552856 lostAndFoundBranches.discard(destination)28572858if source not in self.knownBranches:2859 lostAndFoundBranches.add(source)286028612862for branch in lostAndFoundBranches:2863 self.knownBranches[branch] = branch28642865defgetBranchMappingFromGitBranches(self):2866 branches =p4BranchesInGit(self.importIntoRemotes)2867for branch in branches.keys():2868if branch =="master":2869 branch ="main"2870else:2871 branch = branch[len(self.projectName):]2872 self.knownBranches[branch] = branch28732874defupdateOptionDict(self, d):2875 option_keys = {}2876if self.keepRepoPath:2877 option_keys['keepRepoPath'] =128782879 d["options"] =' '.join(sorted(option_keys.keys()))28802881defreadOptions(self, d):2882 self.keepRepoPath = (d.has_key('options')2883and('keepRepoPath'in d['options']))28842885defgitRefForBranch(self, branch):2886if branch =="main":2887return self.refPrefix +"master"28882889iflen(branch) <=0:2890return branch28912892return self.refPrefix + self.projectName + branch28932894defgitCommitByP4Change(self, ref, change):2895if self.verbose:2896print"looking in ref "+ ref +" for change%susing bisect..."% change28972898 earliestCommit =""2899 latestCommit =parseRevision(ref)29002901while True:2902if self.verbose:2903print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2904 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2905iflen(next) ==0:2906if self.verbose:2907print"argh"2908return""2909 log =extractLogMessageFromGitCommit(next)2910 settings =extractSettingsGitLog(log)2911 currentChange =int(settings['change'])2912if self.verbose:2913print"current change%s"% currentChange29142915if currentChange == change:2916if self.verbose:2917print"found%s"% next2918return next29192920if currentChange < change:2921 earliestCommit ="^%s"% next2922else:2923 latestCommit ="%s"% next29242925return""29262927defimportNewBranch(self, branch, maxChange):2928# make fast-import flush all changes to disk and update the refs using the checkpoint2929# command so that we can try to find the branch parent in the git history2930 self.gitStream.write("checkpoint\n\n");2931 self.gitStream.flush();2932 branchPrefix = self.depotPaths[0] + branch +"/"2933range="@1,%s"% maxChange2934#print "prefix" + branchPrefix2935 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2936iflen(changes) <=0:2937return False2938 firstChange = changes[0]2939#print "first change in branch: %s" % firstChange2940 sourceBranch = self.knownBranches[branch]2941 sourceDepotPath = self.depotPaths[0] + sourceBranch2942 sourceRef = self.gitRefForBranch(sourceBranch)2943#print "source " + sourceBranch29442945 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2946#print "branch parent: %s" % branchParentChange2947 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2948iflen(gitParent) >0:2949 self.initialParents[self.gitRefForBranch(branch)] = gitParent2950#print "parent git commit: %s" % gitParent29512952 self.importChanges(changes)2953return True29542955defsearchParent(self, parent, branch, target):2956 parentFound =False2957for blob inread_pipe_lines(["git","rev-list","--reverse",2958"--no-merges", parent]):2959 blob = blob.strip()2960iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2961 parentFound =True2962if self.verbose:2963print"Found parent of%sin commit%s"% (branch, blob)2964break2965if parentFound:2966return blob2967else:2968return None29692970defimportChanges(self, changes):2971 cnt =12972for change in changes:2973 description =p4_describe(change)2974 self.updateOptionDict(description)29752976if not self.silent:2977 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2978 sys.stdout.flush()2979 cnt = cnt +129802981try:2982if self.detectBranches:2983 branches = self.splitFilesIntoBranches(description)2984for branch in branches.keys():2985## HACK --hwn2986 branchPrefix = self.depotPaths[0] + branch +"/"2987 self.branchPrefixes = [ branchPrefix ]29882989 parent =""29902991 filesForCommit = branches[branch]29922993if self.verbose:2994print"branch is%s"% branch29952996 self.updatedBranches.add(branch)29972998if branch not in self.createdBranches:2999 self.createdBranches.add(branch)3000 parent = self.knownBranches[branch]3001if parent == branch:3002 parent =""3003else:3004 fullBranch = self.projectName + branch3005if fullBranch not in self.p4BranchesInGit:3006if not self.silent:3007print("\nImporting new branch%s"% fullBranch);3008if self.importNewBranch(branch, change -1):3009 parent =""3010 self.p4BranchesInGit.append(fullBranch)3011if not self.silent:3012print("\nResuming with change%s"% change);30133014if self.verbose:3015print"parent determined through known branches:%s"% parent30163017 branch = self.gitRefForBranch(branch)3018 parent = self.gitRefForBranch(parent)30193020if self.verbose:3021print"looking for initial parent for%s; current parent is%s"% (branch, parent)30223023iflen(parent) ==0and branch in self.initialParents:3024 parent = self.initialParents[branch]3025del self.initialParents[branch]30263027 blob =None3028iflen(parent) >0:3029 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3030if self.verbose:3031print"Creating temporary branch: "+ tempBranch3032 self.commit(description, filesForCommit, tempBranch)3033 self.tempBranches.append(tempBranch)3034 self.checkpoint()3035 blob = self.searchParent(parent, branch, tempBranch)3036if blob:3037 self.commit(description, filesForCommit, branch, blob)3038else:3039if self.verbose:3040print"Parent of%snot found. Committing into head of%s"% (branch, parent)3041 self.commit(description, filesForCommit, branch, parent)3042else:3043 files = self.extractFilesFromCommit(description)3044 self.commit(description, files, self.branch,3045 self.initialParent)3046# only needed once, to connect to the previous commit3047 self.initialParent =""3048exceptIOError:3049print self.gitError.read()3050 sys.exit(1)30513052defimportHeadRevision(self, revision):3053print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)30543055 details = {}3056 details["user"] ="git perforce import user"3057 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3058% (' '.join(self.depotPaths), revision))3059 details["change"] = revision3060 newestRevision =030613062 fileCnt =03063 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]30643065for info inp4CmdList(["files"] + fileArgs):30663067if'code'in info and info['code'] =='error':3068 sys.stderr.write("p4 returned an error:%s\n"3069% info['data'])3070if info['data'].find("must refer to client") >=0:3071 sys.stderr.write("This particular p4 error is misleading.\n")3072 sys.stderr.write("Perhaps the depot path was misspelled.\n");3073 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3074 sys.exit(1)3075if'p4ExitCode'in info:3076 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3077 sys.exit(1)307830793080 change =int(info["change"])3081if change > newestRevision:3082 newestRevision = change30833084if info["action"]in self.delete_actions:3085# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3086#fileCnt = fileCnt + 13087continue30883089for prop in["depotFile","rev","action","type"]:3090 details["%s%s"% (prop, fileCnt)] = info[prop]30913092 fileCnt = fileCnt +130933094 details["change"] = newestRevision30953096# Use time from top-most change so that all git p4 clones of3097# the same p4 repo have the same commit SHA1s.3098 res =p4_describe(newestRevision)3099 details["time"] = res["time"]31003101 self.updateOptionDict(details)3102try:3103 self.commit(details, self.extractFilesFromCommit(details), self.branch)3104exceptIOError:3105print"IO error with git fast-import. Is your git version recent enough?"3106print self.gitError.read()310731083109defrun(self, args):3110 self.depotPaths = []3111 self.changeRange =""3112 self.previousDepotPaths = []3113 self.hasOrigin =False31143115# map from branch depot path to parent branch3116 self.knownBranches = {}3117 self.initialParents = {}31183119if self.importIntoRemotes:3120 self.refPrefix ="refs/remotes/p4/"3121else:3122 self.refPrefix ="refs/heads/p4/"31233124if self.syncWithOrigin:3125 self.hasOrigin =originP4BranchesExist()3126if self.hasOrigin:3127if not self.silent:3128print'Syncing with origin first, using "git fetch origin"'3129system("git fetch origin")31303131 branch_arg_given =bool(self.branch)3132iflen(self.branch) ==0:3133 self.branch = self.refPrefix +"master"3134ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3135system("git update-ref%srefs/heads/p4"% self.branch)3136system("git branch -D p4")31373138# accept either the command-line option, or the configuration variable3139if self.useClientSpec:3140# will use this after clone to set the variable3141 self.useClientSpec_from_options =True3142else:3143ifgitConfigBool("git-p4.useclientspec"):3144 self.useClientSpec =True3145if self.useClientSpec:3146 self.clientSpecDirs =getClientSpec()31473148# TODO: should always look at previous commits,3149# merge with previous imports, if possible.3150if args == []:3151if self.hasOrigin:3152createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)31533154# branches holds mapping from branch name to sha13155 branches =p4BranchesInGit(self.importIntoRemotes)31563157# restrict to just this one, disabling detect-branches3158if branch_arg_given:3159 short = self.branch.split("/")[-1]3160if short in branches:3161 self.p4BranchesInGit = [ short ]3162else:3163 self.p4BranchesInGit = branches.keys()31643165iflen(self.p4BranchesInGit) >1:3166if not self.silent:3167print"Importing from/into multiple branches"3168 self.detectBranches =True3169for branch in branches.keys():3170 self.initialParents[self.refPrefix + branch] = \3171 branches[branch]31723173if self.verbose:3174print"branches:%s"% self.p4BranchesInGit31753176 p4Change =03177for branch in self.p4BranchesInGit:3178 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)31793180 settings =extractSettingsGitLog(logMsg)31813182 self.readOptions(settings)3183if(settings.has_key('depot-paths')3184and settings.has_key('change')):3185 change =int(settings['change']) +13186 p4Change =max(p4Change, change)31873188 depotPaths =sorted(settings['depot-paths'])3189if self.previousDepotPaths == []:3190 self.previousDepotPaths = depotPaths3191else:3192 paths = []3193for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3194 prev_list = prev.split("/")3195 cur_list = cur.split("/")3196for i inrange(0,min(len(cur_list),len(prev_list))):3197if cur_list[i] <> prev_list[i]:3198 i = i -13199break32003201 paths.append("/".join(cur_list[:i +1]))32023203 self.previousDepotPaths = paths32043205if p4Change >0:3206 self.depotPaths =sorted(self.previousDepotPaths)3207 self.changeRange ="@%s,#head"% p4Change3208if not self.silent and not self.detectBranches:3209print"Performing incremental import into%sgit branch"% self.branch32103211# accept multiple ref name abbreviations:3212# refs/foo/bar/branch -> use it exactly3213# p4/branch -> prepend refs/remotes/ or refs/heads/3214# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3215if not self.branch.startswith("refs/"):3216if self.importIntoRemotes:3217 prepend ="refs/remotes/"3218else:3219 prepend ="refs/heads/"3220if not self.branch.startswith("p4/"):3221 prepend +="p4/"3222 self.branch = prepend + self.branch32233224iflen(args) ==0and self.depotPaths:3225if not self.silent:3226print"Depot paths:%s"%' '.join(self.depotPaths)3227else:3228if self.depotPaths and self.depotPaths != args:3229print("previous import used depot path%sand now%swas specified. "3230"This doesn't work!"% (' '.join(self.depotPaths),3231' '.join(args)))3232 sys.exit(1)32333234 self.depotPaths =sorted(args)32353236 revision =""3237 self.users = {}32383239# Make sure no revision specifiers are used when --changesfile3240# is specified.3241 bad_changesfile =False3242iflen(self.changesFile) >0:3243for p in self.depotPaths:3244if p.find("@") >=0or p.find("#") >=0:3245 bad_changesfile =True3246break3247if bad_changesfile:3248die("Option --changesfile is incompatible with revision specifiers")32493250 newPaths = []3251for p in self.depotPaths:3252if p.find("@") != -1:3253 atIdx = p.index("@")3254 self.changeRange = p[atIdx:]3255if self.changeRange =="@all":3256 self.changeRange =""3257elif','not in self.changeRange:3258 revision = self.changeRange3259 self.changeRange =""3260 p = p[:atIdx]3261elif p.find("#") != -1:3262 hashIdx = p.index("#")3263 revision = p[hashIdx:]3264 p = p[:hashIdx]3265elif self.previousDepotPaths == []:3266# pay attention to changesfile, if given, else import3267# the entire p4 tree at the head revision3268iflen(self.changesFile) ==0:3269 revision ="#head"32703271 p = re.sub("\.\.\.$","", p)3272if not p.endswith("/"):3273 p +="/"32743275 newPaths.append(p)32763277 self.depotPaths = newPaths32783279# --detect-branches may change this for each branch3280 self.branchPrefixes = self.depotPaths32813282 self.loadUserMapFromCache()3283 self.labels = {}3284if self.detectLabels:3285 self.getLabels();32863287if self.detectBranches:3288## FIXME - what's a P4 projectName ?3289 self.projectName = self.guessProjectName()32903291if self.hasOrigin:3292 self.getBranchMappingFromGitBranches()3293else:3294 self.getBranchMapping()3295if self.verbose:3296print"p4-git branches:%s"% self.p4BranchesInGit3297print"initial parents:%s"% self.initialParents3298for b in self.p4BranchesInGit:3299if b !="master":33003301## FIXME3302 b = b[len(self.projectName):]3303 self.createdBranches.add(b)33043305 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33063307 self.importProcess = subprocess.Popen(["git","fast-import"],3308 stdin=subprocess.PIPE,3309 stdout=subprocess.PIPE,3310 stderr=subprocess.PIPE);3311 self.gitOutput = self.importProcess.stdout3312 self.gitStream = self.importProcess.stdin3313 self.gitError = self.importProcess.stderr33143315if revision:3316 self.importHeadRevision(revision)3317else:3318 changes = []33193320iflen(self.changesFile) >0:3321 output =open(self.changesFile).readlines()3322 changeSet =set()3323for line in output:3324 changeSet.add(int(line))33253326for change in changeSet:3327 changes.append(change)33283329 changes.sort()3330else:3331# catch "git p4 sync" with no new branches, in a repo that3332# does not have any existing p4 branches3333iflen(args) ==0:3334if not self.p4BranchesInGit:3335die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")33363337# The default branch is master, unless --branch is used to3338# specify something else. Make sure it exists, or complain3339# nicely about how to use --branch.3340if not self.detectBranches:3341if notbranch_exists(self.branch):3342if branch_arg_given:3343die("Error: branch%sdoes not exist."% self.branch)3344else:3345die("Error: no branch%s; perhaps specify one with --branch."%3346 self.branch)33473348if self.verbose:3349print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3350 self.changeRange)3351 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)33523353iflen(self.maxChanges) >0:3354 changes = changes[:min(int(self.maxChanges),len(changes))]33553356iflen(changes) ==0:3357if not self.silent:3358print"No changes to import!"3359else:3360if not self.silent and not self.detectBranches:3361print"Import destination:%s"% self.branch33623363 self.updatedBranches =set()33643365if not self.detectBranches:3366if args:3367# start a new branch3368 self.initialParent =""3369else:3370# build on a previous revision3371 self.initialParent =parseRevision(self.branch)33723373 self.importChanges(changes)33743375if not self.silent:3376print""3377iflen(self.updatedBranches) >0:3378 sys.stdout.write("Updated branches: ")3379for b in self.updatedBranches:3380 sys.stdout.write("%s"% b)3381 sys.stdout.write("\n")33823383ifgitConfigBool("git-p4.importLabels"):3384 self.importLabels =True33853386if self.importLabels:3387 p4Labels =getP4Labels(self.depotPaths)3388 gitTags =getGitTags()33893390 missingP4Labels = p4Labels - gitTags3391 self.importP4Labels(self.gitStream, missingP4Labels)33923393 self.gitStream.close()3394if self.importProcess.wait() !=0:3395die("fast-import failed:%s"% self.gitError.read())3396 self.gitOutput.close()3397 self.gitError.close()33983399# Cleanup temporary branches created during import3400if self.tempBranches != []:3401for branch in self.tempBranches:3402read_pipe("git update-ref -d%s"% branch)3403 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34043405# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3406# a convenient shortcut refname "p4".3407if self.importIntoRemotes:3408 head_ref = self.refPrefix +"HEAD"3409if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3410system(["git","symbolic-ref", head_ref, self.branch])34113412return True34133414classP4Rebase(Command):3415def__init__(self):3416 Command.__init__(self)3417 self.options = [3418 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3419]3420 self.importLabels =False3421 self.description = ("Fetches the latest revision from perforce and "3422+"rebases the current work (branch) against it")34233424defrun(self, args):3425 sync =P4Sync()3426 sync.importLabels = self.importLabels3427 sync.run([])34283429return self.rebase()34303431defrebase(self):3432if os.system("git update-index --refresh") !=0:3433die("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.");3434iflen(read_pipe("git diff-index HEAD --")) >0:3435die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");34363437[upstream, settings] =findUpstreamBranchPoint()3438iflen(upstream) ==0:3439die("Cannot find upstream branchpoint for rebase")34403441# the branchpoint may be p4/foo~3, so strip off the parent3442 upstream = re.sub("~[0-9]+$","", upstream)34433444print"Rebasing the current branch onto%s"% upstream3445 oldHead =read_pipe("git rev-parse HEAD").strip()3446system("git rebase%s"% upstream)3447system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3448return True34493450classP4Clone(P4Sync):3451def__init__(self):3452 P4Sync.__init__(self)3453 self.description ="Creates a new git repository and imports from Perforce into it"3454 self.usage ="usage: %prog [options] //depot/path[@revRange]"3455 self.options += [3456 optparse.make_option("--destination", dest="cloneDestination",3457 action='store', default=None,3458help="where to leave result of the clone"),3459 optparse.make_option("--bare", dest="cloneBare",3460 action="store_true", default=False),3461]3462 self.cloneDestination =None3463 self.needsGit =False3464 self.cloneBare =False34653466defdefaultDestination(self, args):3467## TODO: use common prefix of args?3468 depotPath = args[0]3469 depotDir = re.sub("(@[^@]*)$","", depotPath)3470 depotDir = re.sub("(#[^#]*)$","", depotDir)3471 depotDir = re.sub(r"\.\.\.$","", depotDir)3472 depotDir = re.sub(r"/$","", depotDir)3473return os.path.split(depotDir)[1]34743475defrun(self, args):3476iflen(args) <1:3477return False34783479if self.keepRepoPath and not self.cloneDestination:3480 sys.stderr.write("Must specify destination for --keep-path\n")3481 sys.exit(1)34823483 depotPaths = args34843485if not self.cloneDestination andlen(depotPaths) >1:3486 self.cloneDestination = depotPaths[-1]3487 depotPaths = depotPaths[:-1]34883489 self.cloneExclude = ["/"+p for p in self.cloneExclude]3490for p in depotPaths:3491if not p.startswith("//"):3492 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3493return False34943495if not self.cloneDestination:3496 self.cloneDestination = self.defaultDestination(args)34973498print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)34993500if not os.path.exists(self.cloneDestination):3501 os.makedirs(self.cloneDestination)3502chdir(self.cloneDestination)35033504 init_cmd = ["git","init"]3505if self.cloneBare:3506 init_cmd.append("--bare")3507 retcode = subprocess.call(init_cmd)3508if retcode:3509raiseCalledProcessError(retcode, init_cmd)35103511if not P4Sync.run(self, depotPaths):3512return False35133514# create a master branch and check out a work tree3515ifgitBranchExists(self.branch):3516system(["git","branch","master", self.branch ])3517if not self.cloneBare:3518system(["git","checkout","-f"])3519else:3520print'Not checking out any branch, use ' \3521'"git checkout -q -b master <branch>"'35223523# auto-set this variable if invoked with --use-client-spec3524if self.useClientSpec_from_options:3525system("git config --bool git-p4.useclientspec true")35263527return True35283529classP4Branches(Command):3530def__init__(self):3531 Command.__init__(self)3532 self.options = [ ]3533 self.description = ("Shows the git branches that hold imports and their "3534+"corresponding perforce depot paths")3535 self.verbose =False35363537defrun(self, args):3538iforiginP4BranchesExist():3539createOrUpdateBranchesFromOrigin()35403541 cmdline ="git rev-parse --symbolic "3542 cmdline +=" --remotes"35433544for line inread_pipe_lines(cmdline):3545 line = line.strip()35463547if not line.startswith('p4/')or line =="p4/HEAD":3548continue3549 branch = line35503551 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3552 settings =extractSettingsGitLog(log)35533554print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3555return True35563557classHelpFormatter(optparse.IndentedHelpFormatter):3558def__init__(self):3559 optparse.IndentedHelpFormatter.__init__(self)35603561defformat_description(self, description):3562if description:3563return description +"\n"3564else:3565return""35663567defprintUsage(commands):3568print"usage:%s<command> [options]"% sys.argv[0]3569print""3570print"valid commands:%s"%", ".join(commands)3571print""3572print"Try%s<command> --help for command specific help."% sys.argv[0]3573print""35743575commands = {3576"debug": P4Debug,3577"submit": P4Submit,3578"commit": P4Submit,3579"sync": P4Sync,3580"rebase": P4Rebase,3581"clone": P4Clone,3582"rollback": P4RollBack,3583"branches": P4Branches3584}358535863587defmain():3588iflen(sys.argv[1:]) ==0:3589printUsage(commands.keys())3590 sys.exit(2)35913592 cmdName = sys.argv[1]3593try:3594 klass = commands[cmdName]3595 cmd =klass()3596exceptKeyError:3597print"unknown command%s"% cmdName3598print""3599printUsage(commands.keys())3600 sys.exit(2)36013602 options = cmd.options3603 cmd.gitdir = os.environ.get("GIT_DIR",None)36043605 args = sys.argv[2:]36063607 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3608if cmd.needsGit:3609 options.append(optparse.make_option("--git-dir", dest="gitdir"))36103611 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3612 options,3613 description = cmd.description,3614 formatter =HelpFormatter())36153616(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3617global verbose3618 verbose = cmd.verbose3619if cmd.needsGit:3620if cmd.gitdir ==None:3621 cmd.gitdir = os.path.abspath(".git")3622if notisValidGitDir(cmd.gitdir):3623 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3624if os.path.exists(cmd.gitdir):3625 cdup =read_pipe("git rev-parse --show-cdup").strip()3626iflen(cdup) >0:3627chdir(cdup);36283629if notisValidGitDir(cmd.gitdir):3630ifisValidGitDir(cmd.gitdir +"/.git"):3631 cmd.gitdir +="/.git"3632else:3633die("fatal: cannot locate git repository at%s"% cmd.gitdir)36343635 os.environ["GIT_DIR"] = cmd.gitdir36363637if not cmd.run(args):3638 parser.print_help()3639 sys.exit(2)364036413642if __name__ =='__main__':3643main()