1#!/usr/bin/env python 2# 3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. 4# 5# Author: Simon Hausmann <simon@lst.de> 6# Copyright: 2007 Simon Hausmann <simon@lst.de> 7# 2007 Trolltech ASA 8# License: MIT <http://www.opensource.org/licenses/mit-license.php> 9# 10import sys 11if sys.hexversion <0x02040000: 12# The limiter is the subprocess module 13 sys.stderr.write("git-p4: requires Python 2.4 or later.\n") 14 sys.exit(1) 15import os 16import optparse 17import marshal 18import subprocess 19import tempfile 20import time 21import platform 22import re 23import shutil 24import stat 25import zipfile 26import zlib 27import ctypes 28 29try: 30from subprocess import CalledProcessError 31exceptImportError: 32# from python2.7:subprocess.py 33# Exception classes used by this module. 34classCalledProcessError(Exception): 35"""This exception is raised when a process run by check_call() returns 36 a non-zero exit status. The exit status will be stored in the 37 returncode attribute.""" 38def__init__(self, returncode, cmd): 39 self.returncode = returncode 40 self.cmd = cmd 41def__str__(self): 42return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 43 44verbose =False 45 46# Only labels/tags matching this will be imported/exported 47defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 48 49# Grab changes in blocks of this many revisions, unless otherwise requested 50defaultBlockSize =512 51 52defp4_build_cmd(cmd): 53"""Build a suitable p4 command line. 54 55 This consolidates building and returning a p4 command line into one 56 location. It means that hooking into the environment, or other configuration 57 can be done more easily. 58 """ 59 real_cmd = ["p4"] 60 61 user =gitConfig("git-p4.user") 62iflen(user) >0: 63 real_cmd += ["-u",user] 64 65 password =gitConfig("git-p4.password") 66iflen(password) >0: 67 real_cmd += ["-P", password] 68 69 port =gitConfig("git-p4.port") 70iflen(port) >0: 71 real_cmd += ["-p", port] 72 73 host =gitConfig("git-p4.host") 74iflen(host) >0: 75 real_cmd += ["-H", host] 76 77 client =gitConfig("git-p4.client") 78iflen(client) >0: 79 real_cmd += ["-c", client] 80 81 82ifisinstance(cmd,basestring): 83 real_cmd =' '.join(real_cmd) +' '+ cmd 84else: 85 real_cmd += cmd 86return real_cmd 87 88defchdir(path, is_client_path=False): 89"""Do chdir to the given path, and set the PWD environment 90 variable for use by P4. It does not look at getcwd() output. 91 Since we're not using the shell, it is necessary to set the 92 PWD environment variable explicitly. 93 94 Normally, expand the path to force it to be absolute. This 95 addresses the use of relative path names inside P4 settings, 96 e.g. P4CONFIG=.p4config. P4 does not simply open the filename 97 as given; it looks for .p4config using PWD. 98 99 If is_client_path, the path was handed to us directly by p4, 100 and may be a symbolic link. Do not call os.getcwd() in this 101 case, because it will cause p4 to think that PWD is not inside 102 the client path. 103 """ 104 105 os.chdir(path) 106if not is_client_path: 107 path = os.getcwd() 108 os.environ['PWD'] = path 109 110defcalcDiskFree(): 111"""Return free space in bytes on the disk of the given dirname.""" 112if platform.system() =='Windows': 113 free_bytes = ctypes.c_ulonglong(0) 114 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()),None,None, ctypes.pointer(free_bytes)) 115return free_bytes.value 116else: 117 st = os.statvfs(os.getcwd()) 118return st.f_bavail * st.f_frsize 119 120defdie(msg): 121if verbose: 122raiseException(msg) 123else: 124 sys.stderr.write(msg +"\n") 125 sys.exit(1) 126 127defwrite_pipe(c, stdin): 128if verbose: 129 sys.stderr.write('Writing pipe:%s\n'%str(c)) 130 131 expand =isinstance(c,basestring) 132 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 133 pipe = p.stdin 134 val = pipe.write(stdin) 135 pipe.close() 136if p.wait(): 137die('Command failed:%s'%str(c)) 138 139return val 140 141defp4_write_pipe(c, stdin): 142 real_cmd =p4_build_cmd(c) 143returnwrite_pipe(real_cmd, stdin) 144 145defread_pipe(c, ignore_error=False): 146if verbose: 147 sys.stderr.write('Reading pipe:%s\n'%str(c)) 148 149 expand =isinstance(c,basestring) 150 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand) 151(out, err) = p.communicate() 152if p.returncode !=0and not ignore_error: 153die('Command failed:%s\nError:%s'% (str(c), err)) 154return out 155 156defp4_read_pipe(c, ignore_error=False): 157 real_cmd =p4_build_cmd(c) 158returnread_pipe(real_cmd, ignore_error) 159 160defread_pipe_lines(c): 161if verbose: 162 sys.stderr.write('Reading pipe:%s\n'%str(c)) 163 164 expand =isinstance(c, basestring) 165 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 166 pipe = p.stdout 167 val = pipe.readlines() 168if pipe.close()or p.wait(): 169die('Command failed:%s'%str(c)) 170 171return val 172 173defp4_read_pipe_lines(c): 174"""Specifically invoke p4 on the command supplied. """ 175 real_cmd =p4_build_cmd(c) 176returnread_pipe_lines(real_cmd) 177 178defp4_has_command(cmd): 179"""Ask p4 for help on this command. If it returns an error, the 180 command does not exist in this version of p4.""" 181 real_cmd =p4_build_cmd(["help", cmd]) 182 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 183 stderr=subprocess.PIPE) 184 p.communicate() 185return p.returncode ==0 186 187defp4_has_move_command(): 188"""See if the move command exists, that it supports -k, and that 189 it has not been administratively disabled. The arguments 190 must be correct, but the filenames do not have to exist. Use 191 ones with wildcards so even if they exist, it will fail.""" 192 193if notp4_has_command("move"): 194return False 195 cmd =p4_build_cmd(["move","-k","@from","@to"]) 196 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 197(out, err) = p.communicate() 198# return code will be 1 in either case 199if err.find("Invalid option") >=0: 200return False 201if err.find("disabled") >=0: 202return False 203# assume it failed because @... was invalid changelist 204return True 205 206defsystem(cmd, ignore_error=False): 207 expand =isinstance(cmd,basestring) 208if verbose: 209 sys.stderr.write("executing%s\n"%str(cmd)) 210 retcode = subprocess.call(cmd, shell=expand) 211if retcode and not ignore_error: 212raiseCalledProcessError(retcode, cmd) 213 214return retcode 215 216defp4_system(cmd): 217"""Specifically invoke p4 as the system command. """ 218 real_cmd =p4_build_cmd(cmd) 219 expand =isinstance(real_cmd, basestring) 220 retcode = subprocess.call(real_cmd, shell=expand) 221if retcode: 222raiseCalledProcessError(retcode, real_cmd) 223 224_p4_version_string =None 225defp4_version_string(): 226"""Read the version string, showing just the last line, which 227 hopefully is the interesting version bit. 228 229 $ p4 -V 230 Perforce - The Fast Software Configuration Management System. 231 Copyright 1995-2011 Perforce Software. All rights reserved. 232 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 233 """ 234global _p4_version_string 235if not _p4_version_string: 236 a =p4_read_pipe_lines(["-V"]) 237 _p4_version_string = a[-1].rstrip() 238return _p4_version_string 239 240defp4_integrate(src, dest): 241p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 242 243defp4_sync(f, *options): 244p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 245 246defp4_add(f): 247# forcibly add file names with wildcards 248ifwildcard_present(f): 249p4_system(["add","-f", f]) 250else: 251p4_system(["add", f]) 252 253defp4_delete(f): 254p4_system(["delete",wildcard_encode(f)]) 255 256defp4_edit(f, *options): 257p4_system(["edit"] +list(options) + [wildcard_encode(f)]) 258 259defp4_revert(f): 260p4_system(["revert",wildcard_encode(f)]) 261 262defp4_reopen(type, f): 263p4_system(["reopen","-t",type,wildcard_encode(f)]) 264 265defp4_move(src, dest): 266p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 267 268defp4_last_change(): 269 results =p4CmdList(["changes","-m","1"]) 270returnint(results[0]['change']) 271 272defp4_describe(change): 273"""Make sure it returns a valid result by checking for 274 the presence of field "time". Return a dict of the 275 results.""" 276 277 ds =p4CmdList(["describe","-s",str(change)]) 278iflen(ds) !=1: 279die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 280 281 d = ds[0] 282 283if"p4ExitCode"in d: 284die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 285str(d))) 286if"code"in d: 287if d["code"] =="error": 288die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 289 290if"time"not in d: 291die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 292 293return d 294 295# 296# Canonicalize the p4 type and return a tuple of the 297# base type, plus any modifiers. See "p4 help filetypes" 298# for a list and explanation. 299# 300defsplit_p4_type(p4type): 301 302 p4_filetypes_historical = { 303"ctempobj":"binary+Sw", 304"ctext":"text+C", 305"cxtext":"text+Cx", 306"ktext":"text+k", 307"kxtext":"text+kx", 308"ltext":"text+F", 309"tempobj":"binary+FSw", 310"ubinary":"binary+F", 311"uresource":"resource+F", 312"uxbinary":"binary+Fx", 313"xbinary":"binary+x", 314"xltext":"text+Fx", 315"xtempobj":"binary+Swx", 316"xtext":"text+x", 317"xunicode":"unicode+x", 318"xutf16":"utf16+x", 319} 320if p4type in p4_filetypes_historical: 321 p4type = p4_filetypes_historical[p4type] 322 mods ="" 323 s = p4type.split("+") 324 base = s[0] 325 mods ="" 326iflen(s) >1: 327 mods = s[1] 328return(base, mods) 329 330# 331# return the raw p4 type of a file (text, text+ko, etc) 332# 333defp4_type(f): 334 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 335return results[0]['headType'] 336 337# 338# Given a type base and modifier, return a regexp matching 339# the keywords that can be expanded in the file 340# 341defp4_keywords_regexp_for_type(base, type_mods): 342if base in("text","unicode","binary"): 343 kwords =None 344if"ko"in type_mods: 345 kwords ='Id|Header' 346elif"k"in type_mods: 347 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 348else: 349return None 350 pattern = r""" 351 \$ # Starts with a dollar, followed by... 352 (%s) # one of the keywords, followed by... 353 (:[^$\n]+)? # possibly an old expansion, followed by... 354 \$ # another dollar 355 """% kwords 356return pattern 357else: 358return None 359 360# 361# Given a file, return a regexp matching the possible 362# RCS keywords that will be expanded, or None for files 363# with kw expansion turned off. 364# 365defp4_keywords_regexp_for_file(file): 366if not os.path.exists(file): 367return None 368else: 369(type_base, type_mods) =split_p4_type(p4_type(file)) 370returnp4_keywords_regexp_for_type(type_base, type_mods) 371 372defsetP4ExecBit(file, mode): 373# Reopens an already open file and changes the execute bit to match 374# the execute bit setting in the passed in mode. 375 376 p4Type ="+x" 377 378if notisModeExec(mode): 379 p4Type =getP4OpenedType(file) 380 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 381 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 382if p4Type[-1] =="+": 383 p4Type = p4Type[0:-1] 384 385p4_reopen(p4Type,file) 386 387defgetP4OpenedType(file): 388# Returns the perforce file type for the given file. 389 390 result =p4_read_pipe(["opened",wildcard_encode(file)]) 391 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 392if match: 393return match.group(1) 394else: 395die("Could not determine file type for%s(result: '%s')"% (file, result)) 396 397# Return the set of all p4 labels 398defgetP4Labels(depotPaths): 399 labels =set() 400ifisinstance(depotPaths,basestring): 401 depotPaths = [depotPaths] 402 403for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 404 label = l['label'] 405 labels.add(label) 406 407return labels 408 409# Return the set of all git tags 410defgetGitTags(): 411 gitTags =set() 412for line inread_pipe_lines(["git","tag"]): 413 tag = line.strip() 414 gitTags.add(tag) 415return gitTags 416 417defdiffTreePattern(): 418# This is a simple generator for the diff tree regex pattern. This could be 419# a class variable if this and parseDiffTreeEntry were a part of a class. 420 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 421while True: 422yield pattern 423 424defparseDiffTreeEntry(entry): 425"""Parses a single diff tree entry into its component elements. 426 427 See git-diff-tree(1) manpage for details about the format of the diff 428 output. This method returns a dictionary with the following elements: 429 430 src_mode - The mode of the source file 431 dst_mode - The mode of the destination file 432 src_sha1 - The sha1 for the source file 433 dst_sha1 - The sha1 fr the destination file 434 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 435 status_score - The score for the status (applicable for 'C' and 'R' 436 statuses). This is None if there is no score. 437 src - The path for the source file. 438 dst - The path for the destination file. This is only present for 439 copy or renames. If it is not present, this is None. 440 441 If the pattern is not matched, None is returned.""" 442 443 match =diffTreePattern().next().match(entry) 444if match: 445return{ 446'src_mode': match.group(1), 447'dst_mode': match.group(2), 448'src_sha1': match.group(3), 449'dst_sha1': match.group(4), 450'status': match.group(5), 451'status_score': match.group(6), 452'src': match.group(7), 453'dst': match.group(10) 454} 455return None 456 457defisModeExec(mode): 458# Returns True if the given git mode represents an executable file, 459# otherwise False. 460return mode[-3:] =="755" 461 462defisModeExecChanged(src_mode, dst_mode): 463returnisModeExec(src_mode) !=isModeExec(dst_mode) 464 465defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 466 467ifisinstance(cmd,basestring): 468 cmd ="-G "+ cmd 469 expand =True 470else: 471 cmd = ["-G"] + cmd 472 expand =False 473 474 cmd =p4_build_cmd(cmd) 475if verbose: 476 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 477 478# Use a temporary file to avoid deadlocks without 479# subprocess.communicate(), which would put another copy 480# of stdout into memory. 481 stdin_file =None 482if stdin is not None: 483 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 484ifisinstance(stdin,basestring): 485 stdin_file.write(stdin) 486else: 487for i in stdin: 488 stdin_file.write(i +'\n') 489 stdin_file.flush() 490 stdin_file.seek(0) 491 492 p4 = subprocess.Popen(cmd, 493 shell=expand, 494 stdin=stdin_file, 495 stdout=subprocess.PIPE) 496 497 result = [] 498try: 499while True: 500 entry = marshal.load(p4.stdout) 501if cb is not None: 502cb(entry) 503else: 504 result.append(entry) 505exceptEOFError: 506pass 507 exitCode = p4.wait() 508if exitCode !=0: 509 entry = {} 510 entry["p4ExitCode"] = exitCode 511 result.append(entry) 512 513return result 514 515defp4Cmd(cmd): 516list=p4CmdList(cmd) 517 result = {} 518for entry inlist: 519 result.update(entry) 520return result; 521 522defp4Where(depotPath): 523if not depotPath.endswith("/"): 524 depotPath +="/" 525 depotPathLong = depotPath +"..." 526 outputList =p4CmdList(["where", depotPathLong]) 527 output =None 528for entry in outputList: 529if"depotFile"in entry: 530# Search for the base client side depot path, as long as it starts with the branch's P4 path. 531# The base path always ends with "/...". 532if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 533 output = entry 534break 535elif"data"in entry: 536 data = entry.get("data") 537 space = data.find(" ") 538if data[:space] == depotPath: 539 output = entry 540break 541if output ==None: 542return"" 543if output["code"] =="error": 544return"" 545 clientPath ="" 546if"path"in output: 547 clientPath = output.get("path") 548elif"data"in output: 549 data = output.get("data") 550 lastSpace = data.rfind(" ") 551 clientPath = data[lastSpace +1:] 552 553if clientPath.endswith("..."): 554 clientPath = clientPath[:-3] 555return clientPath 556 557defcurrentGitBranch(): 558 retcode =system(["git","symbolic-ref","-q","HEAD"], ignore_error=True) 559if retcode !=0: 560# on a detached head 561return None 562else: 563returnread_pipe(["git","name-rev","HEAD"]).split(" ")[1].strip() 564 565defisValidGitDir(path): 566if(os.path.exists(path +"/HEAD") 567and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 568return True; 569return False 570 571defparseRevision(ref): 572returnread_pipe("git rev-parse%s"% ref).strip() 573 574defbranchExists(ref): 575 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 576 ignore_error=True) 577returnlen(rev) >0 578 579defextractLogMessageFromGitCommit(commit): 580 logMessage ="" 581 582## fixme: title is first line of commit, not 1st paragraph. 583 foundTitle =False 584for log inread_pipe_lines("git cat-file commit%s"% commit): 585if not foundTitle: 586iflen(log) ==1: 587 foundTitle =True 588continue 589 590 logMessage += log 591return logMessage 592 593defextractSettingsGitLog(log): 594 values = {} 595for line in log.split("\n"): 596 line = line.strip() 597 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 598if not m: 599continue 600 601 assignments = m.group(1).split(':') 602for a in assignments: 603 vals = a.split('=') 604 key = vals[0].strip() 605 val = ('='.join(vals[1:])).strip() 606if val.endswith('\"')and val.startswith('"'): 607 val = val[1:-1] 608 609 values[key] = val 610 611 paths = values.get("depot-paths") 612if not paths: 613 paths = values.get("depot-path") 614if paths: 615 values['depot-paths'] = paths.split(',') 616return values 617 618defgitBranchExists(branch): 619 proc = subprocess.Popen(["git","rev-parse", branch], 620 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 621return proc.wait() ==0; 622 623_gitConfig = {} 624 625defgitConfig(key, typeSpecifier=None): 626if not _gitConfig.has_key(key): 627 cmd = ["git","config"] 628if typeSpecifier: 629 cmd += [ typeSpecifier ] 630 cmd += [ key ] 631 s =read_pipe(cmd, ignore_error=True) 632 _gitConfig[key] = s.strip() 633return _gitConfig[key] 634 635defgitConfigBool(key): 636"""Return a bool, using git config --bool. It is True only if the 637 variable is set to true, and False if set to false or not present 638 in the config.""" 639 640if not _gitConfig.has_key(key): 641 _gitConfig[key] =gitConfig(key,'--bool') =="true" 642return _gitConfig[key] 643 644defgitConfigInt(key): 645if not _gitConfig.has_key(key): 646 cmd = ["git","config","--int", key ] 647 s =read_pipe(cmd, ignore_error=True) 648 v = s.strip() 649try: 650 _gitConfig[key] =int(gitConfig(key,'--int')) 651exceptValueError: 652 _gitConfig[key] =None 653return _gitConfig[key] 654 655defgitConfigList(key): 656if not _gitConfig.has_key(key): 657 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 658 _gitConfig[key] = s.strip().split(os.linesep) 659if _gitConfig[key] == ['']: 660 _gitConfig[key] = [] 661return _gitConfig[key] 662 663defp4BranchesInGit(branchesAreInRemotes=True): 664"""Find all the branches whose names start with "p4/", looking 665 in remotes or heads as specified by the argument. Return 666 a dictionary of{ branch: revision }for each one found. 667 The branch names are the short names, without any 668 "p4/" prefix.""" 669 670 branches = {} 671 672 cmdline ="git rev-parse --symbolic " 673if branchesAreInRemotes: 674 cmdline +="--remotes" 675else: 676 cmdline +="--branches" 677 678for line inread_pipe_lines(cmdline): 679 line = line.strip() 680 681# only import to p4/ 682if not line.startswith('p4/'): 683continue 684# special symbolic ref to p4/master 685if line =="p4/HEAD": 686continue 687 688# strip off p4/ prefix 689 branch = line[len("p4/"):] 690 691 branches[branch] =parseRevision(line) 692 693return branches 694 695defbranch_exists(branch): 696"""Make sure that the given ref name really exists.""" 697 698 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 699 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 700 out, _ = p.communicate() 701if p.returncode: 702return False 703# expect exactly one line of output: the branch name 704return out.rstrip() == branch 705 706deffindUpstreamBranchPoint(head ="HEAD"): 707 branches =p4BranchesInGit() 708# map from depot-path to branch name 709 branchByDepotPath = {} 710for branch in branches.keys(): 711 tip = branches[branch] 712 log =extractLogMessageFromGitCommit(tip) 713 settings =extractSettingsGitLog(log) 714if settings.has_key("depot-paths"): 715 paths =",".join(settings["depot-paths"]) 716 branchByDepotPath[paths] ="remotes/p4/"+ branch 717 718 settings =None 719 parent =0 720while parent <65535: 721 commit = head +"~%s"% parent 722 log =extractLogMessageFromGitCommit(commit) 723 settings =extractSettingsGitLog(log) 724if settings.has_key("depot-paths"): 725 paths =",".join(settings["depot-paths"]) 726if branchByDepotPath.has_key(paths): 727return[branchByDepotPath[paths], settings] 728 729 parent = parent +1 730 731return["", settings] 732 733defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 734if not silent: 735print("Creating/updating branch(es) in%sbased on origin branch(es)" 736% localRefPrefix) 737 738 originPrefix ="origin/p4/" 739 740for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 741 line = line.strip() 742if(not line.startswith(originPrefix))or line.endswith("HEAD"): 743continue 744 745 headName = line[len(originPrefix):] 746 remoteHead = localRefPrefix + headName 747 originHead = line 748 749 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 750if(not original.has_key('depot-paths') 751or not original.has_key('change')): 752continue 753 754 update =False 755if notgitBranchExists(remoteHead): 756if verbose: 757print"creating%s"% remoteHead 758 update =True 759else: 760 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 761if settings.has_key('change') >0: 762if settings['depot-paths'] == original['depot-paths']: 763 originP4Change =int(original['change']) 764 p4Change =int(settings['change']) 765if originP4Change > p4Change: 766print("%s(%s) is newer than%s(%s). " 767"Updating p4 branch from origin." 768% (originHead, originP4Change, 769 remoteHead, p4Change)) 770 update =True 771else: 772print("Ignoring:%swas imported from%swhile " 773"%swas imported from%s" 774% (originHead,','.join(original['depot-paths']), 775 remoteHead,','.join(settings['depot-paths']))) 776 777if update: 778system("git update-ref%s %s"% (remoteHead, originHead)) 779 780deforiginP4BranchesExist(): 781returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 782 783 784defp4ParseNumericChangeRange(parts): 785 changeStart =int(parts[0][1:]) 786if parts[1] =='#head': 787 changeEnd =p4_last_change() 788else: 789 changeEnd =int(parts[1]) 790 791return(changeStart, changeEnd) 792 793defchooseBlockSize(blockSize): 794if blockSize: 795return blockSize 796else: 797return defaultBlockSize 798 799defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 800assert depotPaths 801 802# Parse the change range into start and end. Try to find integer 803# revision ranges as these can be broken up into blocks to avoid 804# hitting server-side limits (maxrows, maxscanresults). But if 805# that doesn't work, fall back to using the raw revision specifier 806# strings, without using block mode. 807 808if changeRange is None or changeRange =='': 809 changeStart =1 810 changeEnd =p4_last_change() 811 block_size =chooseBlockSize(requestedBlockSize) 812else: 813 parts = changeRange.split(',') 814assertlen(parts) ==2 815try: 816(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 817 block_size =chooseBlockSize(requestedBlockSize) 818except: 819 changeStart = parts[0][1:] 820 changeEnd = parts[1] 821if requestedBlockSize: 822die("cannot use --changes-block-size with non-numeric revisions") 823 block_size =None 824 825 changes = [] 826 827# Retrieve changes a block at a time, to prevent running 828# into a MaxResults/MaxScanRows error from the server. 829 830while True: 831 cmd = ['changes'] 832 833if block_size: 834 end =min(changeEnd, changeStart + block_size) 835 revisionRange ="%d,%d"% (changeStart, end) 836else: 837 revisionRange ="%s,%s"% (changeStart, changeEnd) 838 839for p in depotPaths: 840 cmd += ["%s...@%s"% (p, revisionRange)] 841 842# Insert changes in chronological order 843for line inreversed(p4_read_pipe_lines(cmd)): 844 changes.append(int(line.split(" ")[1])) 845 846if not block_size: 847break 848 849if end >= changeEnd: 850break 851 852 changeStart = end +1 853 854 changes =sorted(changes) 855return changes 856 857defp4PathStartsWith(path, prefix): 858# This method tries to remedy a potential mixed-case issue: 859# 860# If UserA adds //depot/DirA/file1 861# and UserB adds //depot/dira/file2 862# 863# we may or may not have a problem. If you have core.ignorecase=true, 864# we treat DirA and dira as the same directory 865ifgitConfigBool("core.ignorecase"): 866return path.lower().startswith(prefix.lower()) 867return path.startswith(prefix) 868 869defgetClientSpec(): 870"""Look at the p4 client spec, create a View() object that contains 871 all the mappings, and return it.""" 872 873 specList =p4CmdList("client -o") 874iflen(specList) !=1: 875die('Output from "client -o" is%dlines, expecting 1'% 876len(specList)) 877 878# dictionary of all client parameters 879 entry = specList[0] 880 881# the //client/ name 882 client_name = entry["Client"] 883 884# just the keys that start with "View" 885 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 886 887# hold this new View 888 view =View(client_name) 889 890# append the lines, in order, to the view 891for view_num inrange(len(view_keys)): 892 k ="View%d"% view_num 893if k not in view_keys: 894die("Expected view key%smissing"% k) 895 view.append(entry[k]) 896 897return view 898 899defgetClientRoot(): 900"""Grab the client directory.""" 901 902 output =p4CmdList("client -o") 903iflen(output) !=1: 904die('Output from "client -o" is%dlines, expecting 1'%len(output)) 905 906 entry = output[0] 907if"Root"not in entry: 908die('Client has no "Root"') 909 910return entry["Root"] 911 912# 913# P4 wildcards are not allowed in filenames. P4 complains 914# if you simply add them, but you can force it with "-f", in 915# which case it translates them into %xx encoding internally. 916# 917defwildcard_decode(path): 918# Search for and fix just these four characters. Do % last so 919# that fixing it does not inadvertently create new %-escapes. 920# Cannot have * in a filename in windows; untested as to 921# what p4 would do in such a case. 922if not platform.system() =="Windows": 923 path = path.replace("%2A","*") 924 path = path.replace("%23","#") \ 925.replace("%40","@") \ 926.replace("%25","%") 927return path 928 929defwildcard_encode(path): 930# do % first to avoid double-encoding the %s introduced here 931 path = path.replace("%","%25") \ 932.replace("*","%2A") \ 933.replace("#","%23") \ 934.replace("@","%40") 935return path 936 937defwildcard_present(path): 938 m = re.search("[*#@%]", path) 939return m is not None 940 941classLargeFileSystem(object): 942"""Base class for large file system support.""" 943 944def__init__(self, writeToGitStream): 945 self.largeFiles =set() 946 self.writeToGitStream = writeToGitStream 947 948defgeneratePointer(self, cloneDestination, contentFile): 949"""Return the content of a pointer file that is stored in Git instead of 950 the actual content.""" 951assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 952 953defpushFile(self, localLargeFile): 954"""Push the actual content which is not stored in the Git repository to 955 a server.""" 956assert False,"Method 'pushFile' required in "+ self.__class__.__name__ 957 958defhasLargeFileExtension(self, relPath): 959returnreduce( 960lambda a, b: a or b, 961[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')], 962False 963) 964 965defgenerateTempFile(self, contents): 966 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 967for d in contents: 968 contentFile.write(d) 969 contentFile.close() 970return contentFile.name 971 972defexceedsLargeFileThreshold(self, relPath, contents): 973ifgitConfigInt('git-p4.largeFileThreshold'): 974 contentsSize =sum(len(d)for d in contents) 975if contentsSize >gitConfigInt('git-p4.largeFileThreshold'): 976return True 977ifgitConfigInt('git-p4.largeFileCompressedThreshold'): 978 contentsSize =sum(len(d)for d in contents) 979if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'): 980return False 981 contentTempFile = self.generateTempFile(contents) 982 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 983 zf = zipfile.ZipFile(compressedContentFile.name, mode='w') 984 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) 985 zf.close() 986 compressedContentsSize = zf.infolist()[0].compress_size 987 os.remove(contentTempFile) 988 os.remove(compressedContentFile.name) 989if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'): 990return True 991return False 992 993defaddLargeFile(self, relPath): 994 self.largeFiles.add(relPath) 995 996defremoveLargeFile(self, relPath): 997 self.largeFiles.remove(relPath) 998 999defisLargeFile(self, relPath):1000return relPath in self.largeFiles10011002defprocessContent(self, git_mode, relPath, contents):1003"""Processes the content of git fast import. This method decides if a1004 file is stored in the large file system and handles all necessary1005 steps."""1006if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1007 contentTempFile = self.generateTempFile(contents)1008(git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)10091010# Move temp file to final location in large file system1011 largeFileDir = os.path.dirname(localLargeFile)1012if not os.path.isdir(largeFileDir):1013 os.makedirs(largeFileDir)1014 shutil.move(contentTempFile, localLargeFile)1015 self.addLargeFile(relPath)1016ifgitConfigBool('git-p4.largeFilePush'):1017 self.pushFile(localLargeFile)1018if verbose:1019 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1020return(git_mode, contents)10211022classMockLFS(LargeFileSystem):1023"""Mock large file system for testing."""10241025defgeneratePointer(self, contentFile):1026"""The pointer content is the original content prefixed with "pointer-".1027 The local filename of the large file storage is derived from the file content.1028 """1029withopen(contentFile,'r')as f:1030 content =next(f)1031 gitMode ='100644'1032 pointerContents ='pointer-'+ content1033 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1034return(gitMode, pointerContents, localLargeFile)10351036defpushFile(self, localLargeFile):1037"""The remote filename of the large file storage is the same as the local1038 one but in a different directory.1039 """1040 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1041if not os.path.exists(remotePath):1042 os.makedirs(remotePath)1043 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10441045classGitLFS(LargeFileSystem):1046"""Git LFS as backend for the git-p4 large file system.1047 See https://git-lfs.github.com/ for details."""10481049def__init__(self, *args):1050 LargeFileSystem.__init__(self, *args)1051 self.baseGitAttributes = []10521053defgeneratePointer(self, contentFile):1054"""Generate a Git LFS pointer for the content. Return LFS Pointer file1055 mode and content which is stored in the Git repository instead of1056 the actual content. Return also the new location of the actual1057 content.1058 """1059 pointerProcess = subprocess.Popen(1060['git','lfs','pointer','--file='+ contentFile],1061 stdout=subprocess.PIPE1062)1063 pointerFile = pointerProcess.stdout.read()1064if pointerProcess.wait():1065 os.remove(contentFile)1066die('git-lfs pointer command failed. Did you install the extension?')10671068# Git LFS removed the preamble in the output of the 'pointer' command1069# starting from version 1.2.0. Check for the preamble here to support1070# earlier versions.1071# c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b431072if pointerFile.startswith('Git LFS pointer for'):1073 pointerFile = re.sub(r'Git LFS pointer for.*\n\n','', pointerFile)10741075 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)1076 localLargeFile = os.path.join(1077 os.getcwd(),1078'.git','lfs','objects', oid[:2], oid[2:4],1079 oid,1080)1081# LFS Spec states that pointer files should not have the executable bit set.1082 gitMode ='100644'1083return(gitMode, pointerFile, localLargeFile)10841085defpushFile(self, localLargeFile):1086 uploadProcess = subprocess.Popen(1087['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1088)1089if uploadProcess.wait():1090die('git-lfs push command failed. Did you define a remote?')10911092defgenerateGitAttributes(self):1093return(1094 self.baseGitAttributes +1095[1096'\n',1097'#\n',1098'# Git LFS (see https://git-lfs.github.com/)\n',1099'#\n',1100] +1101['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1102for f insorted(gitConfigList('git-p4.largeFileExtensions'))1103] +1104['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1105for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1106]1107)11081109defaddLargeFile(self, relPath):1110 LargeFileSystem.addLargeFile(self, relPath)1111 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11121113defremoveLargeFile(self, relPath):1114 LargeFileSystem.removeLargeFile(self, relPath)1115 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11161117defprocessContent(self, git_mode, relPath, contents):1118if relPath =='.gitattributes':1119 self.baseGitAttributes = contents1120return(git_mode, self.generateGitAttributes())1121else:1122return LargeFileSystem.processContent(self, git_mode, relPath, contents)11231124class Command:1125def__init__(self):1126 self.usage ="usage: %prog [options]"1127 self.needsGit =True1128 self.verbose =False11291130class P4UserMap:1131def__init__(self):1132 self.userMapFromPerforceServer =False1133 self.myP4UserId =None11341135defp4UserId(self):1136if self.myP4UserId:1137return self.myP4UserId11381139 results =p4CmdList("user -o")1140for r in results:1141if r.has_key('User'):1142 self.myP4UserId = r['User']1143return r['User']1144die("Could not find your p4 user id")11451146defp4UserIsMe(self, p4User):1147# return True if the given p4 user is actually me1148 me = self.p4UserId()1149if not p4User or p4User != me:1150return False1151else:1152return True11531154defgetUserCacheFilename(self):1155 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1156return home +"/.gitp4-usercache.txt"11571158defgetUserMapFromPerforceServer(self):1159if self.userMapFromPerforceServer:1160return1161 self.users = {}1162 self.emails = {}11631164for output inp4CmdList("users"):1165if not output.has_key("User"):1166continue1167 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1168 self.emails[output["Email"]] = output["User"]11691170 mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)1171for mapUserConfig ingitConfigList("git-p4.mapUser"):1172 mapUser = mapUserConfigRegex.findall(mapUserConfig)1173if mapUser andlen(mapUser[0]) ==3:1174 user = mapUser[0][0]1175 fullname = mapUser[0][1]1176 email = mapUser[0][2]1177 self.users[user] = fullname +" <"+ email +">"1178 self.emails[email] = user11791180 s =''1181for(key, val)in self.users.items():1182 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11831184open(self.getUserCacheFilename(),"wb").write(s)1185 self.userMapFromPerforceServer =True11861187defloadUserMapFromCache(self):1188 self.users = {}1189 self.userMapFromPerforceServer =False1190try:1191 cache =open(self.getUserCacheFilename(),"rb")1192 lines = cache.readlines()1193 cache.close()1194for line in lines:1195 entry = line.strip().split("\t")1196 self.users[entry[0]] = entry[1]1197exceptIOError:1198 self.getUserMapFromPerforceServer()11991200classP4Debug(Command):1201def__init__(self):1202 Command.__init__(self)1203 self.options = []1204 self.description ="A tool to debug the output of p4 -G."1205 self.needsGit =False12061207defrun(self, args):1208 j =01209for output inp4CmdList(args):1210print'Element:%d'% j1211 j +=11212print output1213return True12141215classP4RollBack(Command):1216def__init__(self):1217 Command.__init__(self)1218 self.options = [1219 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1220]1221 self.description ="A tool to debug the multi-branch import. Don't use :)"1222 self.rollbackLocalBranches =False12231224defrun(self, args):1225iflen(args) !=1:1226return False1227 maxChange =int(args[0])12281229if"p4ExitCode"inp4Cmd("changes -m 1"):1230die("Problems executing p4");12311232if self.rollbackLocalBranches:1233 refPrefix ="refs/heads/"1234 lines =read_pipe_lines("git rev-parse --symbolic --branches")1235else:1236 refPrefix ="refs/remotes/"1237 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12381239for line in lines:1240if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1241 line = line.strip()1242 ref = refPrefix + line1243 log =extractLogMessageFromGitCommit(ref)1244 settings =extractSettingsGitLog(log)12451246 depotPaths = settings['depot-paths']1247 change = settings['change']12481249 changed =False12501251iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1252for p in depotPaths]))) ==0:1253print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1254system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1255continue12561257while change andint(change) > maxChange:1258 changed =True1259if self.verbose:1260print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1261system("git update-ref%s\"%s^\""% (ref, ref))1262 log =extractLogMessageFromGitCommit(ref)1263 settings =extractSettingsGitLog(log)126412651266 depotPaths = settings['depot-paths']1267 change = settings['change']12681269if changed:1270print"%srewound to%s"% (ref, change)12711272return True12731274classP4Submit(Command, P4UserMap):12751276 conflict_behavior_choices = ("ask","skip","quit")12771278def__init__(self):1279 Command.__init__(self)1280 P4UserMap.__init__(self)1281 self.options = [1282 optparse.make_option("--origin", dest="origin"),1283 optparse.make_option("-M", dest="detectRenames", action="store_true"),1284# preserve the user, requires relevant p4 permissions1285 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1286 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1287 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1288 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1289 optparse.make_option("--conflict", dest="conflict_behavior",1290 choices=self.conflict_behavior_choices),1291 optparse.make_option("--branch", dest="branch"),1292]1293 self.description ="Submit changes from git to the perforce depot."1294 self.usage +=" [name of git branch to submit into perforce depot]"1295 self.origin =""1296 self.detectRenames =False1297 self.preserveUser =gitConfigBool("git-p4.preserveUser")1298 self.dry_run =False1299 self.prepare_p4_only =False1300 self.conflict_behavior =None1301 self.isWindows = (platform.system() =="Windows")1302 self.exportLabels =False1303 self.p4HasMoveCommand =p4_has_move_command()1304 self.branch =None13051306ifgitConfig('git-p4.largeFileSystem'):1307die("Large file system not supported for git-p4 submit command. Please remove it from config.")13081309defcheck(self):1310iflen(p4CmdList("opened ...")) >0:1311die("You have files opened with perforce! Close them before starting the sync.")13121313defseparate_jobs_from_description(self, message):1314"""Extract and return a possible Jobs field in the commit1315 message. It goes into a separate section in the p4 change1316 specification.13171318 A jobs line starts with "Jobs:" and looks like a new field1319 in a form. Values are white-space separated on the same1320 line or on following lines that start with a tab.13211322 This does not parse and extract the full git commit message1323 like a p4 form. It just sees the Jobs: line as a marker1324 to pass everything from then on directly into the p4 form,1325 but outside the description section.13261327 Return a tuple (stripped log message, jobs string)."""13281329 m = re.search(r'^Jobs:', message, re.MULTILINE)1330if m is None:1331return(message,None)13321333 jobtext = message[m.start():]1334 stripped_message = message[:m.start()].rstrip()1335return(stripped_message, jobtext)13361337defprepareLogMessage(self, template, message, jobs):1338"""Edits the template returned from "p4 change -o" to insert1339 the message in the Description field, and the jobs text in1340 the Jobs field."""1341 result =""13421343 inDescriptionSection =False13441345for line in template.split("\n"):1346if line.startswith("#"):1347 result += line +"\n"1348continue13491350if inDescriptionSection:1351if line.startswith("Files:")or line.startswith("Jobs:"):1352 inDescriptionSection =False1353# insert Jobs section1354if jobs:1355 result += jobs +"\n"1356else:1357continue1358else:1359if line.startswith("Description:"):1360 inDescriptionSection =True1361 line +="\n"1362for messageLine in message.split("\n"):1363 line +="\t"+ messageLine +"\n"13641365 result += line +"\n"13661367return result13681369defpatchRCSKeywords(self,file, pattern):1370# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1371(handle, outFileName) = tempfile.mkstemp(dir='.')1372try:1373 outFile = os.fdopen(handle,"w+")1374 inFile =open(file,"r")1375 regexp = re.compile(pattern, re.VERBOSE)1376for line in inFile.readlines():1377 line = regexp.sub(r'$\1$', line)1378 outFile.write(line)1379 inFile.close()1380 outFile.close()1381# Forcibly overwrite the original file1382 os.unlink(file)1383 shutil.move(outFileName,file)1384except:1385# cleanup our temporary file1386 os.unlink(outFileName)1387print"Failed to strip RCS keywords in%s"%file1388raise13891390print"Patched up RCS keywords in%s"%file13911392defp4UserForCommit(self,id):1393# Return the tuple (perforce user,git email) for a given git commit id1394 self.getUserMapFromPerforceServer()1395 gitEmail =read_pipe(["git","log","--max-count=1",1396"--format=%ae",id])1397 gitEmail = gitEmail.strip()1398if not self.emails.has_key(gitEmail):1399return(None,gitEmail)1400else:1401return(self.emails[gitEmail],gitEmail)14021403defcheckValidP4Users(self,commits):1404# check if any git authors cannot be mapped to p4 users1405foridin commits:1406(user,email) = self.p4UserForCommit(id)1407if not user:1408 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1409ifgitConfigBool("git-p4.allowMissingP4Users"):1410print"%s"% msg1411else:1412die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)14131414deflastP4Changelist(self):1415# Get back the last changelist number submitted in this client spec. This1416# then gets used to patch up the username in the change. If the same1417# client spec is being used by multiple processes then this might go1418# wrong.1419 results =p4CmdList("client -o")# find the current client1420 client =None1421for r in results:1422if r.has_key('Client'):1423 client = r['Client']1424break1425if not client:1426die("could not get client spec")1427 results =p4CmdList(["changes","-c", client,"-m","1"])1428for r in results:1429if r.has_key('change'):1430return r['change']1431die("Could not get changelist number for last submit - cannot patch up user details")14321433defmodifyChangelistUser(self, changelist, newUser):1434# fixup the user field of a changelist after it has been submitted.1435 changes =p4CmdList("change -o%s"% changelist)1436iflen(changes) !=1:1437die("Bad output from p4 change modifying%sto user%s"%1438(changelist, newUser))14391440 c = changes[0]1441if c['User'] == newUser:return# nothing to do1442 c['User'] = newUser1443input= marshal.dumps(c)14441445 result =p4CmdList("change -f -i", stdin=input)1446for r in result:1447if r.has_key('code'):1448if r['code'] =='error':1449die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1450if r.has_key('data'):1451print("Updated user field for changelist%sto%s"% (changelist, newUser))1452return1453die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14541455defcanChangeChangelists(self):1456# check to see if we have p4 admin or super-user permissions, either of1457# which are required to modify changelists.1458 results =p4CmdList(["protects", self.depotPath])1459for r in results:1460if r.has_key('perm'):1461if r['perm'] =='admin':1462return11463if r['perm'] =='super':1464return11465return014661467defprepareSubmitTemplate(self):1468"""Run "p4 change -o" to grab a change specification template.1469 This does not use "p4 -G", as it is nice to keep the submission1470 template in original order, since a human might edit it.14711472 Remove lines in the Files section that show changes to files1473 outside the depot path we're committing into."""14741475[upstream, settings] =findUpstreamBranchPoint()14761477 template =""1478 inFilesSection =False1479for line inp4_read_pipe_lines(['change','-o']):1480if line.endswith("\r\n"):1481 line = line[:-2] +"\n"1482if inFilesSection:1483if line.startswith("\t"):1484# path starts and ends with a tab1485 path = line[1:]1486 lastTab = path.rfind("\t")1487if lastTab != -1:1488 path = path[:lastTab]1489if settings.has_key('depot-paths'):1490if not[p for p in settings['depot-paths']1491ifp4PathStartsWith(path, p)]:1492continue1493else:1494if notp4PathStartsWith(path, self.depotPath):1495continue1496else:1497 inFilesSection =False1498else:1499if line.startswith("Files:"):1500 inFilesSection =True15011502 template += line15031504return template15051506defedit_template(self, template_file):1507"""Invoke the editor to let the user change the submission1508 message. Return true if okay to continue with the submit."""15091510# if configured to skip the editing part, just submit1511ifgitConfigBool("git-p4.skipSubmitEdit"):1512return True15131514# look at the modification time, to check later if the user saved1515# the file1516 mtime = os.stat(template_file).st_mtime15171518# invoke the editor1519if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1520 editor = os.environ.get("P4EDITOR")1521else:1522 editor =read_pipe("git var GIT_EDITOR").strip()1523system(["sh","-c", ('%s"$@"'% editor), editor, template_file])15241525# If the file was not saved, prompt to see if this patch should1526# be skipped. But skip this verification step if configured so.1527ifgitConfigBool("git-p4.skipSubmitEditCheck"):1528return True15291530# modification time updated means user saved the file1531if os.stat(template_file).st_mtime > mtime:1532return True15331534while True:1535 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1536if response =='y':1537return True1538if response =='n':1539return False15401541defget_diff_description(self, editedFiles, filesToAdd):1542# diff1543if os.environ.has_key("P4DIFF"):1544del(os.environ["P4DIFF"])1545 diff =""1546for editedFile in editedFiles:1547 diff +=p4_read_pipe(['diff','-du',1548wildcard_encode(editedFile)])15491550# new file diff1551 newdiff =""1552for newFile in filesToAdd:1553 newdiff +="==== new file ====\n"1554 newdiff +="--- /dev/null\n"1555 newdiff +="+++%s\n"% newFile1556 f =open(newFile,"r")1557for line in f.readlines():1558 newdiff +="+"+ line1559 f.close()15601561return(diff + newdiff).replace('\r\n','\n')15621563defapplyCommit(self,id):1564"""Apply one commit, return True if it succeeded."""15651566print"Applying",read_pipe(["git","show","-s",1567"--format=format:%h%s",id])15681569(p4User, gitEmail) = self.p4UserForCommit(id)15701571 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1572 filesToAdd =set()1573 filesToChangeType =set()1574 filesToDelete =set()1575 editedFiles =set()1576 pureRenameCopy =set()1577 filesToChangeExecBit = {}15781579for line in diff:1580 diff =parseDiffTreeEntry(line)1581 modifier = diff['status']1582 path = diff['src']1583if modifier =="M":1584p4_edit(path)1585ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1586 filesToChangeExecBit[path] = diff['dst_mode']1587 editedFiles.add(path)1588elif modifier =="A":1589 filesToAdd.add(path)1590 filesToChangeExecBit[path] = diff['dst_mode']1591if path in filesToDelete:1592 filesToDelete.remove(path)1593elif modifier =="D":1594 filesToDelete.add(path)1595if path in filesToAdd:1596 filesToAdd.remove(path)1597elif modifier =="C":1598 src, dest = diff['src'], diff['dst']1599p4_integrate(src, dest)1600 pureRenameCopy.add(dest)1601if diff['src_sha1'] != diff['dst_sha1']:1602p4_edit(dest)1603 pureRenameCopy.discard(dest)1604ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1605p4_edit(dest)1606 pureRenameCopy.discard(dest)1607 filesToChangeExecBit[dest] = diff['dst_mode']1608if self.isWindows:1609# turn off read-only attribute1610 os.chmod(dest, stat.S_IWRITE)1611 os.unlink(dest)1612 editedFiles.add(dest)1613elif modifier =="R":1614 src, dest = diff['src'], diff['dst']1615if self.p4HasMoveCommand:1616p4_edit(src)# src must be open before move1617p4_move(src, dest)# opens for (move/delete, move/add)1618else:1619p4_integrate(src, dest)1620if diff['src_sha1'] != diff['dst_sha1']:1621p4_edit(dest)1622else:1623 pureRenameCopy.add(dest)1624ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1625if not self.p4HasMoveCommand:1626p4_edit(dest)# with move: already open, writable1627 filesToChangeExecBit[dest] = diff['dst_mode']1628if not self.p4HasMoveCommand:1629if self.isWindows:1630 os.chmod(dest, stat.S_IWRITE)1631 os.unlink(dest)1632 filesToDelete.add(src)1633 editedFiles.add(dest)1634elif modifier =="T":1635 filesToChangeType.add(path)1636else:1637die("unknown modifier%sfor%s"% (modifier, path))16381639 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1640 patchcmd = diffcmd +" | git apply "1641 tryPatchCmd = patchcmd +"--check -"1642 applyPatchCmd = patchcmd +"--check --apply -"1643 patch_succeeded =True16441645if os.system(tryPatchCmd) !=0:1646 fixed_rcs_keywords =False1647 patch_succeeded =False1648print"Unfortunately applying the change failed!"16491650# Patch failed, maybe it's just RCS keyword woes. Look through1651# the patch to see if that's possible.1652ifgitConfigBool("git-p4.attemptRCSCleanup"):1653file=None1654 pattern =None1655 kwfiles = {}1656forfilein editedFiles | filesToDelete:1657# did this file's delta contain RCS keywords?1658 pattern =p4_keywords_regexp_for_file(file)16591660if pattern:1661# this file is a possibility...look for RCS keywords.1662 regexp = re.compile(pattern, re.VERBOSE)1663for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1664if regexp.search(line):1665if verbose:1666print"got keyword match on%sin%sin%s"% (pattern, line,file)1667 kwfiles[file] = pattern1668break16691670forfilein kwfiles:1671if verbose:1672print"zapping%swith%s"% (line,pattern)1673# File is being deleted, so not open in p4. Must1674# disable the read-only bit on windows.1675if self.isWindows andfilenot in editedFiles:1676 os.chmod(file, stat.S_IWRITE)1677 self.patchRCSKeywords(file, kwfiles[file])1678 fixed_rcs_keywords =True16791680if fixed_rcs_keywords:1681print"Retrying the patch with RCS keywords cleaned up"1682if os.system(tryPatchCmd) ==0:1683 patch_succeeded =True16841685if not patch_succeeded:1686for f in editedFiles:1687p4_revert(f)1688return False16891690#1691# Apply the patch for real, and do add/delete/+x handling.1692#1693system(applyPatchCmd)16941695for f in filesToChangeType:1696p4_edit(f,"-t","auto")1697for f in filesToAdd:1698p4_add(f)1699for f in filesToDelete:1700p4_revert(f)1701p4_delete(f)17021703# Set/clear executable bits1704for f in filesToChangeExecBit.keys():1705 mode = filesToChangeExecBit[f]1706setP4ExecBit(f, mode)17071708#1709# Build p4 change description, starting with the contents1710# of the git commit message.1711#1712 logMessage =extractLogMessageFromGitCommit(id)1713 logMessage = logMessage.strip()1714(logMessage, jobs) = self.separate_jobs_from_description(logMessage)17151716 template = self.prepareSubmitTemplate()1717 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)17181719if self.preserveUser:1720 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User17211722if self.checkAuthorship and not self.p4UserIsMe(p4User):1723 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1724 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1725 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"17261727 separatorLine ="######## everything below this line is just the diff #######\n"1728if not self.prepare_p4_only:1729 submitTemplate += separatorLine1730 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)17311732(handle, fileName) = tempfile.mkstemp()1733 tmpFile = os.fdopen(handle,"w+b")1734if self.isWindows:1735 submitTemplate = submitTemplate.replace("\n","\r\n")1736 tmpFile.write(submitTemplate)1737 tmpFile.close()17381739if self.prepare_p4_only:1740#1741# Leave the p4 tree prepared, and the submit template around1742# and let the user decide what to do next1743#1744print1745print"P4 workspace prepared for submission."1746print"To submit or revert, go to client workspace"1747print" "+ self.clientPath1748print1749print"To submit, use\"p4 submit\"to write a new description,"1750print"or\"p4 submit -i <%s\"to use the one prepared by" \1751"\"git p4\"."% fileName1752print"You can delete the file\"%s\"when finished."% fileName17531754if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1755print"To preserve change ownership by user%s, you must\n" \1756"do\"p4 change -f <change>\"after submitting and\n" \1757"edit the User field."1758if pureRenameCopy:1759print"After submitting, renamed files must be re-synced."1760print"Invoke\"p4 sync -f\"on each of these files:"1761for f in pureRenameCopy:1762print" "+ f17631764print1765print"To revert the changes, use\"p4 revert ...\", and delete"1766print"the submit template file\"%s\""% fileName1767if filesToAdd:1768print"Since the commit adds new files, they must be deleted:"1769for f in filesToAdd:1770print" "+ f1771print1772return True17731774#1775# Let the user edit the change description, then submit it.1776#1777 submitted =False17781779try:1780if self.edit_template(fileName):1781# read the edited message and submit1782 tmpFile =open(fileName,"rb")1783 message = tmpFile.read()1784 tmpFile.close()1785if self.isWindows:1786 message = message.replace("\r\n","\n")1787 submitTemplate = message[:message.index(separatorLine)]1788p4_write_pipe(['submit','-i'], submitTemplate)17891790if self.preserveUser:1791if p4User:1792# Get last changelist number. Cannot easily get it from1793# the submit command output as the output is1794# unmarshalled.1795 changelist = self.lastP4Changelist()1796 self.modifyChangelistUser(changelist, p4User)17971798# The rename/copy happened by applying a patch that created a1799# new file. This leaves it writable, which confuses p4.1800for f in pureRenameCopy:1801p4_sync(f,"-f")1802 submitted =True18031804finally:1805# skip this patch1806if not submitted:1807print"Submission cancelled, undoing p4 changes."1808for f in editedFiles:1809p4_revert(f)1810for f in filesToAdd:1811p4_revert(f)1812 os.remove(f)1813for f in filesToDelete:1814p4_revert(f)18151816 os.remove(fileName)1817return submitted18181819# Export git tags as p4 labels. Create a p4 label and then tag1820# with that.1821defexportGitTags(self, gitTags):1822 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1823iflen(validLabelRegexp) ==0:1824 validLabelRegexp = defaultLabelRegexp1825 m = re.compile(validLabelRegexp)18261827for name in gitTags:18281829if not m.match(name):1830if verbose:1831print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1832continue18331834# Get the p4 commit this corresponds to1835 logMessage =extractLogMessageFromGitCommit(name)1836 values =extractSettingsGitLog(logMessage)18371838if not values.has_key('change'):1839# a tag pointing to something not sent to p4; ignore1840if verbose:1841print"git tag%sdoes not give a p4 commit"% name1842continue1843else:1844 changelist = values['change']18451846# Get the tag details.1847 inHeader =True1848 isAnnotated =False1849 body = []1850for l inread_pipe_lines(["git","cat-file","-p", name]):1851 l = l.strip()1852if inHeader:1853if re.match(r'tag\s+', l):1854 isAnnotated =True1855elif re.match(r'\s*$', l):1856 inHeader =False1857continue1858else:1859 body.append(l)18601861if not isAnnotated:1862 body = ["lightweight tag imported by git p4\n"]18631864# Create the label - use the same view as the client spec we are using1865 clientSpec =getClientSpec()18661867 labelTemplate ="Label:%s\n"% name1868 labelTemplate +="Description:\n"1869for b in body:1870 labelTemplate +="\t"+ b +"\n"1871 labelTemplate +="View:\n"1872for depot_side in clientSpec.mappings:1873 labelTemplate +="\t%s\n"% depot_side18741875if self.dry_run:1876print"Would create p4 label%sfor tag"% name1877elif self.prepare_p4_only:1878print"Not creating p4 label%sfor tag due to option" \1879" --prepare-p4-only"% name1880else:1881p4_write_pipe(["label","-i"], labelTemplate)18821883# Use the label1884p4_system(["tag","-l", name] +1885["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18861887if verbose:1888print"created p4 label for tag%s"% name18891890defrun(self, args):1891iflen(args) ==0:1892 self.master =currentGitBranch()1893eliflen(args) ==1:1894 self.master = args[0]1895if notbranchExists(self.master):1896die("Branch%sdoes not exist"% self.master)1897else:1898return False18991900if self.master:1901 allowSubmit =gitConfig("git-p4.allowSubmit")1902iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1903die("%sis not in git-p4.allowSubmit"% self.master)19041905[upstream, settings] =findUpstreamBranchPoint()1906 self.depotPath = settings['depot-paths'][0]1907iflen(self.origin) ==0:1908 self.origin = upstream19091910if self.preserveUser:1911if not self.canChangeChangelists():1912die("Cannot preserve user names without p4 super-user or admin permissions")19131914# if not set from the command line, try the config file1915if self.conflict_behavior is None:1916 val =gitConfig("git-p4.conflict")1917if val:1918if val not in self.conflict_behavior_choices:1919die("Invalid value '%s' for config git-p4.conflict"% val)1920else:1921 val ="ask"1922 self.conflict_behavior = val19231924if self.verbose:1925print"Origin branch is "+ self.origin19261927iflen(self.depotPath) ==0:1928print"Internal error: cannot locate perforce depot path from existing branches"1929 sys.exit(128)19301931 self.useClientSpec =False1932ifgitConfigBool("git-p4.useclientspec"):1933 self.useClientSpec =True1934if self.useClientSpec:1935 self.clientSpecDirs =getClientSpec()19361937# Check for the existance of P4 branches1938 branchesDetected = (len(p4BranchesInGit().keys()) >1)19391940if self.useClientSpec and not branchesDetected:1941# all files are relative to the client spec1942 self.clientPath =getClientRoot()1943else:1944 self.clientPath =p4Where(self.depotPath)19451946if self.clientPath =="":1947die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19481949print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1950 self.oldWorkingDirectory = os.getcwd()19511952# ensure the clientPath exists1953 new_client_dir =False1954if not os.path.exists(self.clientPath):1955 new_client_dir =True1956 os.makedirs(self.clientPath)19571958chdir(self.clientPath, is_client_path=True)1959if self.dry_run:1960print"Would synchronize p4 checkout in%s"% self.clientPath1961else:1962print"Synchronizing p4 checkout..."1963if new_client_dir:1964# old one was destroyed, and maybe nobody told p41965p4_sync("...","-f")1966else:1967p4_sync("...")1968 self.check()19691970 commits = []1971if self.master:1972 commitish = self.master1973else:1974 commitish ='HEAD'19751976for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):1977 commits.append(line.strip())1978 commits.reverse()19791980if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1981 self.checkAuthorship =False1982else:1983 self.checkAuthorship =True19841985if self.preserveUser:1986 self.checkValidP4Users(commits)19871988#1989# Build up a set of options to be passed to diff when1990# submitting each commit to p4.1991#1992if self.detectRenames:1993# command-line -M arg1994 self.diffOpts ="-M"1995else:1996# If not explicitly set check the config variable1997 detectRenames =gitConfig("git-p4.detectRenames")19981999if detectRenames.lower() =="false"or detectRenames =="":2000 self.diffOpts =""2001elif detectRenames.lower() =="true":2002 self.diffOpts ="-M"2003else:2004 self.diffOpts ="-M%s"% detectRenames20052006# no command-line arg for -C or --find-copies-harder, just2007# config variables2008 detectCopies =gitConfig("git-p4.detectCopies")2009if detectCopies.lower() =="false"or detectCopies =="":2010pass2011elif detectCopies.lower() =="true":2012 self.diffOpts +=" -C"2013else:2014 self.diffOpts +=" -C%s"% detectCopies20152016ifgitConfigBool("git-p4.detectCopiesHarder"):2017 self.diffOpts +=" --find-copies-harder"20182019#2020# Apply the commits, one at a time. On failure, ask if should2021# continue to try the rest of the patches, or quit.2022#2023if self.dry_run:2024print"Would apply"2025 applied = []2026 last =len(commits) -12027for i, commit inenumerate(commits):2028if self.dry_run:2029print" ",read_pipe(["git","show","-s",2030"--format=format:%h%s", commit])2031 ok =True2032else:2033 ok = self.applyCommit(commit)2034if ok:2035 applied.append(commit)2036else:2037if self.prepare_p4_only and i < last:2038print"Processing only the first commit due to option" \2039" --prepare-p4-only"2040break2041if i < last:2042 quit =False2043while True:2044# prompt for what to do, or use the option/variable2045if self.conflict_behavior =="ask":2046print"What do you want to do?"2047 response =raw_input("[s]kip this commit but apply"2048" the rest, or [q]uit? ")2049if not response:2050continue2051elif self.conflict_behavior =="skip":2052 response ="s"2053elif self.conflict_behavior =="quit":2054 response ="q"2055else:2056die("Unknown conflict_behavior '%s'"%2057 self.conflict_behavior)20582059if response[0] =="s":2060print"Skipping this commit, but applying the rest"2061break2062if response[0] =="q":2063print"Quitting"2064 quit =True2065break2066if quit:2067break20682069chdir(self.oldWorkingDirectory)20702071if self.dry_run:2072pass2073elif self.prepare_p4_only:2074pass2075eliflen(commits) ==len(applied):2076print"All commits applied!"20772078 sync =P4Sync()2079if self.branch:2080 sync.branch = self.branch2081 sync.run([])20822083 rebase =P4Rebase()2084 rebase.rebase()20852086else:2087iflen(applied) ==0:2088print"No commits applied."2089else:2090print"Applied only the commits marked with '*':"2091for c in commits:2092if c in applied:2093 star ="*"2094else:2095 star =" "2096print star,read_pipe(["git","show","-s",2097"--format=format:%h%s", c])2098print"You will have to do 'git p4 sync' and rebase."20992100ifgitConfigBool("git-p4.exportLabels"):2101 self.exportLabels =True21022103if self.exportLabels:2104 p4Labels =getP4Labels(self.depotPath)2105 gitTags =getGitTags()21062107 missingGitTags = gitTags - p4Labels2108 self.exportGitTags(missingGitTags)21092110# exit with error unless everything applied perfectly2111iflen(commits) !=len(applied):2112 sys.exit(1)21132114return True21152116classView(object):2117"""Represent a p4 view ("p4 help views"), and map files in a2118 repo according to the view."""21192120def__init__(self, client_name):2121 self.mappings = []2122 self.client_prefix ="//%s/"% client_name2123# cache results of "p4 where" to lookup client file locations2124 self.client_spec_path_cache = {}21252126defappend(self, view_line):2127"""Parse a view line, splitting it into depot and client2128 sides. Append to self.mappings, preserving order. This2129 is only needed for tag creation."""21302131# Split the view line into exactly two words. P4 enforces2132# structure on these lines that simplifies this quite a bit.2133#2134# Either or both words may be double-quoted.2135# Single quotes do not matter.2136# Double-quote marks cannot occur inside the words.2137# A + or - prefix is also inside the quotes.2138# There are no quotes unless they contain a space.2139# The line is already white-space stripped.2140# The two words are separated by a single space.2141#2142if view_line[0] =='"':2143# First word is double quoted. Find its end.2144 close_quote_index = view_line.find('"',1)2145if close_quote_index <=0:2146die("No first-word closing quote found:%s"% view_line)2147 depot_side = view_line[1:close_quote_index]2148# skip closing quote and space2149 rhs_index = close_quote_index +1+12150else:2151 space_index = view_line.find(" ")2152if space_index <=0:2153die("No word-splitting space found:%s"% view_line)2154 depot_side = view_line[0:space_index]2155 rhs_index = space_index +121562157# prefix + means overlay on previous mapping2158if depot_side.startswith("+"):2159 depot_side = depot_side[1:]21602161# prefix - means exclude this path, leave out of mappings2162 exclude =False2163if depot_side.startswith("-"):2164 exclude =True2165 depot_side = depot_side[1:]21662167if not exclude:2168 self.mappings.append(depot_side)21692170defconvert_client_path(self, clientFile):2171# chop off //client/ part to make it relative2172if not clientFile.startswith(self.client_prefix):2173die("No prefix '%s' on clientFile '%s'"%2174(self.client_prefix, clientFile))2175return clientFile[len(self.client_prefix):]21762177defupdate_client_spec_path_cache(self, files):2178""" Caching file paths by "p4 where" batch query """21792180# List depot file paths exclude that already cached2181 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21822183iflen(fileArgs) ==0:2184return# All files in cache21852186 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2187for res in where_result:2188if"code"in res and res["code"] =="error":2189# assume error is "... file(s) not in client view"2190continue2191if"clientFile"not in res:2192die("No clientFile in 'p4 where' output")2193if"unmap"in res:2194# it will list all of them, but only one not unmap-ped2195continue2196ifgitConfigBool("core.ignorecase"):2197 res['depotFile'] = res['depotFile'].lower()2198 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])21992200# not found files or unmap files set to ""2201for depotFile in fileArgs:2202ifgitConfigBool("core.ignorecase"):2203 depotFile = depotFile.lower()2204if depotFile not in self.client_spec_path_cache:2205 self.client_spec_path_cache[depotFile] =""22062207defmap_in_client(self, depot_path):2208"""Return the relative location in the client where this2209 depot file should live. Returns "" if the file should2210 not be mapped in the client."""22112212ifgitConfigBool("core.ignorecase"):2213 depot_path = depot_path.lower()22142215if depot_path in self.client_spec_path_cache:2216return self.client_spec_path_cache[depot_path]22172218die("Error:%sis not found in client spec path"% depot_path )2219return""22202221classP4Sync(Command, P4UserMap):2222 delete_actions = ("delete","move/delete","purge")22232224def__init__(self):2225 Command.__init__(self)2226 P4UserMap.__init__(self)2227 self.options = [2228 optparse.make_option("--branch", dest="branch"),2229 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2230 optparse.make_option("--changesfile", dest="changesFile"),2231 optparse.make_option("--silent", dest="silent", action="store_true"),2232 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2233 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2234 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2235help="Import into refs/heads/ , not refs/remotes"),2236 optparse.make_option("--max-changes", dest="maxChanges",2237help="Maximum number of changes to import"),2238 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2239help="Internal block size to use when iteratively calling p4 changes"),2240 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2241help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2242 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2243help="Only sync files that are included in the Perforce Client Spec"),2244 optparse.make_option("-/", dest="cloneExclude",2245 action="append",type="string",2246help="exclude depot path"),2247]2248 self.description ="""Imports from Perforce into a git repository.\n2249 example:2250 //depot/my/project/ -- to import the current head2251 //depot/my/project/@all -- to import everything2252 //depot/my/project/@1,6 -- to import only from revision 1 to 622532254 (a ... is not needed in the path p4 specification, it's added implicitly)"""22552256 self.usage +=" //depot/path[@revRange]"2257 self.silent =False2258 self.createdBranches =set()2259 self.committedChanges =set()2260 self.branch =""2261 self.detectBranches =False2262 self.detectLabels =False2263 self.importLabels =False2264 self.changesFile =""2265 self.syncWithOrigin =True2266 self.importIntoRemotes =True2267 self.maxChanges =""2268 self.changes_block_size =None2269 self.keepRepoPath =False2270 self.depotPaths =None2271 self.p4BranchesInGit = []2272 self.cloneExclude = []2273 self.useClientSpec =False2274 self.useClientSpec_from_options =False2275 self.clientSpecDirs =None2276 self.tempBranches = []2277 self.tempBranchLocation ="git-p4-tmp"2278 self.largeFileSystem =None22792280ifgitConfig('git-p4.largeFileSystem'):2281 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2282 self.largeFileSystem =largeFileSystemConstructor(2283lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2284)22852286ifgitConfig("git-p4.syncFromOrigin") =="false":2287 self.syncWithOrigin =False22882289# This is required for the "append" cloneExclude action2290defensure_value(self, attr, value):2291if nothasattr(self, attr)orgetattr(self, attr)is None:2292setattr(self, attr, value)2293returngetattr(self, attr)22942295# Force a checkpoint in fast-import and wait for it to finish2296defcheckpoint(self):2297 self.gitStream.write("checkpoint\n\n")2298 self.gitStream.write("progress checkpoint\n\n")2299 out = self.gitOutput.readline()2300if self.verbose:2301print"checkpoint finished: "+ out23022303defextractFilesFromCommit(self, commit):2304 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2305for path in self.cloneExclude]2306 files = []2307 fnum =02308while commit.has_key("depotFile%s"% fnum):2309 path = commit["depotFile%s"% fnum]23102311if[p for p in self.cloneExclude2312ifp4PathStartsWith(path, p)]:2313 found =False2314else:2315 found = [p for p in self.depotPaths2316ifp4PathStartsWith(path, p)]2317if not found:2318 fnum = fnum +12319continue23202321file= {}2322file["path"] = path2323file["rev"] = commit["rev%s"% fnum]2324file["action"] = commit["action%s"% fnum]2325file["type"] = commit["type%s"% fnum]2326 files.append(file)2327 fnum = fnum +12328return files23292330defextractJobsFromCommit(self, commit):2331 jobs = []2332 jnum =02333while commit.has_key("job%s"% jnum):2334 job = commit["job%s"% jnum]2335 jobs.append(job)2336 jnum = jnum +12337return jobs23382339defstripRepoPath(self, path, prefixes):2340"""When streaming files, this is called to map a p4 depot path2341 to where it should go in git. The prefixes are either2342 self.depotPaths, or self.branchPrefixes in the case of2343 branch detection."""23442345if self.useClientSpec:2346# branch detection moves files up a level (the branch name)2347# from what client spec interpretation gives2348 path = self.clientSpecDirs.map_in_client(path)2349if self.detectBranches:2350for b in self.knownBranches:2351if path.startswith(b +"/"):2352 path = path[len(b)+1:]23532354elif self.keepRepoPath:2355# Preserve everything in relative path name except leading2356# //depot/; just look at first prefix as they all should2357# be in the same depot.2358 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2359ifp4PathStartsWith(path, depot):2360 path = path[len(depot):]23612362else:2363for p in prefixes:2364ifp4PathStartsWith(path, p):2365 path = path[len(p):]2366break23672368 path =wildcard_decode(path)2369return path23702371defsplitFilesIntoBranches(self, commit):2372"""Look at each depotFile in the commit to figure out to what2373 branch it belongs."""23742375if self.clientSpecDirs:2376 files = self.extractFilesFromCommit(commit)2377 self.clientSpecDirs.update_client_spec_path_cache(files)23782379 branches = {}2380 fnum =02381while commit.has_key("depotFile%s"% fnum):2382 path = commit["depotFile%s"% fnum]2383 found = [p for p in self.depotPaths2384ifp4PathStartsWith(path, p)]2385if not found:2386 fnum = fnum +12387continue23882389file= {}2390file["path"] = path2391file["rev"] = commit["rev%s"% fnum]2392file["action"] = commit["action%s"% fnum]2393file["type"] = commit["type%s"% fnum]2394 fnum = fnum +123952396# start with the full relative path where this file would2397# go in a p4 client2398if self.useClientSpec:2399 relPath = self.clientSpecDirs.map_in_client(path)2400else:2401 relPath = self.stripRepoPath(path, self.depotPaths)24022403for branch in self.knownBranches.keys():2404# add a trailing slash so that a commit into qt/4.2foo2405# doesn't end up in qt/4.2, e.g.2406if relPath.startswith(branch +"/"):2407if branch not in branches:2408 branches[branch] = []2409 branches[branch].append(file)2410break24112412return branches24132414defwriteToGitStream(self, gitMode, relPath, contents):2415 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2416 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2417for d in contents:2418 self.gitStream.write(d)2419 self.gitStream.write('\n')24202421# output one file from the P4 stream2422# - helper for streamP4Files24232424defstreamOneP4File(self,file, contents):2425 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2426if verbose:2427 size =int(self.stream_file['fileSize'])2428 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2429 sys.stdout.flush()24302431(type_base, type_mods) =split_p4_type(file["type"])24322433 git_mode ="100644"2434if"x"in type_mods:2435 git_mode ="100755"2436if type_base =="symlink":2437 git_mode ="120000"2438# p4 print on a symlink sometimes contains "target\n";2439# if it does, remove the newline2440 data =''.join(contents)2441if not data:2442# Some version of p4 allowed creating a symlink that pointed2443# to nothing. This causes p4 errors when checking out such2444# a change, and errors here too. Work around it by ignoring2445# the bad symlink; hopefully a future change fixes it.2446print"\nIgnoring empty symlink in%s"%file['depotFile']2447return2448elif data[-1] =='\n':2449 contents = [data[:-1]]2450else:2451 contents = [data]24522453if type_base =="utf16":2454# p4 delivers different text in the python output to -G2455# than it does when using "print -o", or normal p4 client2456# operations. utf16 is converted to ascii or utf8, perhaps.2457# But ascii text saved as -t utf16 is completely mangled.2458# Invoke print -o to get the real contents.2459#2460# On windows, the newlines will always be mangled by print, so put2461# them back too. This is not needed to the cygwin windows version,2462# just the native "NT" type.2463#2464try:2465 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2466exceptExceptionas e:2467if'Translation of file content failed'instr(e):2468 type_base ='binary'2469else:2470raise e2471else:2472ifp4_version_string().find('/NT') >=0:2473 text = text.replace('\r\n','\n')2474 contents = [ text ]24752476if type_base =="apple":2477# Apple filetype files will be streamed as a concatenation of2478# its appledouble header and the contents. This is useless2479# on both macs and non-macs. If using "print -q -o xx", it2480# will create "xx" with the data, and "%xx" with the header.2481# This is also not very useful.2482#2483# Ideally, someday, this script can learn how to generate2484# appledouble files directly and import those to git, but2485# non-mac machines can never find a use for apple filetype.2486print"\nIgnoring apple filetype file%s"%file['depotFile']2487return24882489# Note that we do not try to de-mangle keywords on utf16 files,2490# even though in theory somebody may want that.2491 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2492if pattern:2493 regexp = re.compile(pattern, re.VERBOSE)2494 text =''.join(contents)2495 text = regexp.sub(r'$\1$', text)2496 contents = [ text ]24972498try:2499 relPath.decode('ascii')2500except:2501 encoding ='utf8'2502ifgitConfig('git-p4.pathEncoding'):2503 encoding =gitConfig('git-p4.pathEncoding')2504 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2505if self.verbose:2506print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)25072508if self.largeFileSystem:2509(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)25102511 self.writeToGitStream(git_mode, relPath, contents)25122513defstreamOneP4Deletion(self,file):2514 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2515if verbose:2516 sys.stdout.write("delete%s\n"% relPath)2517 sys.stdout.flush()2518 self.gitStream.write("D%s\n"% relPath)25192520if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2521 self.largeFileSystem.removeLargeFile(relPath)25222523# handle another chunk of streaming data2524defstreamP4FilesCb(self, marshalled):25252526# catch p4 errors and complain2527 err =None2528if"code"in marshalled:2529if marshalled["code"] =="error":2530if"data"in marshalled:2531 err = marshalled["data"].rstrip()25322533if not err and'fileSize'in self.stream_file:2534 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2535if required_bytes >0:2536 err ='Not enough space left on%s! Free at least%iMB.'% (2537 os.getcwd(), required_bytes/1024/10242538)25392540if err:2541 f =None2542if self.stream_have_file_info:2543if"depotFile"in self.stream_file:2544 f = self.stream_file["depotFile"]2545# force a failure in fast-import, else an empty2546# commit will be made2547 self.gitStream.write("\n")2548 self.gitStream.write("die-now\n")2549 self.gitStream.close()2550# ignore errors, but make sure it exits first2551 self.importProcess.wait()2552if f:2553die("Error from p4 print for%s:%s"% (f, err))2554else:2555die("Error from p4 print:%s"% err)25562557if marshalled.has_key('depotFile')and self.stream_have_file_info:2558# start of a new file - output the old one first2559 self.streamOneP4File(self.stream_file, self.stream_contents)2560 self.stream_file = {}2561 self.stream_contents = []2562 self.stream_have_file_info =False25632564# pick up the new file information... for the2565# 'data' field we need to append to our array2566for k in marshalled.keys():2567if k =='data':2568if'streamContentSize'not in self.stream_file:2569 self.stream_file['streamContentSize'] =02570 self.stream_file['streamContentSize'] +=len(marshalled['data'])2571 self.stream_contents.append(marshalled['data'])2572else:2573 self.stream_file[k] = marshalled[k]25742575if(verbose and2576'streamContentSize'in self.stream_file and2577'fileSize'in self.stream_file and2578'depotFile'in self.stream_file):2579 size =int(self.stream_file["fileSize"])2580if size >0:2581 progress =100*self.stream_file['streamContentSize']/size2582 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2583 sys.stdout.flush()25842585 self.stream_have_file_info =True25862587# Stream directly from "p4 files" into "git fast-import"2588defstreamP4Files(self, files):2589 filesForCommit = []2590 filesToRead = []2591 filesToDelete = []25922593for f in files:2594 filesForCommit.append(f)2595if f['action']in self.delete_actions:2596 filesToDelete.append(f)2597else:2598 filesToRead.append(f)25992600# deleted files...2601for f in filesToDelete:2602 self.streamOneP4Deletion(f)26032604iflen(filesToRead) >0:2605 self.stream_file = {}2606 self.stream_contents = []2607 self.stream_have_file_info =False26082609# curry self argument2610defstreamP4FilesCbSelf(entry):2611 self.streamP4FilesCb(entry)26122613 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]26142615p4CmdList(["-x","-","print"],2616 stdin=fileArgs,2617 cb=streamP4FilesCbSelf)26182619# do the last chunk2620if self.stream_file.has_key('depotFile'):2621 self.streamOneP4File(self.stream_file, self.stream_contents)26222623defmake_email(self, userid):2624if userid in self.users:2625return self.users[userid]2626else:2627return"%s<a@b>"% userid26282629defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2630""" Stream a p4 tag.2631 commit is either a git commit, or a fast-import mark, ":<p4commit>"2632 """26332634if verbose:2635print"writing tag%sfor commit%s"% (labelName, commit)2636 gitStream.write("tag%s\n"% labelName)2637 gitStream.write("from%s\n"% commit)26382639if labelDetails.has_key('Owner'):2640 owner = labelDetails["Owner"]2641else:2642 owner =None26432644# Try to use the owner of the p4 label, or failing that,2645# the current p4 user id.2646if owner:2647 email = self.make_email(owner)2648else:2649 email = self.make_email(self.p4UserId())2650 tagger ="%s %s %s"% (email, epoch, self.tz)26512652 gitStream.write("tagger%s\n"% tagger)26532654print"labelDetails=",labelDetails2655if labelDetails.has_key('Description'):2656 description = labelDetails['Description']2657else:2658 description ='Label from git p4'26592660 gitStream.write("data%d\n"%len(description))2661 gitStream.write(description)2662 gitStream.write("\n")26632664definClientSpec(self, path):2665if not self.clientSpecDirs:2666return True2667 inClientSpec = self.clientSpecDirs.map_in_client(path)2668if not inClientSpec and self.verbose:2669print('Ignoring file outside of client spec:{0}'.format(path))2670return inClientSpec26712672defhasBranchPrefix(self, path):2673if not self.branchPrefixes:2674return True2675 hasPrefix = [p for p in self.branchPrefixes2676ifp4PathStartsWith(path, p)]2677if hasPrefix and self.verbose:2678print('Ignoring file outside of prefix:{0}'.format(path))2679return hasPrefix26802681defcommit(self, details, files, branch, parent =""):2682 epoch = details["time"]2683 author = details["user"]2684 jobs = self.extractJobsFromCommit(details)26852686if self.verbose:2687print('commit into{0}'.format(branch))26882689if self.clientSpecDirs:2690 self.clientSpecDirs.update_client_spec_path_cache(files)26912692 files = [f for f in files2693if self.inClientSpec(f['path'])and self.hasBranchPrefix(f['path'])]26942695if not files and notgitConfigBool('git-p4.keepEmptyCommits'):2696print('Ignoring revision{0}as it would produce an empty commit.'2697.format(details['change']))2698return26992700 self.gitStream.write("commit%s\n"% branch)2701 self.gitStream.write("mark :%s\n"% details["change"])2702 self.committedChanges.add(int(details["change"]))2703 committer =""2704if author not in self.users:2705 self.getUserMapFromPerforceServer()2706 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)27072708 self.gitStream.write("committer%s\n"% committer)27092710 self.gitStream.write("data <<EOT\n")2711 self.gitStream.write(details["desc"])2712iflen(jobs) >0:2713 self.gitStream.write("\nJobs:%s"% (' '.join(jobs)))2714 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2715(','.join(self.branchPrefixes), details["change"]))2716iflen(details['options']) >0:2717 self.gitStream.write(": options =%s"% details['options'])2718 self.gitStream.write("]\nEOT\n\n")27192720iflen(parent) >0:2721if self.verbose:2722print"parent%s"% parent2723 self.gitStream.write("from%s\n"% parent)27242725 self.streamP4Files(files)2726 self.gitStream.write("\n")27272728 change =int(details["change"])27292730if self.labels.has_key(change):2731 label = self.labels[change]2732 labelDetails = label[0]2733 labelRevisions = label[1]2734if self.verbose:2735print"Change%sis labelled%s"% (change, labelDetails)27362737 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2738for p in self.branchPrefixes])27392740iflen(files) ==len(labelRevisions):27412742 cleanedFiles = {}2743for info in files:2744if info["action"]in self.delete_actions:2745continue2746 cleanedFiles[info["depotFile"]] = info["rev"]27472748if cleanedFiles == labelRevisions:2749 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)27502751else:2752if not self.silent:2753print("Tag%sdoes not match with change%s: files do not match."2754% (labelDetails["label"], change))27552756else:2757if not self.silent:2758print("Tag%sdoes not match with change%s: file count is different."2759% (labelDetails["label"], change))27602761# Build a dictionary of changelists and labels, for "detect-labels" option.2762defgetLabels(self):2763 self.labels = {}27642765 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2766iflen(l) >0and not self.silent:2767print"Finding files belonging to labels in%s"% `self.depotPaths`27682769for output in l:2770 label = output["label"]2771 revisions = {}2772 newestChange =02773if self.verbose:2774print"Querying files for label%s"% label2775forfileinp4CmdList(["files"] +2776["%s...@%s"% (p, label)2777for p in self.depotPaths]):2778 revisions[file["depotFile"]] =file["rev"]2779 change =int(file["change"])2780if change > newestChange:2781 newestChange = change27822783 self.labels[newestChange] = [output, revisions]27842785if self.verbose:2786print"Label changes:%s"% self.labels.keys()27872788# Import p4 labels as git tags. A direct mapping does not2789# exist, so assume that if all the files are at the same revision2790# then we can use that, or it's something more complicated we should2791# just ignore.2792defimportP4Labels(self, stream, p4Labels):2793if verbose:2794print"import p4 labels: "+' '.join(p4Labels)27952796 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2797 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2798iflen(validLabelRegexp) ==0:2799 validLabelRegexp = defaultLabelRegexp2800 m = re.compile(validLabelRegexp)28012802for name in p4Labels:2803 commitFound =False28042805if not m.match(name):2806if verbose:2807print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2808continue28092810if name in ignoredP4Labels:2811continue28122813 labelDetails =p4CmdList(['label',"-o", name])[0]28142815# get the most recent changelist for each file in this label2816 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2817for p in self.depotPaths])28182819if change.has_key('change'):2820# find the corresponding git commit; take the oldest commit2821 changelist =int(change['change'])2822if changelist in self.committedChanges:2823 gitCommit =":%d"% changelist # use a fast-import mark2824 commitFound =True2825else:2826 gitCommit =read_pipe(["git","rev-list","--max-count=1",2827"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2828iflen(gitCommit) ==0:2829print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2830else:2831 commitFound =True2832 gitCommit = gitCommit.strip()28332834if commitFound:2835# Convert from p4 time format2836try:2837 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2838exceptValueError:2839print"Could not convert label time%s"% labelDetails['Update']2840 tmwhen =128412842 when =int(time.mktime(tmwhen))2843 self.streamTag(stream, name, labelDetails, gitCommit, when)2844if verbose:2845print"p4 label%smapped to git commit%s"% (name, gitCommit)2846else:2847if verbose:2848print"Label%shas no changelists - possibly deleted?"% name28492850if not commitFound:2851# We can't import this label; don't try again as it will get very2852# expensive repeatedly fetching all the files for labels that will2853# never be imported. If the label is moved in the future, the2854# ignore will need to be removed manually.2855system(["git","config","--add","git-p4.ignoredP4Labels", name])28562857defguessProjectName(self):2858for p in self.depotPaths:2859if p.endswith("/"):2860 p = p[:-1]2861 p = p[p.strip().rfind("/") +1:]2862if not p.endswith("/"):2863 p +="/"2864return p28652866defgetBranchMapping(self):2867 lostAndFoundBranches =set()28682869 user =gitConfig("git-p4.branchUser")2870iflen(user) >0:2871 command ="branches -u%s"% user2872else:2873 command ="branches"28742875for info inp4CmdList(command):2876 details =p4Cmd(["branch","-o", info["branch"]])2877 viewIdx =02878while details.has_key("View%s"% viewIdx):2879 paths = details["View%s"% viewIdx].split(" ")2880 viewIdx = viewIdx +12881# require standard //depot/foo/... //depot/bar/... mapping2882iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2883continue2884 source = paths[0]2885 destination = paths[1]2886## HACK2887ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2888 source = source[len(self.depotPaths[0]):-4]2889 destination = destination[len(self.depotPaths[0]):-4]28902891if destination in self.knownBranches:2892if not self.silent:2893print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2894print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2895continue28962897 self.knownBranches[destination] = source28982899 lostAndFoundBranches.discard(destination)29002901if source not in self.knownBranches:2902 lostAndFoundBranches.add(source)29032904# Perforce does not strictly require branches to be defined, so we also2905# check git config for a branch list.2906#2907# Example of branch definition in git config file:2908# [git-p4]2909# branchList=main:branchA2910# branchList=main:branchB2911# branchList=branchA:branchC2912 configBranches =gitConfigList("git-p4.branchList")2913for branch in configBranches:2914if branch:2915(source, destination) = branch.split(":")2916 self.knownBranches[destination] = source29172918 lostAndFoundBranches.discard(destination)29192920if source not in self.knownBranches:2921 lostAndFoundBranches.add(source)292229232924for branch in lostAndFoundBranches:2925 self.knownBranches[branch] = branch29262927defgetBranchMappingFromGitBranches(self):2928 branches =p4BranchesInGit(self.importIntoRemotes)2929for branch in branches.keys():2930if branch =="master":2931 branch ="main"2932else:2933 branch = branch[len(self.projectName):]2934 self.knownBranches[branch] = branch29352936defupdateOptionDict(self, d):2937 option_keys = {}2938if self.keepRepoPath:2939 option_keys['keepRepoPath'] =129402941 d["options"] =' '.join(sorted(option_keys.keys()))29422943defreadOptions(self, d):2944 self.keepRepoPath = (d.has_key('options')2945and('keepRepoPath'in d['options']))29462947defgitRefForBranch(self, branch):2948if branch =="main":2949return self.refPrefix +"master"29502951iflen(branch) <=0:2952return branch29532954return self.refPrefix + self.projectName + branch29552956defgitCommitByP4Change(self, ref, change):2957if self.verbose:2958print"looking in ref "+ ref +" for change%susing bisect..."% change29592960 earliestCommit =""2961 latestCommit =parseRevision(ref)29622963while True:2964if self.verbose:2965print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2966 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2967iflen(next) ==0:2968if self.verbose:2969print"argh"2970return""2971 log =extractLogMessageFromGitCommit(next)2972 settings =extractSettingsGitLog(log)2973 currentChange =int(settings['change'])2974if self.verbose:2975print"current change%s"% currentChange29762977if currentChange == change:2978if self.verbose:2979print"found%s"% next2980return next29812982if currentChange < change:2983 earliestCommit ="^%s"% next2984else:2985 latestCommit ="%s"% next29862987return""29882989defimportNewBranch(self, branch, maxChange):2990# make fast-import flush all changes to disk and update the refs using the checkpoint2991# command so that we can try to find the branch parent in the git history2992 self.gitStream.write("checkpoint\n\n");2993 self.gitStream.flush();2994 branchPrefix = self.depotPaths[0] + branch +"/"2995range="@1,%s"% maxChange2996#print "prefix" + branchPrefix2997 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2998iflen(changes) <=0:2999return False3000 firstChange = changes[0]3001#print "first change in branch: %s" % firstChange3002 sourceBranch = self.knownBranches[branch]3003 sourceDepotPath = self.depotPaths[0] + sourceBranch3004 sourceRef = self.gitRefForBranch(sourceBranch)3005#print "source " + sourceBranch30063007 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])3008#print "branch parent: %s" % branchParentChange3009 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)3010iflen(gitParent) >0:3011 self.initialParents[self.gitRefForBranch(branch)] = gitParent3012#print "parent git commit: %s" % gitParent30133014 self.importChanges(changes)3015return True30163017defsearchParent(self, parent, branch, target):3018 parentFound =False3019for blob inread_pipe_lines(["git","rev-list","--reverse",3020"--no-merges", parent]):3021 blob = blob.strip()3022iflen(read_pipe(["git","diff-tree", blob, target])) ==0:3023 parentFound =True3024if self.verbose:3025print"Found parent of%sin commit%s"% (branch, blob)3026break3027if parentFound:3028return blob3029else:3030return None30313032defimportChanges(self, changes):3033 cnt =13034for change in changes:3035 description =p4_describe(change)3036 self.updateOptionDict(description)30373038if not self.silent:3039 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))3040 sys.stdout.flush()3041 cnt = cnt +130423043try:3044if self.detectBranches:3045 branches = self.splitFilesIntoBranches(description)3046for branch in branches.keys():3047## HACK --hwn3048 branchPrefix = self.depotPaths[0] + branch +"/"3049 self.branchPrefixes = [ branchPrefix ]30503051 parent =""30523053 filesForCommit = branches[branch]30543055if self.verbose:3056print"branch is%s"% branch30573058 self.updatedBranches.add(branch)30593060if branch not in self.createdBranches:3061 self.createdBranches.add(branch)3062 parent = self.knownBranches[branch]3063if parent == branch:3064 parent =""3065else:3066 fullBranch = self.projectName + branch3067if fullBranch not in self.p4BranchesInGit:3068if not self.silent:3069print("\nImporting new branch%s"% fullBranch);3070if self.importNewBranch(branch, change -1):3071 parent =""3072 self.p4BranchesInGit.append(fullBranch)3073if not self.silent:3074print("\nResuming with change%s"% change);30753076if self.verbose:3077print"parent determined through known branches:%s"% parent30783079 branch = self.gitRefForBranch(branch)3080 parent = self.gitRefForBranch(parent)30813082if self.verbose:3083print"looking for initial parent for%s; current parent is%s"% (branch, parent)30843085iflen(parent) ==0and branch in self.initialParents:3086 parent = self.initialParents[branch]3087del self.initialParents[branch]30883089 blob =None3090iflen(parent) >0:3091 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3092if self.verbose:3093print"Creating temporary branch: "+ tempBranch3094 self.commit(description, filesForCommit, tempBranch)3095 self.tempBranches.append(tempBranch)3096 self.checkpoint()3097 blob = self.searchParent(parent, branch, tempBranch)3098if blob:3099 self.commit(description, filesForCommit, branch, blob)3100else:3101if self.verbose:3102print"Parent of%snot found. Committing into head of%s"% (branch, parent)3103 self.commit(description, filesForCommit, branch, parent)3104else:3105 files = self.extractFilesFromCommit(description)3106 self.commit(description, files, self.branch,3107 self.initialParent)3108# only needed once, to connect to the previous commit3109 self.initialParent =""3110exceptIOError:3111print self.gitError.read()3112 sys.exit(1)31133114defimportHeadRevision(self, revision):3115print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)31163117 details = {}3118 details["user"] ="git perforce import user"3119 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3120% (' '.join(self.depotPaths), revision))3121 details["change"] = revision3122 newestRevision =031233124 fileCnt =03125 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]31263127for info inp4CmdList(["files"] + fileArgs):31283129if'code'in info and info['code'] =='error':3130 sys.stderr.write("p4 returned an error:%s\n"3131% info['data'])3132if info['data'].find("must refer to client") >=0:3133 sys.stderr.write("This particular p4 error is misleading.\n")3134 sys.stderr.write("Perhaps the depot path was misspelled.\n");3135 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3136 sys.exit(1)3137if'p4ExitCode'in info:3138 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3139 sys.exit(1)314031413142 change =int(info["change"])3143if change > newestRevision:3144 newestRevision = change31453146if info["action"]in self.delete_actions:3147# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3148#fileCnt = fileCnt + 13149continue31503151for prop in["depotFile","rev","action","type"]:3152 details["%s%s"% (prop, fileCnt)] = info[prop]31533154 fileCnt = fileCnt +131553156 details["change"] = newestRevision31573158# Use time from top-most change so that all git p4 clones of3159# the same p4 repo have the same commit SHA1s.3160 res =p4_describe(newestRevision)3161 details["time"] = res["time"]31623163 self.updateOptionDict(details)3164try:3165 self.commit(details, self.extractFilesFromCommit(details), self.branch)3166exceptIOError:3167print"IO error with git fast-import. Is your git version recent enough?"3168print self.gitError.read()316931703171defrun(self, args):3172 self.depotPaths = []3173 self.changeRange =""3174 self.previousDepotPaths = []3175 self.hasOrigin =False31763177# map from branch depot path to parent branch3178 self.knownBranches = {}3179 self.initialParents = {}31803181if self.importIntoRemotes:3182 self.refPrefix ="refs/remotes/p4/"3183else:3184 self.refPrefix ="refs/heads/p4/"31853186if self.syncWithOrigin:3187 self.hasOrigin =originP4BranchesExist()3188if self.hasOrigin:3189if not self.silent:3190print'Syncing with origin first, using "git fetch origin"'3191system("git fetch origin")31923193 branch_arg_given =bool(self.branch)3194iflen(self.branch) ==0:3195 self.branch = self.refPrefix +"master"3196ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3197system("git update-ref%srefs/heads/p4"% self.branch)3198system("git branch -D p4")31993200# accept either the command-line option, or the configuration variable3201if self.useClientSpec:3202# will use this after clone to set the variable3203 self.useClientSpec_from_options =True3204else:3205ifgitConfigBool("git-p4.useclientspec"):3206 self.useClientSpec =True3207if self.useClientSpec:3208 self.clientSpecDirs =getClientSpec()32093210# TODO: should always look at previous commits,3211# merge with previous imports, if possible.3212if args == []:3213if self.hasOrigin:3214createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)32153216# branches holds mapping from branch name to sha13217 branches =p4BranchesInGit(self.importIntoRemotes)32183219# restrict to just this one, disabling detect-branches3220if branch_arg_given:3221 short = self.branch.split("/")[-1]3222if short in branches:3223 self.p4BranchesInGit = [ short ]3224else:3225 self.p4BranchesInGit = branches.keys()32263227iflen(self.p4BranchesInGit) >1:3228if not self.silent:3229print"Importing from/into multiple branches"3230 self.detectBranches =True3231for branch in branches.keys():3232 self.initialParents[self.refPrefix + branch] = \3233 branches[branch]32343235if self.verbose:3236print"branches:%s"% self.p4BranchesInGit32373238 p4Change =03239for branch in self.p4BranchesInGit:3240 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)32413242 settings =extractSettingsGitLog(logMsg)32433244 self.readOptions(settings)3245if(settings.has_key('depot-paths')3246and settings.has_key('change')):3247 change =int(settings['change']) +13248 p4Change =max(p4Change, change)32493250 depotPaths =sorted(settings['depot-paths'])3251if self.previousDepotPaths == []:3252 self.previousDepotPaths = depotPaths3253else:3254 paths = []3255for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3256 prev_list = prev.split("/")3257 cur_list = cur.split("/")3258for i inrange(0,min(len(cur_list),len(prev_list))):3259if cur_list[i] <> prev_list[i]:3260 i = i -13261break32623263 paths.append("/".join(cur_list[:i +1]))32643265 self.previousDepotPaths = paths32663267if p4Change >0:3268 self.depotPaths =sorted(self.previousDepotPaths)3269 self.changeRange ="@%s,#head"% p4Change3270if not self.silent and not self.detectBranches:3271print"Performing incremental import into%sgit branch"% self.branch32723273# accept multiple ref name abbreviations:3274# refs/foo/bar/branch -> use it exactly3275# p4/branch -> prepend refs/remotes/ or refs/heads/3276# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3277if not self.branch.startswith("refs/"):3278if self.importIntoRemotes:3279 prepend ="refs/remotes/"3280else:3281 prepend ="refs/heads/"3282if not self.branch.startswith("p4/"):3283 prepend +="p4/"3284 self.branch = prepend + self.branch32853286iflen(args) ==0and self.depotPaths:3287if not self.silent:3288print"Depot paths:%s"%' '.join(self.depotPaths)3289else:3290if self.depotPaths and self.depotPaths != args:3291print("previous import used depot path%sand now%swas specified. "3292"This doesn't work!"% (' '.join(self.depotPaths),3293' '.join(args)))3294 sys.exit(1)32953296 self.depotPaths =sorted(args)32973298 revision =""3299 self.users = {}33003301# Make sure no revision specifiers are used when --changesfile3302# is specified.3303 bad_changesfile =False3304iflen(self.changesFile) >0:3305for p in self.depotPaths:3306if p.find("@") >=0or p.find("#") >=0:3307 bad_changesfile =True3308break3309if bad_changesfile:3310die("Option --changesfile is incompatible with revision specifiers")33113312 newPaths = []3313for p in self.depotPaths:3314if p.find("@") != -1:3315 atIdx = p.index("@")3316 self.changeRange = p[atIdx:]3317if self.changeRange =="@all":3318 self.changeRange =""3319elif','not in self.changeRange:3320 revision = self.changeRange3321 self.changeRange =""3322 p = p[:atIdx]3323elif p.find("#") != -1:3324 hashIdx = p.index("#")3325 revision = p[hashIdx:]3326 p = p[:hashIdx]3327elif self.previousDepotPaths == []:3328# pay attention to changesfile, if given, else import3329# the entire p4 tree at the head revision3330iflen(self.changesFile) ==0:3331 revision ="#head"33323333 p = re.sub("\.\.\.$","", p)3334if not p.endswith("/"):3335 p +="/"33363337 newPaths.append(p)33383339 self.depotPaths = newPaths33403341# --detect-branches may change this for each branch3342 self.branchPrefixes = self.depotPaths33433344 self.loadUserMapFromCache()3345 self.labels = {}3346if self.detectLabels:3347 self.getLabels();33483349if self.detectBranches:3350## FIXME - what's a P4 projectName ?3351 self.projectName = self.guessProjectName()33523353if self.hasOrigin:3354 self.getBranchMappingFromGitBranches()3355else:3356 self.getBranchMapping()3357if self.verbose:3358print"p4-git branches:%s"% self.p4BranchesInGit3359print"initial parents:%s"% self.initialParents3360for b in self.p4BranchesInGit:3361if b !="master":33623363## FIXME3364 b = b[len(self.projectName):]3365 self.createdBranches.add(b)33663367 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33683369 self.importProcess = subprocess.Popen(["git","fast-import"],3370 stdin=subprocess.PIPE,3371 stdout=subprocess.PIPE,3372 stderr=subprocess.PIPE);3373 self.gitOutput = self.importProcess.stdout3374 self.gitStream = self.importProcess.stdin3375 self.gitError = self.importProcess.stderr33763377if revision:3378 self.importHeadRevision(revision)3379else:3380 changes = []33813382iflen(self.changesFile) >0:3383 output =open(self.changesFile).readlines()3384 changeSet =set()3385for line in output:3386 changeSet.add(int(line))33873388for change in changeSet:3389 changes.append(change)33903391 changes.sort()3392else:3393# catch "git p4 sync" with no new branches, in a repo that3394# does not have any existing p4 branches3395iflen(args) ==0:3396if not self.p4BranchesInGit:3397die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")33983399# The default branch is master, unless --branch is used to3400# specify something else. Make sure it exists, or complain3401# nicely about how to use --branch.3402if not self.detectBranches:3403if notbranch_exists(self.branch):3404if branch_arg_given:3405die("Error: branch%sdoes not exist."% self.branch)3406else:3407die("Error: no branch%s; perhaps specify one with --branch."%3408 self.branch)34093410if self.verbose:3411print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3412 self.changeRange)3413 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)34143415iflen(self.maxChanges) >0:3416 changes = changes[:min(int(self.maxChanges),len(changes))]34173418iflen(changes) ==0:3419if not self.silent:3420print"No changes to import!"3421else:3422if not self.silent and not self.detectBranches:3423print"Import destination:%s"% self.branch34243425 self.updatedBranches =set()34263427if not self.detectBranches:3428if args:3429# start a new branch3430 self.initialParent =""3431else:3432# build on a previous revision3433 self.initialParent =parseRevision(self.branch)34343435 self.importChanges(changes)34363437if not self.silent:3438print""3439iflen(self.updatedBranches) >0:3440 sys.stdout.write("Updated branches: ")3441for b in self.updatedBranches:3442 sys.stdout.write("%s"% b)3443 sys.stdout.write("\n")34443445ifgitConfigBool("git-p4.importLabels"):3446 self.importLabels =True34473448if self.importLabels:3449 p4Labels =getP4Labels(self.depotPaths)3450 gitTags =getGitTags()34513452 missingP4Labels = p4Labels - gitTags3453 self.importP4Labels(self.gitStream, missingP4Labels)34543455 self.gitStream.close()3456if self.importProcess.wait() !=0:3457die("fast-import failed:%s"% self.gitError.read())3458 self.gitOutput.close()3459 self.gitError.close()34603461# Cleanup temporary branches created during import3462if self.tempBranches != []:3463for branch in self.tempBranches:3464read_pipe("git update-ref -d%s"% branch)3465 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34663467# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3468# a convenient shortcut refname "p4".3469if self.importIntoRemotes:3470 head_ref = self.refPrefix +"HEAD"3471if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3472system(["git","symbolic-ref", head_ref, self.branch])34733474return True34753476classP4Rebase(Command):3477def__init__(self):3478 Command.__init__(self)3479 self.options = [3480 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3481]3482 self.importLabels =False3483 self.description = ("Fetches the latest revision from perforce and "3484+"rebases the current work (branch) against it")34853486defrun(self, args):3487 sync =P4Sync()3488 sync.importLabels = self.importLabels3489 sync.run([])34903491return self.rebase()34923493defrebase(self):3494if os.system("git update-index --refresh") !=0:3495die("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.");3496iflen(read_pipe("git diff-index HEAD --")) >0:3497die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");34983499[upstream, settings] =findUpstreamBranchPoint()3500iflen(upstream) ==0:3501die("Cannot find upstream branchpoint for rebase")35023503# the branchpoint may be p4/foo~3, so strip off the parent3504 upstream = re.sub("~[0-9]+$","", upstream)35053506print"Rebasing the current branch onto%s"% upstream3507 oldHead =read_pipe("git rev-parse HEAD").strip()3508system("git rebase%s"% upstream)3509system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3510return True35113512classP4Clone(P4Sync):3513def__init__(self):3514 P4Sync.__init__(self)3515 self.description ="Creates a new git repository and imports from Perforce into it"3516 self.usage ="usage: %prog [options] //depot/path[@revRange]"3517 self.options += [3518 optparse.make_option("--destination", dest="cloneDestination",3519 action='store', default=None,3520help="where to leave result of the clone"),3521 optparse.make_option("--bare", dest="cloneBare",3522 action="store_true", default=False),3523]3524 self.cloneDestination =None3525 self.needsGit =False3526 self.cloneBare =False35273528defdefaultDestination(self, args):3529## TODO: use common prefix of args?3530 depotPath = args[0]3531 depotDir = re.sub("(@[^@]*)$","", depotPath)3532 depotDir = re.sub("(#[^#]*)$","", depotDir)3533 depotDir = re.sub(r"\.\.\.$","", depotDir)3534 depotDir = re.sub(r"/$","", depotDir)3535return os.path.split(depotDir)[1]35363537defrun(self, args):3538iflen(args) <1:3539return False35403541if self.keepRepoPath and not self.cloneDestination:3542 sys.stderr.write("Must specify destination for --keep-path\n")3543 sys.exit(1)35443545 depotPaths = args35463547if not self.cloneDestination andlen(depotPaths) >1:3548 self.cloneDestination = depotPaths[-1]3549 depotPaths = depotPaths[:-1]35503551 self.cloneExclude = ["/"+p for p in self.cloneExclude]3552for p in depotPaths:3553if not p.startswith("//"):3554 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3555return False35563557if not self.cloneDestination:3558 self.cloneDestination = self.defaultDestination(args)35593560print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)35613562if not os.path.exists(self.cloneDestination):3563 os.makedirs(self.cloneDestination)3564chdir(self.cloneDestination)35653566 init_cmd = ["git","init"]3567if self.cloneBare:3568 init_cmd.append("--bare")3569 retcode = subprocess.call(init_cmd)3570if retcode:3571raiseCalledProcessError(retcode, init_cmd)35723573if not P4Sync.run(self, depotPaths):3574return False35753576# create a master branch and check out a work tree3577ifgitBranchExists(self.branch):3578system(["git","branch","master", self.branch ])3579if not self.cloneBare:3580system(["git","checkout","-f"])3581else:3582print'Not checking out any branch, use ' \3583'"git checkout -q -b master <branch>"'35843585# auto-set this variable if invoked with --use-client-spec3586if self.useClientSpec_from_options:3587system("git config --bool git-p4.useclientspec true")35883589return True35903591classP4Branches(Command):3592def__init__(self):3593 Command.__init__(self)3594 self.options = [ ]3595 self.description = ("Shows the git branches that hold imports and their "3596+"corresponding perforce depot paths")3597 self.verbose =False35983599defrun(self, args):3600iforiginP4BranchesExist():3601createOrUpdateBranchesFromOrigin()36023603 cmdline ="git rev-parse --symbolic "3604 cmdline +=" --remotes"36053606for line inread_pipe_lines(cmdline):3607 line = line.strip()36083609if not line.startswith('p4/')or line =="p4/HEAD":3610continue3611 branch = line36123613 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3614 settings =extractSettingsGitLog(log)36153616print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3617return True36183619classHelpFormatter(optparse.IndentedHelpFormatter):3620def__init__(self):3621 optparse.IndentedHelpFormatter.__init__(self)36223623defformat_description(self, description):3624if description:3625return description +"\n"3626else:3627return""36283629defprintUsage(commands):3630print"usage:%s<command> [options]"% sys.argv[0]3631print""3632print"valid commands:%s"%", ".join(commands)3633print""3634print"Try%s<command> --help for command specific help."% sys.argv[0]3635print""36363637commands = {3638"debug": P4Debug,3639"submit": P4Submit,3640"commit": P4Submit,3641"sync": P4Sync,3642"rebase": P4Rebase,3643"clone": P4Clone,3644"rollback": P4RollBack,3645"branches": P4Branches3646}364736483649defmain():3650iflen(sys.argv[1:]) ==0:3651printUsage(commands.keys())3652 sys.exit(2)36533654 cmdName = sys.argv[1]3655try:3656 klass = commands[cmdName]3657 cmd =klass()3658exceptKeyError:3659print"unknown command%s"% cmdName3660print""3661printUsage(commands.keys())3662 sys.exit(2)36633664 options = cmd.options3665 cmd.gitdir = os.environ.get("GIT_DIR",None)36663667 args = sys.argv[2:]36683669 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3670if cmd.needsGit:3671 options.append(optparse.make_option("--git-dir", dest="gitdir"))36723673 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3674 options,3675 description = cmd.description,3676 formatter =HelpFormatter())36773678(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3679global verbose3680 verbose = cmd.verbose3681if cmd.needsGit:3682if cmd.gitdir ==None:3683 cmd.gitdir = os.path.abspath(".git")3684if notisValidGitDir(cmd.gitdir):3685 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3686if os.path.exists(cmd.gitdir):3687 cdup =read_pipe("git rev-parse --show-cdup").strip()3688iflen(cdup) >0:3689chdir(cdup);36903691if notisValidGitDir(cmd.gitdir):3692ifisValidGitDir(cmd.gitdir +"/.git"):3693 cmd.gitdir +="/.git"3694else:3695die("fatal: cannot locate git repository at%s"% cmd.gitdir)36963697 os.environ["GIT_DIR"] = cmd.gitdir36983699if not cmd.run(args):3700 parser.print_help()3701 sys.exit(2)370237033704if __name__ =='__main__':3705main()