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): 257p4_system(["edit",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# Accumulate change numbers in a dictionary to avoid duplicates 826 changes = {} 827 828for p in depotPaths: 829# Retrieve changes a block at a time, to prevent running 830# into a MaxResults/MaxScanRows error from the server. 831 832while True: 833 cmd = ['changes'] 834 835if block_size: 836 end =min(changeEnd, changeStart + block_size) 837 revisionRange ="%d,%d"% (changeStart, end) 838else: 839 revisionRange ="%s,%s"% (changeStart, changeEnd) 840 841 cmd += ["%s...@%s"% (p, revisionRange)] 842 843for line inp4_read_pipe_lines(cmd): 844 changeNum =int(line.split(" ")[1]) 845 changes[changeNum] =True 846 847if not block_size: 848break 849 850if end >= changeEnd: 851break 852 853 changeStart = end +1 854 855 changelist = changes.keys() 856 changelist.sort() 857return changelist 858 859defp4PathStartsWith(path, prefix): 860# This method tries to remedy a potential mixed-case issue: 861# 862# If UserA adds //depot/DirA/file1 863# and UserB adds //depot/dira/file2 864# 865# we may or may not have a problem. If you have core.ignorecase=true, 866# we treat DirA and dira as the same directory 867ifgitConfigBool("core.ignorecase"): 868return path.lower().startswith(prefix.lower()) 869return path.startswith(prefix) 870 871defgetClientSpec(): 872"""Look at the p4 client spec, create a View() object that contains 873 all the mappings, and return it.""" 874 875 specList =p4CmdList("client -o") 876iflen(specList) !=1: 877die('Output from "client -o" is%dlines, expecting 1'% 878len(specList)) 879 880# dictionary of all client parameters 881 entry = specList[0] 882 883# the //client/ name 884 client_name = entry["Client"] 885 886# just the keys that start with "View" 887 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 888 889# hold this new View 890 view =View(client_name) 891 892# append the lines, in order, to the view 893for view_num inrange(len(view_keys)): 894 k ="View%d"% view_num 895if k not in view_keys: 896die("Expected view key%smissing"% k) 897 view.append(entry[k]) 898 899return view 900 901defgetClientRoot(): 902"""Grab the client directory.""" 903 904 output =p4CmdList("client -o") 905iflen(output) !=1: 906die('Output from "client -o" is%dlines, expecting 1'%len(output)) 907 908 entry = output[0] 909if"Root"not in entry: 910die('Client has no "Root"') 911 912return entry["Root"] 913 914# 915# P4 wildcards are not allowed in filenames. P4 complains 916# if you simply add them, but you can force it with "-f", in 917# which case it translates them into %xx encoding internally. 918# 919defwildcard_decode(path): 920# Search for and fix just these four characters. Do % last so 921# that fixing it does not inadvertently create new %-escapes. 922# Cannot have * in a filename in windows; untested as to 923# what p4 would do in such a case. 924if not platform.system() =="Windows": 925 path = path.replace("%2A","*") 926 path = path.replace("%23","#") \ 927.replace("%40","@") \ 928.replace("%25","%") 929return path 930 931defwildcard_encode(path): 932# do % first to avoid double-encoding the %s introduced here 933 path = path.replace("%","%25") \ 934.replace("*","%2A") \ 935.replace("#","%23") \ 936.replace("@","%40") 937return path 938 939defwildcard_present(path): 940 m = re.search("[*#@%]", path) 941return m is not None 942 943classLargeFileSystem(object): 944"""Base class for large file system support.""" 945 946def__init__(self, writeToGitStream): 947 self.largeFiles =set() 948 self.writeToGitStream = writeToGitStream 949 950defgeneratePointer(self, cloneDestination, contentFile): 951"""Return the content of a pointer file that is stored in Git instead of 952 the actual content.""" 953assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 954 955defpushFile(self, localLargeFile): 956"""Push the actual content which is not stored in the Git repository to 957 a server.""" 958assert False,"Method 'pushFile' required in "+ self.__class__.__name__ 959 960defhasLargeFileExtension(self, relPath): 961returnreduce( 962lambda a, b: a or b, 963[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')], 964False 965) 966 967defgenerateTempFile(self, contents): 968 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 969for d in contents: 970 contentFile.write(d) 971 contentFile.close() 972return contentFile.name 973 974defexceedsLargeFileThreshold(self, relPath, contents): 975ifgitConfigInt('git-p4.largeFileThreshold'): 976 contentsSize =sum(len(d)for d in contents) 977if contentsSize >gitConfigInt('git-p4.largeFileThreshold'): 978return True 979ifgitConfigInt('git-p4.largeFileCompressedThreshold'): 980 contentsSize =sum(len(d)for d in contents) 981if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'): 982return False 983 contentTempFile = self.generateTempFile(contents) 984 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 985 zf = zipfile.ZipFile(compressedContentFile.name, mode='w') 986 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) 987 zf.close() 988 compressedContentsSize = zf.infolist()[0].compress_size 989 os.remove(contentTempFile) 990 os.remove(compressedContentFile.name) 991if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'): 992return True 993return False 994 995defaddLargeFile(self, relPath): 996 self.largeFiles.add(relPath) 997 998defremoveLargeFile(self, relPath): 999 self.largeFiles.remove(relPath)10001001defisLargeFile(self, relPath):1002return relPath in self.largeFiles10031004defprocessContent(self, git_mode, relPath, contents):1005"""Processes the content of git fast import. This method decides if a1006 file is stored in the large file system and handles all necessary1007 steps."""1008if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1009 contentTempFile = self.generateTempFile(contents)1010(git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)10111012# 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 """1061 pointerProcess = subprocess.Popen(1062['git','lfs','pointer','--file='+ contentFile],1063 stdout=subprocess.PIPE1064)1065 pointerFile = pointerProcess.stdout.read()1066if pointerProcess.wait():1067 os.remove(contentFile)1068die('git-lfs pointer command failed. Did you install the extension?')1069 pointerContents = [i+'\n'for i in pointerFile.split('\n')[2:][:-1]]1070 oid = pointerContents[1].split(' ')[1].split(':')[1][:-1]1071 localLargeFile = os.path.join(1072 os.getcwd(),1073'.git','lfs','objects', oid[:2], oid[2:4],1074 oid,1075)1076# LFS Spec states that pointer files should not have the executable bit set.1077 gitMode ='100644'1078return(gitMode, pointerContents, localLargeFile)10791080defpushFile(self, localLargeFile):1081 uploadProcess = subprocess.Popen(1082['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1083)1084if uploadProcess.wait():1085die('git-lfs push command failed. Did you define a remote?')10861087defgenerateGitAttributes(self):1088return(1089 self.baseGitAttributes +1090[1091'\n',1092'#\n',1093'# Git LFS (see https://git-lfs.github.com/)\n',1094'#\n',1095] +1096['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1097for f insorted(gitConfigList('git-p4.largeFileExtensions'))1098] +1099['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1100for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1101]1102)11031104defaddLargeFile(self, relPath):1105 LargeFileSystem.addLargeFile(self, relPath)1106 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11071108defremoveLargeFile(self, relPath):1109 LargeFileSystem.removeLargeFile(self, relPath)1110 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11111112defprocessContent(self, git_mode, relPath, contents):1113if relPath =='.gitattributes':1114 self.baseGitAttributes = contents1115return(git_mode, self.generateGitAttributes())1116else:1117return LargeFileSystem.processContent(self, git_mode, relPath, contents)11181119class Command:1120def__init__(self):1121 self.usage ="usage: %prog [options]"1122 self.needsGit =True1123 self.verbose =False11241125class P4UserMap:1126def__init__(self):1127 self.userMapFromPerforceServer =False1128 self.myP4UserId =None11291130defp4UserId(self):1131if self.myP4UserId:1132return self.myP4UserId11331134 results =p4CmdList("user -o")1135for r in results:1136if r.has_key('User'):1137 self.myP4UserId = r['User']1138return r['User']1139die("Could not find your p4 user id")11401141defp4UserIsMe(self, p4User):1142# return True if the given p4 user is actually me1143 me = self.p4UserId()1144if not p4User or p4User != me:1145return False1146else:1147return True11481149defgetUserCacheFilename(self):1150 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1151return home +"/.gitp4-usercache.txt"11521153defgetUserMapFromPerforceServer(self):1154if self.userMapFromPerforceServer:1155return1156 self.users = {}1157 self.emails = {}11581159for output inp4CmdList("users"):1160if not output.has_key("User"):1161continue1162 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1163 self.emails[output["Email"]] = output["User"]116411651166 s =''1167for(key, val)in self.users.items():1168 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11691170open(self.getUserCacheFilename(),"wb").write(s)1171 self.userMapFromPerforceServer =True11721173defloadUserMapFromCache(self):1174 self.users = {}1175 self.userMapFromPerforceServer =False1176try:1177 cache =open(self.getUserCacheFilename(),"rb")1178 lines = cache.readlines()1179 cache.close()1180for line in lines:1181 entry = line.strip().split("\t")1182 self.users[entry[0]] = entry[1]1183exceptIOError:1184 self.getUserMapFromPerforceServer()11851186classP4Debug(Command):1187def__init__(self):1188 Command.__init__(self)1189 self.options = []1190 self.description ="A tool to debug the output of p4 -G."1191 self.needsGit =False11921193defrun(self, args):1194 j =01195for output inp4CmdList(args):1196print'Element:%d'% j1197 j +=11198print output1199return True12001201classP4RollBack(Command):1202def__init__(self):1203 Command.__init__(self)1204 self.options = [1205 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1206]1207 self.description ="A tool to debug the multi-branch import. Don't use :)"1208 self.rollbackLocalBranches =False12091210defrun(self, args):1211iflen(args) !=1:1212return False1213 maxChange =int(args[0])12141215if"p4ExitCode"inp4Cmd("changes -m 1"):1216die("Problems executing p4");12171218if self.rollbackLocalBranches:1219 refPrefix ="refs/heads/"1220 lines =read_pipe_lines("git rev-parse --symbolic --branches")1221else:1222 refPrefix ="refs/remotes/"1223 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12241225for line in lines:1226if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1227 line = line.strip()1228 ref = refPrefix + line1229 log =extractLogMessageFromGitCommit(ref)1230 settings =extractSettingsGitLog(log)12311232 depotPaths = settings['depot-paths']1233 change = settings['change']12341235 changed =False12361237iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1238for p in depotPaths]))) ==0:1239print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1240system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1241continue12421243while change andint(change) > maxChange:1244 changed =True1245if self.verbose:1246print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1247system("git update-ref%s\"%s^\""% (ref, ref))1248 log =extractLogMessageFromGitCommit(ref)1249 settings =extractSettingsGitLog(log)125012511252 depotPaths = settings['depot-paths']1253 change = settings['change']12541255if changed:1256print"%srewound to%s"% (ref, change)12571258return True12591260classP4Submit(Command, P4UserMap):12611262 conflict_behavior_choices = ("ask","skip","quit")12631264def__init__(self):1265 Command.__init__(self)1266 P4UserMap.__init__(self)1267 self.options = [1268 optparse.make_option("--origin", dest="origin"),1269 optparse.make_option("-M", dest="detectRenames", action="store_true"),1270# preserve the user, requires relevant p4 permissions1271 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1272 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1273 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1274 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1275 optparse.make_option("--conflict", dest="conflict_behavior",1276 choices=self.conflict_behavior_choices),1277 optparse.make_option("--branch", dest="branch"),1278]1279 self.description ="Submit changes from git to the perforce depot."1280 self.usage +=" [name of git branch to submit into perforce depot]"1281 self.origin =""1282 self.detectRenames =False1283 self.preserveUser =gitConfigBool("git-p4.preserveUser")1284 self.dry_run =False1285 self.prepare_p4_only =False1286 self.conflict_behavior =None1287 self.isWindows = (platform.system() =="Windows")1288 self.exportLabels =False1289 self.p4HasMoveCommand =p4_has_move_command()1290 self.branch =None12911292ifgitConfig('git-p4.largeFileSystem'):1293die("Large file system not supported for git-p4 submit command. Please remove it from config.")12941295defcheck(self):1296iflen(p4CmdList("opened ...")) >0:1297die("You have files opened with perforce! Close them before starting the sync.")12981299defseparate_jobs_from_description(self, message):1300"""Extract and return a possible Jobs field in the commit1301 message. It goes into a separate section in the p4 change1302 specification.13031304 A jobs line starts with "Jobs:" and looks like a new field1305 in a form. Values are white-space separated on the same1306 line or on following lines that start with a tab.13071308 This does not parse and extract the full git commit message1309 like a p4 form. It just sees the Jobs: line as a marker1310 to pass everything from then on directly into the p4 form,1311 but outside the description section.13121313 Return a tuple (stripped log message, jobs string)."""13141315 m = re.search(r'^Jobs:', message, re.MULTILINE)1316if m is None:1317return(message,None)13181319 jobtext = message[m.start():]1320 stripped_message = message[:m.start()].rstrip()1321return(stripped_message, jobtext)13221323defprepareLogMessage(self, template, message, jobs):1324"""Edits the template returned from "p4 change -o" to insert1325 the message in the Description field, and the jobs text in1326 the Jobs field."""1327 result =""13281329 inDescriptionSection =False13301331for line in template.split("\n"):1332if line.startswith("#"):1333 result += line +"\n"1334continue13351336if inDescriptionSection:1337if line.startswith("Files:")or line.startswith("Jobs:"):1338 inDescriptionSection =False1339# insert Jobs section1340if jobs:1341 result += jobs +"\n"1342else:1343continue1344else:1345if line.startswith("Description:"):1346 inDescriptionSection =True1347 line +="\n"1348for messageLine in message.split("\n"):1349 line +="\t"+ messageLine +"\n"13501351 result += line +"\n"13521353return result13541355defpatchRCSKeywords(self,file, pattern):1356# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1357(handle, outFileName) = tempfile.mkstemp(dir='.')1358try:1359 outFile = os.fdopen(handle,"w+")1360 inFile =open(file,"r")1361 regexp = re.compile(pattern, re.VERBOSE)1362for line in inFile.readlines():1363 line = regexp.sub(r'$\1$', line)1364 outFile.write(line)1365 inFile.close()1366 outFile.close()1367# Forcibly overwrite the original file1368 os.unlink(file)1369 shutil.move(outFileName,file)1370except:1371# cleanup our temporary file1372 os.unlink(outFileName)1373print"Failed to strip RCS keywords in%s"%file1374raise13751376print"Patched up RCS keywords in%s"%file13771378defp4UserForCommit(self,id):1379# Return the tuple (perforce user,git email) for a given git commit id1380 self.getUserMapFromPerforceServer()1381 gitEmail =read_pipe(["git","log","--max-count=1",1382"--format=%ae",id])1383 gitEmail = gitEmail.strip()1384if not self.emails.has_key(gitEmail):1385return(None,gitEmail)1386else:1387return(self.emails[gitEmail],gitEmail)13881389defcheckValidP4Users(self,commits):1390# check if any git authors cannot be mapped to p4 users1391foridin commits:1392(user,email) = self.p4UserForCommit(id)1393if not user:1394 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1395ifgitConfigBool("git-p4.allowMissingP4Users"):1396print"%s"% msg1397else:1398die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)13991400deflastP4Changelist(self):1401# Get back the last changelist number submitted in this client spec. This1402# then gets used to patch up the username in the change. If the same1403# client spec is being used by multiple processes then this might go1404# wrong.1405 results =p4CmdList("client -o")# find the current client1406 client =None1407for r in results:1408if r.has_key('Client'):1409 client = r['Client']1410break1411if not client:1412die("could not get client spec")1413 results =p4CmdList(["changes","-c", client,"-m","1"])1414for r in results:1415if r.has_key('change'):1416return r['change']1417die("Could not get changelist number for last submit - cannot patch up user details")14181419defmodifyChangelistUser(self, changelist, newUser):1420# fixup the user field of a changelist after it has been submitted.1421 changes =p4CmdList("change -o%s"% changelist)1422iflen(changes) !=1:1423die("Bad output from p4 change modifying%sto user%s"%1424(changelist, newUser))14251426 c = changes[0]1427if c['User'] == newUser:return# nothing to do1428 c['User'] = newUser1429input= marshal.dumps(c)14301431 result =p4CmdList("change -f -i", stdin=input)1432for r in result:1433if r.has_key('code'):1434if r['code'] =='error':1435die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1436if r.has_key('data'):1437print("Updated user field for changelist%sto%s"% (changelist, newUser))1438return1439die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14401441defcanChangeChangelists(self):1442# check to see if we have p4 admin or super-user permissions, either of1443# which are required to modify changelists.1444 results =p4CmdList(["protects", self.depotPath])1445for r in results:1446if r.has_key('perm'):1447if r['perm'] =='admin':1448return11449if r['perm'] =='super':1450return11451return014521453defprepareSubmitTemplate(self):1454"""Run "p4 change -o" to grab a change specification template.1455 This does not use "p4 -G", as it is nice to keep the submission1456 template in original order, since a human might edit it.14571458 Remove lines in the Files section that show changes to files1459 outside the depot path we're committing into."""14601461 template =""1462 inFilesSection =False1463for line inp4_read_pipe_lines(['change','-o']):1464if line.endswith("\r\n"):1465 line = line[:-2] +"\n"1466if inFilesSection:1467if line.startswith("\t"):1468# path starts and ends with a tab1469 path = line[1:]1470 lastTab = path.rfind("\t")1471if lastTab != -1:1472 path = path[:lastTab]1473if notp4PathStartsWith(path, self.depotPath):1474continue1475else:1476 inFilesSection =False1477else:1478if line.startswith("Files:"):1479 inFilesSection =True14801481 template += line14821483return template14841485defedit_template(self, template_file):1486"""Invoke the editor to let the user change the submission1487 message. Return true if okay to continue with the submit."""14881489# if configured to skip the editing part, just submit1490ifgitConfigBool("git-p4.skipSubmitEdit"):1491return True14921493# look at the modification time, to check later if the user saved1494# the file1495 mtime = os.stat(template_file).st_mtime14961497# invoke the editor1498if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1499 editor = os.environ.get("P4EDITOR")1500else:1501 editor =read_pipe("git var GIT_EDITOR").strip()1502system(["sh","-c", ('%s"$@"'% editor), editor, template_file])15031504# If the file was not saved, prompt to see if this patch should1505# be skipped. But skip this verification step if configured so.1506ifgitConfigBool("git-p4.skipSubmitEditCheck"):1507return True15081509# modification time updated means user saved the file1510if os.stat(template_file).st_mtime > mtime:1511return True15121513while True:1514 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1515if response =='y':1516return True1517if response =='n':1518return False15191520defget_diff_description(self, editedFiles, filesToAdd):1521# diff1522if os.environ.has_key("P4DIFF"):1523del(os.environ["P4DIFF"])1524 diff =""1525for editedFile in editedFiles:1526 diff +=p4_read_pipe(['diff','-du',1527wildcard_encode(editedFile)])15281529# new file diff1530 newdiff =""1531for newFile in filesToAdd:1532 newdiff +="==== new file ====\n"1533 newdiff +="--- /dev/null\n"1534 newdiff +="+++%s\n"% newFile1535 f =open(newFile,"r")1536for line in f.readlines():1537 newdiff +="+"+ line1538 f.close()15391540return(diff + newdiff).replace('\r\n','\n')15411542defapplyCommit(self,id):1543"""Apply one commit, return True if it succeeded."""15441545print"Applying",read_pipe(["git","show","-s",1546"--format=format:%h%s",id])15471548(p4User, gitEmail) = self.p4UserForCommit(id)15491550 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1551 filesToAdd =set()1552 filesToDelete =set()1553 editedFiles =set()1554 pureRenameCopy =set()1555 filesToChangeExecBit = {}15561557for line in diff:1558 diff =parseDiffTreeEntry(line)1559 modifier = diff['status']1560 path = diff['src']1561if modifier =="M":1562p4_edit(path)1563ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1564 filesToChangeExecBit[path] = diff['dst_mode']1565 editedFiles.add(path)1566elif modifier =="A":1567 filesToAdd.add(path)1568 filesToChangeExecBit[path] = diff['dst_mode']1569if path in filesToDelete:1570 filesToDelete.remove(path)1571elif modifier =="D":1572 filesToDelete.add(path)1573if path in filesToAdd:1574 filesToAdd.remove(path)1575elif modifier =="C":1576 src, dest = diff['src'], diff['dst']1577p4_integrate(src, dest)1578 pureRenameCopy.add(dest)1579if diff['src_sha1'] != diff['dst_sha1']:1580p4_edit(dest)1581 pureRenameCopy.discard(dest)1582ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1583p4_edit(dest)1584 pureRenameCopy.discard(dest)1585 filesToChangeExecBit[dest] = diff['dst_mode']1586if self.isWindows:1587# turn off read-only attribute1588 os.chmod(dest, stat.S_IWRITE)1589 os.unlink(dest)1590 editedFiles.add(dest)1591elif modifier =="R":1592 src, dest = diff['src'], diff['dst']1593if self.p4HasMoveCommand:1594p4_edit(src)# src must be open before move1595p4_move(src, dest)# opens for (move/delete, move/add)1596else:1597p4_integrate(src, dest)1598if diff['src_sha1'] != diff['dst_sha1']:1599p4_edit(dest)1600else:1601 pureRenameCopy.add(dest)1602ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1603if not self.p4HasMoveCommand:1604p4_edit(dest)# with move: already open, writable1605 filesToChangeExecBit[dest] = diff['dst_mode']1606if not self.p4HasMoveCommand:1607if self.isWindows:1608 os.chmod(dest, stat.S_IWRITE)1609 os.unlink(dest)1610 filesToDelete.add(src)1611 editedFiles.add(dest)1612else:1613die("unknown modifier%sfor%s"% (modifier, path))16141615 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1616 patchcmd = diffcmd +" | git apply "1617 tryPatchCmd = patchcmd +"--check -"1618 applyPatchCmd = patchcmd +"--check --apply -"1619 patch_succeeded =True16201621if os.system(tryPatchCmd) !=0:1622 fixed_rcs_keywords =False1623 patch_succeeded =False1624print"Unfortunately applying the change failed!"16251626# Patch failed, maybe it's just RCS keyword woes. Look through1627# the patch to see if that's possible.1628ifgitConfigBool("git-p4.attemptRCSCleanup"):1629file=None1630 pattern =None1631 kwfiles = {}1632forfilein editedFiles | filesToDelete:1633# did this file's delta contain RCS keywords?1634 pattern =p4_keywords_regexp_for_file(file)16351636if pattern:1637# this file is a possibility...look for RCS keywords.1638 regexp = re.compile(pattern, re.VERBOSE)1639for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1640if regexp.search(line):1641if verbose:1642print"got keyword match on%sin%sin%s"% (pattern, line,file)1643 kwfiles[file] = pattern1644break16451646forfilein kwfiles:1647if verbose:1648print"zapping%swith%s"% (line,pattern)1649# File is being deleted, so not open in p4. Must1650# disable the read-only bit on windows.1651if self.isWindows andfilenot in editedFiles:1652 os.chmod(file, stat.S_IWRITE)1653 self.patchRCSKeywords(file, kwfiles[file])1654 fixed_rcs_keywords =True16551656if fixed_rcs_keywords:1657print"Retrying the patch with RCS keywords cleaned up"1658if os.system(tryPatchCmd) ==0:1659 patch_succeeded =True16601661if not patch_succeeded:1662for f in editedFiles:1663p4_revert(f)1664return False16651666#1667# Apply the patch for real, and do add/delete/+x handling.1668#1669system(applyPatchCmd)16701671for f in filesToAdd:1672p4_add(f)1673for f in filesToDelete:1674p4_revert(f)1675p4_delete(f)16761677# Set/clear executable bits1678for f in filesToChangeExecBit.keys():1679 mode = filesToChangeExecBit[f]1680setP4ExecBit(f, mode)16811682#1683# Build p4 change description, starting with the contents1684# of the git commit message.1685#1686 logMessage =extractLogMessageFromGitCommit(id)1687 logMessage = logMessage.strip()1688(logMessage, jobs) = self.separate_jobs_from_description(logMessage)16891690 template = self.prepareSubmitTemplate()1691 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)16921693if self.preserveUser:1694 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User16951696if self.checkAuthorship and not self.p4UserIsMe(p4User):1697 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1698 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1699 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"17001701 separatorLine ="######## everything below this line is just the diff #######\n"1702if not self.prepare_p4_only:1703 submitTemplate += separatorLine1704 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)17051706(handle, fileName) = tempfile.mkstemp()1707 tmpFile = os.fdopen(handle,"w+b")1708if self.isWindows:1709 submitTemplate = submitTemplate.replace("\n","\r\n")1710 tmpFile.write(submitTemplate)1711 tmpFile.close()17121713if self.prepare_p4_only:1714#1715# Leave the p4 tree prepared, and the submit template around1716# and let the user decide what to do next1717#1718print1719print"P4 workspace prepared for submission."1720print"To submit or revert, go to client workspace"1721print" "+ self.clientPath1722print1723print"To submit, use\"p4 submit\"to write a new description,"1724print"or\"p4 submit -i <%s\"to use the one prepared by" \1725"\"git p4\"."% fileName1726print"You can delete the file\"%s\"when finished."% fileName17271728if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1729print"To preserve change ownership by user%s, you must\n" \1730"do\"p4 change -f <change>\"after submitting and\n" \1731"edit the User field."1732if pureRenameCopy:1733print"After submitting, renamed files must be re-synced."1734print"Invoke\"p4 sync -f\"on each of these files:"1735for f in pureRenameCopy:1736print" "+ f17371738print1739print"To revert the changes, use\"p4 revert ...\", and delete"1740print"the submit template file\"%s\""% fileName1741if filesToAdd:1742print"Since the commit adds new files, they must be deleted:"1743for f in filesToAdd:1744print" "+ f1745print1746return True17471748#1749# Let the user edit the change description, then submit it.1750#1751 submitted =False17521753try:1754if self.edit_template(fileName):1755# read the edited message and submit1756 tmpFile =open(fileName,"rb")1757 message = tmpFile.read()1758 tmpFile.close()1759if self.isWindows:1760 message = message.replace("\r\n","\n")1761 submitTemplate = message[:message.index(separatorLine)]1762p4_write_pipe(['submit','-i'], submitTemplate)17631764if self.preserveUser:1765if p4User:1766# Get last changelist number. Cannot easily get it from1767# the submit command output as the output is1768# unmarshalled.1769 changelist = self.lastP4Changelist()1770 self.modifyChangelistUser(changelist, p4User)17711772# The rename/copy happened by applying a patch that created a1773# new file. This leaves it writable, which confuses p4.1774for f in pureRenameCopy:1775p4_sync(f,"-f")1776 submitted =True17771778finally:1779# skip this patch1780if not submitted:1781print"Submission cancelled, undoing p4 changes."1782for f in editedFiles:1783p4_revert(f)1784for f in filesToAdd:1785p4_revert(f)1786 os.remove(f)1787for f in filesToDelete:1788p4_revert(f)17891790 os.remove(fileName)1791return submitted17921793# Export git tags as p4 labels. Create a p4 label and then tag1794# with that.1795defexportGitTags(self, gitTags):1796 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1797iflen(validLabelRegexp) ==0:1798 validLabelRegexp = defaultLabelRegexp1799 m = re.compile(validLabelRegexp)18001801for name in gitTags:18021803if not m.match(name):1804if verbose:1805print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1806continue18071808# Get the p4 commit this corresponds to1809 logMessage =extractLogMessageFromGitCommit(name)1810 values =extractSettingsGitLog(logMessage)18111812if not values.has_key('change'):1813# a tag pointing to something not sent to p4; ignore1814if verbose:1815print"git tag%sdoes not give a p4 commit"% name1816continue1817else:1818 changelist = values['change']18191820# Get the tag details.1821 inHeader =True1822 isAnnotated =False1823 body = []1824for l inread_pipe_lines(["git","cat-file","-p", name]):1825 l = l.strip()1826if inHeader:1827if re.match(r'tag\s+', l):1828 isAnnotated =True1829elif re.match(r'\s*$', l):1830 inHeader =False1831continue1832else:1833 body.append(l)18341835if not isAnnotated:1836 body = ["lightweight tag imported by git p4\n"]18371838# Create the label - use the same view as the client spec we are using1839 clientSpec =getClientSpec()18401841 labelTemplate ="Label:%s\n"% name1842 labelTemplate +="Description:\n"1843for b in body:1844 labelTemplate +="\t"+ b +"\n"1845 labelTemplate +="View:\n"1846for depot_side in clientSpec.mappings:1847 labelTemplate +="\t%s\n"% depot_side18481849if self.dry_run:1850print"Would create p4 label%sfor tag"% name1851elif self.prepare_p4_only:1852print"Not creating p4 label%sfor tag due to option" \1853" --prepare-p4-only"% name1854else:1855p4_write_pipe(["label","-i"], labelTemplate)18561857# Use the label1858p4_system(["tag","-l", name] +1859["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18601861if verbose:1862print"created p4 label for tag%s"% name18631864defrun(self, args):1865iflen(args) ==0:1866 self.master =currentGitBranch()1867eliflen(args) ==1:1868 self.master = args[0]1869if notbranchExists(self.master):1870die("Branch%sdoes not exist"% self.master)1871else:1872return False18731874if self.master:1875 allowSubmit =gitConfig("git-p4.allowSubmit")1876iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1877die("%sis not in git-p4.allowSubmit"% self.master)18781879[upstream, settings] =findUpstreamBranchPoint()1880 self.depotPath = settings['depot-paths'][0]1881iflen(self.origin) ==0:1882 self.origin = upstream18831884if self.preserveUser:1885if not self.canChangeChangelists():1886die("Cannot preserve user names without p4 super-user or admin permissions")18871888# if not set from the command line, try the config file1889if self.conflict_behavior is None:1890 val =gitConfig("git-p4.conflict")1891if val:1892if val not in self.conflict_behavior_choices:1893die("Invalid value '%s' for config git-p4.conflict"% val)1894else:1895 val ="ask"1896 self.conflict_behavior = val18971898if self.verbose:1899print"Origin branch is "+ self.origin19001901iflen(self.depotPath) ==0:1902print"Internal error: cannot locate perforce depot path from existing branches"1903 sys.exit(128)19041905 self.useClientSpec =False1906ifgitConfigBool("git-p4.useclientspec"):1907 self.useClientSpec =True1908if self.useClientSpec:1909 self.clientSpecDirs =getClientSpec()19101911# Check for the existance of P4 branches1912 branchesDetected = (len(p4BranchesInGit().keys()) >1)19131914if self.useClientSpec and not branchesDetected:1915# all files are relative to the client spec1916 self.clientPath =getClientRoot()1917else:1918 self.clientPath =p4Where(self.depotPath)19191920if self.clientPath =="":1921die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19221923print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1924 self.oldWorkingDirectory = os.getcwd()19251926# ensure the clientPath exists1927 new_client_dir =False1928if not os.path.exists(self.clientPath):1929 new_client_dir =True1930 os.makedirs(self.clientPath)19311932chdir(self.clientPath, is_client_path=True)1933if self.dry_run:1934print"Would synchronize p4 checkout in%s"% self.clientPath1935else:1936print"Synchronizing p4 checkout..."1937if new_client_dir:1938# old one was destroyed, and maybe nobody told p41939p4_sync("...","-f")1940else:1941p4_sync("...")1942 self.check()19431944 commits = []1945if self.master:1946 commitish = self.master1947else:1948 commitish ='HEAD'19491950for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):1951 commits.append(line.strip())1952 commits.reverse()19531954if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1955 self.checkAuthorship =False1956else:1957 self.checkAuthorship =True19581959if self.preserveUser:1960 self.checkValidP4Users(commits)19611962#1963# Build up a set of options to be passed to diff when1964# submitting each commit to p4.1965#1966if self.detectRenames:1967# command-line -M arg1968 self.diffOpts ="-M"1969else:1970# If not explicitly set check the config variable1971 detectRenames =gitConfig("git-p4.detectRenames")19721973if detectRenames.lower() =="false"or detectRenames =="":1974 self.diffOpts =""1975elif detectRenames.lower() =="true":1976 self.diffOpts ="-M"1977else:1978 self.diffOpts ="-M%s"% detectRenames19791980# no command-line arg for -C or --find-copies-harder, just1981# config variables1982 detectCopies =gitConfig("git-p4.detectCopies")1983if detectCopies.lower() =="false"or detectCopies =="":1984pass1985elif detectCopies.lower() =="true":1986 self.diffOpts +=" -C"1987else:1988 self.diffOpts +=" -C%s"% detectCopies19891990ifgitConfigBool("git-p4.detectCopiesHarder"):1991 self.diffOpts +=" --find-copies-harder"19921993#1994# Apply the commits, one at a time. On failure, ask if should1995# continue to try the rest of the patches, or quit.1996#1997if self.dry_run:1998print"Would apply"1999 applied = []2000 last =len(commits) -12001for i, commit inenumerate(commits):2002if self.dry_run:2003print" ",read_pipe(["git","show","-s",2004"--format=format:%h%s", commit])2005 ok =True2006else:2007 ok = self.applyCommit(commit)2008if ok:2009 applied.append(commit)2010else:2011if self.prepare_p4_only and i < last:2012print"Processing only the first commit due to option" \2013" --prepare-p4-only"2014break2015if i < last:2016 quit =False2017while True:2018# prompt for what to do, or use the option/variable2019if self.conflict_behavior =="ask":2020print"What do you want to do?"2021 response =raw_input("[s]kip this commit but apply"2022" the rest, or [q]uit? ")2023if not response:2024continue2025elif self.conflict_behavior =="skip":2026 response ="s"2027elif self.conflict_behavior =="quit":2028 response ="q"2029else:2030die("Unknown conflict_behavior '%s'"%2031 self.conflict_behavior)20322033if response[0] =="s":2034print"Skipping this commit, but applying the rest"2035break2036if response[0] =="q":2037print"Quitting"2038 quit =True2039break2040if quit:2041break20422043chdir(self.oldWorkingDirectory)20442045if self.dry_run:2046pass2047elif self.prepare_p4_only:2048pass2049eliflen(commits) ==len(applied):2050print"All commits applied!"20512052 sync =P4Sync()2053if self.branch:2054 sync.branch = self.branch2055 sync.run([])20562057 rebase =P4Rebase()2058 rebase.rebase()20592060else:2061iflen(applied) ==0:2062print"No commits applied."2063else:2064print"Applied only the commits marked with '*':"2065for c in commits:2066if c in applied:2067 star ="*"2068else:2069 star =" "2070print star,read_pipe(["git","show","-s",2071"--format=format:%h%s", c])2072print"You will have to do 'git p4 sync' and rebase."20732074ifgitConfigBool("git-p4.exportLabels"):2075 self.exportLabels =True20762077if self.exportLabels:2078 p4Labels =getP4Labels(self.depotPath)2079 gitTags =getGitTags()20802081 missingGitTags = gitTags - p4Labels2082 self.exportGitTags(missingGitTags)20832084# exit with error unless everything applied perfectly2085iflen(commits) !=len(applied):2086 sys.exit(1)20872088return True20892090classView(object):2091"""Represent a p4 view ("p4 help views"), and map files in a2092 repo according to the view."""20932094def__init__(self, client_name):2095 self.mappings = []2096 self.client_prefix ="//%s/"% client_name2097# cache results of "p4 where" to lookup client file locations2098 self.client_spec_path_cache = {}20992100defappend(self, view_line):2101"""Parse a view line, splitting it into depot and client2102 sides. Append to self.mappings, preserving order. This2103 is only needed for tag creation."""21042105# Split the view line into exactly two words. P4 enforces2106# structure on these lines that simplifies this quite a bit.2107#2108# Either or both words may be double-quoted.2109# Single quotes do not matter.2110# Double-quote marks cannot occur inside the words.2111# A + or - prefix is also inside the quotes.2112# There are no quotes unless they contain a space.2113# The line is already white-space stripped.2114# The two words are separated by a single space.2115#2116if view_line[0] =='"':2117# First word is double quoted. Find its end.2118 close_quote_index = view_line.find('"',1)2119if close_quote_index <=0:2120die("No first-word closing quote found:%s"% view_line)2121 depot_side = view_line[1:close_quote_index]2122# skip closing quote and space2123 rhs_index = close_quote_index +1+12124else:2125 space_index = view_line.find(" ")2126if space_index <=0:2127die("No word-splitting space found:%s"% view_line)2128 depot_side = view_line[0:space_index]2129 rhs_index = space_index +121302131# prefix + means overlay on previous mapping2132if depot_side.startswith("+"):2133 depot_side = depot_side[1:]21342135# prefix - means exclude this path, leave out of mappings2136 exclude =False2137if depot_side.startswith("-"):2138 exclude =True2139 depot_side = depot_side[1:]21402141if not exclude:2142 self.mappings.append(depot_side)21432144defconvert_client_path(self, clientFile):2145# chop off //client/ part to make it relative2146if not clientFile.startswith(self.client_prefix):2147die("No prefix '%s' on clientFile '%s'"%2148(self.client_prefix, clientFile))2149return clientFile[len(self.client_prefix):]21502151defupdate_client_spec_path_cache(self, files):2152""" Caching file paths by "p4 where" batch query """21532154# List depot file paths exclude that already cached2155 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21562157iflen(fileArgs) ==0:2158return# All files in cache21592160 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2161for res in where_result:2162if"code"in res and res["code"] =="error":2163# assume error is "... file(s) not in client view"2164continue2165if"clientFile"not in res:2166die("No clientFile in 'p4 where' output")2167if"unmap"in res:2168# it will list all of them, but only one not unmap-ped2169continue2170ifgitConfigBool("core.ignorecase"):2171 res['depotFile'] = res['depotFile'].lower()2172 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])21732174# not found files or unmap files set to ""2175for depotFile in fileArgs:2176ifgitConfigBool("core.ignorecase"):2177 depotFile = depotFile.lower()2178if depotFile not in self.client_spec_path_cache:2179 self.client_spec_path_cache[depotFile] =""21802181defmap_in_client(self, depot_path):2182"""Return the relative location in the client where this2183 depot file should live. Returns "" if the file should2184 not be mapped in the client."""21852186ifgitConfigBool("core.ignorecase"):2187 depot_path = depot_path.lower()21882189if depot_path in self.client_spec_path_cache:2190return self.client_spec_path_cache[depot_path]21912192die("Error:%sis not found in client spec path"% depot_path )2193return""21942195classP4Sync(Command, P4UserMap):2196 delete_actions = ("delete","move/delete","purge")21972198def__init__(self):2199 Command.__init__(self)2200 P4UserMap.__init__(self)2201 self.options = [2202 optparse.make_option("--branch", dest="branch"),2203 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2204 optparse.make_option("--changesfile", dest="changesFile"),2205 optparse.make_option("--silent", dest="silent", action="store_true"),2206 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2207 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2208 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2209help="Import into refs/heads/ , not refs/remotes"),2210 optparse.make_option("--max-changes", dest="maxChanges",2211help="Maximum number of changes to import"),2212 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2213help="Internal block size to use when iteratively calling p4 changes"),2214 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2215help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2216 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2217help="Only sync files that are included in the Perforce Client Spec"),2218 optparse.make_option("-/", dest="cloneExclude",2219 action="append",type="string",2220help="exclude depot path"),2221]2222 self.description ="""Imports from Perforce into a git repository.\n2223 example:2224 //depot/my/project/ -- to import the current head2225 //depot/my/project/@all -- to import everything2226 //depot/my/project/@1,6 -- to import only from revision 1 to 622272228 (a ... is not needed in the path p4 specification, it's added implicitly)"""22292230 self.usage +=" //depot/path[@revRange]"2231 self.silent =False2232 self.createdBranches =set()2233 self.committedChanges =set()2234 self.branch =""2235 self.detectBranches =False2236 self.detectLabels =False2237 self.importLabels =False2238 self.changesFile =""2239 self.syncWithOrigin =True2240 self.importIntoRemotes =True2241 self.maxChanges =""2242 self.changes_block_size =None2243 self.keepRepoPath =False2244 self.depotPaths =None2245 self.p4BranchesInGit = []2246 self.cloneExclude = []2247 self.useClientSpec =False2248 self.useClientSpec_from_options =False2249 self.clientSpecDirs =None2250 self.tempBranches = []2251 self.tempBranchLocation ="git-p4-tmp"2252 self.largeFileSystem =None22532254ifgitConfig('git-p4.largeFileSystem'):2255 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2256 self.largeFileSystem =largeFileSystemConstructor(2257lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2258)22592260ifgitConfig("git-p4.syncFromOrigin") =="false":2261 self.syncWithOrigin =False22622263# This is required for the "append" cloneExclude action2264defensure_value(self, attr, value):2265if nothasattr(self, attr)orgetattr(self, attr)is None:2266setattr(self, attr, value)2267returngetattr(self, attr)22682269# Force a checkpoint in fast-import and wait for it to finish2270defcheckpoint(self):2271 self.gitStream.write("checkpoint\n\n")2272 self.gitStream.write("progress checkpoint\n\n")2273 out = self.gitOutput.readline()2274if self.verbose:2275print"checkpoint finished: "+ out22762277defextractFilesFromCommit(self, commit):2278 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2279for path in self.cloneExclude]2280 files = []2281 fnum =02282while commit.has_key("depotFile%s"% fnum):2283 path = commit["depotFile%s"% fnum]22842285if[p for p in self.cloneExclude2286ifp4PathStartsWith(path, p)]:2287 found =False2288else:2289 found = [p for p in self.depotPaths2290ifp4PathStartsWith(path, p)]2291if not found:2292 fnum = fnum +12293continue22942295file= {}2296file["path"] = path2297file["rev"] = commit["rev%s"% fnum]2298file["action"] = commit["action%s"% fnum]2299file["type"] = commit["type%s"% fnum]2300 files.append(file)2301 fnum = fnum +12302return files23032304defstripRepoPath(self, path, prefixes):2305"""When streaming files, this is called to map a p4 depot path2306 to where it should go in git. The prefixes are either2307 self.depotPaths, or self.branchPrefixes in the case of2308 branch detection."""23092310if self.useClientSpec:2311# branch detection moves files up a level (the branch name)2312# from what client spec interpretation gives2313 path = self.clientSpecDirs.map_in_client(path)2314if self.detectBranches:2315for b in self.knownBranches:2316if path.startswith(b +"/"):2317 path = path[len(b)+1:]23182319elif self.keepRepoPath:2320# Preserve everything in relative path name except leading2321# //depot/; just look at first prefix as they all should2322# be in the same depot.2323 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2324ifp4PathStartsWith(path, depot):2325 path = path[len(depot):]23262327else:2328for p in prefixes:2329ifp4PathStartsWith(path, p):2330 path = path[len(p):]2331break23322333 path =wildcard_decode(path)2334return path23352336defsplitFilesIntoBranches(self, commit):2337"""Look at each depotFile in the commit to figure out to what2338 branch it belongs."""23392340if self.clientSpecDirs:2341 files = self.extractFilesFromCommit(commit)2342 self.clientSpecDirs.update_client_spec_path_cache(files)23432344 branches = {}2345 fnum =02346while commit.has_key("depotFile%s"% fnum):2347 path = commit["depotFile%s"% fnum]2348 found = [p for p in self.depotPaths2349ifp4PathStartsWith(path, p)]2350if not found:2351 fnum = fnum +12352continue23532354file= {}2355file["path"] = path2356file["rev"] = commit["rev%s"% fnum]2357file["action"] = commit["action%s"% fnum]2358file["type"] = commit["type%s"% fnum]2359 fnum = fnum +123602361# start with the full relative path where this file would2362# go in a p4 client2363if self.useClientSpec:2364 relPath = self.clientSpecDirs.map_in_client(path)2365else:2366 relPath = self.stripRepoPath(path, self.depotPaths)23672368for branch in self.knownBranches.keys():2369# add a trailing slash so that a commit into qt/4.2foo2370# doesn't end up in qt/4.2, e.g.2371if relPath.startswith(branch +"/"):2372if branch not in branches:2373 branches[branch] = []2374 branches[branch].append(file)2375break23762377return branches23782379defwriteToGitStream(self, gitMode, relPath, contents):2380 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2381 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2382for d in contents:2383 self.gitStream.write(d)2384 self.gitStream.write('\n')23852386# output one file from the P4 stream2387# - helper for streamP4Files23882389defstreamOneP4File(self,file, contents):2390 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2391if verbose:2392 size =int(self.stream_file['fileSize'])2393 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2394 sys.stdout.flush()23952396(type_base, type_mods) =split_p4_type(file["type"])23972398 git_mode ="100644"2399if"x"in type_mods:2400 git_mode ="100755"2401if type_base =="symlink":2402 git_mode ="120000"2403# p4 print on a symlink sometimes contains "target\n";2404# if it does, remove the newline2405 data =''.join(contents)2406if not data:2407# Some version of p4 allowed creating a symlink that pointed2408# to nothing. This causes p4 errors when checking out such2409# a change, and errors here too. Work around it by ignoring2410# the bad symlink; hopefully a future change fixes it.2411print"\nIgnoring empty symlink in%s"%file['depotFile']2412return2413elif data[-1] =='\n':2414 contents = [data[:-1]]2415else:2416 contents = [data]24172418if type_base =="utf16":2419# p4 delivers different text in the python output to -G2420# than it does when using "print -o", or normal p4 client2421# operations. utf16 is converted to ascii or utf8, perhaps.2422# But ascii text saved as -t utf16 is completely mangled.2423# Invoke print -o to get the real contents.2424#2425# On windows, the newlines will always be mangled by print, so put2426# them back too. This is not needed to the cygwin windows version,2427# just the native "NT" type.2428#2429try:2430 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2431exceptExceptionas e:2432if'Translation of file content failed'instr(e):2433 type_base ='binary'2434else:2435raise e2436else:2437ifp4_version_string().find('/NT') >=0:2438 text = text.replace('\r\n','\n')2439 contents = [ text ]24402441if type_base =="apple":2442# Apple filetype files will be streamed as a concatenation of2443# its appledouble header and the contents. This is useless2444# on both macs and non-macs. If using "print -q -o xx", it2445# will create "xx" with the data, and "%xx" with the header.2446# This is also not very useful.2447#2448# Ideally, someday, this script can learn how to generate2449# appledouble files directly and import those to git, but2450# non-mac machines can never find a use for apple filetype.2451print"\nIgnoring apple filetype file%s"%file['depotFile']2452return24532454# Note that we do not try to de-mangle keywords on utf16 files,2455# even though in theory somebody may want that.2456 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2457if pattern:2458 regexp = re.compile(pattern, re.VERBOSE)2459 text =''.join(contents)2460 text = regexp.sub(r'$\1$', text)2461 contents = [ text ]24622463try:2464 relPath.decode('ascii')2465except:2466 encoding ='utf8'2467ifgitConfig('git-p4.pathEncoding'):2468 encoding =gitConfig('git-p4.pathEncoding')2469 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2470if self.verbose:2471print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)24722473if self.largeFileSystem:2474(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)24752476 self.writeToGitStream(git_mode, relPath, contents)24772478defstreamOneP4Deletion(self,file):2479 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2480if verbose:2481 sys.stdout.write("delete%s\n"% relPath)2482 sys.stdout.flush()2483 self.gitStream.write("D%s\n"% relPath)24842485if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2486 self.largeFileSystem.removeLargeFile(relPath)24872488# handle another chunk of streaming data2489defstreamP4FilesCb(self, marshalled):24902491# catch p4 errors and complain2492 err =None2493if"code"in marshalled:2494if marshalled["code"] =="error":2495if"data"in marshalled:2496 err = marshalled["data"].rstrip()24972498if not err and'fileSize'in self.stream_file:2499 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2500if required_bytes >0:2501 err ='Not enough space left on%s! Free at least%iMB.'% (2502 os.getcwd(), required_bytes/1024/10242503)25042505if err:2506 f =None2507if self.stream_have_file_info:2508if"depotFile"in self.stream_file:2509 f = self.stream_file["depotFile"]2510# force a failure in fast-import, else an empty2511# commit will be made2512 self.gitStream.write("\n")2513 self.gitStream.write("die-now\n")2514 self.gitStream.close()2515# ignore errors, but make sure it exits first2516 self.importProcess.wait()2517if f:2518die("Error from p4 print for%s:%s"% (f, err))2519else:2520die("Error from p4 print:%s"% err)25212522if marshalled.has_key('depotFile')and self.stream_have_file_info:2523# start of a new file - output the old one first2524 self.streamOneP4File(self.stream_file, self.stream_contents)2525 self.stream_file = {}2526 self.stream_contents = []2527 self.stream_have_file_info =False25282529# pick up the new file information... for the2530# 'data' field we need to append to our array2531for k in marshalled.keys():2532if k =='data':2533if'streamContentSize'not in self.stream_file:2534 self.stream_file['streamContentSize'] =02535 self.stream_file['streamContentSize'] +=len(marshalled['data'])2536 self.stream_contents.append(marshalled['data'])2537else:2538 self.stream_file[k] = marshalled[k]25392540if(verbose and2541'streamContentSize'in self.stream_file and2542'fileSize'in self.stream_file and2543'depotFile'in self.stream_file):2544 size =int(self.stream_file["fileSize"])2545if size >0:2546 progress =100*self.stream_file['streamContentSize']/size2547 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2548 sys.stdout.flush()25492550 self.stream_have_file_info =True25512552# Stream directly from "p4 files" into "git fast-import"2553defstreamP4Files(self, files):2554 filesForCommit = []2555 filesToRead = []2556 filesToDelete = []25572558for f in files:2559# if using a client spec, only add the files that have2560# a path in the client2561if self.clientSpecDirs:2562if self.clientSpecDirs.map_in_client(f['path']) =="":2563continue25642565 filesForCommit.append(f)2566if f['action']in self.delete_actions:2567 filesToDelete.append(f)2568else:2569 filesToRead.append(f)25702571# deleted files...2572for f in filesToDelete:2573 self.streamOneP4Deletion(f)25742575iflen(filesToRead) >0:2576 self.stream_file = {}2577 self.stream_contents = []2578 self.stream_have_file_info =False25792580# curry self argument2581defstreamP4FilesCbSelf(entry):2582 self.streamP4FilesCb(entry)25832584 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]25852586p4CmdList(["-x","-","print"],2587 stdin=fileArgs,2588 cb=streamP4FilesCbSelf)25892590# do the last chunk2591if self.stream_file.has_key('depotFile'):2592 self.streamOneP4File(self.stream_file, self.stream_contents)25932594defmake_email(self, userid):2595if userid in self.users:2596return self.users[userid]2597else:2598return"%s<a@b>"% userid25992600defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2601""" Stream a p4 tag.2602 commit is either a git commit, or a fast-import mark, ":<p4commit>"2603 """26042605if verbose:2606print"writing tag%sfor commit%s"% (labelName, commit)2607 gitStream.write("tag%s\n"% labelName)2608 gitStream.write("from%s\n"% commit)26092610if labelDetails.has_key('Owner'):2611 owner = labelDetails["Owner"]2612else:2613 owner =None26142615# Try to use the owner of the p4 label, or failing that,2616# the current p4 user id.2617if owner:2618 email = self.make_email(owner)2619else:2620 email = self.make_email(self.p4UserId())2621 tagger ="%s %s %s"% (email, epoch, self.tz)26222623 gitStream.write("tagger%s\n"% tagger)26242625print"labelDetails=",labelDetails2626if labelDetails.has_key('Description'):2627 description = labelDetails['Description']2628else:2629 description ='Label from git p4'26302631 gitStream.write("data%d\n"%len(description))2632 gitStream.write(description)2633 gitStream.write("\n")26342635defcommit(self, details, files, branch, parent =""):2636 epoch = details["time"]2637 author = details["user"]26382639if self.verbose:2640print"commit into%s"% branch26412642# start with reading files; if that fails, we should not2643# create a commit.2644 new_files = []2645for f in files:2646if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2647 new_files.append(f)2648else:2649 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])26502651if self.clientSpecDirs:2652 self.clientSpecDirs.update_client_spec_path_cache(files)26532654 self.gitStream.write("commit%s\n"% branch)2655 self.gitStream.write("mark :%s\n"% details["change"])2656 self.committedChanges.add(int(details["change"]))2657 committer =""2658if author not in self.users:2659 self.getUserMapFromPerforceServer()2660 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)26612662 self.gitStream.write("committer%s\n"% committer)26632664 self.gitStream.write("data <<EOT\n")2665 self.gitStream.write(details["desc"])2666 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2667(','.join(self.branchPrefixes), details["change"]))2668iflen(details['options']) >0:2669 self.gitStream.write(": options =%s"% details['options'])2670 self.gitStream.write("]\nEOT\n\n")26712672iflen(parent) >0:2673if self.verbose:2674print"parent%s"% parent2675 self.gitStream.write("from%s\n"% parent)26762677 self.streamP4Files(new_files)2678 self.gitStream.write("\n")26792680 change =int(details["change"])26812682if self.labels.has_key(change):2683 label = self.labels[change]2684 labelDetails = label[0]2685 labelRevisions = label[1]2686if self.verbose:2687print"Change%sis labelled%s"% (change, labelDetails)26882689 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2690for p in self.branchPrefixes])26912692iflen(files) ==len(labelRevisions):26932694 cleanedFiles = {}2695for info in files:2696if info["action"]in self.delete_actions:2697continue2698 cleanedFiles[info["depotFile"]] = info["rev"]26992700if cleanedFiles == labelRevisions:2701 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)27022703else:2704if not self.silent:2705print("Tag%sdoes not match with change%s: files do not match."2706% (labelDetails["label"], change))27072708else:2709if not self.silent:2710print("Tag%sdoes not match with change%s: file count is different."2711% (labelDetails["label"], change))27122713# Build a dictionary of changelists and labels, for "detect-labels" option.2714defgetLabels(self):2715 self.labels = {}27162717 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2718iflen(l) >0and not self.silent:2719print"Finding files belonging to labels in%s"% `self.depotPaths`27202721for output in l:2722 label = output["label"]2723 revisions = {}2724 newestChange =02725if self.verbose:2726print"Querying files for label%s"% label2727forfileinp4CmdList(["files"] +2728["%s...@%s"% (p, label)2729for p in self.depotPaths]):2730 revisions[file["depotFile"]] =file["rev"]2731 change =int(file["change"])2732if change > newestChange:2733 newestChange = change27342735 self.labels[newestChange] = [output, revisions]27362737if self.verbose:2738print"Label changes:%s"% self.labels.keys()27392740# Import p4 labels as git tags. A direct mapping does not2741# exist, so assume that if all the files are at the same revision2742# then we can use that, or it's something more complicated we should2743# just ignore.2744defimportP4Labels(self, stream, p4Labels):2745if verbose:2746print"import p4 labels: "+' '.join(p4Labels)27472748 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2749 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2750iflen(validLabelRegexp) ==0:2751 validLabelRegexp = defaultLabelRegexp2752 m = re.compile(validLabelRegexp)27532754for name in p4Labels:2755 commitFound =False27562757if not m.match(name):2758if verbose:2759print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2760continue27612762if name in ignoredP4Labels:2763continue27642765 labelDetails =p4CmdList(['label',"-o", name])[0]27662767# get the most recent changelist for each file in this label2768 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2769for p in self.depotPaths])27702771if change.has_key('change'):2772# find the corresponding git commit; take the oldest commit2773 changelist =int(change['change'])2774if changelist in self.committedChanges:2775 gitCommit =":%d"% changelist # use a fast-import mark2776 commitFound =True2777else:2778 gitCommit =read_pipe(["git","rev-list","--max-count=1",2779"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2780iflen(gitCommit) ==0:2781print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2782else:2783 commitFound =True2784 gitCommit = gitCommit.strip()27852786if commitFound:2787# Convert from p4 time format2788try:2789 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2790exceptValueError:2791print"Could not convert label time%s"% labelDetails['Update']2792 tmwhen =127932794 when =int(time.mktime(tmwhen))2795 self.streamTag(stream, name, labelDetails, gitCommit, when)2796if verbose:2797print"p4 label%smapped to git commit%s"% (name, gitCommit)2798else:2799if verbose:2800print"Label%shas no changelists - possibly deleted?"% name28012802if not commitFound:2803# We can't import this label; don't try again as it will get very2804# expensive repeatedly fetching all the files for labels that will2805# never be imported. If the label is moved in the future, the2806# ignore will need to be removed manually.2807system(["git","config","--add","git-p4.ignoredP4Labels", name])28082809defguessProjectName(self):2810for p in self.depotPaths:2811if p.endswith("/"):2812 p = p[:-1]2813 p = p[p.strip().rfind("/") +1:]2814if not p.endswith("/"):2815 p +="/"2816return p28172818defgetBranchMapping(self):2819 lostAndFoundBranches =set()28202821 user =gitConfig("git-p4.branchUser")2822iflen(user) >0:2823 command ="branches -u%s"% user2824else:2825 command ="branches"28262827for info inp4CmdList(command):2828 details =p4Cmd(["branch","-o", info["branch"]])2829 viewIdx =02830while details.has_key("View%s"% viewIdx):2831 paths = details["View%s"% viewIdx].split(" ")2832 viewIdx = viewIdx +12833# require standard //depot/foo/... //depot/bar/... mapping2834iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2835continue2836 source = paths[0]2837 destination = paths[1]2838## HACK2839ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2840 source = source[len(self.depotPaths[0]):-4]2841 destination = destination[len(self.depotPaths[0]):-4]28422843if destination in self.knownBranches:2844if not self.silent:2845print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2846print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2847continue28482849 self.knownBranches[destination] = source28502851 lostAndFoundBranches.discard(destination)28522853if source not in self.knownBranches:2854 lostAndFoundBranches.add(source)28552856# Perforce does not strictly require branches to be defined, so we also2857# check git config for a branch list.2858#2859# Example of branch definition in git config file:2860# [git-p4]2861# branchList=main:branchA2862# branchList=main:branchB2863# branchList=branchA:branchC2864 configBranches =gitConfigList("git-p4.branchList")2865for branch in configBranches:2866if branch:2867(source, destination) = branch.split(":")2868 self.knownBranches[destination] = source28692870 lostAndFoundBranches.discard(destination)28712872if source not in self.knownBranches:2873 lostAndFoundBranches.add(source)287428752876for branch in lostAndFoundBranches:2877 self.knownBranches[branch] = branch28782879defgetBranchMappingFromGitBranches(self):2880 branches =p4BranchesInGit(self.importIntoRemotes)2881for branch in branches.keys():2882if branch =="master":2883 branch ="main"2884else:2885 branch = branch[len(self.projectName):]2886 self.knownBranches[branch] = branch28872888defupdateOptionDict(self, d):2889 option_keys = {}2890if self.keepRepoPath:2891 option_keys['keepRepoPath'] =128922893 d["options"] =' '.join(sorted(option_keys.keys()))28942895defreadOptions(self, d):2896 self.keepRepoPath = (d.has_key('options')2897and('keepRepoPath'in d['options']))28982899defgitRefForBranch(self, branch):2900if branch =="main":2901return self.refPrefix +"master"29022903iflen(branch) <=0:2904return branch29052906return self.refPrefix + self.projectName + branch29072908defgitCommitByP4Change(self, ref, change):2909if self.verbose:2910print"looking in ref "+ ref +" for change%susing bisect..."% change29112912 earliestCommit =""2913 latestCommit =parseRevision(ref)29142915while True:2916if self.verbose:2917print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2918 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2919iflen(next) ==0:2920if self.verbose:2921print"argh"2922return""2923 log =extractLogMessageFromGitCommit(next)2924 settings =extractSettingsGitLog(log)2925 currentChange =int(settings['change'])2926if self.verbose:2927print"current change%s"% currentChange29282929if currentChange == change:2930if self.verbose:2931print"found%s"% next2932return next29332934if currentChange < change:2935 earliestCommit ="^%s"% next2936else:2937 latestCommit ="%s"% next29382939return""29402941defimportNewBranch(self, branch, maxChange):2942# make fast-import flush all changes to disk and update the refs using the checkpoint2943# command so that we can try to find the branch parent in the git history2944 self.gitStream.write("checkpoint\n\n");2945 self.gitStream.flush();2946 branchPrefix = self.depotPaths[0] + branch +"/"2947range="@1,%s"% maxChange2948#print "prefix" + branchPrefix2949 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2950iflen(changes) <=0:2951return False2952 firstChange = changes[0]2953#print "first change in branch: %s" % firstChange2954 sourceBranch = self.knownBranches[branch]2955 sourceDepotPath = self.depotPaths[0] + sourceBranch2956 sourceRef = self.gitRefForBranch(sourceBranch)2957#print "source " + sourceBranch29582959 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2960#print "branch parent: %s" % branchParentChange2961 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2962iflen(gitParent) >0:2963 self.initialParents[self.gitRefForBranch(branch)] = gitParent2964#print "parent git commit: %s" % gitParent29652966 self.importChanges(changes)2967return True29682969defsearchParent(self, parent, branch, target):2970 parentFound =False2971for blob inread_pipe_lines(["git","rev-list","--reverse",2972"--no-merges", parent]):2973 blob = blob.strip()2974iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2975 parentFound =True2976if self.verbose:2977print"Found parent of%sin commit%s"% (branch, blob)2978break2979if parentFound:2980return blob2981else:2982return None29832984defimportChanges(self, changes):2985 cnt =12986for change in changes:2987 description =p4_describe(change)2988 self.updateOptionDict(description)29892990if not self.silent:2991 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2992 sys.stdout.flush()2993 cnt = cnt +129942995try:2996if self.detectBranches:2997 branches = self.splitFilesIntoBranches(description)2998for branch in branches.keys():2999## HACK --hwn3000 branchPrefix = self.depotPaths[0] + branch +"/"3001 self.branchPrefixes = [ branchPrefix ]30023003 parent =""30043005 filesForCommit = branches[branch]30063007if self.verbose:3008print"branch is%s"% branch30093010 self.updatedBranches.add(branch)30113012if branch not in self.createdBranches:3013 self.createdBranches.add(branch)3014 parent = self.knownBranches[branch]3015if parent == branch:3016 parent =""3017else:3018 fullBranch = self.projectName + branch3019if fullBranch not in self.p4BranchesInGit:3020if not self.silent:3021print("\nImporting new branch%s"% fullBranch);3022if self.importNewBranch(branch, change -1):3023 parent =""3024 self.p4BranchesInGit.append(fullBranch)3025if not self.silent:3026print("\nResuming with change%s"% change);30273028if self.verbose:3029print"parent determined through known branches:%s"% parent30303031 branch = self.gitRefForBranch(branch)3032 parent = self.gitRefForBranch(parent)30333034if self.verbose:3035print"looking for initial parent for%s; current parent is%s"% (branch, parent)30363037iflen(parent) ==0and branch in self.initialParents:3038 parent = self.initialParents[branch]3039del self.initialParents[branch]30403041 blob =None3042iflen(parent) >0:3043 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3044if self.verbose:3045print"Creating temporary branch: "+ tempBranch3046 self.commit(description, filesForCommit, tempBranch)3047 self.tempBranches.append(tempBranch)3048 self.checkpoint()3049 blob = self.searchParent(parent, branch, tempBranch)3050if blob:3051 self.commit(description, filesForCommit, branch, blob)3052else:3053if self.verbose:3054print"Parent of%snot found. Committing into head of%s"% (branch, parent)3055 self.commit(description, filesForCommit, branch, parent)3056else:3057 files = self.extractFilesFromCommit(description)3058 self.commit(description, files, self.branch,3059 self.initialParent)3060# only needed once, to connect to the previous commit3061 self.initialParent =""3062exceptIOError:3063print self.gitError.read()3064 sys.exit(1)30653066defimportHeadRevision(self, revision):3067print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)30683069 details = {}3070 details["user"] ="git perforce import user"3071 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3072% (' '.join(self.depotPaths), revision))3073 details["change"] = revision3074 newestRevision =030753076 fileCnt =03077 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]30783079for info inp4CmdList(["files"] + fileArgs):30803081if'code'in info and info['code'] =='error':3082 sys.stderr.write("p4 returned an error:%s\n"3083% info['data'])3084if info['data'].find("must refer to client") >=0:3085 sys.stderr.write("This particular p4 error is misleading.\n")3086 sys.stderr.write("Perhaps the depot path was misspelled.\n");3087 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3088 sys.exit(1)3089if'p4ExitCode'in info:3090 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3091 sys.exit(1)309230933094 change =int(info["change"])3095if change > newestRevision:3096 newestRevision = change30973098if info["action"]in self.delete_actions:3099# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3100#fileCnt = fileCnt + 13101continue31023103for prop in["depotFile","rev","action","type"]:3104 details["%s%s"% (prop, fileCnt)] = info[prop]31053106 fileCnt = fileCnt +131073108 details["change"] = newestRevision31093110# Use time from top-most change so that all git p4 clones of3111# the same p4 repo have the same commit SHA1s.3112 res =p4_describe(newestRevision)3113 details["time"] = res["time"]31143115 self.updateOptionDict(details)3116try:3117 self.commit(details, self.extractFilesFromCommit(details), self.branch)3118exceptIOError:3119print"IO error with git fast-import. Is your git version recent enough?"3120print self.gitError.read()312131223123defrun(self, args):3124 self.depotPaths = []3125 self.changeRange =""3126 self.previousDepotPaths = []3127 self.hasOrigin =False31283129# map from branch depot path to parent branch3130 self.knownBranches = {}3131 self.initialParents = {}31323133if self.importIntoRemotes:3134 self.refPrefix ="refs/remotes/p4/"3135else:3136 self.refPrefix ="refs/heads/p4/"31373138if self.syncWithOrigin:3139 self.hasOrigin =originP4BranchesExist()3140if self.hasOrigin:3141if not self.silent:3142print'Syncing with origin first, using "git fetch origin"'3143system("git fetch origin")31443145 branch_arg_given =bool(self.branch)3146iflen(self.branch) ==0:3147 self.branch = self.refPrefix +"master"3148ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3149system("git update-ref%srefs/heads/p4"% self.branch)3150system("git branch -D p4")31513152# accept either the command-line option, or the configuration variable3153if self.useClientSpec:3154# will use this after clone to set the variable3155 self.useClientSpec_from_options =True3156else:3157ifgitConfigBool("git-p4.useclientspec"):3158 self.useClientSpec =True3159if self.useClientSpec:3160 self.clientSpecDirs =getClientSpec()31613162# TODO: should always look at previous commits,3163# merge with previous imports, if possible.3164if args == []:3165if self.hasOrigin:3166createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)31673168# branches holds mapping from branch name to sha13169 branches =p4BranchesInGit(self.importIntoRemotes)31703171# restrict to just this one, disabling detect-branches3172if branch_arg_given:3173 short = self.branch.split("/")[-1]3174if short in branches:3175 self.p4BranchesInGit = [ short ]3176else:3177 self.p4BranchesInGit = branches.keys()31783179iflen(self.p4BranchesInGit) >1:3180if not self.silent:3181print"Importing from/into multiple branches"3182 self.detectBranches =True3183for branch in branches.keys():3184 self.initialParents[self.refPrefix + branch] = \3185 branches[branch]31863187if self.verbose:3188print"branches:%s"% self.p4BranchesInGit31893190 p4Change =03191for branch in self.p4BranchesInGit:3192 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)31933194 settings =extractSettingsGitLog(logMsg)31953196 self.readOptions(settings)3197if(settings.has_key('depot-paths')3198and settings.has_key('change')):3199 change =int(settings['change']) +13200 p4Change =max(p4Change, change)32013202 depotPaths =sorted(settings['depot-paths'])3203if self.previousDepotPaths == []:3204 self.previousDepotPaths = depotPaths3205else:3206 paths = []3207for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3208 prev_list = prev.split("/")3209 cur_list = cur.split("/")3210for i inrange(0,min(len(cur_list),len(prev_list))):3211if cur_list[i] <> prev_list[i]:3212 i = i -13213break32143215 paths.append("/".join(cur_list[:i +1]))32163217 self.previousDepotPaths = paths32183219if p4Change >0:3220 self.depotPaths =sorted(self.previousDepotPaths)3221 self.changeRange ="@%s,#head"% p4Change3222if not self.silent and not self.detectBranches:3223print"Performing incremental import into%sgit branch"% self.branch32243225# accept multiple ref name abbreviations:3226# refs/foo/bar/branch -> use it exactly3227# p4/branch -> prepend refs/remotes/ or refs/heads/3228# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3229if not self.branch.startswith("refs/"):3230if self.importIntoRemotes:3231 prepend ="refs/remotes/"3232else:3233 prepend ="refs/heads/"3234if not self.branch.startswith("p4/"):3235 prepend +="p4/"3236 self.branch = prepend + self.branch32373238iflen(args) ==0and self.depotPaths:3239if not self.silent:3240print"Depot paths:%s"%' '.join(self.depotPaths)3241else:3242if self.depotPaths and self.depotPaths != args:3243print("previous import used depot path%sand now%swas specified. "3244"This doesn't work!"% (' '.join(self.depotPaths),3245' '.join(args)))3246 sys.exit(1)32473248 self.depotPaths =sorted(args)32493250 revision =""3251 self.users = {}32523253# Make sure no revision specifiers are used when --changesfile3254# is specified.3255 bad_changesfile =False3256iflen(self.changesFile) >0:3257for p in self.depotPaths:3258if p.find("@") >=0or p.find("#") >=0:3259 bad_changesfile =True3260break3261if bad_changesfile:3262die("Option --changesfile is incompatible with revision specifiers")32633264 newPaths = []3265for p in self.depotPaths:3266if p.find("@") != -1:3267 atIdx = p.index("@")3268 self.changeRange = p[atIdx:]3269if self.changeRange =="@all":3270 self.changeRange =""3271elif','not in self.changeRange:3272 revision = self.changeRange3273 self.changeRange =""3274 p = p[:atIdx]3275elif p.find("#") != -1:3276 hashIdx = p.index("#")3277 revision = p[hashIdx:]3278 p = p[:hashIdx]3279elif self.previousDepotPaths == []:3280# pay attention to changesfile, if given, else import3281# the entire p4 tree at the head revision3282iflen(self.changesFile) ==0:3283 revision ="#head"32843285 p = re.sub("\.\.\.$","", p)3286if not p.endswith("/"):3287 p +="/"32883289 newPaths.append(p)32903291 self.depotPaths = newPaths32923293# --detect-branches may change this for each branch3294 self.branchPrefixes = self.depotPaths32953296 self.loadUserMapFromCache()3297 self.labels = {}3298if self.detectLabels:3299 self.getLabels();33003301if self.detectBranches:3302## FIXME - what's a P4 projectName ?3303 self.projectName = self.guessProjectName()33043305if self.hasOrigin:3306 self.getBranchMappingFromGitBranches()3307else:3308 self.getBranchMapping()3309if self.verbose:3310print"p4-git branches:%s"% self.p4BranchesInGit3311print"initial parents:%s"% self.initialParents3312for b in self.p4BranchesInGit:3313if b !="master":33143315## FIXME3316 b = b[len(self.projectName):]3317 self.createdBranches.add(b)33183319 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33203321 self.importProcess = subprocess.Popen(["git","fast-import"],3322 stdin=subprocess.PIPE,3323 stdout=subprocess.PIPE,3324 stderr=subprocess.PIPE);3325 self.gitOutput = self.importProcess.stdout3326 self.gitStream = self.importProcess.stdin3327 self.gitError = self.importProcess.stderr33283329if revision:3330 self.importHeadRevision(revision)3331else:3332 changes = []33333334iflen(self.changesFile) >0:3335 output =open(self.changesFile).readlines()3336 changeSet =set()3337for line in output:3338 changeSet.add(int(line))33393340for change in changeSet:3341 changes.append(change)33423343 changes.sort()3344else:3345# catch "git p4 sync" with no new branches, in a repo that3346# does not have any existing p4 branches3347iflen(args) ==0:3348if not self.p4BranchesInGit:3349die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")33503351# The default branch is master, unless --branch is used to3352# specify something else. Make sure it exists, or complain3353# nicely about how to use --branch.3354if not self.detectBranches:3355if notbranch_exists(self.branch):3356if branch_arg_given:3357die("Error: branch%sdoes not exist."% self.branch)3358else:3359die("Error: no branch%s; perhaps specify one with --branch."%3360 self.branch)33613362if self.verbose:3363print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3364 self.changeRange)3365 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)33663367iflen(self.maxChanges) >0:3368 changes = changes[:min(int(self.maxChanges),len(changes))]33693370iflen(changes) ==0:3371if not self.silent:3372print"No changes to import!"3373else:3374if not self.silent and not self.detectBranches:3375print"Import destination:%s"% self.branch33763377 self.updatedBranches =set()33783379if not self.detectBranches:3380if args:3381# start a new branch3382 self.initialParent =""3383else:3384# build on a previous revision3385 self.initialParent =parseRevision(self.branch)33863387 self.importChanges(changes)33883389if not self.silent:3390print""3391iflen(self.updatedBranches) >0:3392 sys.stdout.write("Updated branches: ")3393for b in self.updatedBranches:3394 sys.stdout.write("%s"% b)3395 sys.stdout.write("\n")33963397ifgitConfigBool("git-p4.importLabels"):3398 self.importLabels =True33993400if self.importLabels:3401 p4Labels =getP4Labels(self.depotPaths)3402 gitTags =getGitTags()34033404 missingP4Labels = p4Labels - gitTags3405 self.importP4Labels(self.gitStream, missingP4Labels)34063407 self.gitStream.close()3408if self.importProcess.wait() !=0:3409die("fast-import failed:%s"% self.gitError.read())3410 self.gitOutput.close()3411 self.gitError.close()34123413# Cleanup temporary branches created during import3414if self.tempBranches != []:3415for branch in self.tempBranches:3416read_pipe("git update-ref -d%s"% branch)3417 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34183419# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3420# a convenient shortcut refname "p4".3421if self.importIntoRemotes:3422 head_ref = self.refPrefix +"HEAD"3423if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3424system(["git","symbolic-ref", head_ref, self.branch])34253426return True34273428classP4Rebase(Command):3429def__init__(self):3430 Command.__init__(self)3431 self.options = [3432 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3433]3434 self.importLabels =False3435 self.description = ("Fetches the latest revision from perforce and "3436+"rebases the current work (branch) against it")34373438defrun(self, args):3439 sync =P4Sync()3440 sync.importLabels = self.importLabels3441 sync.run([])34423443return self.rebase()34443445defrebase(self):3446if os.system("git update-index --refresh") !=0:3447die("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.");3448iflen(read_pipe("git diff-index HEAD --")) >0:3449die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");34503451[upstream, settings] =findUpstreamBranchPoint()3452iflen(upstream) ==0:3453die("Cannot find upstream branchpoint for rebase")34543455# the branchpoint may be p4/foo~3, so strip off the parent3456 upstream = re.sub("~[0-9]+$","", upstream)34573458print"Rebasing the current branch onto%s"% upstream3459 oldHead =read_pipe("git rev-parse HEAD").strip()3460system("git rebase%s"% upstream)3461system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3462return True34633464classP4Clone(P4Sync):3465def__init__(self):3466 P4Sync.__init__(self)3467 self.description ="Creates a new git repository and imports from Perforce into it"3468 self.usage ="usage: %prog [options] //depot/path[@revRange]"3469 self.options += [3470 optparse.make_option("--destination", dest="cloneDestination",3471 action='store', default=None,3472help="where to leave result of the clone"),3473 optparse.make_option("--bare", dest="cloneBare",3474 action="store_true", default=False),3475]3476 self.cloneDestination =None3477 self.needsGit =False3478 self.cloneBare =False34793480defdefaultDestination(self, args):3481## TODO: use common prefix of args?3482 depotPath = args[0]3483 depotDir = re.sub("(@[^@]*)$","", depotPath)3484 depotDir = re.sub("(#[^#]*)$","", depotDir)3485 depotDir = re.sub(r"\.\.\.$","", depotDir)3486 depotDir = re.sub(r"/$","", depotDir)3487return os.path.split(depotDir)[1]34883489defrun(self, args):3490iflen(args) <1:3491return False34923493if self.keepRepoPath and not self.cloneDestination:3494 sys.stderr.write("Must specify destination for --keep-path\n")3495 sys.exit(1)34963497 depotPaths = args34983499if not self.cloneDestination andlen(depotPaths) >1:3500 self.cloneDestination = depotPaths[-1]3501 depotPaths = depotPaths[:-1]35023503 self.cloneExclude = ["/"+p for p in self.cloneExclude]3504for p in depotPaths:3505if not p.startswith("//"):3506 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3507return False35083509if not self.cloneDestination:3510 self.cloneDestination = self.defaultDestination(args)35113512print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)35133514if not os.path.exists(self.cloneDestination):3515 os.makedirs(self.cloneDestination)3516chdir(self.cloneDestination)35173518 init_cmd = ["git","init"]3519if self.cloneBare:3520 init_cmd.append("--bare")3521 retcode = subprocess.call(init_cmd)3522if retcode:3523raiseCalledProcessError(retcode, init_cmd)35243525if not P4Sync.run(self, depotPaths):3526return False35273528# create a master branch and check out a work tree3529ifgitBranchExists(self.branch):3530system(["git","branch","master", self.branch ])3531if not self.cloneBare:3532system(["git","checkout","-f"])3533else:3534print'Not checking out any branch, use ' \3535'"git checkout -q -b master <branch>"'35363537# auto-set this variable if invoked with --use-client-spec3538if self.useClientSpec_from_options:3539system("git config --bool git-p4.useclientspec true")35403541return True35423543classP4Branches(Command):3544def__init__(self):3545 Command.__init__(self)3546 self.options = [ ]3547 self.description = ("Shows the git branches that hold imports and their "3548+"corresponding perforce depot paths")3549 self.verbose =False35503551defrun(self, args):3552iforiginP4BranchesExist():3553createOrUpdateBranchesFromOrigin()35543555 cmdline ="git rev-parse --symbolic "3556 cmdline +=" --remotes"35573558for line inread_pipe_lines(cmdline):3559 line = line.strip()35603561if not line.startswith('p4/')or line =="p4/HEAD":3562continue3563 branch = line35643565 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3566 settings =extractSettingsGitLog(log)35673568print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3569return True35703571classHelpFormatter(optparse.IndentedHelpFormatter):3572def__init__(self):3573 optparse.IndentedHelpFormatter.__init__(self)35743575defformat_description(self, description):3576if description:3577return description +"\n"3578else:3579return""35803581defprintUsage(commands):3582print"usage:%s<command> [options]"% sys.argv[0]3583print""3584print"valid commands:%s"%", ".join(commands)3585print""3586print"Try%s<command> --help for command specific help."% sys.argv[0]3587print""35883589commands = {3590"debug": P4Debug,3591"submit": P4Submit,3592"commit": P4Submit,3593"sync": P4Sync,3594"rebase": P4Rebase,3595"clone": P4Clone,3596"rollback": P4RollBack,3597"branches": P4Branches3598}359936003601defmain():3602iflen(sys.argv[1:]) ==0:3603printUsage(commands.keys())3604 sys.exit(2)36053606 cmdName = sys.argv[1]3607try:3608 klass = commands[cmdName]3609 cmd =klass()3610exceptKeyError:3611print"unknown command%s"% cmdName3612print""3613printUsage(commands.keys())3614 sys.exit(2)36153616 options = cmd.options3617 cmd.gitdir = os.environ.get("GIT_DIR",None)36183619 args = sys.argv[2:]36203621 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3622if cmd.needsGit:3623 options.append(optparse.make_option("--git-dir", dest="gitdir"))36243625 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3626 options,3627 description = cmd.description,3628 formatter =HelpFormatter())36293630(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3631global verbose3632 verbose = cmd.verbose3633if cmd.needsGit:3634if cmd.gitdir ==None:3635 cmd.gitdir = os.path.abspath(".git")3636if notisValidGitDir(cmd.gitdir):3637 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3638if os.path.exists(cmd.gitdir):3639 cdup =read_pipe("git rev-parse --show-cdup").strip()3640iflen(cdup) >0:3641chdir(cdup);36423643if notisValidGitDir(cmd.gitdir):3644ifisValidGitDir(cmd.gitdir +"/.git"):3645 cmd.gitdir +="/.git"3646else:3647die("fatal: cannot locate git repository at%s"% cmd.gitdir)36483649 os.environ["GIT_DIR"] = cmd.gitdir36503651if not cmd.run(args):3652 parser.print_help()3653 sys.exit(2)365436553656if __name__ =='__main__':3657main()