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, ignore_error=False): 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 and not ignore_error: 212raiseCalledProcessError(retcode, cmd) 213 214return retcode 215 216defp4_system(cmd): 217"""Specifically invoke p4 as the system command. """ 218 real_cmd =p4_build_cmd(cmd) 219 expand =isinstance(real_cmd, basestring) 220 retcode = subprocess.call(real_cmd, shell=expand) 221if retcode: 222raiseCalledProcessError(retcode, real_cmd) 223 224_p4_version_string =None 225defp4_version_string(): 226"""Read the version string, showing just the last line, which 227 hopefully is the interesting version bit. 228 229 $ p4 -V 230 Perforce - The Fast Software Configuration Management System. 231 Copyright 1995-2011 Perforce Software. All rights reserved. 232 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 233 """ 234global _p4_version_string 235if not _p4_version_string: 236 a =p4_read_pipe_lines(["-V"]) 237 _p4_version_string = a[-1].rstrip() 238return _p4_version_string 239 240defp4_integrate(src, dest): 241p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 242 243defp4_sync(f, *options): 244p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 245 246defp4_add(f): 247# forcibly add file names with wildcards 248ifwildcard_present(f): 249p4_system(["add","-f", f]) 250else: 251p4_system(["add", f]) 252 253defp4_delete(f): 254p4_system(["delete",wildcard_encode(f)]) 255 256defp4_edit(f, *options): 257p4_system(["edit"] +list(options) + [wildcard_encode(f)]) 258 259defp4_revert(f): 260p4_system(["revert",wildcard_encode(f)]) 261 262defp4_reopen(type, f): 263p4_system(["reopen","-t",type,wildcard_encode(f)]) 264 265defp4_move(src, dest): 266p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 267 268defp4_last_change(): 269 results =p4CmdList(["changes","-m","1"]) 270returnint(results[0]['change']) 271 272defp4_describe(change): 273"""Make sure it returns a valid result by checking for 274 the presence of field "time". Return a dict of the 275 results.""" 276 277 ds =p4CmdList(["describe","-s",str(change)]) 278iflen(ds) !=1: 279die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 280 281 d = ds[0] 282 283if"p4ExitCode"in d: 284die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 285str(d))) 286if"code"in d: 287if d["code"] =="error": 288die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 289 290if"time"not in d: 291die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 292 293return d 294 295# 296# Canonicalize the p4 type and return a tuple of the 297# base type, plus any modifiers. See "p4 help filetypes" 298# for a list and explanation. 299# 300defsplit_p4_type(p4type): 301 302 p4_filetypes_historical = { 303"ctempobj":"binary+Sw", 304"ctext":"text+C", 305"cxtext":"text+Cx", 306"ktext":"text+k", 307"kxtext":"text+kx", 308"ltext":"text+F", 309"tempobj":"binary+FSw", 310"ubinary":"binary+F", 311"uresource":"resource+F", 312"uxbinary":"binary+Fx", 313"xbinary":"binary+x", 314"xltext":"text+Fx", 315"xtempobj":"binary+Swx", 316"xtext":"text+x", 317"xunicode":"unicode+x", 318"xutf16":"utf16+x", 319} 320if p4type in p4_filetypes_historical: 321 p4type = p4_filetypes_historical[p4type] 322 mods ="" 323 s = p4type.split("+") 324 base = s[0] 325 mods ="" 326iflen(s) >1: 327 mods = s[1] 328return(base, mods) 329 330# 331# return the raw p4 type of a file (text, text+ko, etc) 332# 333defp4_type(f): 334 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 335return results[0]['headType'] 336 337# 338# Given a type base and modifier, return a regexp matching 339# the keywords that can be expanded in the file 340# 341defp4_keywords_regexp_for_type(base, type_mods): 342if base in("text","unicode","binary"): 343 kwords =None 344if"ko"in type_mods: 345 kwords ='Id|Header' 346elif"k"in type_mods: 347 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 348else: 349return None 350 pattern = r""" 351 \$ # Starts with a dollar, followed by... 352 (%s) # one of the keywords, followed by... 353 (:[^$\n]+)? # possibly an old expansion, followed by... 354 \$ # another dollar 355 """% kwords 356return pattern 357else: 358return None 359 360# 361# Given a file, return a regexp matching the possible 362# RCS keywords that will be expanded, or None for files 363# with kw expansion turned off. 364# 365defp4_keywords_regexp_for_file(file): 366if not os.path.exists(file): 367return None 368else: 369(type_base, type_mods) =split_p4_type(p4_type(file)) 370returnp4_keywords_regexp_for_type(type_base, type_mods) 371 372defsetP4ExecBit(file, mode): 373# Reopens an already open file and changes the execute bit to match 374# the execute bit setting in the passed in mode. 375 376 p4Type ="+x" 377 378if notisModeExec(mode): 379 p4Type =getP4OpenedType(file) 380 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 381 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 382if p4Type[-1] =="+": 383 p4Type = p4Type[0:-1] 384 385p4_reopen(p4Type,file) 386 387defgetP4OpenedType(file): 388# Returns the perforce file type for the given file. 389 390 result =p4_read_pipe(["opened",wildcard_encode(file)]) 391 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 392if match: 393return match.group(1) 394else: 395die("Could not determine file type for%s(result: '%s')"% (file, result)) 396 397# Return the set of all p4 labels 398defgetP4Labels(depotPaths): 399 labels =set() 400ifisinstance(depotPaths,basestring): 401 depotPaths = [depotPaths] 402 403for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 404 label = l['label'] 405 labels.add(label) 406 407return labels 408 409# Return the set of all git tags 410defgetGitTags(): 411 gitTags =set() 412for line inread_pipe_lines(["git","tag"]): 413 tag = line.strip() 414 gitTags.add(tag) 415return gitTags 416 417defdiffTreePattern(): 418# This is a simple generator for the diff tree regex pattern. This could be 419# a class variable if this and parseDiffTreeEntry were a part of a class. 420 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 421while True: 422yield pattern 423 424defparseDiffTreeEntry(entry): 425"""Parses a single diff tree entry into its component elements. 426 427 See git-diff-tree(1) manpage for details about the format of the diff 428 output. This method returns a dictionary with the following elements: 429 430 src_mode - The mode of the source file 431 dst_mode - The mode of the destination file 432 src_sha1 - The sha1 for the source file 433 dst_sha1 - The sha1 fr the destination file 434 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 435 status_score - The score for the status (applicable for 'C' and 'R' 436 statuses). This is None if there is no score. 437 src - The path for the source file. 438 dst - The path for the destination file. This is only present for 439 copy or renames. If it is not present, this is None. 440 441 If the pattern is not matched, None is returned.""" 442 443 match =diffTreePattern().next().match(entry) 444if match: 445return{ 446'src_mode': match.group(1), 447'dst_mode': match.group(2), 448'src_sha1': match.group(3), 449'dst_sha1': match.group(4), 450'status': match.group(5), 451'status_score': match.group(6), 452'src': match.group(7), 453'dst': match.group(10) 454} 455return None 456 457defisModeExec(mode): 458# Returns True if the given git mode represents an executable file, 459# otherwise False. 460return mode[-3:] =="755" 461 462defisModeExecChanged(src_mode, dst_mode): 463returnisModeExec(src_mode) !=isModeExec(dst_mode) 464 465defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 466 467ifisinstance(cmd,basestring): 468 cmd ="-G "+ cmd 469 expand =True 470else: 471 cmd = ["-G"] + cmd 472 expand =False 473 474 cmd =p4_build_cmd(cmd) 475if verbose: 476 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 477 478# Use a temporary file to avoid deadlocks without 479# subprocess.communicate(), which would put another copy 480# of stdout into memory. 481 stdin_file =None 482if stdin is not None: 483 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 484ifisinstance(stdin,basestring): 485 stdin_file.write(stdin) 486else: 487for i in stdin: 488 stdin_file.write(i +'\n') 489 stdin_file.flush() 490 stdin_file.seek(0) 491 492 p4 = subprocess.Popen(cmd, 493 shell=expand, 494 stdin=stdin_file, 495 stdout=subprocess.PIPE) 496 497 result = [] 498try: 499while True: 500 entry = marshal.load(p4.stdout) 501if cb is not None: 502cb(entry) 503else: 504 result.append(entry) 505exceptEOFError: 506pass 507 exitCode = p4.wait() 508if exitCode !=0: 509 entry = {} 510 entry["p4ExitCode"] = exitCode 511 result.append(entry) 512 513return result 514 515defp4Cmd(cmd): 516list=p4CmdList(cmd) 517 result = {} 518for entry inlist: 519 result.update(entry) 520return result; 521 522defp4Where(depotPath): 523if not depotPath.endswith("/"): 524 depotPath +="/" 525 depotPathLong = depotPath +"..." 526 outputList =p4CmdList(["where", depotPathLong]) 527 output =None 528for entry in outputList: 529if"depotFile"in entry: 530# Search for the base client side depot path, as long as it starts with the branch's P4 path. 531# The base path always ends with "/...". 532if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 533 output = entry 534break 535elif"data"in entry: 536 data = entry.get("data") 537 space = data.find(" ") 538if data[:space] == depotPath: 539 output = entry 540break 541if output ==None: 542return"" 543if output["code"] =="error": 544return"" 545 clientPath ="" 546if"path"in output: 547 clientPath = output.get("path") 548elif"data"in output: 549 data = output.get("data") 550 lastSpace = data.rfind(" ") 551 clientPath = data[lastSpace +1:] 552 553if clientPath.endswith("..."): 554 clientPath = clientPath[:-3] 555return clientPath 556 557defcurrentGitBranch(): 558 retcode =system(["git","symbolic-ref","-q","HEAD"], ignore_error=True) 559if retcode !=0: 560# on a detached head 561return None 562else: 563returnread_pipe(["git","name-rev","HEAD"]).split(" ")[1].strip() 564 565defisValidGitDir(path): 566if(os.path.exists(path +"/HEAD") 567and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 568return True; 569return False 570 571defparseRevision(ref): 572returnread_pipe("git rev-parse%s"% ref).strip() 573 574defbranchExists(ref): 575 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 576 ignore_error=True) 577returnlen(rev) >0 578 579defextractLogMessageFromGitCommit(commit): 580 logMessage ="" 581 582## fixme: title is first line of commit, not 1st paragraph. 583 foundTitle =False 584for log inread_pipe_lines("git cat-file commit%s"% commit): 585if not foundTitle: 586iflen(log) ==1: 587 foundTitle =True 588continue 589 590 logMessage += log 591return logMessage 592 593defextractSettingsGitLog(log): 594 values = {} 595for line in log.split("\n"): 596 line = line.strip() 597 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 598if not m: 599continue 600 601 assignments = m.group(1).split(':') 602for a in assignments: 603 vals = a.split('=') 604 key = vals[0].strip() 605 val = ('='.join(vals[1:])).strip() 606if val.endswith('\"')and val.startswith('"'): 607 val = val[1:-1] 608 609 values[key] = val 610 611 paths = values.get("depot-paths") 612if not paths: 613 paths = values.get("depot-path") 614if paths: 615 values['depot-paths'] = paths.split(',') 616return values 617 618defgitBranchExists(branch): 619 proc = subprocess.Popen(["git","rev-parse", branch], 620 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 621return proc.wait() ==0; 622 623_gitConfig = {} 624 625defgitConfig(key, typeSpecifier=None): 626if not _gitConfig.has_key(key): 627 cmd = ["git","config"] 628if typeSpecifier: 629 cmd += [ typeSpecifier ] 630 cmd += [ key ] 631 s =read_pipe(cmd, ignore_error=True) 632 _gitConfig[key] = s.strip() 633return _gitConfig[key] 634 635defgitConfigBool(key): 636"""Return a bool, using git config --bool. It is True only if the 637 variable is set to true, and False if set to false or not present 638 in the config.""" 639 640if not _gitConfig.has_key(key): 641 _gitConfig[key] =gitConfig(key,'--bool') =="true" 642return _gitConfig[key] 643 644defgitConfigInt(key): 645if not _gitConfig.has_key(key): 646 cmd = ["git","config","--int", key ] 647 s =read_pipe(cmd, ignore_error=True) 648 v = s.strip() 649try: 650 _gitConfig[key] =int(gitConfig(key,'--int')) 651exceptValueError: 652 _gitConfig[key] =None 653return _gitConfig[key] 654 655defgitConfigList(key): 656if not _gitConfig.has_key(key): 657 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 658 _gitConfig[key] = s.strip().split(os.linesep) 659if _gitConfig[key] == ['']: 660 _gitConfig[key] = [] 661return _gitConfig[key] 662 663defp4BranchesInGit(branchesAreInRemotes=True): 664"""Find all the branches whose names start with "p4/", looking 665 in remotes or heads as specified by the argument. Return 666 a dictionary of{ branch: revision }for each one found. 667 The branch names are the short names, without any 668 "p4/" prefix.""" 669 670 branches = {} 671 672 cmdline ="git rev-parse --symbolic " 673if branchesAreInRemotes: 674 cmdline +="--remotes" 675else: 676 cmdline +="--branches" 677 678for line inread_pipe_lines(cmdline): 679 line = line.strip() 680 681# only import to p4/ 682if not line.startswith('p4/'): 683continue 684# special symbolic ref to p4/master 685if line =="p4/HEAD": 686continue 687 688# strip off p4/ prefix 689 branch = line[len("p4/"):] 690 691 branches[branch] =parseRevision(line) 692 693return branches 694 695defbranch_exists(branch): 696"""Make sure that the given ref name really exists.""" 697 698 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 699 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 700 out, _ = p.communicate() 701if p.returncode: 702return False 703# expect exactly one line of output: the branch name 704return out.rstrip() == branch 705 706deffindUpstreamBranchPoint(head ="HEAD"): 707 branches =p4BranchesInGit() 708# map from depot-path to branch name 709 branchByDepotPath = {} 710for branch in branches.keys(): 711 tip = branches[branch] 712 log =extractLogMessageFromGitCommit(tip) 713 settings =extractSettingsGitLog(log) 714if settings.has_key("depot-paths"): 715 paths =",".join(settings["depot-paths"]) 716 branchByDepotPath[paths] ="remotes/p4/"+ branch 717 718 settings =None 719 parent =0 720while parent <65535: 721 commit = head +"~%s"% parent 722 log =extractLogMessageFromGitCommit(commit) 723 settings =extractSettingsGitLog(log) 724if settings.has_key("depot-paths"): 725 paths =",".join(settings["depot-paths"]) 726if branchByDepotPath.has_key(paths): 727return[branchByDepotPath[paths], settings] 728 729 parent = parent +1 730 731return["", settings] 732 733defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 734if not silent: 735print("Creating/updating branch(es) in%sbased on origin branch(es)" 736% localRefPrefix) 737 738 originPrefix ="origin/p4/" 739 740for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 741 line = line.strip() 742if(not line.startswith(originPrefix))or line.endswith("HEAD"): 743continue 744 745 headName = line[len(originPrefix):] 746 remoteHead = localRefPrefix + headName 747 originHead = line 748 749 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 750if(not original.has_key('depot-paths') 751or not original.has_key('change')): 752continue 753 754 update =False 755if notgitBranchExists(remoteHead): 756if verbose: 757print"creating%s"% remoteHead 758 update =True 759else: 760 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 761if settings.has_key('change') >0: 762if settings['depot-paths'] == original['depot-paths']: 763 originP4Change =int(original['change']) 764 p4Change =int(settings['change']) 765if originP4Change > p4Change: 766print("%s(%s) is newer than%s(%s). " 767"Updating p4 branch from origin." 768% (originHead, originP4Change, 769 remoteHead, p4Change)) 770 update =True 771else: 772print("Ignoring:%swas imported from%swhile " 773"%swas imported from%s" 774% (originHead,','.join(original['depot-paths']), 775 remoteHead,','.join(settings['depot-paths']))) 776 777if update: 778system("git update-ref%s %s"% (remoteHead, originHead)) 779 780deforiginP4BranchesExist(): 781returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 782 783 784defp4ParseNumericChangeRange(parts): 785 changeStart =int(parts[0][1:]) 786if parts[1] =='#head': 787 changeEnd =p4_last_change() 788else: 789 changeEnd =int(parts[1]) 790 791return(changeStart, changeEnd) 792 793defchooseBlockSize(blockSize): 794if blockSize: 795return blockSize 796else: 797return defaultBlockSize 798 799defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 800assert depotPaths 801 802# Parse the change range into start and end. Try to find integer 803# revision ranges as these can be broken up into blocks to avoid 804# hitting server-side limits (maxrows, maxscanresults). But if 805# that doesn't work, fall back to using the raw revision specifier 806# strings, without using block mode. 807 808if changeRange is None or changeRange =='': 809 changeStart =1 810 changeEnd =p4_last_change() 811 block_size =chooseBlockSize(requestedBlockSize) 812else: 813 parts = changeRange.split(',') 814assertlen(parts) ==2 815try: 816(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 817 block_size =chooseBlockSize(requestedBlockSize) 818except: 819 changeStart = parts[0][1:] 820 changeEnd = parts[1] 821if requestedBlockSize: 822die("cannot use --changes-block-size with non-numeric revisions") 823 block_size =None 824 825 changes = [] 826 827# Retrieve changes a block at a time, to prevent running 828# into a MaxResults/MaxScanRows error from the server. 829 830while True: 831 cmd = ['changes'] 832 833if block_size: 834 end =min(changeEnd, changeStart + block_size) 835 revisionRange ="%d,%d"% (changeStart, end) 836else: 837 revisionRange ="%s,%s"% (changeStart, changeEnd) 838 839for p in depotPaths: 840 cmd += ["%s...@%s"% (p, revisionRange)] 841 842# Insert changes in chronological order 843for line inreversed(p4_read_pipe_lines(cmd)): 844 changes.append(int(line.split(" ")[1])) 845 846if not block_size: 847break 848 849if end >= changeEnd: 850break 851 852 changeStart = end +1 853 854 changes =sorted(changes) 855return changes 856 857defp4PathStartsWith(path, prefix): 858# This method tries to remedy a potential mixed-case issue: 859# 860# If UserA adds //depot/DirA/file1 861# and UserB adds //depot/dira/file2 862# 863# we may or may not have a problem. If you have core.ignorecase=true, 864# we treat DirA and dira as the same directory 865ifgitConfigBool("core.ignorecase"): 866return path.lower().startswith(prefix.lower()) 867return path.startswith(prefix) 868 869defgetClientSpec(): 870"""Look at the p4 client spec, create a View() object that contains 871 all the mappings, and return it.""" 872 873 specList =p4CmdList("client -o") 874iflen(specList) !=1: 875die('Output from "client -o" is%dlines, expecting 1'% 876len(specList)) 877 878# dictionary of all client parameters 879 entry = specList[0] 880 881# the //client/ name 882 client_name = entry["Client"] 883 884# just the keys that start with "View" 885 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 886 887# hold this new View 888 view =View(client_name) 889 890# append the lines, in order, to the view 891for view_num inrange(len(view_keys)): 892 k ="View%d"% view_num 893if k not in view_keys: 894die("Expected view key%smissing"% k) 895 view.append(entry[k]) 896 897return view 898 899defgetClientRoot(): 900"""Grab the client directory.""" 901 902 output =p4CmdList("client -o") 903iflen(output) !=1: 904die('Output from "client -o" is%dlines, expecting 1'%len(output)) 905 906 entry = output[0] 907if"Root"not in entry: 908die('Client has no "Root"') 909 910return entry["Root"] 911 912# 913# P4 wildcards are not allowed in filenames. P4 complains 914# if you simply add them, but you can force it with "-f", in 915# which case it translates them into %xx encoding internally. 916# 917defwildcard_decode(path): 918# Search for and fix just these four characters. Do % last so 919# that fixing it does not inadvertently create new %-escapes. 920# Cannot have * in a filename in windows; untested as to 921# what p4 would do in such a case. 922if not platform.system() =="Windows": 923 path = path.replace("%2A","*") 924 path = path.replace("%23","#") \ 925.replace("%40","@") \ 926.replace("%25","%") 927return path 928 929defwildcard_encode(path): 930# do % first to avoid double-encoding the %s introduced here 931 path = path.replace("%","%25") \ 932.replace("*","%2A") \ 933.replace("#","%23") \ 934.replace("@","%40") 935return path 936 937defwildcard_present(path): 938 m = re.search("[*#@%]", path) 939return m is not None 940 941classLargeFileSystem(object): 942"""Base class for large file system support.""" 943 944def__init__(self, writeToGitStream): 945 self.largeFiles =set() 946 self.writeToGitStream = writeToGitStream 947 948defgeneratePointer(self, cloneDestination, contentFile): 949"""Return the content of a pointer file that is stored in Git instead of 950 the actual content.""" 951assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 952 953defpushFile(self, localLargeFile): 954"""Push the actual content which is not stored in the Git repository to 955 a server.""" 956assert False,"Method 'pushFile' required in "+ self.__class__.__name__ 957 958defhasLargeFileExtension(self, relPath): 959returnreduce( 960lambda a, b: a or b, 961[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')], 962False 963) 964 965defgenerateTempFile(self, contents): 966 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 967for d in contents: 968 contentFile.write(d) 969 contentFile.close() 970return contentFile.name 971 972defexceedsLargeFileThreshold(self, relPath, contents): 973ifgitConfigInt('git-p4.largeFileThreshold'): 974 contentsSize =sum(len(d)for d in contents) 975if contentsSize >gitConfigInt('git-p4.largeFileThreshold'): 976return True 977ifgitConfigInt('git-p4.largeFileCompressedThreshold'): 978 contentsSize =sum(len(d)for d in contents) 979if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'): 980return False 981 contentTempFile = self.generateTempFile(contents) 982 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 983 zf = zipfile.ZipFile(compressedContentFile.name, mode='w') 984 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) 985 zf.close() 986 compressedContentsSize = zf.infolist()[0].compress_size 987 os.remove(contentTempFile) 988 os.remove(compressedContentFile.name) 989if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'): 990return True 991return False 992 993defaddLargeFile(self, relPath): 994 self.largeFiles.add(relPath) 995 996defremoveLargeFile(self, relPath): 997 self.largeFiles.remove(relPath) 998 999defisLargeFile(self, relPath):1000return relPath in self.largeFiles10011002defprocessContent(self, git_mode, relPath, contents):1003"""Processes the content of git fast import. This method decides if a1004 file is stored in the large file system and handles all necessary1005 steps."""1006if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1007 contentTempFile = self.generateTempFile(contents)1008(git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)10091010# Move temp file to final location in large file system1011 largeFileDir = os.path.dirname(localLargeFile)1012if not os.path.isdir(largeFileDir):1013 os.makedirs(largeFileDir)1014 shutil.move(contentTempFile, localLargeFile)1015 self.addLargeFile(relPath)1016ifgitConfigBool('git-p4.largeFilePush'):1017 self.pushFile(localLargeFile)1018if verbose:1019 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1020return(git_mode, contents)10211022classMockLFS(LargeFileSystem):1023"""Mock large file system for testing."""10241025defgeneratePointer(self, contentFile):1026"""The pointer content is the original content prefixed with "pointer-".1027 The local filename of the large file storage is derived from the file content.1028 """1029withopen(contentFile,'r')as f:1030 content =next(f)1031 gitMode ='100644'1032 pointerContents ='pointer-'+ content1033 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1034return(gitMode, pointerContents, localLargeFile)10351036defpushFile(self, localLargeFile):1037"""The remote filename of the large file storage is the same as the local1038 one but in a different directory.1039 """1040 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1041if not os.path.exists(remotePath):1042 os.makedirs(remotePath)1043 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10441045classGitLFS(LargeFileSystem):1046"""Git LFS as backend for the git-p4 large file system.1047 See https://git-lfs.github.com/ for details."""10481049def__init__(self, *args):1050 LargeFileSystem.__init__(self, *args)1051 self.baseGitAttributes = []10521053defgeneratePointer(self, contentFile):1054"""Generate a Git LFS pointer for the content. Return LFS Pointer file1055 mode and content which is stored in the Git repository instead of1056 the actual content. Return also the new location of the actual1057 content.1058 """1059 pointerProcess = subprocess.Popen(1060['git','lfs','pointer','--file='+ contentFile],1061 stdout=subprocess.PIPE1062)1063 pointerFile = pointerProcess.stdout.read()1064if pointerProcess.wait():1065 os.remove(contentFile)1066die('git-lfs pointer command failed. Did you install the extension?')1067 pointerContents = [i+'\n'for i in pointerFile.split('\n')[2:][:-1]]1068 oid = pointerContents[1].split(' ')[1].split(':')[1][:-1]1069 localLargeFile = os.path.join(1070 os.getcwd(),1071'.git','lfs','objects', oid[:2], oid[2:4],1072 oid,1073)1074# LFS Spec states that pointer files should not have the executable bit set.1075 gitMode ='100644'1076return(gitMode, pointerContents, localLargeFile)10771078defpushFile(self, localLargeFile):1079 uploadProcess = subprocess.Popen(1080['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1081)1082if uploadProcess.wait():1083die('git-lfs push command failed. Did you define a remote?')10841085defgenerateGitAttributes(self):1086return(1087 self.baseGitAttributes +1088[1089'\n',1090'#\n',1091'# Git LFS (see https://git-lfs.github.com/)\n',1092'#\n',1093] +1094['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1095for f insorted(gitConfigList('git-p4.largeFileExtensions'))1096] +1097['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1098for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1099]1100)11011102defaddLargeFile(self, relPath):1103 LargeFileSystem.addLargeFile(self, relPath)1104 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11051106defremoveLargeFile(self, relPath):1107 LargeFileSystem.removeLargeFile(self, relPath)1108 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11091110defprocessContent(self, git_mode, relPath, contents):1111if relPath =='.gitattributes':1112 self.baseGitAttributes = contents1113return(git_mode, self.generateGitAttributes())1114else:1115return LargeFileSystem.processContent(self, git_mode, relPath, contents)11161117class Command:1118def__init__(self):1119 self.usage ="usage: %prog [options]"1120 self.needsGit =True1121 self.verbose =False11221123class P4UserMap:1124def__init__(self):1125 self.userMapFromPerforceServer =False1126 self.myP4UserId =None11271128defp4UserId(self):1129if self.myP4UserId:1130return self.myP4UserId11311132 results =p4CmdList("user -o")1133for r in results:1134if r.has_key('User'):1135 self.myP4UserId = r['User']1136return r['User']1137die("Could not find your p4 user id")11381139defp4UserIsMe(self, p4User):1140# return True if the given p4 user is actually me1141 me = self.p4UserId()1142if not p4User or p4User != me:1143return False1144else:1145return True11461147defgetUserCacheFilename(self):1148 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1149return home +"/.gitp4-usercache.txt"11501151defgetUserMapFromPerforceServer(self):1152if self.userMapFromPerforceServer:1153return1154 self.users = {}1155 self.emails = {}11561157for output inp4CmdList("users"):1158if not output.has_key("User"):1159continue1160 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1161 self.emails[output["Email"]] = output["User"]116211631164 s =''1165for(key, val)in self.users.items():1166 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11671168open(self.getUserCacheFilename(),"wb").write(s)1169 self.userMapFromPerforceServer =True11701171defloadUserMapFromCache(self):1172 self.users = {}1173 self.userMapFromPerforceServer =False1174try:1175 cache =open(self.getUserCacheFilename(),"rb")1176 lines = cache.readlines()1177 cache.close()1178for line in lines:1179 entry = line.strip().split("\t")1180 self.users[entry[0]] = entry[1]1181exceptIOError:1182 self.getUserMapFromPerforceServer()11831184classP4Debug(Command):1185def__init__(self):1186 Command.__init__(self)1187 self.options = []1188 self.description ="A tool to debug the output of p4 -G."1189 self.needsGit =False11901191defrun(self, args):1192 j =01193for output inp4CmdList(args):1194print'Element:%d'% j1195 j +=11196print output1197return True11981199classP4RollBack(Command):1200def__init__(self):1201 Command.__init__(self)1202 self.options = [1203 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1204]1205 self.description ="A tool to debug the multi-branch import. Don't use :)"1206 self.rollbackLocalBranches =False12071208defrun(self, args):1209iflen(args) !=1:1210return False1211 maxChange =int(args[0])12121213if"p4ExitCode"inp4Cmd("changes -m 1"):1214die("Problems executing p4");12151216if self.rollbackLocalBranches:1217 refPrefix ="refs/heads/"1218 lines =read_pipe_lines("git rev-parse --symbolic --branches")1219else:1220 refPrefix ="refs/remotes/"1221 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12221223for line in lines:1224if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1225 line = line.strip()1226 ref = refPrefix + line1227 log =extractLogMessageFromGitCommit(ref)1228 settings =extractSettingsGitLog(log)12291230 depotPaths = settings['depot-paths']1231 change = settings['change']12321233 changed =False12341235iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1236for p in depotPaths]))) ==0:1237print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1238system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1239continue12401241while change andint(change) > maxChange:1242 changed =True1243if self.verbose:1244print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1245system("git update-ref%s\"%s^\""% (ref, ref))1246 log =extractLogMessageFromGitCommit(ref)1247 settings =extractSettingsGitLog(log)124812491250 depotPaths = settings['depot-paths']1251 change = settings['change']12521253if changed:1254print"%srewound to%s"% (ref, change)12551256return True12571258classP4Submit(Command, P4UserMap):12591260 conflict_behavior_choices = ("ask","skip","quit")12611262def__init__(self):1263 Command.__init__(self)1264 P4UserMap.__init__(self)1265 self.options = [1266 optparse.make_option("--origin", dest="origin"),1267 optparse.make_option("-M", dest="detectRenames", action="store_true"),1268# preserve the user, requires relevant p4 permissions1269 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1270 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1271 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1272 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1273 optparse.make_option("--conflict", dest="conflict_behavior",1274 choices=self.conflict_behavior_choices),1275 optparse.make_option("--branch", dest="branch"),1276]1277 self.description ="Submit changes from git to the perforce depot."1278 self.usage +=" [name of git branch to submit into perforce depot]"1279 self.origin =""1280 self.detectRenames =False1281 self.preserveUser =gitConfigBool("git-p4.preserveUser")1282 self.dry_run =False1283 self.prepare_p4_only =False1284 self.conflict_behavior =None1285 self.isWindows = (platform.system() =="Windows")1286 self.exportLabels =False1287 self.p4HasMoveCommand =p4_has_move_command()1288 self.branch =None12891290ifgitConfig('git-p4.largeFileSystem'):1291die("Large file system not supported for git-p4 submit command. Please remove it from config.")12921293defcheck(self):1294iflen(p4CmdList("opened ...")) >0:1295die("You have files opened with perforce! Close them before starting the sync.")12961297defseparate_jobs_from_description(self, message):1298"""Extract and return a possible Jobs field in the commit1299 message. It goes into a separate section in the p4 change1300 specification.13011302 A jobs line starts with "Jobs:" and looks like a new field1303 in a form. Values are white-space separated on the same1304 line or on following lines that start with a tab.13051306 This does not parse and extract the full git commit message1307 like a p4 form. It just sees the Jobs: line as a marker1308 to pass everything from then on directly into the p4 form,1309 but outside the description section.13101311 Return a tuple (stripped log message, jobs string)."""13121313 m = re.search(r'^Jobs:', message, re.MULTILINE)1314if m is None:1315return(message,None)13161317 jobtext = message[m.start():]1318 stripped_message = message[:m.start()].rstrip()1319return(stripped_message, jobtext)13201321defprepareLogMessage(self, template, message, jobs):1322"""Edits the template returned from "p4 change -o" to insert1323 the message in the Description field, and the jobs text in1324 the Jobs field."""1325 result =""13261327 inDescriptionSection =False13281329for line in template.split("\n"):1330if line.startswith("#"):1331 result += line +"\n"1332continue13331334if inDescriptionSection:1335if line.startswith("Files:")or line.startswith("Jobs:"):1336 inDescriptionSection =False1337# insert Jobs section1338if jobs:1339 result += jobs +"\n"1340else:1341continue1342else:1343if line.startswith("Description:"):1344 inDescriptionSection =True1345 line +="\n"1346for messageLine in message.split("\n"):1347 line +="\t"+ messageLine +"\n"13481349 result += line +"\n"13501351return result13521353defpatchRCSKeywords(self,file, pattern):1354# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1355(handle, outFileName) = tempfile.mkstemp(dir='.')1356try:1357 outFile = os.fdopen(handle,"w+")1358 inFile =open(file,"r")1359 regexp = re.compile(pattern, re.VERBOSE)1360for line in inFile.readlines():1361 line = regexp.sub(r'$\1$', line)1362 outFile.write(line)1363 inFile.close()1364 outFile.close()1365# Forcibly overwrite the original file1366 os.unlink(file)1367 shutil.move(outFileName,file)1368except:1369# cleanup our temporary file1370 os.unlink(outFileName)1371print"Failed to strip RCS keywords in%s"%file1372raise13731374print"Patched up RCS keywords in%s"%file13751376defp4UserForCommit(self,id):1377# Return the tuple (perforce user,git email) for a given git commit id1378 self.getUserMapFromPerforceServer()1379 gitEmail =read_pipe(["git","log","--max-count=1",1380"--format=%ae",id])1381 gitEmail = gitEmail.strip()1382if not self.emails.has_key(gitEmail):1383return(None,gitEmail)1384else:1385return(self.emails[gitEmail],gitEmail)13861387defcheckValidP4Users(self,commits):1388# check if any git authors cannot be mapped to p4 users1389foridin commits:1390(user,email) = self.p4UserForCommit(id)1391if not user:1392 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1393ifgitConfigBool("git-p4.allowMissingP4Users"):1394print"%s"% msg1395else:1396die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)13971398deflastP4Changelist(self):1399# Get back the last changelist number submitted in this client spec. This1400# then gets used to patch up the username in the change. If the same1401# client spec is being used by multiple processes then this might go1402# wrong.1403 results =p4CmdList("client -o")# find the current client1404 client =None1405for r in results:1406if r.has_key('Client'):1407 client = r['Client']1408break1409if not client:1410die("could not get client spec")1411 results =p4CmdList(["changes","-c", client,"-m","1"])1412for r in results:1413if r.has_key('change'):1414return r['change']1415die("Could not get changelist number for last submit - cannot patch up user details")14161417defmodifyChangelistUser(self, changelist, newUser):1418# fixup the user field of a changelist after it has been submitted.1419 changes =p4CmdList("change -o%s"% changelist)1420iflen(changes) !=1:1421die("Bad output from p4 change modifying%sto user%s"%1422(changelist, newUser))14231424 c = changes[0]1425if c['User'] == newUser:return# nothing to do1426 c['User'] = newUser1427input= marshal.dumps(c)14281429 result =p4CmdList("change -f -i", stdin=input)1430for r in result:1431if r.has_key('code'):1432if r['code'] =='error':1433die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1434if r.has_key('data'):1435print("Updated user field for changelist%sto%s"% (changelist, newUser))1436return1437die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14381439defcanChangeChangelists(self):1440# check to see if we have p4 admin or super-user permissions, either of1441# which are required to modify changelists.1442 results =p4CmdList(["protects", self.depotPath])1443for r in results:1444if r.has_key('perm'):1445if r['perm'] =='admin':1446return11447if r['perm'] =='super':1448return11449return014501451defprepareSubmitTemplate(self):1452"""Run "p4 change -o" to grab a change specification template.1453 This does not use "p4 -G", as it is nice to keep the submission1454 template in original order, since a human might edit it.14551456 Remove lines in the Files section that show changes to files1457 outside the depot path we're committing into."""14581459[upstream, settings] =findUpstreamBranchPoint()14601461 template =""1462 inFilesSection =False1463for line inp4_read_pipe_lines(['change','-o']):1464if line.endswith("\r\n"):1465 line = line[:-2] +"\n"1466if inFilesSection:1467if line.startswith("\t"):1468# path starts and ends with a tab1469 path = line[1:]1470 lastTab = path.rfind("\t")1471if lastTab != -1:1472 path = path[:lastTab]1473if settings.has_key('depot-paths'):1474if not[p for p in settings['depot-paths']1475ifp4PathStartsWith(path, p)]:1476continue1477else:1478if notp4PathStartsWith(path, self.depotPath):1479continue1480else:1481 inFilesSection =False1482else:1483if line.startswith("Files:"):1484 inFilesSection =True14851486 template += line14871488return template14891490defedit_template(self, template_file):1491"""Invoke the editor to let the user change the submission1492 message. Return true if okay to continue with the submit."""14931494# if configured to skip the editing part, just submit1495ifgitConfigBool("git-p4.skipSubmitEdit"):1496return True14971498# look at the modification time, to check later if the user saved1499# the file1500 mtime = os.stat(template_file).st_mtime15011502# invoke the editor1503if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1504 editor = os.environ.get("P4EDITOR")1505else:1506 editor =read_pipe("git var GIT_EDITOR").strip()1507system(["sh","-c", ('%s"$@"'% editor), editor, template_file])15081509# If the file was not saved, prompt to see if this patch should1510# be skipped. But skip this verification step if configured so.1511ifgitConfigBool("git-p4.skipSubmitEditCheck"):1512return True15131514# modification time updated means user saved the file1515if os.stat(template_file).st_mtime > mtime:1516return True15171518while True:1519 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1520if response =='y':1521return True1522if response =='n':1523return False15241525defget_diff_description(self, editedFiles, filesToAdd):1526# diff1527if os.environ.has_key("P4DIFF"):1528del(os.environ["P4DIFF"])1529 diff =""1530for editedFile in editedFiles:1531 diff +=p4_read_pipe(['diff','-du',1532wildcard_encode(editedFile)])15331534# new file diff1535 newdiff =""1536for newFile in filesToAdd:1537 newdiff +="==== new file ====\n"1538 newdiff +="--- /dev/null\n"1539 newdiff +="+++%s\n"% newFile1540 f =open(newFile,"r")1541for line in f.readlines():1542 newdiff +="+"+ line1543 f.close()15441545return(diff + newdiff).replace('\r\n','\n')15461547defapplyCommit(self,id):1548"""Apply one commit, return True if it succeeded."""15491550print"Applying",read_pipe(["git","show","-s",1551"--format=format:%h%s",id])15521553(p4User, gitEmail) = self.p4UserForCommit(id)15541555 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1556 filesToAdd =set()1557 filesToChangeType =set()1558 filesToDelete =set()1559 editedFiles =set()1560 pureRenameCopy =set()1561 filesToChangeExecBit = {}15621563for line in diff:1564 diff =parseDiffTreeEntry(line)1565 modifier = diff['status']1566 path = diff['src']1567if modifier =="M":1568p4_edit(path)1569ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1570 filesToChangeExecBit[path] = diff['dst_mode']1571 editedFiles.add(path)1572elif modifier =="A":1573 filesToAdd.add(path)1574 filesToChangeExecBit[path] = diff['dst_mode']1575if path in filesToDelete:1576 filesToDelete.remove(path)1577elif modifier =="D":1578 filesToDelete.add(path)1579if path in filesToAdd:1580 filesToAdd.remove(path)1581elif modifier =="C":1582 src, dest = diff['src'], diff['dst']1583p4_integrate(src, dest)1584 pureRenameCopy.add(dest)1585if diff['src_sha1'] != diff['dst_sha1']:1586p4_edit(dest)1587 pureRenameCopy.discard(dest)1588ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1589p4_edit(dest)1590 pureRenameCopy.discard(dest)1591 filesToChangeExecBit[dest] = diff['dst_mode']1592if self.isWindows:1593# turn off read-only attribute1594 os.chmod(dest, stat.S_IWRITE)1595 os.unlink(dest)1596 editedFiles.add(dest)1597elif modifier =="R":1598 src, dest = diff['src'], diff['dst']1599if self.p4HasMoveCommand:1600p4_edit(src)# src must be open before move1601p4_move(src, dest)# opens for (move/delete, move/add)1602else:1603p4_integrate(src, dest)1604if diff['src_sha1'] != diff['dst_sha1']:1605p4_edit(dest)1606else:1607 pureRenameCopy.add(dest)1608ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1609if not self.p4HasMoveCommand:1610p4_edit(dest)# with move: already open, writable1611 filesToChangeExecBit[dest] = diff['dst_mode']1612if not self.p4HasMoveCommand:1613if self.isWindows:1614 os.chmod(dest, stat.S_IWRITE)1615 os.unlink(dest)1616 filesToDelete.add(src)1617 editedFiles.add(dest)1618elif modifier =="T":1619 filesToChangeType.add(path)1620else:1621die("unknown modifier%sfor%s"% (modifier, path))16221623 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1624 patchcmd = diffcmd +" | git apply "1625 tryPatchCmd = patchcmd +"--check -"1626 applyPatchCmd = patchcmd +"--check --apply -"1627 patch_succeeded =True16281629if os.system(tryPatchCmd) !=0:1630 fixed_rcs_keywords =False1631 patch_succeeded =False1632print"Unfortunately applying the change failed!"16331634# Patch failed, maybe it's just RCS keyword woes. Look through1635# the patch to see if that's possible.1636ifgitConfigBool("git-p4.attemptRCSCleanup"):1637file=None1638 pattern =None1639 kwfiles = {}1640forfilein editedFiles | filesToDelete:1641# did this file's delta contain RCS keywords?1642 pattern =p4_keywords_regexp_for_file(file)16431644if pattern:1645# this file is a possibility...look for RCS keywords.1646 regexp = re.compile(pattern, re.VERBOSE)1647for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1648if regexp.search(line):1649if verbose:1650print"got keyword match on%sin%sin%s"% (pattern, line,file)1651 kwfiles[file] = pattern1652break16531654forfilein kwfiles:1655if verbose:1656print"zapping%swith%s"% (line,pattern)1657# File is being deleted, so not open in p4. Must1658# disable the read-only bit on windows.1659if self.isWindows andfilenot in editedFiles:1660 os.chmod(file, stat.S_IWRITE)1661 self.patchRCSKeywords(file, kwfiles[file])1662 fixed_rcs_keywords =True16631664if fixed_rcs_keywords:1665print"Retrying the patch with RCS keywords cleaned up"1666if os.system(tryPatchCmd) ==0:1667 patch_succeeded =True16681669if not patch_succeeded:1670for f in editedFiles:1671p4_revert(f)1672return False16731674#1675# Apply the patch for real, and do add/delete/+x handling.1676#1677system(applyPatchCmd)16781679for f in filesToChangeType:1680p4_edit(f,"-t","auto")1681for f in filesToAdd:1682p4_add(f)1683for f in filesToDelete:1684p4_revert(f)1685p4_delete(f)16861687# Set/clear executable bits1688for f in filesToChangeExecBit.keys():1689 mode = filesToChangeExecBit[f]1690setP4ExecBit(f, mode)16911692#1693# Build p4 change description, starting with the contents1694# of the git commit message.1695#1696 logMessage =extractLogMessageFromGitCommit(id)1697 logMessage = logMessage.strip()1698(logMessage, jobs) = self.separate_jobs_from_description(logMessage)16991700 template = self.prepareSubmitTemplate()1701 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)17021703if self.preserveUser:1704 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User17051706if self.checkAuthorship and not self.p4UserIsMe(p4User):1707 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1708 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1709 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"17101711 separatorLine ="######## everything below this line is just the diff #######\n"1712if not self.prepare_p4_only:1713 submitTemplate += separatorLine1714 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)17151716(handle, fileName) = tempfile.mkstemp()1717 tmpFile = os.fdopen(handle,"w+b")1718if self.isWindows:1719 submitTemplate = submitTemplate.replace("\n","\r\n")1720 tmpFile.write(submitTemplate)1721 tmpFile.close()17221723if self.prepare_p4_only:1724#1725# Leave the p4 tree prepared, and the submit template around1726# and let the user decide what to do next1727#1728print1729print"P4 workspace prepared for submission."1730print"To submit or revert, go to client workspace"1731print" "+ self.clientPath1732print1733print"To submit, use\"p4 submit\"to write a new description,"1734print"or\"p4 submit -i <%s\"to use the one prepared by" \1735"\"git p4\"."% fileName1736print"You can delete the file\"%s\"when finished."% fileName17371738if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1739print"To preserve change ownership by user%s, you must\n" \1740"do\"p4 change -f <change>\"after submitting and\n" \1741"edit the User field."1742if pureRenameCopy:1743print"After submitting, renamed files must be re-synced."1744print"Invoke\"p4 sync -f\"on each of these files:"1745for f in pureRenameCopy:1746print" "+ f17471748print1749print"To revert the changes, use\"p4 revert ...\", and delete"1750print"the submit template file\"%s\""% fileName1751if filesToAdd:1752print"Since the commit adds new files, they must be deleted:"1753for f in filesToAdd:1754print" "+ f1755print1756return True17571758#1759# Let the user edit the change description, then submit it.1760#1761 submitted =False17621763try:1764if self.edit_template(fileName):1765# read the edited message and submit1766 tmpFile =open(fileName,"rb")1767 message = tmpFile.read()1768 tmpFile.close()1769if self.isWindows:1770 message = message.replace("\r\n","\n")1771 submitTemplate = message[:message.index(separatorLine)]1772p4_write_pipe(['submit','-i'], submitTemplate)17731774if self.preserveUser:1775if p4User:1776# Get last changelist number. Cannot easily get it from1777# the submit command output as the output is1778# unmarshalled.1779 changelist = self.lastP4Changelist()1780 self.modifyChangelistUser(changelist, p4User)17811782# The rename/copy happened by applying a patch that created a1783# new file. This leaves it writable, which confuses p4.1784for f in pureRenameCopy:1785p4_sync(f,"-f")1786 submitted =True17871788finally:1789# skip this patch1790if not submitted:1791print"Submission cancelled, undoing p4 changes."1792for f in editedFiles:1793p4_revert(f)1794for f in filesToAdd:1795p4_revert(f)1796 os.remove(f)1797for f in filesToDelete:1798p4_revert(f)17991800 os.remove(fileName)1801return submitted18021803# Export git tags as p4 labels. Create a p4 label and then tag1804# with that.1805defexportGitTags(self, gitTags):1806 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1807iflen(validLabelRegexp) ==0:1808 validLabelRegexp = defaultLabelRegexp1809 m = re.compile(validLabelRegexp)18101811for name in gitTags:18121813if not m.match(name):1814if verbose:1815print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1816continue18171818# Get the p4 commit this corresponds to1819 logMessage =extractLogMessageFromGitCommit(name)1820 values =extractSettingsGitLog(logMessage)18211822if not values.has_key('change'):1823# a tag pointing to something not sent to p4; ignore1824if verbose:1825print"git tag%sdoes not give a p4 commit"% name1826continue1827else:1828 changelist = values['change']18291830# Get the tag details.1831 inHeader =True1832 isAnnotated =False1833 body = []1834for l inread_pipe_lines(["git","cat-file","-p", name]):1835 l = l.strip()1836if inHeader:1837if re.match(r'tag\s+', l):1838 isAnnotated =True1839elif re.match(r'\s*$', l):1840 inHeader =False1841continue1842else:1843 body.append(l)18441845if not isAnnotated:1846 body = ["lightweight tag imported by git p4\n"]18471848# Create the label - use the same view as the client spec we are using1849 clientSpec =getClientSpec()18501851 labelTemplate ="Label:%s\n"% name1852 labelTemplate +="Description:\n"1853for b in body:1854 labelTemplate +="\t"+ b +"\n"1855 labelTemplate +="View:\n"1856for depot_side in clientSpec.mappings:1857 labelTemplate +="\t%s\n"% depot_side18581859if self.dry_run:1860print"Would create p4 label%sfor tag"% name1861elif self.prepare_p4_only:1862print"Not creating p4 label%sfor tag due to option" \1863" --prepare-p4-only"% name1864else:1865p4_write_pipe(["label","-i"], labelTemplate)18661867# Use the label1868p4_system(["tag","-l", name] +1869["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18701871if verbose:1872print"created p4 label for tag%s"% name18731874defrun(self, args):1875iflen(args) ==0:1876 self.master =currentGitBranch()1877eliflen(args) ==1:1878 self.master = args[0]1879if notbranchExists(self.master):1880die("Branch%sdoes not exist"% self.master)1881else:1882return False18831884if self.master:1885 allowSubmit =gitConfig("git-p4.allowSubmit")1886iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1887die("%sis not in git-p4.allowSubmit"% self.master)18881889[upstream, settings] =findUpstreamBranchPoint()1890 self.depotPath = settings['depot-paths'][0]1891iflen(self.origin) ==0:1892 self.origin = upstream18931894if self.preserveUser:1895if not self.canChangeChangelists():1896die("Cannot preserve user names without p4 super-user or admin permissions")18971898# if not set from the command line, try the config file1899if self.conflict_behavior is None:1900 val =gitConfig("git-p4.conflict")1901if val:1902if val not in self.conflict_behavior_choices:1903die("Invalid value '%s' for config git-p4.conflict"% val)1904else:1905 val ="ask"1906 self.conflict_behavior = val19071908if self.verbose:1909print"Origin branch is "+ self.origin19101911iflen(self.depotPath) ==0:1912print"Internal error: cannot locate perforce depot path from existing branches"1913 sys.exit(128)19141915 self.useClientSpec =False1916ifgitConfigBool("git-p4.useclientspec"):1917 self.useClientSpec =True1918if self.useClientSpec:1919 self.clientSpecDirs =getClientSpec()19201921# Check for the existance of P4 branches1922 branchesDetected = (len(p4BranchesInGit().keys()) >1)19231924if self.useClientSpec and not branchesDetected:1925# all files are relative to the client spec1926 self.clientPath =getClientRoot()1927else:1928 self.clientPath =p4Where(self.depotPath)19291930if self.clientPath =="":1931die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19321933print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1934 self.oldWorkingDirectory = os.getcwd()19351936# ensure the clientPath exists1937 new_client_dir =False1938if not os.path.exists(self.clientPath):1939 new_client_dir =True1940 os.makedirs(self.clientPath)19411942chdir(self.clientPath, is_client_path=True)1943if self.dry_run:1944print"Would synchronize p4 checkout in%s"% self.clientPath1945else:1946print"Synchronizing p4 checkout..."1947if new_client_dir:1948# old one was destroyed, and maybe nobody told p41949p4_sync("...","-f")1950else:1951p4_sync("...")1952 self.check()19531954 commits = []1955if self.master:1956 commitish = self.master1957else:1958 commitish ='HEAD'19591960for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):1961 commits.append(line.strip())1962 commits.reverse()19631964if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1965 self.checkAuthorship =False1966else:1967 self.checkAuthorship =True19681969if self.preserveUser:1970 self.checkValidP4Users(commits)19711972#1973# Build up a set of options to be passed to diff when1974# submitting each commit to p4.1975#1976if self.detectRenames:1977# command-line -M arg1978 self.diffOpts ="-M"1979else:1980# If not explicitly set check the config variable1981 detectRenames =gitConfig("git-p4.detectRenames")19821983if detectRenames.lower() =="false"or detectRenames =="":1984 self.diffOpts =""1985elif detectRenames.lower() =="true":1986 self.diffOpts ="-M"1987else:1988 self.diffOpts ="-M%s"% detectRenames19891990# no command-line arg for -C or --find-copies-harder, just1991# config variables1992 detectCopies =gitConfig("git-p4.detectCopies")1993if detectCopies.lower() =="false"or detectCopies =="":1994pass1995elif detectCopies.lower() =="true":1996 self.diffOpts +=" -C"1997else:1998 self.diffOpts +=" -C%s"% detectCopies19992000ifgitConfigBool("git-p4.detectCopiesHarder"):2001 self.diffOpts +=" --find-copies-harder"20022003#2004# Apply the commits, one at a time. On failure, ask if should2005# continue to try the rest of the patches, or quit.2006#2007if self.dry_run:2008print"Would apply"2009 applied = []2010 last =len(commits) -12011for i, commit inenumerate(commits):2012if self.dry_run:2013print" ",read_pipe(["git","show","-s",2014"--format=format:%h%s", commit])2015 ok =True2016else:2017 ok = self.applyCommit(commit)2018if ok:2019 applied.append(commit)2020else:2021if self.prepare_p4_only and i < last:2022print"Processing only the first commit due to option" \2023" --prepare-p4-only"2024break2025if i < last:2026 quit =False2027while True:2028# prompt for what to do, or use the option/variable2029if self.conflict_behavior =="ask":2030print"What do you want to do?"2031 response =raw_input("[s]kip this commit but apply"2032" the rest, or [q]uit? ")2033if not response:2034continue2035elif self.conflict_behavior =="skip":2036 response ="s"2037elif self.conflict_behavior =="quit":2038 response ="q"2039else:2040die("Unknown conflict_behavior '%s'"%2041 self.conflict_behavior)20422043if response[0] =="s":2044print"Skipping this commit, but applying the rest"2045break2046if response[0] =="q":2047print"Quitting"2048 quit =True2049break2050if quit:2051break20522053chdir(self.oldWorkingDirectory)20542055if self.dry_run:2056pass2057elif self.prepare_p4_only:2058pass2059eliflen(commits) ==len(applied):2060print"All commits applied!"20612062 sync =P4Sync()2063if self.branch:2064 sync.branch = self.branch2065 sync.run([])20662067 rebase =P4Rebase()2068 rebase.rebase()20692070else:2071iflen(applied) ==0:2072print"No commits applied."2073else:2074print"Applied only the commits marked with '*':"2075for c in commits:2076if c in applied:2077 star ="*"2078else:2079 star =" "2080print star,read_pipe(["git","show","-s",2081"--format=format:%h%s", c])2082print"You will have to do 'git p4 sync' and rebase."20832084ifgitConfigBool("git-p4.exportLabels"):2085 self.exportLabels =True20862087if self.exportLabels:2088 p4Labels =getP4Labels(self.depotPath)2089 gitTags =getGitTags()20902091 missingGitTags = gitTags - p4Labels2092 self.exportGitTags(missingGitTags)20932094# exit with error unless everything applied perfectly2095iflen(commits) !=len(applied):2096 sys.exit(1)20972098return True20992100classView(object):2101"""Represent a p4 view ("p4 help views"), and map files in a2102 repo according to the view."""21032104def__init__(self, client_name):2105 self.mappings = []2106 self.client_prefix ="//%s/"% client_name2107# cache results of "p4 where" to lookup client file locations2108 self.client_spec_path_cache = {}21092110defappend(self, view_line):2111"""Parse a view line, splitting it into depot and client2112 sides. Append to self.mappings, preserving order. This2113 is only needed for tag creation."""21142115# Split the view line into exactly two words. P4 enforces2116# structure on these lines that simplifies this quite a bit.2117#2118# Either or both words may be double-quoted.2119# Single quotes do not matter.2120# Double-quote marks cannot occur inside the words.2121# A + or - prefix is also inside the quotes.2122# There are no quotes unless they contain a space.2123# The line is already white-space stripped.2124# The two words are separated by a single space.2125#2126if view_line[0] =='"':2127# First word is double quoted. Find its end.2128 close_quote_index = view_line.find('"',1)2129if close_quote_index <=0:2130die("No first-word closing quote found:%s"% view_line)2131 depot_side = view_line[1:close_quote_index]2132# skip closing quote and space2133 rhs_index = close_quote_index +1+12134else:2135 space_index = view_line.find(" ")2136if space_index <=0:2137die("No word-splitting space found:%s"% view_line)2138 depot_side = view_line[0:space_index]2139 rhs_index = space_index +121402141# prefix + means overlay on previous mapping2142if depot_side.startswith("+"):2143 depot_side = depot_side[1:]21442145# prefix - means exclude this path, leave out of mappings2146 exclude =False2147if depot_side.startswith("-"):2148 exclude =True2149 depot_side = depot_side[1:]21502151if not exclude:2152 self.mappings.append(depot_side)21532154defconvert_client_path(self, clientFile):2155# chop off //client/ part to make it relative2156if not clientFile.startswith(self.client_prefix):2157die("No prefix '%s' on clientFile '%s'"%2158(self.client_prefix, clientFile))2159return clientFile[len(self.client_prefix):]21602161defupdate_client_spec_path_cache(self, files):2162""" Caching file paths by "p4 where" batch query """21632164# List depot file paths exclude that already cached2165 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21662167iflen(fileArgs) ==0:2168return# All files in cache21692170 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2171for res in where_result:2172if"code"in res and res["code"] =="error":2173# assume error is "... file(s) not in client view"2174continue2175if"clientFile"not in res:2176die("No clientFile in 'p4 where' output")2177if"unmap"in res:2178# it will list all of them, but only one not unmap-ped2179continue2180ifgitConfigBool("core.ignorecase"):2181 res['depotFile'] = res['depotFile'].lower()2182 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])21832184# not found files or unmap files set to ""2185for depotFile in fileArgs:2186ifgitConfigBool("core.ignorecase"):2187 depotFile = depotFile.lower()2188if depotFile not in self.client_spec_path_cache:2189 self.client_spec_path_cache[depotFile] =""21902191defmap_in_client(self, depot_path):2192"""Return the relative location in the client where this2193 depot file should live. Returns "" if the file should2194 not be mapped in the client."""21952196ifgitConfigBool("core.ignorecase"):2197 depot_path = depot_path.lower()21982199if depot_path in self.client_spec_path_cache:2200return self.client_spec_path_cache[depot_path]22012202die("Error:%sis not found in client spec path"% depot_path )2203return""22042205classP4Sync(Command, P4UserMap):2206 delete_actions = ("delete","move/delete","purge")22072208def__init__(self):2209 Command.__init__(self)2210 P4UserMap.__init__(self)2211 self.options = [2212 optparse.make_option("--branch", dest="branch"),2213 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2214 optparse.make_option("--changesfile", dest="changesFile"),2215 optparse.make_option("--silent", dest="silent", action="store_true"),2216 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2217 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2218 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2219help="Import into refs/heads/ , not refs/remotes"),2220 optparse.make_option("--max-changes", dest="maxChanges",2221help="Maximum number of changes to import"),2222 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2223help="Internal block size to use when iteratively calling p4 changes"),2224 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2225help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2226 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2227help="Only sync files that are included in the Perforce Client Spec"),2228 optparse.make_option("-/", dest="cloneExclude",2229 action="append",type="string",2230help="exclude depot path"),2231]2232 self.description ="""Imports from Perforce into a git repository.\n2233 example:2234 //depot/my/project/ -- to import the current head2235 //depot/my/project/@all -- to import everything2236 //depot/my/project/@1,6 -- to import only from revision 1 to 622372238 (a ... is not needed in the path p4 specification, it's added implicitly)"""22392240 self.usage +=" //depot/path[@revRange]"2241 self.silent =False2242 self.createdBranches =set()2243 self.committedChanges =set()2244 self.branch =""2245 self.detectBranches =False2246 self.detectLabels =False2247 self.importLabels =False2248 self.changesFile =""2249 self.syncWithOrigin =True2250 self.importIntoRemotes =True2251 self.maxChanges =""2252 self.changes_block_size =None2253 self.keepRepoPath =False2254 self.depotPaths =None2255 self.p4BranchesInGit = []2256 self.cloneExclude = []2257 self.useClientSpec =False2258 self.useClientSpec_from_options =False2259 self.clientSpecDirs =None2260 self.tempBranches = []2261 self.tempBranchLocation ="git-p4-tmp"2262 self.largeFileSystem =None22632264ifgitConfig('git-p4.largeFileSystem'):2265 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2266 self.largeFileSystem =largeFileSystemConstructor(2267lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2268)22692270ifgitConfig("git-p4.syncFromOrigin") =="false":2271 self.syncWithOrigin =False22722273# This is required for the "append" cloneExclude action2274defensure_value(self, attr, value):2275if nothasattr(self, attr)orgetattr(self, attr)is None:2276setattr(self, attr, value)2277returngetattr(self, attr)22782279# Force a checkpoint in fast-import and wait for it to finish2280defcheckpoint(self):2281 self.gitStream.write("checkpoint\n\n")2282 self.gitStream.write("progress checkpoint\n\n")2283 out = self.gitOutput.readline()2284if self.verbose:2285print"checkpoint finished: "+ out22862287defextractFilesFromCommit(self, commit):2288 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2289for path in self.cloneExclude]2290 files = []2291 fnum =02292while commit.has_key("depotFile%s"% fnum):2293 path = commit["depotFile%s"% fnum]22942295if[p for p in self.cloneExclude2296ifp4PathStartsWith(path, p)]:2297 found =False2298else:2299 found = [p for p in self.depotPaths2300ifp4PathStartsWith(path, p)]2301if not found:2302 fnum = fnum +12303continue23042305file= {}2306file["path"] = path2307file["rev"] = commit["rev%s"% fnum]2308file["action"] = commit["action%s"% fnum]2309file["type"] = commit["type%s"% fnum]2310 files.append(file)2311 fnum = fnum +12312return files23132314defstripRepoPath(self, path, prefixes):2315"""When streaming files, this is called to map a p4 depot path2316 to where it should go in git. The prefixes are either2317 self.depotPaths, or self.branchPrefixes in the case of2318 branch detection."""23192320if self.useClientSpec:2321# branch detection moves files up a level (the branch name)2322# from what client spec interpretation gives2323 path = self.clientSpecDirs.map_in_client(path)2324if self.detectBranches:2325for b in self.knownBranches:2326if path.startswith(b +"/"):2327 path = path[len(b)+1:]23282329elif self.keepRepoPath:2330# Preserve everything in relative path name except leading2331# //depot/; just look at first prefix as they all should2332# be in the same depot.2333 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2334ifp4PathStartsWith(path, depot):2335 path = path[len(depot):]23362337else:2338for p in prefixes:2339ifp4PathStartsWith(path, p):2340 path = path[len(p):]2341break23422343 path =wildcard_decode(path)2344return path23452346defsplitFilesIntoBranches(self, commit):2347"""Look at each depotFile in the commit to figure out to what2348 branch it belongs."""23492350if self.clientSpecDirs:2351 files = self.extractFilesFromCommit(commit)2352 self.clientSpecDirs.update_client_spec_path_cache(files)23532354 branches = {}2355 fnum =02356while commit.has_key("depotFile%s"% fnum):2357 path = commit["depotFile%s"% fnum]2358 found = [p for p in self.depotPaths2359ifp4PathStartsWith(path, p)]2360if not found:2361 fnum = fnum +12362continue23632364file= {}2365file["path"] = path2366file["rev"] = commit["rev%s"% fnum]2367file["action"] = commit["action%s"% fnum]2368file["type"] = commit["type%s"% fnum]2369 fnum = fnum +123702371# start with the full relative path where this file would2372# go in a p4 client2373if self.useClientSpec:2374 relPath = self.clientSpecDirs.map_in_client(path)2375else:2376 relPath = self.stripRepoPath(path, self.depotPaths)23772378for branch in self.knownBranches.keys():2379# add a trailing slash so that a commit into qt/4.2foo2380# doesn't end up in qt/4.2, e.g.2381if relPath.startswith(branch +"/"):2382if branch not in branches:2383 branches[branch] = []2384 branches[branch].append(file)2385break23862387return branches23882389defwriteToGitStream(self, gitMode, relPath, contents):2390 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2391 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2392for d in contents:2393 self.gitStream.write(d)2394 self.gitStream.write('\n')23952396# output one file from the P4 stream2397# - helper for streamP4Files23982399defstreamOneP4File(self,file, contents):2400 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2401if verbose:2402 size =int(self.stream_file['fileSize'])2403 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2404 sys.stdout.flush()24052406(type_base, type_mods) =split_p4_type(file["type"])24072408 git_mode ="100644"2409if"x"in type_mods:2410 git_mode ="100755"2411if type_base =="symlink":2412 git_mode ="120000"2413# p4 print on a symlink sometimes contains "target\n";2414# if it does, remove the newline2415 data =''.join(contents)2416if not data:2417# Some version of p4 allowed creating a symlink that pointed2418# to nothing. This causes p4 errors when checking out such2419# a change, and errors here too. Work around it by ignoring2420# the bad symlink; hopefully a future change fixes it.2421print"\nIgnoring empty symlink in%s"%file['depotFile']2422return2423elif data[-1] =='\n':2424 contents = [data[:-1]]2425else:2426 contents = [data]24272428if type_base =="utf16":2429# p4 delivers different text in the python output to -G2430# than it does when using "print -o", or normal p4 client2431# operations. utf16 is converted to ascii or utf8, perhaps.2432# But ascii text saved as -t utf16 is completely mangled.2433# Invoke print -o to get the real contents.2434#2435# On windows, the newlines will always be mangled by print, so put2436# them back too. This is not needed to the cygwin windows version,2437# just the native "NT" type.2438#2439try:2440 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2441exceptExceptionas e:2442if'Translation of file content failed'instr(e):2443 type_base ='binary'2444else:2445raise e2446else:2447ifp4_version_string().find('/NT') >=0:2448 text = text.replace('\r\n','\n')2449 contents = [ text ]24502451if type_base =="apple":2452# Apple filetype files will be streamed as a concatenation of2453# its appledouble header and the contents. This is useless2454# on both macs and non-macs. If using "print -q -o xx", it2455# will create "xx" with the data, and "%xx" with the header.2456# This is also not very useful.2457#2458# Ideally, someday, this script can learn how to generate2459# appledouble files directly and import those to git, but2460# non-mac machines can never find a use for apple filetype.2461print"\nIgnoring apple filetype file%s"%file['depotFile']2462return24632464# Note that we do not try to de-mangle keywords on utf16 files,2465# even though in theory somebody may want that.2466 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2467if pattern:2468 regexp = re.compile(pattern, re.VERBOSE)2469 text =''.join(contents)2470 text = regexp.sub(r'$\1$', text)2471 contents = [ text ]24722473try:2474 relPath.decode('ascii')2475except:2476 encoding ='utf8'2477ifgitConfig('git-p4.pathEncoding'):2478 encoding =gitConfig('git-p4.pathEncoding')2479 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2480if self.verbose:2481print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)24822483if self.largeFileSystem:2484(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)24852486 self.writeToGitStream(git_mode, relPath, contents)24872488defstreamOneP4Deletion(self,file):2489 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2490if verbose:2491 sys.stdout.write("delete%s\n"% relPath)2492 sys.stdout.flush()2493 self.gitStream.write("D%s\n"% relPath)24942495if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2496 self.largeFileSystem.removeLargeFile(relPath)24972498# handle another chunk of streaming data2499defstreamP4FilesCb(self, marshalled):25002501# catch p4 errors and complain2502 err =None2503if"code"in marshalled:2504if marshalled["code"] =="error":2505if"data"in marshalled:2506 err = marshalled["data"].rstrip()25072508if not err and'fileSize'in self.stream_file:2509 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2510if required_bytes >0:2511 err ='Not enough space left on%s! Free at least%iMB.'% (2512 os.getcwd(), required_bytes/1024/10242513)25142515if err:2516 f =None2517if self.stream_have_file_info:2518if"depotFile"in self.stream_file:2519 f = self.stream_file["depotFile"]2520# force a failure in fast-import, else an empty2521# commit will be made2522 self.gitStream.write("\n")2523 self.gitStream.write("die-now\n")2524 self.gitStream.close()2525# ignore errors, but make sure it exits first2526 self.importProcess.wait()2527if f:2528die("Error from p4 print for%s:%s"% (f, err))2529else:2530die("Error from p4 print:%s"% err)25312532if marshalled.has_key('depotFile')and self.stream_have_file_info:2533# start of a new file - output the old one first2534 self.streamOneP4File(self.stream_file, self.stream_contents)2535 self.stream_file = {}2536 self.stream_contents = []2537 self.stream_have_file_info =False25382539# pick up the new file information... for the2540# 'data' field we need to append to our array2541for k in marshalled.keys():2542if k =='data':2543if'streamContentSize'not in self.stream_file:2544 self.stream_file['streamContentSize'] =02545 self.stream_file['streamContentSize'] +=len(marshalled['data'])2546 self.stream_contents.append(marshalled['data'])2547else:2548 self.stream_file[k] = marshalled[k]25492550if(verbose and2551'streamContentSize'in self.stream_file and2552'fileSize'in self.stream_file and2553'depotFile'in self.stream_file):2554 size =int(self.stream_file["fileSize"])2555if size >0:2556 progress =100*self.stream_file['streamContentSize']/size2557 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2558 sys.stdout.flush()25592560 self.stream_have_file_info =True25612562# Stream directly from "p4 files" into "git fast-import"2563defstreamP4Files(self, files):2564 filesForCommit = []2565 filesToRead = []2566 filesToDelete = []25672568for f in files:2569 filesForCommit.append(f)2570if f['action']in self.delete_actions:2571 filesToDelete.append(f)2572else:2573 filesToRead.append(f)25742575# deleted files...2576for f in filesToDelete:2577 self.streamOneP4Deletion(f)25782579iflen(filesToRead) >0:2580 self.stream_file = {}2581 self.stream_contents = []2582 self.stream_have_file_info =False25832584# curry self argument2585defstreamP4FilesCbSelf(entry):2586 self.streamP4FilesCb(entry)25872588 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]25892590p4CmdList(["-x","-","print"],2591 stdin=fileArgs,2592 cb=streamP4FilesCbSelf)25932594# do the last chunk2595if self.stream_file.has_key('depotFile'):2596 self.streamOneP4File(self.stream_file, self.stream_contents)25972598defmake_email(self, userid):2599if userid in self.users:2600return self.users[userid]2601else:2602return"%s<a@b>"% userid26032604defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2605""" Stream a p4 tag.2606 commit is either a git commit, or a fast-import mark, ":<p4commit>"2607 """26082609if verbose:2610print"writing tag%sfor commit%s"% (labelName, commit)2611 gitStream.write("tag%s\n"% labelName)2612 gitStream.write("from%s\n"% commit)26132614if labelDetails.has_key('Owner'):2615 owner = labelDetails["Owner"]2616else:2617 owner =None26182619# Try to use the owner of the p4 label, or failing that,2620# the current p4 user id.2621if owner:2622 email = self.make_email(owner)2623else:2624 email = self.make_email(self.p4UserId())2625 tagger ="%s %s %s"% (email, epoch, self.tz)26262627 gitStream.write("tagger%s\n"% tagger)26282629print"labelDetails=",labelDetails2630if labelDetails.has_key('Description'):2631 description = labelDetails['Description']2632else:2633 description ='Label from git p4'26342635 gitStream.write("data%d\n"%len(description))2636 gitStream.write(description)2637 gitStream.write("\n")26382639definClientSpec(self, path):2640if not self.clientSpecDirs:2641return True2642 inClientSpec = self.clientSpecDirs.map_in_client(path)2643if not inClientSpec and self.verbose:2644print('Ignoring file outside of client spec:{0}'.format(path))2645return inClientSpec26462647defhasBranchPrefix(self, path):2648if not self.branchPrefixes:2649return True2650 hasPrefix = [p for p in self.branchPrefixes2651ifp4PathStartsWith(path, p)]2652if hasPrefix and self.verbose:2653print('Ignoring file outside of prefix:{0}'.format(path))2654return hasPrefix26552656defcommit(self, details, files, branch, parent =""):2657 epoch = details["time"]2658 author = details["user"]26592660if self.verbose:2661print('commit into{0}'.format(branch))26622663if self.clientSpecDirs:2664 self.clientSpecDirs.update_client_spec_path_cache(files)26652666 files = [f for f in files2667if self.inClientSpec(f['path'])and self.hasBranchPrefix(f['path'])]26682669if not files and notgitConfigBool('git-p4.keepEmptyCommits'):2670print('Ignoring revision{0}as it would produce an empty commit.'2671.format(details['change']))2672return26732674 self.gitStream.write("commit%s\n"% branch)2675 self.gitStream.write("mark :%s\n"% details["change"])2676 self.committedChanges.add(int(details["change"]))2677 committer =""2678if author not in self.users:2679 self.getUserMapFromPerforceServer()2680 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)26812682 self.gitStream.write("committer%s\n"% committer)26832684 self.gitStream.write("data <<EOT\n")2685 self.gitStream.write(details["desc"])2686 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2687(','.join(self.branchPrefixes), details["change"]))2688iflen(details['options']) >0:2689 self.gitStream.write(": options =%s"% details['options'])2690 self.gitStream.write("]\nEOT\n\n")26912692iflen(parent) >0:2693if self.verbose:2694print"parent%s"% parent2695 self.gitStream.write("from%s\n"% parent)26962697 self.streamP4Files(files)2698 self.gitStream.write("\n")26992700 change =int(details["change"])27012702if self.labels.has_key(change):2703 label = self.labels[change]2704 labelDetails = label[0]2705 labelRevisions = label[1]2706if self.verbose:2707print"Change%sis labelled%s"% (change, labelDetails)27082709 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2710for p in self.branchPrefixes])27112712iflen(files) ==len(labelRevisions):27132714 cleanedFiles = {}2715for info in files:2716if info["action"]in self.delete_actions:2717continue2718 cleanedFiles[info["depotFile"]] = info["rev"]27192720if cleanedFiles == labelRevisions:2721 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)27222723else:2724if not self.silent:2725print("Tag%sdoes not match with change%s: files do not match."2726% (labelDetails["label"], change))27272728else:2729if not self.silent:2730print("Tag%sdoes not match with change%s: file count is different."2731% (labelDetails["label"], change))27322733# Build a dictionary of changelists and labels, for "detect-labels" option.2734defgetLabels(self):2735 self.labels = {}27362737 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2738iflen(l) >0and not self.silent:2739print"Finding files belonging to labels in%s"% `self.depotPaths`27402741for output in l:2742 label = output["label"]2743 revisions = {}2744 newestChange =02745if self.verbose:2746print"Querying files for label%s"% label2747forfileinp4CmdList(["files"] +2748["%s...@%s"% (p, label)2749for p in self.depotPaths]):2750 revisions[file["depotFile"]] =file["rev"]2751 change =int(file["change"])2752if change > newestChange:2753 newestChange = change27542755 self.labels[newestChange] = [output, revisions]27562757if self.verbose:2758print"Label changes:%s"% self.labels.keys()27592760# Import p4 labels as git tags. A direct mapping does not2761# exist, so assume that if all the files are at the same revision2762# then we can use that, or it's something more complicated we should2763# just ignore.2764defimportP4Labels(self, stream, p4Labels):2765if verbose:2766print"import p4 labels: "+' '.join(p4Labels)27672768 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2769 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2770iflen(validLabelRegexp) ==0:2771 validLabelRegexp = defaultLabelRegexp2772 m = re.compile(validLabelRegexp)27732774for name in p4Labels:2775 commitFound =False27762777if not m.match(name):2778if verbose:2779print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2780continue27812782if name in ignoredP4Labels:2783continue27842785 labelDetails =p4CmdList(['label',"-o", name])[0]27862787# get the most recent changelist for each file in this label2788 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2789for p in self.depotPaths])27902791if change.has_key('change'):2792# find the corresponding git commit; take the oldest commit2793 changelist =int(change['change'])2794if changelist in self.committedChanges:2795 gitCommit =":%d"% changelist # use a fast-import mark2796 commitFound =True2797else:2798 gitCommit =read_pipe(["git","rev-list","--max-count=1",2799"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2800iflen(gitCommit) ==0:2801print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2802else:2803 commitFound =True2804 gitCommit = gitCommit.strip()28052806if commitFound:2807# Convert from p4 time format2808try:2809 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2810exceptValueError:2811print"Could not convert label time%s"% labelDetails['Update']2812 tmwhen =128132814 when =int(time.mktime(tmwhen))2815 self.streamTag(stream, name, labelDetails, gitCommit, when)2816if verbose:2817print"p4 label%smapped to git commit%s"% (name, gitCommit)2818else:2819if verbose:2820print"Label%shas no changelists - possibly deleted?"% name28212822if not commitFound:2823# We can't import this label; don't try again as it will get very2824# expensive repeatedly fetching all the files for labels that will2825# never be imported. If the label is moved in the future, the2826# ignore will need to be removed manually.2827system(["git","config","--add","git-p4.ignoredP4Labels", name])28282829defguessProjectName(self):2830for p in self.depotPaths:2831if p.endswith("/"):2832 p = p[:-1]2833 p = p[p.strip().rfind("/") +1:]2834if not p.endswith("/"):2835 p +="/"2836return p28372838defgetBranchMapping(self):2839 lostAndFoundBranches =set()28402841 user =gitConfig("git-p4.branchUser")2842iflen(user) >0:2843 command ="branches -u%s"% user2844else:2845 command ="branches"28462847for info inp4CmdList(command):2848 details =p4Cmd(["branch","-o", info["branch"]])2849 viewIdx =02850while details.has_key("View%s"% viewIdx):2851 paths = details["View%s"% viewIdx].split(" ")2852 viewIdx = viewIdx +12853# require standard //depot/foo/... //depot/bar/... mapping2854iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2855continue2856 source = paths[0]2857 destination = paths[1]2858## HACK2859ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2860 source = source[len(self.depotPaths[0]):-4]2861 destination = destination[len(self.depotPaths[0]):-4]28622863if destination in self.knownBranches:2864if not self.silent:2865print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2866print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2867continue28682869 self.knownBranches[destination] = source28702871 lostAndFoundBranches.discard(destination)28722873if source not in self.knownBranches:2874 lostAndFoundBranches.add(source)28752876# Perforce does not strictly require branches to be defined, so we also2877# check git config for a branch list.2878#2879# Example of branch definition in git config file:2880# [git-p4]2881# branchList=main:branchA2882# branchList=main:branchB2883# branchList=branchA:branchC2884 configBranches =gitConfigList("git-p4.branchList")2885for branch in configBranches:2886if branch:2887(source, destination) = branch.split(":")2888 self.knownBranches[destination] = source28892890 lostAndFoundBranches.discard(destination)28912892if source not in self.knownBranches:2893 lostAndFoundBranches.add(source)289428952896for branch in lostAndFoundBranches:2897 self.knownBranches[branch] = branch28982899defgetBranchMappingFromGitBranches(self):2900 branches =p4BranchesInGit(self.importIntoRemotes)2901for branch in branches.keys():2902if branch =="master":2903 branch ="main"2904else:2905 branch = branch[len(self.projectName):]2906 self.knownBranches[branch] = branch29072908defupdateOptionDict(self, d):2909 option_keys = {}2910if self.keepRepoPath:2911 option_keys['keepRepoPath'] =129122913 d["options"] =' '.join(sorted(option_keys.keys()))29142915defreadOptions(self, d):2916 self.keepRepoPath = (d.has_key('options')2917and('keepRepoPath'in d['options']))29182919defgitRefForBranch(self, branch):2920if branch =="main":2921return self.refPrefix +"master"29222923iflen(branch) <=0:2924return branch29252926return self.refPrefix + self.projectName + branch29272928defgitCommitByP4Change(self, ref, change):2929if self.verbose:2930print"looking in ref "+ ref +" for change%susing bisect..."% change29312932 earliestCommit =""2933 latestCommit =parseRevision(ref)29342935while True:2936if self.verbose:2937print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2938 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2939iflen(next) ==0:2940if self.verbose:2941print"argh"2942return""2943 log =extractLogMessageFromGitCommit(next)2944 settings =extractSettingsGitLog(log)2945 currentChange =int(settings['change'])2946if self.verbose:2947print"current change%s"% currentChange29482949if currentChange == change:2950if self.verbose:2951print"found%s"% next2952return next29532954if currentChange < change:2955 earliestCommit ="^%s"% next2956else:2957 latestCommit ="%s"% next29582959return""29602961defimportNewBranch(self, branch, maxChange):2962# make fast-import flush all changes to disk and update the refs using the checkpoint2963# command so that we can try to find the branch parent in the git history2964 self.gitStream.write("checkpoint\n\n");2965 self.gitStream.flush();2966 branchPrefix = self.depotPaths[0] + branch +"/"2967range="@1,%s"% maxChange2968#print "prefix" + branchPrefix2969 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2970iflen(changes) <=0:2971return False2972 firstChange = changes[0]2973#print "first change in branch: %s" % firstChange2974 sourceBranch = self.knownBranches[branch]2975 sourceDepotPath = self.depotPaths[0] + sourceBranch2976 sourceRef = self.gitRefForBranch(sourceBranch)2977#print "source " + sourceBranch29782979 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2980#print "branch parent: %s" % branchParentChange2981 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2982iflen(gitParent) >0:2983 self.initialParents[self.gitRefForBranch(branch)] = gitParent2984#print "parent git commit: %s" % gitParent29852986 self.importChanges(changes)2987return True29882989defsearchParent(self, parent, branch, target):2990 parentFound =False2991for blob inread_pipe_lines(["git","rev-list","--reverse",2992"--no-merges", parent]):2993 blob = blob.strip()2994iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2995 parentFound =True2996if self.verbose:2997print"Found parent of%sin commit%s"% (branch, blob)2998break2999if parentFound:3000return blob3001else:3002return None30033004defimportChanges(self, changes):3005 cnt =13006for change in changes:3007 description =p4_describe(change)3008 self.updateOptionDict(description)30093010if not self.silent:3011 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))3012 sys.stdout.flush()3013 cnt = cnt +130143015try:3016if self.detectBranches:3017 branches = self.splitFilesIntoBranches(description)3018for branch in branches.keys():3019## HACK --hwn3020 branchPrefix = self.depotPaths[0] + branch +"/"3021 self.branchPrefixes = [ branchPrefix ]30223023 parent =""30243025 filesForCommit = branches[branch]30263027if self.verbose:3028print"branch is%s"% branch30293030 self.updatedBranches.add(branch)30313032if branch not in self.createdBranches:3033 self.createdBranches.add(branch)3034 parent = self.knownBranches[branch]3035if parent == branch:3036 parent =""3037else:3038 fullBranch = self.projectName + branch3039if fullBranch not in self.p4BranchesInGit:3040if not self.silent:3041print("\nImporting new branch%s"% fullBranch);3042if self.importNewBranch(branch, change -1):3043 parent =""3044 self.p4BranchesInGit.append(fullBranch)3045if not self.silent:3046print("\nResuming with change%s"% change);30473048if self.verbose:3049print"parent determined through known branches:%s"% parent30503051 branch = self.gitRefForBranch(branch)3052 parent = self.gitRefForBranch(parent)30533054if self.verbose:3055print"looking for initial parent for%s; current parent is%s"% (branch, parent)30563057iflen(parent) ==0and branch in self.initialParents:3058 parent = self.initialParents[branch]3059del self.initialParents[branch]30603061 blob =None3062iflen(parent) >0:3063 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3064if self.verbose:3065print"Creating temporary branch: "+ tempBranch3066 self.commit(description, filesForCommit, tempBranch)3067 self.tempBranches.append(tempBranch)3068 self.checkpoint()3069 blob = self.searchParent(parent, branch, tempBranch)3070if blob:3071 self.commit(description, filesForCommit, branch, blob)3072else:3073if self.verbose:3074print"Parent of%snot found. Committing into head of%s"% (branch, parent)3075 self.commit(description, filesForCommit, branch, parent)3076else:3077 files = self.extractFilesFromCommit(description)3078 self.commit(description, files, self.branch,3079 self.initialParent)3080# only needed once, to connect to the previous commit3081 self.initialParent =""3082exceptIOError:3083print self.gitError.read()3084 sys.exit(1)30853086defimportHeadRevision(self, revision):3087print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)30883089 details = {}3090 details["user"] ="git perforce import user"3091 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3092% (' '.join(self.depotPaths), revision))3093 details["change"] = revision3094 newestRevision =030953096 fileCnt =03097 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]30983099for info inp4CmdList(["files"] + fileArgs):31003101if'code'in info and info['code'] =='error':3102 sys.stderr.write("p4 returned an error:%s\n"3103% info['data'])3104if info['data'].find("must refer to client") >=0:3105 sys.stderr.write("This particular p4 error is misleading.\n")3106 sys.stderr.write("Perhaps the depot path was misspelled.\n");3107 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3108 sys.exit(1)3109if'p4ExitCode'in info:3110 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3111 sys.exit(1)311231133114 change =int(info["change"])3115if change > newestRevision:3116 newestRevision = change31173118if info["action"]in self.delete_actions:3119# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3120#fileCnt = fileCnt + 13121continue31223123for prop in["depotFile","rev","action","type"]:3124 details["%s%s"% (prop, fileCnt)] = info[prop]31253126 fileCnt = fileCnt +131273128 details["change"] = newestRevision31293130# Use time from top-most change so that all git p4 clones of3131# the same p4 repo have the same commit SHA1s.3132 res =p4_describe(newestRevision)3133 details["time"] = res["time"]31343135 self.updateOptionDict(details)3136try:3137 self.commit(details, self.extractFilesFromCommit(details), self.branch)3138exceptIOError:3139print"IO error with git fast-import. Is your git version recent enough?"3140print self.gitError.read()314131423143defrun(self, args):3144 self.depotPaths = []3145 self.changeRange =""3146 self.previousDepotPaths = []3147 self.hasOrigin =False31483149# map from branch depot path to parent branch3150 self.knownBranches = {}3151 self.initialParents = {}31523153if self.importIntoRemotes:3154 self.refPrefix ="refs/remotes/p4/"3155else:3156 self.refPrefix ="refs/heads/p4/"31573158if self.syncWithOrigin:3159 self.hasOrigin =originP4BranchesExist()3160if self.hasOrigin:3161if not self.silent:3162print'Syncing with origin first, using "git fetch origin"'3163system("git fetch origin")31643165 branch_arg_given =bool(self.branch)3166iflen(self.branch) ==0:3167 self.branch = self.refPrefix +"master"3168ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3169system("git update-ref%srefs/heads/p4"% self.branch)3170system("git branch -D p4")31713172# accept either the command-line option, or the configuration variable3173if self.useClientSpec:3174# will use this after clone to set the variable3175 self.useClientSpec_from_options =True3176else:3177ifgitConfigBool("git-p4.useclientspec"):3178 self.useClientSpec =True3179if self.useClientSpec:3180 self.clientSpecDirs =getClientSpec()31813182# TODO: should always look at previous commits,3183# merge with previous imports, if possible.3184if args == []:3185if self.hasOrigin:3186createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)31873188# branches holds mapping from branch name to sha13189 branches =p4BranchesInGit(self.importIntoRemotes)31903191# restrict to just this one, disabling detect-branches3192if branch_arg_given:3193 short = self.branch.split("/")[-1]3194if short in branches:3195 self.p4BranchesInGit = [ short ]3196else:3197 self.p4BranchesInGit = branches.keys()31983199iflen(self.p4BranchesInGit) >1:3200if not self.silent:3201print"Importing from/into multiple branches"3202 self.detectBranches =True3203for branch in branches.keys():3204 self.initialParents[self.refPrefix + branch] = \3205 branches[branch]32063207if self.verbose:3208print"branches:%s"% self.p4BranchesInGit32093210 p4Change =03211for branch in self.p4BranchesInGit:3212 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)32133214 settings =extractSettingsGitLog(logMsg)32153216 self.readOptions(settings)3217if(settings.has_key('depot-paths')3218and settings.has_key('change')):3219 change =int(settings['change']) +13220 p4Change =max(p4Change, change)32213222 depotPaths =sorted(settings['depot-paths'])3223if self.previousDepotPaths == []:3224 self.previousDepotPaths = depotPaths3225else:3226 paths = []3227for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3228 prev_list = prev.split("/")3229 cur_list = cur.split("/")3230for i inrange(0,min(len(cur_list),len(prev_list))):3231if cur_list[i] <> prev_list[i]:3232 i = i -13233break32343235 paths.append("/".join(cur_list[:i +1]))32363237 self.previousDepotPaths = paths32383239if p4Change >0:3240 self.depotPaths =sorted(self.previousDepotPaths)3241 self.changeRange ="@%s,#head"% p4Change3242if not self.silent and not self.detectBranches:3243print"Performing incremental import into%sgit branch"% self.branch32443245# accept multiple ref name abbreviations:3246# refs/foo/bar/branch -> use it exactly3247# p4/branch -> prepend refs/remotes/ or refs/heads/3248# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3249if not self.branch.startswith("refs/"):3250if self.importIntoRemotes:3251 prepend ="refs/remotes/"3252else:3253 prepend ="refs/heads/"3254if not self.branch.startswith("p4/"):3255 prepend +="p4/"3256 self.branch = prepend + self.branch32573258iflen(args) ==0and self.depotPaths:3259if not self.silent:3260print"Depot paths:%s"%' '.join(self.depotPaths)3261else:3262if self.depotPaths and self.depotPaths != args:3263print("previous import used depot path%sand now%swas specified. "3264"This doesn't work!"% (' '.join(self.depotPaths),3265' '.join(args)))3266 sys.exit(1)32673268 self.depotPaths =sorted(args)32693270 revision =""3271 self.users = {}32723273# Make sure no revision specifiers are used when --changesfile3274# is specified.3275 bad_changesfile =False3276iflen(self.changesFile) >0:3277for p in self.depotPaths:3278if p.find("@") >=0or p.find("#") >=0:3279 bad_changesfile =True3280break3281if bad_changesfile:3282die("Option --changesfile is incompatible with revision specifiers")32833284 newPaths = []3285for p in self.depotPaths:3286if p.find("@") != -1:3287 atIdx = p.index("@")3288 self.changeRange = p[atIdx:]3289if self.changeRange =="@all":3290 self.changeRange =""3291elif','not in self.changeRange:3292 revision = self.changeRange3293 self.changeRange =""3294 p = p[:atIdx]3295elif p.find("#") != -1:3296 hashIdx = p.index("#")3297 revision = p[hashIdx:]3298 p = p[:hashIdx]3299elif self.previousDepotPaths == []:3300# pay attention to changesfile, if given, else import3301# the entire p4 tree at the head revision3302iflen(self.changesFile) ==0:3303 revision ="#head"33043305 p = re.sub("\.\.\.$","", p)3306if not p.endswith("/"):3307 p +="/"33083309 newPaths.append(p)33103311 self.depotPaths = newPaths33123313# --detect-branches may change this for each branch3314 self.branchPrefixes = self.depotPaths33153316 self.loadUserMapFromCache()3317 self.labels = {}3318if self.detectLabels:3319 self.getLabels();33203321if self.detectBranches:3322## FIXME - what's a P4 projectName ?3323 self.projectName = self.guessProjectName()33243325if self.hasOrigin:3326 self.getBranchMappingFromGitBranches()3327else:3328 self.getBranchMapping()3329if self.verbose:3330print"p4-git branches:%s"% self.p4BranchesInGit3331print"initial parents:%s"% self.initialParents3332for b in self.p4BranchesInGit:3333if b !="master":33343335## FIXME3336 b = b[len(self.projectName):]3337 self.createdBranches.add(b)33383339 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33403341 self.importProcess = subprocess.Popen(["git","fast-import"],3342 stdin=subprocess.PIPE,3343 stdout=subprocess.PIPE,3344 stderr=subprocess.PIPE);3345 self.gitOutput = self.importProcess.stdout3346 self.gitStream = self.importProcess.stdin3347 self.gitError = self.importProcess.stderr33483349if revision:3350 self.importHeadRevision(revision)3351else:3352 changes = []33533354iflen(self.changesFile) >0:3355 output =open(self.changesFile).readlines()3356 changeSet =set()3357for line in output:3358 changeSet.add(int(line))33593360for change in changeSet:3361 changes.append(change)33623363 changes.sort()3364else:3365# catch "git p4 sync" with no new branches, in a repo that3366# does not have any existing p4 branches3367iflen(args) ==0:3368if not self.p4BranchesInGit:3369die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")33703371# The default branch is master, unless --branch is used to3372# specify something else. Make sure it exists, or complain3373# nicely about how to use --branch.3374if not self.detectBranches:3375if notbranch_exists(self.branch):3376if branch_arg_given:3377die("Error: branch%sdoes not exist."% self.branch)3378else:3379die("Error: no branch%s; perhaps specify one with --branch."%3380 self.branch)33813382if self.verbose:3383print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3384 self.changeRange)3385 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)33863387iflen(self.maxChanges) >0:3388 changes = changes[:min(int(self.maxChanges),len(changes))]33893390iflen(changes) ==0:3391if not self.silent:3392print"No changes to import!"3393else:3394if not self.silent and not self.detectBranches:3395print"Import destination:%s"% self.branch33963397 self.updatedBranches =set()33983399if not self.detectBranches:3400if args:3401# start a new branch3402 self.initialParent =""3403else:3404# build on a previous revision3405 self.initialParent =parseRevision(self.branch)34063407 self.importChanges(changes)34083409if not self.silent:3410print""3411iflen(self.updatedBranches) >0:3412 sys.stdout.write("Updated branches: ")3413for b in self.updatedBranches:3414 sys.stdout.write("%s"% b)3415 sys.stdout.write("\n")34163417ifgitConfigBool("git-p4.importLabels"):3418 self.importLabels =True34193420if self.importLabels:3421 p4Labels =getP4Labels(self.depotPaths)3422 gitTags =getGitTags()34233424 missingP4Labels = p4Labels - gitTags3425 self.importP4Labels(self.gitStream, missingP4Labels)34263427 self.gitStream.close()3428if self.importProcess.wait() !=0:3429die("fast-import failed:%s"% self.gitError.read())3430 self.gitOutput.close()3431 self.gitError.close()34323433# Cleanup temporary branches created during import3434if self.tempBranches != []:3435for branch in self.tempBranches:3436read_pipe("git update-ref -d%s"% branch)3437 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34383439# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3440# a convenient shortcut refname "p4".3441if self.importIntoRemotes:3442 head_ref = self.refPrefix +"HEAD"3443if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3444system(["git","symbolic-ref", head_ref, self.branch])34453446return True34473448classP4Rebase(Command):3449def__init__(self):3450 Command.__init__(self)3451 self.options = [3452 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3453]3454 self.importLabels =False3455 self.description = ("Fetches the latest revision from perforce and "3456+"rebases the current work (branch) against it")34573458defrun(self, args):3459 sync =P4Sync()3460 sync.importLabels = self.importLabels3461 sync.run([])34623463return self.rebase()34643465defrebase(self):3466if os.system("git update-index --refresh") !=0:3467die("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.");3468iflen(read_pipe("git diff-index HEAD --")) >0:3469die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");34703471[upstream, settings] =findUpstreamBranchPoint()3472iflen(upstream) ==0:3473die("Cannot find upstream branchpoint for rebase")34743475# the branchpoint may be p4/foo~3, so strip off the parent3476 upstream = re.sub("~[0-9]+$","", upstream)34773478print"Rebasing the current branch onto%s"% upstream3479 oldHead =read_pipe("git rev-parse HEAD").strip()3480system("git rebase%s"% upstream)3481system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3482return True34833484classP4Clone(P4Sync):3485def__init__(self):3486 P4Sync.__init__(self)3487 self.description ="Creates a new git repository and imports from Perforce into it"3488 self.usage ="usage: %prog [options] //depot/path[@revRange]"3489 self.options += [3490 optparse.make_option("--destination", dest="cloneDestination",3491 action='store', default=None,3492help="where to leave result of the clone"),3493 optparse.make_option("--bare", dest="cloneBare",3494 action="store_true", default=False),3495]3496 self.cloneDestination =None3497 self.needsGit =False3498 self.cloneBare =False34993500defdefaultDestination(self, args):3501## TODO: use common prefix of args?3502 depotPath = args[0]3503 depotDir = re.sub("(@[^@]*)$","", depotPath)3504 depotDir = re.sub("(#[^#]*)$","", depotDir)3505 depotDir = re.sub(r"\.\.\.$","", depotDir)3506 depotDir = re.sub(r"/$","", depotDir)3507return os.path.split(depotDir)[1]35083509defrun(self, args):3510iflen(args) <1:3511return False35123513if self.keepRepoPath and not self.cloneDestination:3514 sys.stderr.write("Must specify destination for --keep-path\n")3515 sys.exit(1)35163517 depotPaths = args35183519if not self.cloneDestination andlen(depotPaths) >1:3520 self.cloneDestination = depotPaths[-1]3521 depotPaths = depotPaths[:-1]35223523 self.cloneExclude = ["/"+p for p in self.cloneExclude]3524for p in depotPaths:3525if not p.startswith("//"):3526 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3527return False35283529if not self.cloneDestination:3530 self.cloneDestination = self.defaultDestination(args)35313532print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)35333534if not os.path.exists(self.cloneDestination):3535 os.makedirs(self.cloneDestination)3536chdir(self.cloneDestination)35373538 init_cmd = ["git","init"]3539if self.cloneBare:3540 init_cmd.append("--bare")3541 retcode = subprocess.call(init_cmd)3542if retcode:3543raiseCalledProcessError(retcode, init_cmd)35443545if not P4Sync.run(self, depotPaths):3546return False35473548# create a master branch and check out a work tree3549ifgitBranchExists(self.branch):3550system(["git","branch","master", self.branch ])3551if not self.cloneBare:3552system(["git","checkout","-f"])3553else:3554print'Not checking out any branch, use ' \3555'"git checkout -q -b master <branch>"'35563557# auto-set this variable if invoked with --use-client-spec3558if self.useClientSpec_from_options:3559system("git config --bool git-p4.useclientspec true")35603561return True35623563classP4Branches(Command):3564def__init__(self):3565 Command.__init__(self)3566 self.options = [ ]3567 self.description = ("Shows the git branches that hold imports and their "3568+"corresponding perforce depot paths")3569 self.verbose =False35703571defrun(self, args):3572iforiginP4BranchesExist():3573createOrUpdateBranchesFromOrigin()35743575 cmdline ="git rev-parse --symbolic "3576 cmdline +=" --remotes"35773578for line inread_pipe_lines(cmdline):3579 line = line.strip()35803581if not line.startswith('p4/')or line =="p4/HEAD":3582continue3583 branch = line35843585 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3586 settings =extractSettingsGitLog(log)35873588print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3589return True35903591classHelpFormatter(optparse.IndentedHelpFormatter):3592def__init__(self):3593 optparse.IndentedHelpFormatter.__init__(self)35943595defformat_description(self, description):3596if description:3597return description +"\n"3598else:3599return""36003601defprintUsage(commands):3602print"usage:%s<command> [options]"% sys.argv[0]3603print""3604print"valid commands:%s"%", ".join(commands)3605print""3606print"Try%s<command> --help for command specific help."% sys.argv[0]3607print""36083609commands = {3610"debug": P4Debug,3611"submit": P4Submit,3612"commit": P4Submit,3613"sync": P4Sync,3614"rebase": P4Rebase,3615"clone": P4Clone,3616"rollback": P4RollBack,3617"branches": P4Branches3618}361936203621defmain():3622iflen(sys.argv[1:]) ==0:3623printUsage(commands.keys())3624 sys.exit(2)36253626 cmdName = sys.argv[1]3627try:3628 klass = commands[cmdName]3629 cmd =klass()3630exceptKeyError:3631print"unknown command%s"% cmdName3632print""3633printUsage(commands.keys())3634 sys.exit(2)36353636 options = cmd.options3637 cmd.gitdir = os.environ.get("GIT_DIR",None)36383639 args = sys.argv[2:]36403641 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3642if cmd.needsGit:3643 options.append(optparse.make_option("--git-dir", dest="gitdir"))36443645 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3646 options,3647 description = cmd.description,3648 formatter =HelpFormatter())36493650(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3651global verbose3652 verbose = cmd.verbose3653if cmd.needsGit:3654if cmd.gitdir ==None:3655 cmd.gitdir = os.path.abspath(".git")3656if notisValidGitDir(cmd.gitdir):3657 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3658if os.path.exists(cmd.gitdir):3659 cdup =read_pipe("git rev-parse --show-cdup").strip()3660iflen(cdup) >0:3661chdir(cdup);36623663if notisValidGitDir(cmd.gitdir):3664ifisValidGitDir(cmd.gitdir +"/.git"):3665 cmd.gitdir +="/.git"3666else:3667die("fatal: cannot locate git repository at%s"% cmd.gitdir)36683669 os.environ["GIT_DIR"] = cmd.gitdir36703671if not cmd.run(args):3672 parser.print_help()3673 sys.exit(2)367436753676if __name__ =='__main__':3677main()