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(pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)1009if pointer_git_mode:1010 git_mode = pointer_git_mode1011if localLargeFile:1012# Move temp file to final location in large file system1013 largeFileDir = os.path.dirname(localLargeFile)1014if not os.path.isdir(largeFileDir):1015 os.makedirs(largeFileDir)1016 shutil.move(contentTempFile, localLargeFile)1017 self.addLargeFile(relPath)1018ifgitConfigBool('git-p4.largeFilePush'):1019 self.pushFile(localLargeFile)1020if verbose:1021 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1022return(git_mode, contents)10231024classMockLFS(LargeFileSystem):1025"""Mock large file system for testing."""10261027defgeneratePointer(self, contentFile):1028"""The pointer content is the original content prefixed with "pointer-".1029 The local filename of the large file storage is derived from the file content.1030 """1031withopen(contentFile,'r')as f:1032 content =next(f)1033 gitMode ='100644'1034 pointerContents ='pointer-'+ content1035 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1036return(gitMode, pointerContents, localLargeFile)10371038defpushFile(self, localLargeFile):1039"""The remote filename of the large file storage is the same as the local1040 one but in a different directory.1041 """1042 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1043if not os.path.exists(remotePath):1044 os.makedirs(remotePath)1045 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10461047classGitLFS(LargeFileSystem):1048"""Git LFS as backend for the git-p4 large file system.1049 See https://git-lfs.github.com/ for details."""10501051def__init__(self, *args):1052 LargeFileSystem.__init__(self, *args)1053 self.baseGitAttributes = []10541055defgeneratePointer(self, contentFile):1056"""Generate a Git LFS pointer for the content. Return LFS Pointer file1057 mode and content which is stored in the Git repository instead of1058 the actual content. Return also the new location of the actual1059 content.1060 """1061if os.path.getsize(contentFile) ==0:1062return(None,'',None)10631064 pointerProcess = subprocess.Popen(1065['git','lfs','pointer','--file='+ contentFile],1066 stdout=subprocess.PIPE1067)1068 pointerFile = pointerProcess.stdout.read()1069if pointerProcess.wait():1070 os.remove(contentFile)1071die('git-lfs pointer command failed. Did you install the extension?')10721073# Git LFS removed the preamble in the output of the 'pointer' command1074# starting from version 1.2.0. Check for the preamble here to support1075# earlier versions.1076# c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b431077if pointerFile.startswith('Git LFS pointer for'):1078 pointerFile = re.sub(r'Git LFS pointer for.*\n\n','', pointerFile)10791080 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)1081 localLargeFile = os.path.join(1082 os.getcwd(),1083'.git','lfs','objects', oid[:2], oid[2:4],1084 oid,1085)1086# LFS Spec states that pointer files should not have the executable bit set.1087 gitMode ='100644'1088return(gitMode, pointerFile, localLargeFile)10891090defpushFile(self, localLargeFile):1091 uploadProcess = subprocess.Popen(1092['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1093)1094if uploadProcess.wait():1095die('git-lfs push command failed. Did you define a remote?')10961097defgenerateGitAttributes(self):1098return(1099 self.baseGitAttributes +1100[1101'\n',1102'#\n',1103'# Git LFS (see https://git-lfs.github.com/)\n',1104'#\n',1105] +1106['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1107for f insorted(gitConfigList('git-p4.largeFileExtensions'))1108] +1109['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1110for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1111]1112)11131114defaddLargeFile(self, relPath):1115 LargeFileSystem.addLargeFile(self, relPath)1116 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11171118defremoveLargeFile(self, relPath):1119 LargeFileSystem.removeLargeFile(self, relPath)1120 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11211122defprocessContent(self, git_mode, relPath, contents):1123if relPath =='.gitattributes':1124 self.baseGitAttributes = contents1125return(git_mode, self.generateGitAttributes())1126else:1127return LargeFileSystem.processContent(self, git_mode, relPath, contents)11281129class Command:1130def__init__(self):1131 self.usage ="usage: %prog [options]"1132 self.needsGit =True1133 self.verbose =False11341135class P4UserMap:1136def__init__(self):1137 self.userMapFromPerforceServer =False1138 self.myP4UserId =None11391140defp4UserId(self):1141if self.myP4UserId:1142return self.myP4UserId11431144 results =p4CmdList("user -o")1145for r in results:1146if r.has_key('User'):1147 self.myP4UserId = r['User']1148return r['User']1149die("Could not find your p4 user id")11501151defp4UserIsMe(self, p4User):1152# return True if the given p4 user is actually me1153 me = self.p4UserId()1154if not p4User or p4User != me:1155return False1156else:1157return True11581159defgetUserCacheFilename(self):1160 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1161return home +"/.gitp4-usercache.txt"11621163defgetUserMapFromPerforceServer(self):1164if self.userMapFromPerforceServer:1165return1166 self.users = {}1167 self.emails = {}11681169for output inp4CmdList("users"):1170if not output.has_key("User"):1171continue1172 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1173 self.emails[output["Email"]] = output["User"]11741175 mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)1176for mapUserConfig ingitConfigList("git-p4.mapUser"):1177 mapUser = mapUserConfigRegex.findall(mapUserConfig)1178if mapUser andlen(mapUser[0]) ==3:1179 user = mapUser[0][0]1180 fullname = mapUser[0][1]1181 email = mapUser[0][2]1182 self.users[user] = fullname +" <"+ email +">"1183 self.emails[email] = user11841185 s =''1186for(key, val)in self.users.items():1187 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11881189open(self.getUserCacheFilename(),"wb").write(s)1190 self.userMapFromPerforceServer =True11911192defloadUserMapFromCache(self):1193 self.users = {}1194 self.userMapFromPerforceServer =False1195try:1196 cache =open(self.getUserCacheFilename(),"rb")1197 lines = cache.readlines()1198 cache.close()1199for line in lines:1200 entry = line.strip().split("\t")1201 self.users[entry[0]] = entry[1]1202exceptIOError:1203 self.getUserMapFromPerforceServer()12041205classP4Debug(Command):1206def__init__(self):1207 Command.__init__(self)1208 self.options = []1209 self.description ="A tool to debug the output of p4 -G."1210 self.needsGit =False12111212defrun(self, args):1213 j =01214for output inp4CmdList(args):1215print'Element:%d'% j1216 j +=11217print output1218return True12191220classP4RollBack(Command):1221def__init__(self):1222 Command.__init__(self)1223 self.options = [1224 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1225]1226 self.description ="A tool to debug the multi-branch import. Don't use :)"1227 self.rollbackLocalBranches =False12281229defrun(self, args):1230iflen(args) !=1:1231return False1232 maxChange =int(args[0])12331234if"p4ExitCode"inp4Cmd("changes -m 1"):1235die("Problems executing p4");12361237if self.rollbackLocalBranches:1238 refPrefix ="refs/heads/"1239 lines =read_pipe_lines("git rev-parse --symbolic --branches")1240else:1241 refPrefix ="refs/remotes/"1242 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12431244for line in lines:1245if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1246 line = line.strip()1247 ref = refPrefix + line1248 log =extractLogMessageFromGitCommit(ref)1249 settings =extractSettingsGitLog(log)12501251 depotPaths = settings['depot-paths']1252 change = settings['change']12531254 changed =False12551256iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1257for p in depotPaths]))) ==0:1258print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1259system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1260continue12611262while change andint(change) > maxChange:1263 changed =True1264if self.verbose:1265print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1266system("git update-ref%s\"%s^\""% (ref, ref))1267 log =extractLogMessageFromGitCommit(ref)1268 settings =extractSettingsGitLog(log)126912701271 depotPaths = settings['depot-paths']1272 change = settings['change']12731274if changed:1275print"%srewound to%s"% (ref, change)12761277return True12781279classP4Submit(Command, P4UserMap):12801281 conflict_behavior_choices = ("ask","skip","quit")12821283def__init__(self):1284 Command.__init__(self)1285 P4UserMap.__init__(self)1286 self.options = [1287 optparse.make_option("--origin", dest="origin"),1288 optparse.make_option("-M", dest="detectRenames", action="store_true"),1289# preserve the user, requires relevant p4 permissions1290 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1291 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1292 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1293 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1294 optparse.make_option("--conflict", dest="conflict_behavior",1295 choices=self.conflict_behavior_choices),1296 optparse.make_option("--branch", dest="branch"),1297]1298 self.description ="Submit changes from git to the perforce depot."1299 self.usage +=" [name of git branch to submit into perforce depot]"1300 self.origin =""1301 self.detectRenames =False1302 self.preserveUser =gitConfigBool("git-p4.preserveUser")1303 self.dry_run =False1304 self.prepare_p4_only =False1305 self.conflict_behavior =None1306 self.isWindows = (platform.system() =="Windows")1307 self.exportLabels =False1308 self.p4HasMoveCommand =p4_has_move_command()1309 self.branch =None13101311ifgitConfig('git-p4.largeFileSystem'):1312die("Large file system not supported for git-p4 submit command. Please remove it from config.")13131314defcheck(self):1315iflen(p4CmdList("opened ...")) >0:1316die("You have files opened with perforce! Close them before starting the sync.")13171318defseparate_jobs_from_description(self, message):1319"""Extract and return a possible Jobs field in the commit1320 message. It goes into a separate section in the p4 change1321 specification.13221323 A jobs line starts with "Jobs:" and looks like a new field1324 in a form. Values are white-space separated on the same1325 line or on following lines that start with a tab.13261327 This does not parse and extract the full git commit message1328 like a p4 form. It just sees the Jobs: line as a marker1329 to pass everything from then on directly into the p4 form,1330 but outside the description section.13311332 Return a tuple (stripped log message, jobs string)."""13331334 m = re.search(r'^Jobs:', message, re.MULTILINE)1335if m is None:1336return(message,None)13371338 jobtext = message[m.start():]1339 stripped_message = message[:m.start()].rstrip()1340return(stripped_message, jobtext)13411342defprepareLogMessage(self, template, message, jobs):1343"""Edits the template returned from "p4 change -o" to insert1344 the message in the Description field, and the jobs text in1345 the Jobs field."""1346 result =""13471348 inDescriptionSection =False13491350for line in template.split("\n"):1351if line.startswith("#"):1352 result += line +"\n"1353continue13541355if inDescriptionSection:1356if line.startswith("Files:")or line.startswith("Jobs:"):1357 inDescriptionSection =False1358# insert Jobs section1359if jobs:1360 result += jobs +"\n"1361else:1362continue1363else:1364if line.startswith("Description:"):1365 inDescriptionSection =True1366 line +="\n"1367for messageLine in message.split("\n"):1368 line +="\t"+ messageLine +"\n"13691370 result += line +"\n"13711372return result13731374defpatchRCSKeywords(self,file, pattern):1375# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1376(handle, outFileName) = tempfile.mkstemp(dir='.')1377try:1378 outFile = os.fdopen(handle,"w+")1379 inFile =open(file,"r")1380 regexp = re.compile(pattern, re.VERBOSE)1381for line in inFile.readlines():1382 line = regexp.sub(r'$\1$', line)1383 outFile.write(line)1384 inFile.close()1385 outFile.close()1386# Forcibly overwrite the original file1387 os.unlink(file)1388 shutil.move(outFileName,file)1389except:1390# cleanup our temporary file1391 os.unlink(outFileName)1392print"Failed to strip RCS keywords in%s"%file1393raise13941395print"Patched up RCS keywords in%s"%file13961397defp4UserForCommit(self,id):1398# Return the tuple (perforce user,git email) for a given git commit id1399 self.getUserMapFromPerforceServer()1400 gitEmail =read_pipe(["git","log","--max-count=1",1401"--format=%ae",id])1402 gitEmail = gitEmail.strip()1403if not self.emails.has_key(gitEmail):1404return(None,gitEmail)1405else:1406return(self.emails[gitEmail],gitEmail)14071408defcheckValidP4Users(self,commits):1409# check if any git authors cannot be mapped to p4 users1410foridin commits:1411(user,email) = self.p4UserForCommit(id)1412if not user:1413 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1414ifgitConfigBool("git-p4.allowMissingP4Users"):1415print"%s"% msg1416else:1417die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)14181419deflastP4Changelist(self):1420# Get back the last changelist number submitted in this client spec. This1421# then gets used to patch up the username in the change. If the same1422# client spec is being used by multiple processes then this might go1423# wrong.1424 results =p4CmdList("client -o")# find the current client1425 client =None1426for r in results:1427if r.has_key('Client'):1428 client = r['Client']1429break1430if not client:1431die("could not get client spec")1432 results =p4CmdList(["changes","-c", client,"-m","1"])1433for r in results:1434if r.has_key('change'):1435return r['change']1436die("Could not get changelist number for last submit - cannot patch up user details")14371438defmodifyChangelistUser(self, changelist, newUser):1439# fixup the user field of a changelist after it has been submitted.1440 changes =p4CmdList("change -o%s"% changelist)1441iflen(changes) !=1:1442die("Bad output from p4 change modifying%sto user%s"%1443(changelist, newUser))14441445 c = changes[0]1446if c['User'] == newUser:return# nothing to do1447 c['User'] = newUser1448input= marshal.dumps(c)14491450 result =p4CmdList("change -f -i", stdin=input)1451for r in result:1452if r.has_key('code'):1453if r['code'] =='error':1454die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1455if r.has_key('data'):1456print("Updated user field for changelist%sto%s"% (changelist, newUser))1457return1458die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14591460defcanChangeChangelists(self):1461# check to see if we have p4 admin or super-user permissions, either of1462# which are required to modify changelists.1463 results =p4CmdList(["protects", self.depotPath])1464for r in results:1465if r.has_key('perm'):1466if r['perm'] =='admin':1467return11468if r['perm'] =='super':1469return11470return014711472defprepareSubmitTemplate(self):1473"""Run "p4 change -o" to grab a change specification template.1474 This does not use "p4 -G", as it is nice to keep the submission1475 template in original order, since a human might edit it.14761477 Remove lines in the Files section that show changes to files1478 outside the depot path we're committing into."""14791480[upstream, settings] =findUpstreamBranchPoint()14811482 template =""1483 inFilesSection =False1484for line inp4_read_pipe_lines(['change','-o']):1485if line.endswith("\r\n"):1486 line = line[:-2] +"\n"1487if inFilesSection:1488if line.startswith("\t"):1489# path starts and ends with a tab1490 path = line[1:]1491 lastTab = path.rfind("\t")1492if lastTab != -1:1493 path = path[:lastTab]1494if settings.has_key('depot-paths'):1495if not[p for p in settings['depot-paths']1496ifp4PathStartsWith(path, p)]:1497continue1498else:1499if notp4PathStartsWith(path, self.depotPath):1500continue1501else:1502 inFilesSection =False1503else:1504if line.startswith("Files:"):1505 inFilesSection =True15061507 template += line15081509return template15101511defedit_template(self, template_file):1512"""Invoke the editor to let the user change the submission1513 message. Return true if okay to continue with the submit."""15141515# if configured to skip the editing part, just submit1516ifgitConfigBool("git-p4.skipSubmitEdit"):1517return True15181519# look at the modification time, to check later if the user saved1520# the file1521 mtime = os.stat(template_file).st_mtime15221523# invoke the editor1524if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1525 editor = os.environ.get("P4EDITOR")1526else:1527 editor =read_pipe("git var GIT_EDITOR").strip()1528system(["sh","-c", ('%s"$@"'% editor), editor, template_file])15291530# If the file was not saved, prompt to see if this patch should1531# be skipped. But skip this verification step if configured so.1532ifgitConfigBool("git-p4.skipSubmitEditCheck"):1533return True15341535# modification time updated means user saved the file1536if os.stat(template_file).st_mtime > mtime:1537return True15381539while True:1540 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1541if response =='y':1542return True1543if response =='n':1544return False15451546defget_diff_description(self, editedFiles, filesToAdd):1547# diff1548if os.environ.has_key("P4DIFF"):1549del(os.environ["P4DIFF"])1550 diff =""1551for editedFile in editedFiles:1552 diff +=p4_read_pipe(['diff','-du',1553wildcard_encode(editedFile)])15541555# new file diff1556 newdiff =""1557for newFile in filesToAdd:1558 newdiff +="==== new file ====\n"1559 newdiff +="--- /dev/null\n"1560 newdiff +="+++%s\n"% newFile1561 f =open(newFile,"r")1562for line in f.readlines():1563 newdiff +="+"+ line1564 f.close()15651566return(diff + newdiff).replace('\r\n','\n')15671568defapplyCommit(self,id):1569"""Apply one commit, return True if it succeeded."""15701571print"Applying",read_pipe(["git","show","-s",1572"--format=format:%h%s",id])15731574(p4User, gitEmail) = self.p4UserForCommit(id)15751576 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1577 filesToAdd =set()1578 filesToChangeType =set()1579 filesToDelete =set()1580 editedFiles =set()1581 pureRenameCopy =set()1582 filesToChangeExecBit = {}15831584for line in diff:1585 diff =parseDiffTreeEntry(line)1586 modifier = diff['status']1587 path = diff['src']1588if modifier =="M":1589p4_edit(path)1590ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1591 filesToChangeExecBit[path] = diff['dst_mode']1592 editedFiles.add(path)1593elif modifier =="A":1594 filesToAdd.add(path)1595 filesToChangeExecBit[path] = diff['dst_mode']1596if path in filesToDelete:1597 filesToDelete.remove(path)1598elif modifier =="D":1599 filesToDelete.add(path)1600if path in filesToAdd:1601 filesToAdd.remove(path)1602elif modifier =="C":1603 src, dest = diff['src'], diff['dst']1604p4_integrate(src, dest)1605 pureRenameCopy.add(dest)1606if diff['src_sha1'] != diff['dst_sha1']:1607p4_edit(dest)1608 pureRenameCopy.discard(dest)1609ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1610p4_edit(dest)1611 pureRenameCopy.discard(dest)1612 filesToChangeExecBit[dest] = diff['dst_mode']1613if self.isWindows:1614# turn off read-only attribute1615 os.chmod(dest, stat.S_IWRITE)1616 os.unlink(dest)1617 editedFiles.add(dest)1618elif modifier =="R":1619 src, dest = diff['src'], diff['dst']1620if self.p4HasMoveCommand:1621p4_edit(src)# src must be open before move1622p4_move(src, dest)# opens for (move/delete, move/add)1623else:1624p4_integrate(src, dest)1625if diff['src_sha1'] != diff['dst_sha1']:1626p4_edit(dest)1627else:1628 pureRenameCopy.add(dest)1629ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1630if not self.p4HasMoveCommand:1631p4_edit(dest)# with move: already open, writable1632 filesToChangeExecBit[dest] = diff['dst_mode']1633if not self.p4HasMoveCommand:1634if self.isWindows:1635 os.chmod(dest, stat.S_IWRITE)1636 os.unlink(dest)1637 filesToDelete.add(src)1638 editedFiles.add(dest)1639elif modifier =="T":1640 filesToChangeType.add(path)1641else:1642die("unknown modifier%sfor%s"% (modifier, path))16431644 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1645 patchcmd = diffcmd +" | git apply "1646 tryPatchCmd = patchcmd +"--check -"1647 applyPatchCmd = patchcmd +"--check --apply -"1648 patch_succeeded =True16491650if os.system(tryPatchCmd) !=0:1651 fixed_rcs_keywords =False1652 patch_succeeded =False1653print"Unfortunately applying the change failed!"16541655# Patch failed, maybe it's just RCS keyword woes. Look through1656# the patch to see if that's possible.1657ifgitConfigBool("git-p4.attemptRCSCleanup"):1658file=None1659 pattern =None1660 kwfiles = {}1661forfilein editedFiles | filesToDelete:1662# did this file's delta contain RCS keywords?1663 pattern =p4_keywords_regexp_for_file(file)16641665if pattern:1666# this file is a possibility...look for RCS keywords.1667 regexp = re.compile(pattern, re.VERBOSE)1668for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1669if regexp.search(line):1670if verbose:1671print"got keyword match on%sin%sin%s"% (pattern, line,file)1672 kwfiles[file] = pattern1673break16741675forfilein kwfiles:1676if verbose:1677print"zapping%swith%s"% (line,pattern)1678# File is being deleted, so not open in p4. Must1679# disable the read-only bit on windows.1680if self.isWindows andfilenot in editedFiles:1681 os.chmod(file, stat.S_IWRITE)1682 self.patchRCSKeywords(file, kwfiles[file])1683 fixed_rcs_keywords =True16841685if fixed_rcs_keywords:1686print"Retrying the patch with RCS keywords cleaned up"1687if os.system(tryPatchCmd) ==0:1688 patch_succeeded =True16891690if not patch_succeeded:1691for f in editedFiles:1692p4_revert(f)1693return False16941695#1696# Apply the patch for real, and do add/delete/+x handling.1697#1698system(applyPatchCmd)16991700for f in filesToChangeType:1701p4_edit(f,"-t","auto")1702for f in filesToAdd:1703p4_add(f)1704for f in filesToDelete:1705p4_revert(f)1706p4_delete(f)17071708# Set/clear executable bits1709for f in filesToChangeExecBit.keys():1710 mode = filesToChangeExecBit[f]1711setP4ExecBit(f, mode)17121713#1714# Build p4 change description, starting with the contents1715# of the git commit message.1716#1717 logMessage =extractLogMessageFromGitCommit(id)1718 logMessage = logMessage.strip()1719(logMessage, jobs) = self.separate_jobs_from_description(logMessage)17201721 template = self.prepareSubmitTemplate()1722 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)17231724if self.preserveUser:1725 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User17261727if self.checkAuthorship and not self.p4UserIsMe(p4User):1728 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1729 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1730 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"17311732 separatorLine ="######## everything below this line is just the diff #######\n"1733if not self.prepare_p4_only:1734 submitTemplate += separatorLine1735 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)17361737(handle, fileName) = tempfile.mkstemp()1738 tmpFile = os.fdopen(handle,"w+b")1739if self.isWindows:1740 submitTemplate = submitTemplate.replace("\n","\r\n")1741 tmpFile.write(submitTemplate)1742 tmpFile.close()17431744if self.prepare_p4_only:1745#1746# Leave the p4 tree prepared, and the submit template around1747# and let the user decide what to do next1748#1749print1750print"P4 workspace prepared for submission."1751print"To submit or revert, go to client workspace"1752print" "+ self.clientPath1753print1754print"To submit, use\"p4 submit\"to write a new description,"1755print"or\"p4 submit -i <%s\"to use the one prepared by" \1756"\"git p4\"."% fileName1757print"You can delete the file\"%s\"when finished."% fileName17581759if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1760print"To preserve change ownership by user%s, you must\n" \1761"do\"p4 change -f <change>\"after submitting and\n" \1762"edit the User field."1763if pureRenameCopy:1764print"After submitting, renamed files must be re-synced."1765print"Invoke\"p4 sync -f\"on each of these files:"1766for f in pureRenameCopy:1767print" "+ f17681769print1770print"To revert the changes, use\"p4 revert ...\", and delete"1771print"the submit template file\"%s\""% fileName1772if filesToAdd:1773print"Since the commit adds new files, they must be deleted:"1774for f in filesToAdd:1775print" "+ f1776print1777return True17781779#1780# Let the user edit the change description, then submit it.1781#1782 submitted =False17831784try:1785if self.edit_template(fileName):1786# read the edited message and submit1787 tmpFile =open(fileName,"rb")1788 message = tmpFile.read()1789 tmpFile.close()1790if self.isWindows:1791 message = message.replace("\r\n","\n")1792 submitTemplate = message[:message.index(separatorLine)]1793p4_write_pipe(['submit','-i'], submitTemplate)17941795if self.preserveUser:1796if p4User:1797# Get last changelist number. Cannot easily get it from1798# the submit command output as the output is1799# unmarshalled.1800 changelist = self.lastP4Changelist()1801 self.modifyChangelistUser(changelist, p4User)18021803# The rename/copy happened by applying a patch that created a1804# new file. This leaves it writable, which confuses p4.1805for f in pureRenameCopy:1806p4_sync(f,"-f")1807 submitted =True18081809finally:1810# skip this patch1811if not submitted:1812print"Submission cancelled, undoing p4 changes."1813for f in editedFiles:1814p4_revert(f)1815for f in filesToAdd:1816p4_revert(f)1817 os.remove(f)1818for f in filesToDelete:1819p4_revert(f)18201821 os.remove(fileName)1822return submitted18231824# Export git tags as p4 labels. Create a p4 label and then tag1825# with that.1826defexportGitTags(self, gitTags):1827 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1828iflen(validLabelRegexp) ==0:1829 validLabelRegexp = defaultLabelRegexp1830 m = re.compile(validLabelRegexp)18311832for name in gitTags:18331834if not m.match(name):1835if verbose:1836print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1837continue18381839# Get the p4 commit this corresponds to1840 logMessage =extractLogMessageFromGitCommit(name)1841 values =extractSettingsGitLog(logMessage)18421843if not values.has_key('change'):1844# a tag pointing to something not sent to p4; ignore1845if verbose:1846print"git tag%sdoes not give a p4 commit"% name1847continue1848else:1849 changelist = values['change']18501851# Get the tag details.1852 inHeader =True1853 isAnnotated =False1854 body = []1855for l inread_pipe_lines(["git","cat-file","-p", name]):1856 l = l.strip()1857if inHeader:1858if re.match(r'tag\s+', l):1859 isAnnotated =True1860elif re.match(r'\s*$', l):1861 inHeader =False1862continue1863else:1864 body.append(l)18651866if not isAnnotated:1867 body = ["lightweight tag imported by git p4\n"]18681869# Create the label - use the same view as the client spec we are using1870 clientSpec =getClientSpec()18711872 labelTemplate ="Label:%s\n"% name1873 labelTemplate +="Description:\n"1874for b in body:1875 labelTemplate +="\t"+ b +"\n"1876 labelTemplate +="View:\n"1877for depot_side in clientSpec.mappings:1878 labelTemplate +="\t%s\n"% depot_side18791880if self.dry_run:1881print"Would create p4 label%sfor tag"% name1882elif self.prepare_p4_only:1883print"Not creating p4 label%sfor tag due to option" \1884" --prepare-p4-only"% name1885else:1886p4_write_pipe(["label","-i"], labelTemplate)18871888# Use the label1889p4_system(["tag","-l", name] +1890["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18911892if verbose:1893print"created p4 label for tag%s"% name18941895defrun(self, args):1896iflen(args) ==0:1897 self.master =currentGitBranch()1898eliflen(args) ==1:1899 self.master = args[0]1900if notbranchExists(self.master):1901die("Branch%sdoes not exist"% self.master)1902else:1903return False19041905if self.master:1906 allowSubmit =gitConfig("git-p4.allowSubmit")1907iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1908die("%sis not in git-p4.allowSubmit"% self.master)19091910[upstream, settings] =findUpstreamBranchPoint()1911 self.depotPath = settings['depot-paths'][0]1912iflen(self.origin) ==0:1913 self.origin = upstream19141915if self.preserveUser:1916if not self.canChangeChangelists():1917die("Cannot preserve user names without p4 super-user or admin permissions")19181919# if not set from the command line, try the config file1920if self.conflict_behavior is None:1921 val =gitConfig("git-p4.conflict")1922if val:1923if val not in self.conflict_behavior_choices:1924die("Invalid value '%s' for config git-p4.conflict"% val)1925else:1926 val ="ask"1927 self.conflict_behavior = val19281929if self.verbose:1930print"Origin branch is "+ self.origin19311932iflen(self.depotPath) ==0:1933print"Internal error: cannot locate perforce depot path from existing branches"1934 sys.exit(128)19351936 self.useClientSpec =False1937ifgitConfigBool("git-p4.useclientspec"):1938 self.useClientSpec =True1939if self.useClientSpec:1940 self.clientSpecDirs =getClientSpec()19411942# Check for the existence of P4 branches1943 branchesDetected = (len(p4BranchesInGit().keys()) >1)19441945if self.useClientSpec and not branchesDetected:1946# all files are relative to the client spec1947 self.clientPath =getClientRoot()1948else:1949 self.clientPath =p4Where(self.depotPath)19501951if self.clientPath =="":1952die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19531954print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1955 self.oldWorkingDirectory = os.getcwd()19561957# ensure the clientPath exists1958 new_client_dir =False1959if not os.path.exists(self.clientPath):1960 new_client_dir =True1961 os.makedirs(self.clientPath)19621963chdir(self.clientPath, is_client_path=True)1964if self.dry_run:1965print"Would synchronize p4 checkout in%s"% self.clientPath1966else:1967print"Synchronizing p4 checkout..."1968if new_client_dir:1969# old one was destroyed, and maybe nobody told p41970p4_sync("...","-f")1971else:1972p4_sync("...")1973 self.check()19741975 commits = []1976if self.master:1977 commitish = self.master1978else:1979 commitish ='HEAD'19801981for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):1982 commits.append(line.strip())1983 commits.reverse()19841985if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1986 self.checkAuthorship =False1987else:1988 self.checkAuthorship =True19891990if self.preserveUser:1991 self.checkValidP4Users(commits)19921993#1994# Build up a set of options to be passed to diff when1995# submitting each commit to p4.1996#1997if self.detectRenames:1998# command-line -M arg1999 self.diffOpts ="-M"2000else:2001# If not explicitly set check the config variable2002 detectRenames =gitConfig("git-p4.detectRenames")20032004if detectRenames.lower() =="false"or detectRenames =="":2005 self.diffOpts =""2006elif detectRenames.lower() =="true":2007 self.diffOpts ="-M"2008else:2009 self.diffOpts ="-M%s"% detectRenames20102011# no command-line arg for -C or --find-copies-harder, just2012# config variables2013 detectCopies =gitConfig("git-p4.detectCopies")2014if detectCopies.lower() =="false"or detectCopies =="":2015pass2016elif detectCopies.lower() =="true":2017 self.diffOpts +=" -C"2018else:2019 self.diffOpts +=" -C%s"% detectCopies20202021ifgitConfigBool("git-p4.detectCopiesHarder"):2022 self.diffOpts +=" --find-copies-harder"20232024#2025# Apply the commits, one at a time. On failure, ask if should2026# continue to try the rest of the patches, or quit.2027#2028if self.dry_run:2029print"Would apply"2030 applied = []2031 last =len(commits) -12032for i, commit inenumerate(commits):2033if self.dry_run:2034print" ",read_pipe(["git","show","-s",2035"--format=format:%h%s", commit])2036 ok =True2037else:2038 ok = self.applyCommit(commit)2039if ok:2040 applied.append(commit)2041else:2042if self.prepare_p4_only and i < last:2043print"Processing only the first commit due to option" \2044" --prepare-p4-only"2045break2046if i < last:2047 quit =False2048while True:2049# prompt for what to do, or use the option/variable2050if self.conflict_behavior =="ask":2051print"What do you want to do?"2052 response =raw_input("[s]kip this commit but apply"2053" the rest, or [q]uit? ")2054if not response:2055continue2056elif self.conflict_behavior =="skip":2057 response ="s"2058elif self.conflict_behavior =="quit":2059 response ="q"2060else:2061die("Unknown conflict_behavior '%s'"%2062 self.conflict_behavior)20632064if response[0] =="s":2065print"Skipping this commit, but applying the rest"2066break2067if response[0] =="q":2068print"Quitting"2069 quit =True2070break2071if quit:2072break20732074chdir(self.oldWorkingDirectory)20752076if self.dry_run:2077pass2078elif self.prepare_p4_only:2079pass2080eliflen(commits) ==len(applied):2081print"All commits applied!"20822083 sync =P4Sync()2084if self.branch:2085 sync.branch = self.branch2086 sync.run([])20872088 rebase =P4Rebase()2089 rebase.rebase()20902091else:2092iflen(applied) ==0:2093print"No commits applied."2094else:2095print"Applied only the commits marked with '*':"2096for c in commits:2097if c in applied:2098 star ="*"2099else:2100 star =" "2101print star,read_pipe(["git","show","-s",2102"--format=format:%h%s", c])2103print"You will have to do 'git p4 sync' and rebase."21042105ifgitConfigBool("git-p4.exportLabels"):2106 self.exportLabels =True21072108if self.exportLabels:2109 p4Labels =getP4Labels(self.depotPath)2110 gitTags =getGitTags()21112112 missingGitTags = gitTags - p4Labels2113 self.exportGitTags(missingGitTags)21142115# exit with error unless everything applied perfectly2116iflen(commits) !=len(applied):2117 sys.exit(1)21182119return True21202121classView(object):2122"""Represent a p4 view ("p4 help views"), and map files in a2123 repo according to the view."""21242125def__init__(self, client_name):2126 self.mappings = []2127 self.client_prefix ="//%s/"% client_name2128# cache results of "p4 where" to lookup client file locations2129 self.client_spec_path_cache = {}21302131defappend(self, view_line):2132"""Parse a view line, splitting it into depot and client2133 sides. Append to self.mappings, preserving order. This2134 is only needed for tag creation."""21352136# Split the view line into exactly two words. P4 enforces2137# structure on these lines that simplifies this quite a bit.2138#2139# Either or both words may be double-quoted.2140# Single quotes do not matter.2141# Double-quote marks cannot occur inside the words.2142# A + or - prefix is also inside the quotes.2143# There are no quotes unless they contain a space.2144# The line is already white-space stripped.2145# The two words are separated by a single space.2146#2147if view_line[0] =='"':2148# First word is double quoted. Find its end.2149 close_quote_index = view_line.find('"',1)2150if close_quote_index <=0:2151die("No first-word closing quote found:%s"% view_line)2152 depot_side = view_line[1:close_quote_index]2153# skip closing quote and space2154 rhs_index = close_quote_index +1+12155else:2156 space_index = view_line.find(" ")2157if space_index <=0:2158die("No word-splitting space found:%s"% view_line)2159 depot_side = view_line[0:space_index]2160 rhs_index = space_index +121612162# prefix + means overlay on previous mapping2163if depot_side.startswith("+"):2164 depot_side = depot_side[1:]21652166# prefix - means exclude this path, leave out of mappings2167 exclude =False2168if depot_side.startswith("-"):2169 exclude =True2170 depot_side = depot_side[1:]21712172if not exclude:2173 self.mappings.append(depot_side)21742175defconvert_client_path(self, clientFile):2176# chop off //client/ part to make it relative2177if not clientFile.startswith(self.client_prefix):2178die("No prefix '%s' on clientFile '%s'"%2179(self.client_prefix, clientFile))2180return clientFile[len(self.client_prefix):]21812182defupdate_client_spec_path_cache(self, files):2183""" Caching file paths by "p4 where" batch query """21842185# List depot file paths exclude that already cached2186 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21872188iflen(fileArgs) ==0:2189return# All files in cache21902191 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2192for res in where_result:2193if"code"in res and res["code"] =="error":2194# assume error is "... file(s) not in client view"2195continue2196if"clientFile"not in res:2197die("No clientFile in 'p4 where' output")2198if"unmap"in res:2199# it will list all of them, but only one not unmap-ped2200continue2201ifgitConfigBool("core.ignorecase"):2202 res['depotFile'] = res['depotFile'].lower()2203 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])22042205# not found files or unmap files set to ""2206for depotFile in fileArgs:2207ifgitConfigBool("core.ignorecase"):2208 depotFile = depotFile.lower()2209if depotFile not in self.client_spec_path_cache:2210 self.client_spec_path_cache[depotFile] =""22112212defmap_in_client(self, depot_path):2213"""Return the relative location in the client where this2214 depot file should live. Returns "" if the file should2215 not be mapped in the client."""22162217ifgitConfigBool("core.ignorecase"):2218 depot_path = depot_path.lower()22192220if depot_path in self.client_spec_path_cache:2221return self.client_spec_path_cache[depot_path]22222223die("Error:%sis not found in client spec path"% depot_path )2224return""22252226classP4Sync(Command, P4UserMap):2227 delete_actions = ("delete","move/delete","purge")22282229def__init__(self):2230 Command.__init__(self)2231 P4UserMap.__init__(self)2232 self.options = [2233 optparse.make_option("--branch", dest="branch"),2234 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2235 optparse.make_option("--changesfile", dest="changesFile"),2236 optparse.make_option("--silent", dest="silent", action="store_true"),2237 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2238 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2239 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2240help="Import into refs/heads/ , not refs/remotes"),2241 optparse.make_option("--max-changes", dest="maxChanges",2242help="Maximum number of changes to import"),2243 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2244help="Internal block size to use when iteratively calling p4 changes"),2245 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2246help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2247 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2248help="Only sync files that are included in the Perforce Client Spec"),2249 optparse.make_option("-/", dest="cloneExclude",2250 action="append",type="string",2251help="exclude depot path"),2252]2253 self.description ="""Imports from Perforce into a git repository.\n2254 example:2255 //depot/my/project/ -- to import the current head2256 //depot/my/project/@all -- to import everything2257 //depot/my/project/@1,6 -- to import only from revision 1 to 622582259 (a ... is not needed in the path p4 specification, it's added implicitly)"""22602261 self.usage +=" //depot/path[@revRange]"2262 self.silent =False2263 self.createdBranches =set()2264 self.committedChanges =set()2265 self.branch =""2266 self.detectBranches =False2267 self.detectLabels =False2268 self.importLabels =False2269 self.changesFile =""2270 self.syncWithOrigin =True2271 self.importIntoRemotes =True2272 self.maxChanges =""2273 self.changes_block_size =None2274 self.keepRepoPath =False2275 self.depotPaths =None2276 self.p4BranchesInGit = []2277 self.cloneExclude = []2278 self.useClientSpec =False2279 self.useClientSpec_from_options =False2280 self.clientSpecDirs =None2281 self.tempBranches = []2282 self.tempBranchLocation ="refs/git-p4-tmp"2283 self.largeFileSystem =None22842285ifgitConfig('git-p4.largeFileSystem'):2286 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2287 self.largeFileSystem =largeFileSystemConstructor(2288lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2289)22902291ifgitConfig("git-p4.syncFromOrigin") =="false":2292 self.syncWithOrigin =False22932294# This is required for the "append" cloneExclude action2295defensure_value(self, attr, value):2296if nothasattr(self, attr)orgetattr(self, attr)is None:2297setattr(self, attr, value)2298returngetattr(self, attr)22992300# Force a checkpoint in fast-import and wait for it to finish2301defcheckpoint(self):2302 self.gitStream.write("checkpoint\n\n")2303 self.gitStream.write("progress checkpoint\n\n")2304 out = self.gitOutput.readline()2305if self.verbose:2306print"checkpoint finished: "+ out23072308defextractFilesFromCommit(self, commit):2309 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2310for path in self.cloneExclude]2311 files = []2312 fnum =02313while commit.has_key("depotFile%s"% fnum):2314 path = commit["depotFile%s"% fnum]23152316if[p for p in self.cloneExclude2317ifp4PathStartsWith(path, p)]:2318 found =False2319else:2320 found = [p for p in self.depotPaths2321ifp4PathStartsWith(path, p)]2322if not found:2323 fnum = fnum +12324continue23252326file= {}2327file["path"] = path2328file["rev"] = commit["rev%s"% fnum]2329file["action"] = commit["action%s"% fnum]2330file["type"] = commit["type%s"% fnum]2331 files.append(file)2332 fnum = fnum +12333return files23342335defextractJobsFromCommit(self, commit):2336 jobs = []2337 jnum =02338while commit.has_key("job%s"% jnum):2339 job = commit["job%s"% jnum]2340 jobs.append(job)2341 jnum = jnum +12342return jobs23432344defstripRepoPath(self, path, prefixes):2345"""When streaming files, this is called to map a p4 depot path2346 to where it should go in git. The prefixes are either2347 self.depotPaths, or self.branchPrefixes in the case of2348 branch detection."""23492350if self.useClientSpec:2351# branch detection moves files up a level (the branch name)2352# from what client spec interpretation gives2353 path = self.clientSpecDirs.map_in_client(path)2354if self.detectBranches:2355for b in self.knownBranches:2356if path.startswith(b +"/"):2357 path = path[len(b)+1:]23582359elif self.keepRepoPath:2360# Preserve everything in relative path name except leading2361# //depot/; just look at first prefix as they all should2362# be in the same depot.2363 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2364ifp4PathStartsWith(path, depot):2365 path = path[len(depot):]23662367else:2368for p in prefixes:2369ifp4PathStartsWith(path, p):2370 path = path[len(p):]2371break23722373 path =wildcard_decode(path)2374return path23752376defsplitFilesIntoBranches(self, commit):2377"""Look at each depotFile in the commit to figure out to what2378 branch it belongs."""23792380if self.clientSpecDirs:2381 files = self.extractFilesFromCommit(commit)2382 self.clientSpecDirs.update_client_spec_path_cache(files)23832384 branches = {}2385 fnum =02386while commit.has_key("depotFile%s"% fnum):2387 path = commit["depotFile%s"% fnum]2388 found = [p for p in self.depotPaths2389ifp4PathStartsWith(path, p)]2390if not found:2391 fnum = fnum +12392continue23932394file= {}2395file["path"] = path2396file["rev"] = commit["rev%s"% fnum]2397file["action"] = commit["action%s"% fnum]2398file["type"] = commit["type%s"% fnum]2399 fnum = fnum +124002401# start with the full relative path where this file would2402# go in a p4 client2403if self.useClientSpec:2404 relPath = self.clientSpecDirs.map_in_client(path)2405else:2406 relPath = self.stripRepoPath(path, self.depotPaths)24072408for branch in self.knownBranches.keys():2409# add a trailing slash so that a commit into qt/4.2foo2410# doesn't end up in qt/4.2, e.g.2411if relPath.startswith(branch +"/"):2412if branch not in branches:2413 branches[branch] = []2414 branches[branch].append(file)2415break24162417return branches24182419defwriteToGitStream(self, gitMode, relPath, contents):2420 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2421 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2422for d in contents:2423 self.gitStream.write(d)2424 self.gitStream.write('\n')24252426# output one file from the P4 stream2427# - helper for streamP4Files24282429defstreamOneP4File(self,file, contents):2430 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2431if verbose:2432 size =int(self.stream_file['fileSize'])2433 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2434 sys.stdout.flush()24352436(type_base, type_mods) =split_p4_type(file["type"])24372438 git_mode ="100644"2439if"x"in type_mods:2440 git_mode ="100755"2441if type_base =="symlink":2442 git_mode ="120000"2443# p4 print on a symlink sometimes contains "target\n";2444# if it does, remove the newline2445 data =''.join(contents)2446if not data:2447# Some version of p4 allowed creating a symlink that pointed2448# to nothing. This causes p4 errors when checking out such2449# a change, and errors here too. Work around it by ignoring2450# the bad symlink; hopefully a future change fixes it.2451print"\nIgnoring empty symlink in%s"%file['depotFile']2452return2453elif data[-1] =='\n':2454 contents = [data[:-1]]2455else:2456 contents = [data]24572458if type_base =="utf16":2459# p4 delivers different text in the python output to -G2460# than it does when using "print -o", or normal p4 client2461# operations. utf16 is converted to ascii or utf8, perhaps.2462# But ascii text saved as -t utf16 is completely mangled.2463# Invoke print -o to get the real contents.2464#2465# On windows, the newlines will always be mangled by print, so put2466# them back too. This is not needed to the cygwin windows version,2467# just the native "NT" type.2468#2469try:2470 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2471exceptExceptionas e:2472if'Translation of file content failed'instr(e):2473 type_base ='binary'2474else:2475raise e2476else:2477ifp4_version_string().find('/NT') >=0:2478 text = text.replace('\r\n','\n')2479 contents = [ text ]24802481if type_base =="apple":2482# Apple filetype files will be streamed as a concatenation of2483# its appledouble header and the contents. This is useless2484# on both macs and non-macs. If using "print -q -o xx", it2485# will create "xx" with the data, and "%xx" with the header.2486# This is also not very useful.2487#2488# Ideally, someday, this script can learn how to generate2489# appledouble files directly and import those to git, but2490# non-mac machines can never find a use for apple filetype.2491print"\nIgnoring apple filetype file%s"%file['depotFile']2492return24932494# Note that we do not try to de-mangle keywords on utf16 files,2495# even though in theory somebody may want that.2496 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2497if pattern:2498 regexp = re.compile(pattern, re.VERBOSE)2499 text =''.join(contents)2500 text = regexp.sub(r'$\1$', text)2501 contents = [ text ]25022503try:2504 relPath.decode('ascii')2505except:2506 encoding ='utf8'2507ifgitConfig('git-p4.pathEncoding'):2508 encoding =gitConfig('git-p4.pathEncoding')2509 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2510if self.verbose:2511print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)25122513if self.largeFileSystem:2514(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)25152516 self.writeToGitStream(git_mode, relPath, contents)25172518defstreamOneP4Deletion(self,file):2519 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2520if verbose:2521 sys.stdout.write("delete%s\n"% relPath)2522 sys.stdout.flush()2523 self.gitStream.write("D%s\n"% relPath)25242525if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2526 self.largeFileSystem.removeLargeFile(relPath)25272528# handle another chunk of streaming data2529defstreamP4FilesCb(self, marshalled):25302531# catch p4 errors and complain2532 err =None2533if"code"in marshalled:2534if marshalled["code"] =="error":2535if"data"in marshalled:2536 err = marshalled["data"].rstrip()25372538if not err and'fileSize'in self.stream_file:2539 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2540if required_bytes >0:2541 err ='Not enough space left on%s! Free at least%iMB.'% (2542 os.getcwd(), required_bytes/1024/10242543)25442545if err:2546 f =None2547if self.stream_have_file_info:2548if"depotFile"in self.stream_file:2549 f = self.stream_file["depotFile"]2550# force a failure in fast-import, else an empty2551# commit will be made2552 self.gitStream.write("\n")2553 self.gitStream.write("die-now\n")2554 self.gitStream.close()2555# ignore errors, but make sure it exits first2556 self.importProcess.wait()2557if f:2558die("Error from p4 print for%s:%s"% (f, err))2559else:2560die("Error from p4 print:%s"% err)25612562if marshalled.has_key('depotFile')and self.stream_have_file_info:2563# start of a new file - output the old one first2564 self.streamOneP4File(self.stream_file, self.stream_contents)2565 self.stream_file = {}2566 self.stream_contents = []2567 self.stream_have_file_info =False25682569# pick up the new file information... for the2570# 'data' field we need to append to our array2571for k in marshalled.keys():2572if k =='data':2573if'streamContentSize'not in self.stream_file:2574 self.stream_file['streamContentSize'] =02575 self.stream_file['streamContentSize'] +=len(marshalled['data'])2576 self.stream_contents.append(marshalled['data'])2577else:2578 self.stream_file[k] = marshalled[k]25792580if(verbose and2581'streamContentSize'in self.stream_file and2582'fileSize'in self.stream_file and2583'depotFile'in self.stream_file):2584 size =int(self.stream_file["fileSize"])2585if size >0:2586 progress =100*self.stream_file['streamContentSize']/size2587 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2588 sys.stdout.flush()25892590 self.stream_have_file_info =True25912592# Stream directly from "p4 files" into "git fast-import"2593defstreamP4Files(self, files):2594 filesForCommit = []2595 filesToRead = []2596 filesToDelete = []25972598for f in files:2599 filesForCommit.append(f)2600if f['action']in self.delete_actions:2601 filesToDelete.append(f)2602else:2603 filesToRead.append(f)26042605# deleted files...2606for f in filesToDelete:2607 self.streamOneP4Deletion(f)26082609iflen(filesToRead) >0:2610 self.stream_file = {}2611 self.stream_contents = []2612 self.stream_have_file_info =False26132614# curry self argument2615defstreamP4FilesCbSelf(entry):2616 self.streamP4FilesCb(entry)26172618 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]26192620p4CmdList(["-x","-","print"],2621 stdin=fileArgs,2622 cb=streamP4FilesCbSelf)26232624# do the last chunk2625if self.stream_file.has_key('depotFile'):2626 self.streamOneP4File(self.stream_file, self.stream_contents)26272628defmake_email(self, userid):2629if userid in self.users:2630return self.users[userid]2631else:2632return"%s<a@b>"% userid26332634defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2635""" Stream a p4 tag.2636 commit is either a git commit, or a fast-import mark, ":<p4commit>"2637 """26382639if verbose:2640print"writing tag%sfor commit%s"% (labelName, commit)2641 gitStream.write("tag%s\n"% labelName)2642 gitStream.write("from%s\n"% commit)26432644if labelDetails.has_key('Owner'):2645 owner = labelDetails["Owner"]2646else:2647 owner =None26482649# Try to use the owner of the p4 label, or failing that,2650# the current p4 user id.2651if owner:2652 email = self.make_email(owner)2653else:2654 email = self.make_email(self.p4UserId())2655 tagger ="%s %s %s"% (email, epoch, self.tz)26562657 gitStream.write("tagger%s\n"% tagger)26582659print"labelDetails=",labelDetails2660if labelDetails.has_key('Description'):2661 description = labelDetails['Description']2662else:2663 description ='Label from git p4'26642665 gitStream.write("data%d\n"%len(description))2666 gitStream.write(description)2667 gitStream.write("\n")26682669definClientSpec(self, path):2670if not self.clientSpecDirs:2671return True2672 inClientSpec = self.clientSpecDirs.map_in_client(path)2673if not inClientSpec and self.verbose:2674print('Ignoring file outside of client spec:{0}'.format(path))2675return inClientSpec26762677defhasBranchPrefix(self, path):2678if not self.branchPrefixes:2679return True2680 hasPrefix = [p for p in self.branchPrefixes2681ifp4PathStartsWith(path, p)]2682if not hasPrefix and self.verbose:2683print('Ignoring file outside of prefix:{0}'.format(path))2684return hasPrefix26852686defcommit(self, details, files, branch, parent =""):2687 epoch = details["time"]2688 author = details["user"]2689 jobs = self.extractJobsFromCommit(details)26902691if self.verbose:2692print('commit into{0}'.format(branch))26932694if self.clientSpecDirs:2695 self.clientSpecDirs.update_client_spec_path_cache(files)26962697 files = [f for f in files2698if self.inClientSpec(f['path'])and self.hasBranchPrefix(f['path'])]26992700if not files and notgitConfigBool('git-p4.keepEmptyCommits'):2701print('Ignoring revision{0}as it would produce an empty commit.'2702.format(details['change']))2703return27042705 self.gitStream.write("commit%s\n"% branch)2706 self.gitStream.write("mark :%s\n"% details["change"])2707 self.committedChanges.add(int(details["change"]))2708 committer =""2709if author not in self.users:2710 self.getUserMapFromPerforceServer()2711 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)27122713 self.gitStream.write("committer%s\n"% committer)27142715 self.gitStream.write("data <<EOT\n")2716 self.gitStream.write(details["desc"])2717iflen(jobs) >0:2718 self.gitStream.write("\nJobs:%s"% (' '.join(jobs)))2719 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2720(','.join(self.branchPrefixes), details["change"]))2721iflen(details['options']) >0:2722 self.gitStream.write(": options =%s"% details['options'])2723 self.gitStream.write("]\nEOT\n\n")27242725iflen(parent) >0:2726if self.verbose:2727print"parent%s"% parent2728 self.gitStream.write("from%s\n"% parent)27292730 self.streamP4Files(files)2731 self.gitStream.write("\n")27322733 change =int(details["change"])27342735if self.labels.has_key(change):2736 label = self.labels[change]2737 labelDetails = label[0]2738 labelRevisions = label[1]2739if self.verbose:2740print"Change%sis labelled%s"% (change, labelDetails)27412742 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2743for p in self.branchPrefixes])27442745iflen(files) ==len(labelRevisions):27462747 cleanedFiles = {}2748for info in files:2749if info["action"]in self.delete_actions:2750continue2751 cleanedFiles[info["depotFile"]] = info["rev"]27522753if cleanedFiles == labelRevisions:2754 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)27552756else:2757if not self.silent:2758print("Tag%sdoes not match with change%s: files do not match."2759% (labelDetails["label"], change))27602761else:2762if not self.silent:2763print("Tag%sdoes not match with change%s: file count is different."2764% (labelDetails["label"], change))27652766# Build a dictionary of changelists and labels, for "detect-labels" option.2767defgetLabels(self):2768 self.labels = {}27692770 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2771iflen(l) >0and not self.silent:2772print"Finding files belonging to labels in%s"% `self.depotPaths`27732774for output in l:2775 label = output["label"]2776 revisions = {}2777 newestChange =02778if self.verbose:2779print"Querying files for label%s"% label2780forfileinp4CmdList(["files"] +2781["%s...@%s"% (p, label)2782for p in self.depotPaths]):2783 revisions[file["depotFile"]] =file["rev"]2784 change =int(file["change"])2785if change > newestChange:2786 newestChange = change27872788 self.labels[newestChange] = [output, revisions]27892790if self.verbose:2791print"Label changes:%s"% self.labels.keys()27922793# Import p4 labels as git tags. A direct mapping does not2794# exist, so assume that if all the files are at the same revision2795# then we can use that, or it's something more complicated we should2796# just ignore.2797defimportP4Labels(self, stream, p4Labels):2798if verbose:2799print"import p4 labels: "+' '.join(p4Labels)28002801 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2802 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2803iflen(validLabelRegexp) ==0:2804 validLabelRegexp = defaultLabelRegexp2805 m = re.compile(validLabelRegexp)28062807for name in p4Labels:2808 commitFound =False28092810if not m.match(name):2811if verbose:2812print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2813continue28142815if name in ignoredP4Labels:2816continue28172818 labelDetails =p4CmdList(['label',"-o", name])[0]28192820# get the most recent changelist for each file in this label2821 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2822for p in self.depotPaths])28232824if change.has_key('change'):2825# find the corresponding git commit; take the oldest commit2826 changelist =int(change['change'])2827if changelist in self.committedChanges:2828 gitCommit =":%d"% changelist # use a fast-import mark2829 commitFound =True2830else:2831 gitCommit =read_pipe(["git","rev-list","--max-count=1",2832"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2833iflen(gitCommit) ==0:2834print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2835else:2836 commitFound =True2837 gitCommit = gitCommit.strip()28382839if commitFound:2840# Convert from p4 time format2841try:2842 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2843exceptValueError:2844print"Could not convert label time%s"% labelDetails['Update']2845 tmwhen =128462847 when =int(time.mktime(tmwhen))2848 self.streamTag(stream, name, labelDetails, gitCommit, when)2849if verbose:2850print"p4 label%smapped to git commit%s"% (name, gitCommit)2851else:2852if verbose:2853print"Label%shas no changelists - possibly deleted?"% name28542855if not commitFound:2856# We can't import this label; don't try again as it will get very2857# expensive repeatedly fetching all the files for labels that will2858# never be imported. If the label is moved in the future, the2859# ignore will need to be removed manually.2860system(["git","config","--add","git-p4.ignoredP4Labels", name])28612862defguessProjectName(self):2863for p in self.depotPaths:2864if p.endswith("/"):2865 p = p[:-1]2866 p = p[p.strip().rfind("/") +1:]2867if not p.endswith("/"):2868 p +="/"2869return p28702871defgetBranchMapping(self):2872 lostAndFoundBranches =set()28732874 user =gitConfig("git-p4.branchUser")2875iflen(user) >0:2876 command ="branches -u%s"% user2877else:2878 command ="branches"28792880for info inp4CmdList(command):2881 details =p4Cmd(["branch","-o", info["branch"]])2882 viewIdx =02883while details.has_key("View%s"% viewIdx):2884 paths = details["View%s"% viewIdx].split(" ")2885 viewIdx = viewIdx +12886# require standard //depot/foo/... //depot/bar/... mapping2887iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2888continue2889 source = paths[0]2890 destination = paths[1]2891## HACK2892ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2893 source = source[len(self.depotPaths[0]):-4]2894 destination = destination[len(self.depotPaths[0]):-4]28952896if destination in self.knownBranches:2897if not self.silent:2898print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2899print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2900continue29012902 self.knownBranches[destination] = source29032904 lostAndFoundBranches.discard(destination)29052906if source not in self.knownBranches:2907 lostAndFoundBranches.add(source)29082909# Perforce does not strictly require branches to be defined, so we also2910# check git config for a branch list.2911#2912# Example of branch definition in git config file:2913# [git-p4]2914# branchList=main:branchA2915# branchList=main:branchB2916# branchList=branchA:branchC2917 configBranches =gitConfigList("git-p4.branchList")2918for branch in configBranches:2919if branch:2920(source, destination) = branch.split(":")2921 self.knownBranches[destination] = source29222923 lostAndFoundBranches.discard(destination)29242925if source not in self.knownBranches:2926 lostAndFoundBranches.add(source)292729282929for branch in lostAndFoundBranches:2930 self.knownBranches[branch] = branch29312932defgetBranchMappingFromGitBranches(self):2933 branches =p4BranchesInGit(self.importIntoRemotes)2934for branch in branches.keys():2935if branch =="master":2936 branch ="main"2937else:2938 branch = branch[len(self.projectName):]2939 self.knownBranches[branch] = branch29402941defupdateOptionDict(self, d):2942 option_keys = {}2943if self.keepRepoPath:2944 option_keys['keepRepoPath'] =129452946 d["options"] =' '.join(sorted(option_keys.keys()))29472948defreadOptions(self, d):2949 self.keepRepoPath = (d.has_key('options')2950and('keepRepoPath'in d['options']))29512952defgitRefForBranch(self, branch):2953if branch =="main":2954return self.refPrefix +"master"29552956iflen(branch) <=0:2957return branch29582959return self.refPrefix + self.projectName + branch29602961defgitCommitByP4Change(self, ref, change):2962if self.verbose:2963print"looking in ref "+ ref +" for change%susing bisect..."% change29642965 earliestCommit =""2966 latestCommit =parseRevision(ref)29672968while True:2969if self.verbose:2970print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2971 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2972iflen(next) ==0:2973if self.verbose:2974print"argh"2975return""2976 log =extractLogMessageFromGitCommit(next)2977 settings =extractSettingsGitLog(log)2978 currentChange =int(settings['change'])2979if self.verbose:2980print"current change%s"% currentChange29812982if currentChange == change:2983if self.verbose:2984print"found%s"% next2985return next29862987if currentChange < change:2988 earliestCommit ="^%s"% next2989else:2990 latestCommit ="%s"% next29912992return""29932994defimportNewBranch(self, branch, maxChange):2995# make fast-import flush all changes to disk and update the refs using the checkpoint2996# command so that we can try to find the branch parent in the git history2997 self.gitStream.write("checkpoint\n\n");2998 self.gitStream.flush();2999 branchPrefix = self.depotPaths[0] + branch +"/"3000range="@1,%s"% maxChange3001#print "prefix" + branchPrefix3002 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)3003iflen(changes) <=0:3004return False3005 firstChange = changes[0]3006#print "first change in branch: %s" % firstChange3007 sourceBranch = self.knownBranches[branch]3008 sourceDepotPath = self.depotPaths[0] + sourceBranch3009 sourceRef = self.gitRefForBranch(sourceBranch)3010#print "source " + sourceBranch30113012 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])3013#print "branch parent: %s" % branchParentChange3014 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)3015iflen(gitParent) >0:3016 self.initialParents[self.gitRefForBranch(branch)] = gitParent3017#print "parent git commit: %s" % gitParent30183019 self.importChanges(changes)3020return True30213022defsearchParent(self, parent, branch, target):3023 parentFound =False3024for blob inread_pipe_lines(["git","rev-list","--reverse",3025"--no-merges", parent]):3026 blob = blob.strip()3027iflen(read_pipe(["git","diff-tree", blob, target])) ==0:3028 parentFound =True3029if self.verbose:3030print"Found parent of%sin commit%s"% (branch, blob)3031break3032if parentFound:3033return blob3034else:3035return None30363037defimportChanges(self, changes):3038 cnt =13039for change in changes:3040 description =p4_describe(change)3041 self.updateOptionDict(description)30423043if not self.silent:3044 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))3045 sys.stdout.flush()3046 cnt = cnt +130473048try:3049if self.detectBranches:3050 branches = self.splitFilesIntoBranches(description)3051for branch in branches.keys():3052## HACK --hwn3053 branchPrefix = self.depotPaths[0] + branch +"/"3054 self.branchPrefixes = [ branchPrefix ]30553056 parent =""30573058 filesForCommit = branches[branch]30593060if self.verbose:3061print"branch is%s"% branch30623063 self.updatedBranches.add(branch)30643065if branch not in self.createdBranches:3066 self.createdBranches.add(branch)3067 parent = self.knownBranches[branch]3068if parent == branch:3069 parent =""3070else:3071 fullBranch = self.projectName + branch3072if fullBranch not in self.p4BranchesInGit:3073if not self.silent:3074print("\nImporting new branch%s"% fullBranch);3075if self.importNewBranch(branch, change -1):3076 parent =""3077 self.p4BranchesInGit.append(fullBranch)3078if not self.silent:3079print("\nResuming with change%s"% change);30803081if self.verbose:3082print"parent determined through known branches:%s"% parent30833084 branch = self.gitRefForBranch(branch)3085 parent = self.gitRefForBranch(parent)30863087if self.verbose:3088print"looking for initial parent for%s; current parent is%s"% (branch, parent)30893090iflen(parent) ==0and branch in self.initialParents:3091 parent = self.initialParents[branch]3092del self.initialParents[branch]30933094 blob =None3095iflen(parent) >0:3096 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3097if self.verbose:3098print"Creating temporary branch: "+ tempBranch3099 self.commit(description, filesForCommit, tempBranch)3100 self.tempBranches.append(tempBranch)3101 self.checkpoint()3102 blob = self.searchParent(parent, branch, tempBranch)3103if blob:3104 self.commit(description, filesForCommit, branch, blob)3105else:3106if self.verbose:3107print"Parent of%snot found. Committing into head of%s"% (branch, parent)3108 self.commit(description, filesForCommit, branch, parent)3109else:3110 files = self.extractFilesFromCommit(description)3111 self.commit(description, files, self.branch,3112 self.initialParent)3113# only needed once, to connect to the previous commit3114 self.initialParent =""3115exceptIOError:3116print self.gitError.read()3117 sys.exit(1)31183119defimportHeadRevision(self, revision):3120print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)31213122 details = {}3123 details["user"] ="git perforce import user"3124 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3125% (' '.join(self.depotPaths), revision))3126 details["change"] = revision3127 newestRevision =031283129 fileCnt =03130 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]31313132for info inp4CmdList(["files"] + fileArgs):31333134if'code'in info and info['code'] =='error':3135 sys.stderr.write("p4 returned an error:%s\n"3136% info['data'])3137if info['data'].find("must refer to client") >=0:3138 sys.stderr.write("This particular p4 error is misleading.\n")3139 sys.stderr.write("Perhaps the depot path was misspelled.\n");3140 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3141 sys.exit(1)3142if'p4ExitCode'in info:3143 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3144 sys.exit(1)314531463147 change =int(info["change"])3148if change > newestRevision:3149 newestRevision = change31503151if info["action"]in self.delete_actions:3152# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3153#fileCnt = fileCnt + 13154continue31553156for prop in["depotFile","rev","action","type"]:3157 details["%s%s"% (prop, fileCnt)] = info[prop]31583159 fileCnt = fileCnt +131603161 details["change"] = newestRevision31623163# Use time from top-most change so that all git p4 clones of3164# the same p4 repo have the same commit SHA1s.3165 res =p4_describe(newestRevision)3166 details["time"] = res["time"]31673168 self.updateOptionDict(details)3169try:3170 self.commit(details, self.extractFilesFromCommit(details), self.branch)3171exceptIOError:3172print"IO error with git fast-import. Is your git version recent enough?"3173print self.gitError.read()317431753176defrun(self, args):3177 self.depotPaths = []3178 self.changeRange =""3179 self.previousDepotPaths = []3180 self.hasOrigin =False31813182# map from branch depot path to parent branch3183 self.knownBranches = {}3184 self.initialParents = {}31853186if self.importIntoRemotes:3187 self.refPrefix ="refs/remotes/p4/"3188else:3189 self.refPrefix ="refs/heads/p4/"31903191if self.syncWithOrigin:3192 self.hasOrigin =originP4BranchesExist()3193if self.hasOrigin:3194if not self.silent:3195print'Syncing with origin first, using "git fetch origin"'3196system("git fetch origin")31973198 branch_arg_given =bool(self.branch)3199iflen(self.branch) ==0:3200 self.branch = self.refPrefix +"master"3201ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3202system("git update-ref%srefs/heads/p4"% self.branch)3203system("git branch -D p4")32043205# accept either the command-line option, or the configuration variable3206if self.useClientSpec:3207# will use this after clone to set the variable3208 self.useClientSpec_from_options =True3209else:3210ifgitConfigBool("git-p4.useclientspec"):3211 self.useClientSpec =True3212if self.useClientSpec:3213 self.clientSpecDirs =getClientSpec()32143215# TODO: should always look at previous commits,3216# merge with previous imports, if possible.3217if args == []:3218if self.hasOrigin:3219createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)32203221# branches holds mapping from branch name to sha13222 branches =p4BranchesInGit(self.importIntoRemotes)32233224# restrict to just this one, disabling detect-branches3225if branch_arg_given:3226 short = self.branch.split("/")[-1]3227if short in branches:3228 self.p4BranchesInGit = [ short ]3229else:3230 self.p4BranchesInGit = branches.keys()32313232iflen(self.p4BranchesInGit) >1:3233if not self.silent:3234print"Importing from/into multiple branches"3235 self.detectBranches =True3236for branch in branches.keys():3237 self.initialParents[self.refPrefix + branch] = \3238 branches[branch]32393240if self.verbose:3241print"branches:%s"% self.p4BranchesInGit32423243 p4Change =03244for branch in self.p4BranchesInGit:3245 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)32463247 settings =extractSettingsGitLog(logMsg)32483249 self.readOptions(settings)3250if(settings.has_key('depot-paths')3251and settings.has_key('change')):3252 change =int(settings['change']) +13253 p4Change =max(p4Change, change)32543255 depotPaths =sorted(settings['depot-paths'])3256if self.previousDepotPaths == []:3257 self.previousDepotPaths = depotPaths3258else:3259 paths = []3260for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3261 prev_list = prev.split("/")3262 cur_list = cur.split("/")3263for i inrange(0,min(len(cur_list),len(prev_list))):3264if cur_list[i] <> prev_list[i]:3265 i = i -13266break32673268 paths.append("/".join(cur_list[:i +1]))32693270 self.previousDepotPaths = paths32713272if p4Change >0:3273 self.depotPaths =sorted(self.previousDepotPaths)3274 self.changeRange ="@%s,#head"% p4Change3275if not self.silent and not self.detectBranches:3276print"Performing incremental import into%sgit branch"% self.branch32773278# accept multiple ref name abbreviations:3279# refs/foo/bar/branch -> use it exactly3280# p4/branch -> prepend refs/remotes/ or refs/heads/3281# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3282if not self.branch.startswith("refs/"):3283if self.importIntoRemotes:3284 prepend ="refs/remotes/"3285else:3286 prepend ="refs/heads/"3287if not self.branch.startswith("p4/"):3288 prepend +="p4/"3289 self.branch = prepend + self.branch32903291iflen(args) ==0and self.depotPaths:3292if not self.silent:3293print"Depot paths:%s"%' '.join(self.depotPaths)3294else:3295if self.depotPaths and self.depotPaths != args:3296print("previous import used depot path%sand now%swas specified. "3297"This doesn't work!"% (' '.join(self.depotPaths),3298' '.join(args)))3299 sys.exit(1)33003301 self.depotPaths =sorted(args)33023303 revision =""3304 self.users = {}33053306# Make sure no revision specifiers are used when --changesfile3307# is specified.3308 bad_changesfile =False3309iflen(self.changesFile) >0:3310for p in self.depotPaths:3311if p.find("@") >=0or p.find("#") >=0:3312 bad_changesfile =True3313break3314if bad_changesfile:3315die("Option --changesfile is incompatible with revision specifiers")33163317 newPaths = []3318for p in self.depotPaths:3319if p.find("@") != -1:3320 atIdx = p.index("@")3321 self.changeRange = p[atIdx:]3322if self.changeRange =="@all":3323 self.changeRange =""3324elif','not in self.changeRange:3325 revision = self.changeRange3326 self.changeRange =""3327 p = p[:atIdx]3328elif p.find("#") != -1:3329 hashIdx = p.index("#")3330 revision = p[hashIdx:]3331 p = p[:hashIdx]3332elif self.previousDepotPaths == []:3333# pay attention to changesfile, if given, else import3334# the entire p4 tree at the head revision3335iflen(self.changesFile) ==0:3336 revision ="#head"33373338 p = re.sub("\.\.\.$","", p)3339if not p.endswith("/"):3340 p +="/"33413342 newPaths.append(p)33433344 self.depotPaths = newPaths33453346# --detect-branches may change this for each branch3347 self.branchPrefixes = self.depotPaths33483349 self.loadUserMapFromCache()3350 self.labels = {}3351if self.detectLabels:3352 self.getLabels();33533354if self.detectBranches:3355## FIXME - what's a P4 projectName ?3356 self.projectName = self.guessProjectName()33573358if self.hasOrigin:3359 self.getBranchMappingFromGitBranches()3360else:3361 self.getBranchMapping()3362if self.verbose:3363print"p4-git branches:%s"% self.p4BranchesInGit3364print"initial parents:%s"% self.initialParents3365for b in self.p4BranchesInGit:3366if b !="master":33673368## FIXME3369 b = b[len(self.projectName):]3370 self.createdBranches.add(b)33713372 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33733374 self.importProcess = subprocess.Popen(["git","fast-import"],3375 stdin=subprocess.PIPE,3376 stdout=subprocess.PIPE,3377 stderr=subprocess.PIPE);3378 self.gitOutput = self.importProcess.stdout3379 self.gitStream = self.importProcess.stdin3380 self.gitError = self.importProcess.stderr33813382if revision:3383 self.importHeadRevision(revision)3384else:3385 changes = []33863387iflen(self.changesFile) >0:3388 output =open(self.changesFile).readlines()3389 changeSet =set()3390for line in output:3391 changeSet.add(int(line))33923393for change in changeSet:3394 changes.append(change)33953396 changes.sort()3397else:3398# catch "git p4 sync" with no new branches, in a repo that3399# does not have any existing p4 branches3400iflen(args) ==0:3401if not self.p4BranchesInGit:3402die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")34033404# The default branch is master, unless --branch is used to3405# specify something else. Make sure it exists, or complain3406# nicely about how to use --branch.3407if not self.detectBranches:3408if notbranch_exists(self.branch):3409if branch_arg_given:3410die("Error: branch%sdoes not exist."% self.branch)3411else:3412die("Error: no branch%s; perhaps specify one with --branch."%3413 self.branch)34143415if self.verbose:3416print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3417 self.changeRange)3418 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)34193420iflen(self.maxChanges) >0:3421 changes = changes[:min(int(self.maxChanges),len(changes))]34223423iflen(changes) ==0:3424if not self.silent:3425print"No changes to import!"3426else:3427if not self.silent and not self.detectBranches:3428print"Import destination:%s"% self.branch34293430 self.updatedBranches =set()34313432if not self.detectBranches:3433if args:3434# start a new branch3435 self.initialParent =""3436else:3437# build on a previous revision3438 self.initialParent =parseRevision(self.branch)34393440 self.importChanges(changes)34413442if not self.silent:3443print""3444iflen(self.updatedBranches) >0:3445 sys.stdout.write("Updated branches: ")3446for b in self.updatedBranches:3447 sys.stdout.write("%s"% b)3448 sys.stdout.write("\n")34493450ifgitConfigBool("git-p4.importLabels"):3451 self.importLabels =True34523453if self.importLabels:3454 p4Labels =getP4Labels(self.depotPaths)3455 gitTags =getGitTags()34563457 missingP4Labels = p4Labels - gitTags3458 self.importP4Labels(self.gitStream, missingP4Labels)34593460 self.gitStream.close()3461if self.importProcess.wait() !=0:3462die("fast-import failed:%s"% self.gitError.read())3463 self.gitOutput.close()3464 self.gitError.close()34653466# Cleanup temporary branches created during import3467if self.tempBranches != []:3468for branch in self.tempBranches:3469read_pipe("git update-ref -d%s"% branch)3470 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34713472# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3473# a convenient shortcut refname "p4".3474if self.importIntoRemotes:3475 head_ref = self.refPrefix +"HEAD"3476if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3477system(["git","symbolic-ref", head_ref, self.branch])34783479return True34803481classP4Rebase(Command):3482def__init__(self):3483 Command.__init__(self)3484 self.options = [3485 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3486]3487 self.importLabels =False3488 self.description = ("Fetches the latest revision from perforce and "3489+"rebases the current work (branch) against it")34903491defrun(self, args):3492 sync =P4Sync()3493 sync.importLabels = self.importLabels3494 sync.run([])34953496return self.rebase()34973498defrebase(self):3499if os.system("git update-index --refresh") !=0:3500die("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.");3501iflen(read_pipe("git diff-index HEAD --")) >0:3502die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");35033504[upstream, settings] =findUpstreamBranchPoint()3505iflen(upstream) ==0:3506die("Cannot find upstream branchpoint for rebase")35073508# the branchpoint may be p4/foo~3, so strip off the parent3509 upstream = re.sub("~[0-9]+$","", upstream)35103511print"Rebasing the current branch onto%s"% upstream3512 oldHead =read_pipe("git rev-parse HEAD").strip()3513system("git rebase%s"% upstream)3514system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3515return True35163517classP4Clone(P4Sync):3518def__init__(self):3519 P4Sync.__init__(self)3520 self.description ="Creates a new git repository and imports from Perforce into it"3521 self.usage ="usage: %prog [options] //depot/path[@revRange]"3522 self.options += [3523 optparse.make_option("--destination", dest="cloneDestination",3524 action='store', default=None,3525help="where to leave result of the clone"),3526 optparse.make_option("--bare", dest="cloneBare",3527 action="store_true", default=False),3528]3529 self.cloneDestination =None3530 self.needsGit =False3531 self.cloneBare =False35323533defdefaultDestination(self, args):3534## TODO: use common prefix of args?3535 depotPath = args[0]3536 depotDir = re.sub("(@[^@]*)$","", depotPath)3537 depotDir = re.sub("(#[^#]*)$","", depotDir)3538 depotDir = re.sub(r"\.\.\.$","", depotDir)3539 depotDir = re.sub(r"/$","", depotDir)3540return os.path.split(depotDir)[1]35413542defrun(self, args):3543iflen(args) <1:3544return False35453546if self.keepRepoPath and not self.cloneDestination:3547 sys.stderr.write("Must specify destination for --keep-path\n")3548 sys.exit(1)35493550 depotPaths = args35513552if not self.cloneDestination andlen(depotPaths) >1:3553 self.cloneDestination = depotPaths[-1]3554 depotPaths = depotPaths[:-1]35553556 self.cloneExclude = ["/"+p for p in self.cloneExclude]3557for p in depotPaths:3558if not p.startswith("//"):3559 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3560return False35613562if not self.cloneDestination:3563 self.cloneDestination = self.defaultDestination(args)35643565print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)35663567if not os.path.exists(self.cloneDestination):3568 os.makedirs(self.cloneDestination)3569chdir(self.cloneDestination)35703571 init_cmd = ["git","init"]3572if self.cloneBare:3573 init_cmd.append("--bare")3574 retcode = subprocess.call(init_cmd)3575if retcode:3576raiseCalledProcessError(retcode, init_cmd)35773578if not P4Sync.run(self, depotPaths):3579return False35803581# create a master branch and check out a work tree3582ifgitBranchExists(self.branch):3583system(["git","branch","master", self.branch ])3584if not self.cloneBare:3585system(["git","checkout","-f"])3586else:3587print'Not checking out any branch, use ' \3588'"git checkout -q -b master <branch>"'35893590# auto-set this variable if invoked with --use-client-spec3591if self.useClientSpec_from_options:3592system("git config --bool git-p4.useclientspec true")35933594return True35953596classP4Branches(Command):3597def__init__(self):3598 Command.__init__(self)3599 self.options = [ ]3600 self.description = ("Shows the git branches that hold imports and their "3601+"corresponding perforce depot paths")3602 self.verbose =False36033604defrun(self, args):3605iforiginP4BranchesExist():3606createOrUpdateBranchesFromOrigin()36073608 cmdline ="git rev-parse --symbolic "3609 cmdline +=" --remotes"36103611for line inread_pipe_lines(cmdline):3612 line = line.strip()36133614if not line.startswith('p4/')or line =="p4/HEAD":3615continue3616 branch = line36173618 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3619 settings =extractSettingsGitLog(log)36203621print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3622return True36233624classHelpFormatter(optparse.IndentedHelpFormatter):3625def__init__(self):3626 optparse.IndentedHelpFormatter.__init__(self)36273628defformat_description(self, description):3629if description:3630return description +"\n"3631else:3632return""36333634defprintUsage(commands):3635print"usage:%s<command> [options]"% sys.argv[0]3636print""3637print"valid commands:%s"%", ".join(commands)3638print""3639print"Try%s<command> --help for command specific help."% sys.argv[0]3640print""36413642commands = {3643"debug": P4Debug,3644"submit": P4Submit,3645"commit": P4Submit,3646"sync": P4Sync,3647"rebase": P4Rebase,3648"clone": P4Clone,3649"rollback": P4RollBack,3650"branches": P4Branches3651}365236533654defmain():3655iflen(sys.argv[1:]) ==0:3656printUsage(commands.keys())3657 sys.exit(2)36583659 cmdName = sys.argv[1]3660try:3661 klass = commands[cmdName]3662 cmd =klass()3663exceptKeyError:3664print"unknown command%s"% cmdName3665print""3666printUsage(commands.keys())3667 sys.exit(2)36683669 options = cmd.options3670 cmd.gitdir = os.environ.get("GIT_DIR",None)36713672 args = sys.argv[2:]36733674 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3675if cmd.needsGit:3676 options.append(optparse.make_option("--git-dir", dest="gitdir"))36773678 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3679 options,3680 description = cmd.description,3681 formatter =HelpFormatter())36823683(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3684global verbose3685 verbose = cmd.verbose3686if cmd.needsGit:3687if cmd.gitdir ==None:3688 cmd.gitdir = os.path.abspath(".git")3689if notisValidGitDir(cmd.gitdir):3690 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3691if os.path.exists(cmd.gitdir):3692 cdup =read_pipe("git rev-parse --show-cdup").strip()3693iflen(cdup) >0:3694chdir(cdup);36953696if notisValidGitDir(cmd.gitdir):3697ifisValidGitDir(cmd.gitdir +"/.git"):3698 cmd.gitdir +="/.git"3699else:3700die("fatal: cannot locate git repository at%s"% cmd.gitdir)37013702 os.environ["GIT_DIR"] = cmd.gitdir37033704if not cmd.run(args):3705 parser.print_help()3706 sys.exit(2)370737083709if __name__ =='__main__':3710main()