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# 10 11import optparse, sys, os, marshal, subprocess, shelve 12import tempfile, getopt, os.path, time, platform 13import re, shutil 14 15verbose =False 16 17# Only labels/tags matching this will be imported/exported 18defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 19 20defp4_build_cmd(cmd): 21"""Build a suitable p4 command line. 22 23 This consolidates building and returning a p4 command line into one 24 location. It means that hooking into the environment, or other configuration 25 can be done more easily. 26 """ 27 real_cmd = ["p4"] 28 29 user =gitConfig("git-p4.user") 30iflen(user) >0: 31 real_cmd += ["-u",user] 32 33 password =gitConfig("git-p4.password") 34iflen(password) >0: 35 real_cmd += ["-P", password] 36 37 port =gitConfig("git-p4.port") 38iflen(port) >0: 39 real_cmd += ["-p", port] 40 41 host =gitConfig("git-p4.host") 42iflen(host) >0: 43 real_cmd += ["-H", host] 44 45 client =gitConfig("git-p4.client") 46iflen(client) >0: 47 real_cmd += ["-c", client] 48 49 50ifisinstance(cmd,basestring): 51 real_cmd =' '.join(real_cmd) +' '+ cmd 52else: 53 real_cmd += cmd 54return real_cmd 55 56defchdir(dir): 57# P4 uses the PWD environment variable rather than getcwd(). Since we're 58# not using the shell, we have to set it ourselves. This path could 59# be relative, so go there first, then figure out where we ended up. 60 os.chdir(dir) 61 os.environ['PWD'] = os.getcwd() 62 63defdie(msg): 64if verbose: 65raiseException(msg) 66else: 67 sys.stderr.write(msg +"\n") 68 sys.exit(1) 69 70defwrite_pipe(c, stdin): 71if verbose: 72 sys.stderr.write('Writing pipe:%s\n'%str(c)) 73 74 expand =isinstance(c,basestring) 75 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 76 pipe = p.stdin 77 val = pipe.write(stdin) 78 pipe.close() 79if p.wait(): 80die('Command failed:%s'%str(c)) 81 82return val 83 84defp4_write_pipe(c, stdin): 85 real_cmd =p4_build_cmd(c) 86returnwrite_pipe(real_cmd, stdin) 87 88defread_pipe(c, ignore_error=False): 89if verbose: 90 sys.stderr.write('Reading pipe:%s\n'%str(c)) 91 92 expand =isinstance(c,basestring) 93 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 94 pipe = p.stdout 95 val = pipe.read() 96if p.wait()and not ignore_error: 97die('Command failed:%s'%str(c)) 98 99return val 100 101defp4_read_pipe(c, ignore_error=False): 102 real_cmd =p4_build_cmd(c) 103returnread_pipe(real_cmd, ignore_error) 104 105defread_pipe_lines(c): 106if verbose: 107 sys.stderr.write('Reading pipe:%s\n'%str(c)) 108 109 expand =isinstance(c, basestring) 110 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 111 pipe = p.stdout 112 val = pipe.readlines() 113if pipe.close()or p.wait(): 114die('Command failed:%s'%str(c)) 115 116return val 117 118defp4_read_pipe_lines(c): 119"""Specifically invoke p4 on the command supplied. """ 120 real_cmd =p4_build_cmd(c) 121returnread_pipe_lines(real_cmd) 122 123defp4_has_command(cmd): 124"""Ask p4 for help on this command. If it returns an error, the 125 command does not exist in this version of p4.""" 126 real_cmd =p4_build_cmd(["help", cmd]) 127 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 128 stderr=subprocess.PIPE) 129 p.communicate() 130return p.returncode ==0 131 132defp4_has_move_command(): 133"""See if the move command exists, that it supports -k, and that 134 it has not been administratively disabled. The arguments 135 must be correct, but the filenames do not have to exist. Use 136 ones with wildcards so even if they exist, it will fail.""" 137 138if notp4_has_command("move"): 139return False 140 cmd =p4_build_cmd(["move","-k","@from","@to"]) 141 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 142(out, err) = p.communicate() 143# return code will be 1 in either case 144if err.find("Invalid option") >=0: 145return False 146if err.find("disabled") >=0: 147return False 148# assume it failed because @... was invalid changelist 149return True 150 151defsystem(cmd): 152 expand =isinstance(cmd,basestring) 153if verbose: 154 sys.stderr.write("executing%s\n"%str(cmd)) 155 subprocess.check_call(cmd, shell=expand) 156 157defp4_system(cmd): 158"""Specifically invoke p4 as the system command. """ 159 real_cmd =p4_build_cmd(cmd) 160 expand =isinstance(real_cmd, basestring) 161 subprocess.check_call(real_cmd, shell=expand) 162 163defp4_integrate(src, dest): 164p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 165 166defp4_sync(f, *options): 167p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 168 169defp4_add(f): 170# forcibly add file names with wildcards 171ifwildcard_present(f): 172p4_system(["add","-f", f]) 173else: 174p4_system(["add", f]) 175 176defp4_delete(f): 177p4_system(["delete",wildcard_encode(f)]) 178 179defp4_edit(f): 180p4_system(["edit",wildcard_encode(f)]) 181 182defp4_revert(f): 183p4_system(["revert",wildcard_encode(f)]) 184 185defp4_reopen(type, f): 186p4_system(["reopen","-t",type,wildcard_encode(f)]) 187 188defp4_move(src, dest): 189p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 190 191defp4_describe(change): 192"""Make sure it returns a valid result by checking for 193 the presence of field "time". Return a dict of the 194 results.""" 195 196 ds =p4CmdList(["describe","-s",str(change)]) 197iflen(ds) !=1: 198die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 199 200 d = ds[0] 201 202if"p4ExitCode"in d: 203die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 204str(d))) 205if"code"in d: 206if d["code"] =="error": 207die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 208 209if"time"not in d: 210die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 211 212return d 213 214# 215# Canonicalize the p4 type and return a tuple of the 216# base type, plus any modifiers. See "p4 help filetypes" 217# for a list and explanation. 218# 219defsplit_p4_type(p4type): 220 221 p4_filetypes_historical = { 222"ctempobj":"binary+Sw", 223"ctext":"text+C", 224"cxtext":"text+Cx", 225"ktext":"text+k", 226"kxtext":"text+kx", 227"ltext":"text+F", 228"tempobj":"binary+FSw", 229"ubinary":"binary+F", 230"uresource":"resource+F", 231"uxbinary":"binary+Fx", 232"xbinary":"binary+x", 233"xltext":"text+Fx", 234"xtempobj":"binary+Swx", 235"xtext":"text+x", 236"xunicode":"unicode+x", 237"xutf16":"utf16+x", 238} 239if p4type in p4_filetypes_historical: 240 p4type = p4_filetypes_historical[p4type] 241 mods ="" 242 s = p4type.split("+") 243 base = s[0] 244 mods ="" 245iflen(s) >1: 246 mods = s[1] 247return(base, mods) 248 249# 250# return the raw p4 type of a file (text, text+ko, etc) 251# 252defp4_type(file): 253 results =p4CmdList(["fstat","-T","headType",file]) 254return results[0]['headType'] 255 256# 257# Given a type base and modifier, return a regexp matching 258# the keywords that can be expanded in the file 259# 260defp4_keywords_regexp_for_type(base, type_mods): 261if base in("text","unicode","binary"): 262 kwords =None 263if"ko"in type_mods: 264 kwords ='Id|Header' 265elif"k"in type_mods: 266 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 267else: 268return None 269 pattern = r""" 270 \$ # Starts with a dollar, followed by... 271 (%s) # one of the keywords, followed by... 272 (:[^$\n]+)? # possibly an old expansion, followed by... 273 \$ # another dollar 274 """% kwords 275return pattern 276else: 277return None 278 279# 280# Given a file, return a regexp matching the possible 281# RCS keywords that will be expanded, or None for files 282# with kw expansion turned off. 283# 284defp4_keywords_regexp_for_file(file): 285if not os.path.exists(file): 286return None 287else: 288(type_base, type_mods) =split_p4_type(p4_type(file)) 289returnp4_keywords_regexp_for_type(type_base, type_mods) 290 291defsetP4ExecBit(file, mode): 292# Reopens an already open file and changes the execute bit to match 293# the execute bit setting in the passed in mode. 294 295 p4Type ="+x" 296 297if notisModeExec(mode): 298 p4Type =getP4OpenedType(file) 299 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 300 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 301if p4Type[-1] =="+": 302 p4Type = p4Type[0:-1] 303 304p4_reopen(p4Type,file) 305 306defgetP4OpenedType(file): 307# Returns the perforce file type for the given file. 308 309 result =p4_read_pipe(["opened",wildcard_encode(file)]) 310 match = re.match(".*\((.+)\)\r?$", result) 311if match: 312return match.group(1) 313else: 314die("Could not determine file type for%s(result: '%s')"% (file, result)) 315 316# Return the set of all p4 labels 317defgetP4Labels(depotPaths): 318 labels =set() 319ifisinstance(depotPaths,basestring): 320 depotPaths = [depotPaths] 321 322for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 323 label = l['label'] 324 labels.add(label) 325 326return labels 327 328# Return the set of all git tags 329defgetGitTags(): 330 gitTags =set() 331for line inread_pipe_lines(["git","tag"]): 332 tag = line.strip() 333 gitTags.add(tag) 334return gitTags 335 336defdiffTreePattern(): 337# This is a simple generator for the diff tree regex pattern. This could be 338# a class variable if this and parseDiffTreeEntry were a part of a class. 339 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 340while True: 341yield pattern 342 343defparseDiffTreeEntry(entry): 344"""Parses a single diff tree entry into its component elements. 345 346 See git-diff-tree(1) manpage for details about the format of the diff 347 output. This method returns a dictionary with the following elements: 348 349 src_mode - The mode of the source file 350 dst_mode - The mode of the destination file 351 src_sha1 - The sha1 for the source file 352 dst_sha1 - The sha1 fr the destination file 353 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 354 status_score - The score for the status (applicable for 'C' and 'R' 355 statuses). This is None if there is no score. 356 src - The path for the source file. 357 dst - The path for the destination file. This is only present for 358 copy or renames. If it is not present, this is None. 359 360 If the pattern is not matched, None is returned.""" 361 362 match =diffTreePattern().next().match(entry) 363if match: 364return{ 365'src_mode': match.group(1), 366'dst_mode': match.group(2), 367'src_sha1': match.group(3), 368'dst_sha1': match.group(4), 369'status': match.group(5), 370'status_score': match.group(6), 371'src': match.group(7), 372'dst': match.group(10) 373} 374return None 375 376defisModeExec(mode): 377# Returns True if the given git mode represents an executable file, 378# otherwise False. 379return mode[-3:] =="755" 380 381defisModeExecChanged(src_mode, dst_mode): 382returnisModeExec(src_mode) !=isModeExec(dst_mode) 383 384defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 385 386ifisinstance(cmd,basestring): 387 cmd ="-G "+ cmd 388 expand =True 389else: 390 cmd = ["-G"] + cmd 391 expand =False 392 393 cmd =p4_build_cmd(cmd) 394if verbose: 395 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 396 397# Use a temporary file to avoid deadlocks without 398# subprocess.communicate(), which would put another copy 399# of stdout into memory. 400 stdin_file =None 401if stdin is not None: 402 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 403ifisinstance(stdin,basestring): 404 stdin_file.write(stdin) 405else: 406for i in stdin: 407 stdin_file.write(i +'\n') 408 stdin_file.flush() 409 stdin_file.seek(0) 410 411 p4 = subprocess.Popen(cmd, 412 shell=expand, 413 stdin=stdin_file, 414 stdout=subprocess.PIPE) 415 416 result = [] 417try: 418while True: 419 entry = marshal.load(p4.stdout) 420if cb is not None: 421cb(entry) 422else: 423 result.append(entry) 424exceptEOFError: 425pass 426 exitCode = p4.wait() 427if exitCode !=0: 428 entry = {} 429 entry["p4ExitCode"] = exitCode 430 result.append(entry) 431 432return result 433 434defp4Cmd(cmd): 435list=p4CmdList(cmd) 436 result = {} 437for entry inlist: 438 result.update(entry) 439return result; 440 441defp4Where(depotPath): 442if not depotPath.endswith("/"): 443 depotPath +="/" 444 depotPath = depotPath +"..." 445 outputList =p4CmdList(["where", depotPath]) 446 output =None 447for entry in outputList: 448if"depotFile"in entry: 449if entry["depotFile"] == depotPath: 450 output = entry 451break 452elif"data"in entry: 453 data = entry.get("data") 454 space = data.find(" ") 455if data[:space] == depotPath: 456 output = entry 457break 458if output ==None: 459return"" 460if output["code"] =="error": 461return"" 462 clientPath ="" 463if"path"in output: 464 clientPath = output.get("path") 465elif"data"in output: 466 data = output.get("data") 467 lastSpace = data.rfind(" ") 468 clientPath = data[lastSpace +1:] 469 470if clientPath.endswith("..."): 471 clientPath = clientPath[:-3] 472return clientPath 473 474defcurrentGitBranch(): 475returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 476 477defisValidGitDir(path): 478if(os.path.exists(path +"/HEAD") 479and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 480return True; 481return False 482 483defparseRevision(ref): 484returnread_pipe("git rev-parse%s"% ref).strip() 485 486defbranchExists(ref): 487 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 488 ignore_error=True) 489returnlen(rev) >0 490 491defextractLogMessageFromGitCommit(commit): 492 logMessage ="" 493 494## fixme: title is first line of commit, not 1st paragraph. 495 foundTitle =False 496for log inread_pipe_lines("git cat-file commit%s"% commit): 497if not foundTitle: 498iflen(log) ==1: 499 foundTitle =True 500continue 501 502 logMessage += log 503return logMessage 504 505defextractSettingsGitLog(log): 506 values = {} 507for line in log.split("\n"): 508 line = line.strip() 509 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 510if not m: 511continue 512 513 assignments = m.group(1).split(':') 514for a in assignments: 515 vals = a.split('=') 516 key = vals[0].strip() 517 val = ('='.join(vals[1:])).strip() 518if val.endswith('\"')and val.startswith('"'): 519 val = val[1:-1] 520 521 values[key] = val 522 523 paths = values.get("depot-paths") 524if not paths: 525 paths = values.get("depot-path") 526if paths: 527 values['depot-paths'] = paths.split(',') 528return values 529 530defgitBranchExists(branch): 531 proc = subprocess.Popen(["git","rev-parse", branch], 532 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 533return proc.wait() ==0; 534 535_gitConfig = {} 536defgitConfig(key, args =None):# set args to "--bool", for instance 537if not _gitConfig.has_key(key): 538 argsFilter ="" 539if args !=None: 540 argsFilter ="%s"% args 541 cmd ="git config%s%s"% (argsFilter, key) 542 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 543return _gitConfig[key] 544 545defgitConfigList(key): 546if not _gitConfig.has_key(key): 547 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 548return _gitConfig[key] 549 550defp4BranchesInGit(branchesAreInRemotes =True): 551 branches = {} 552 553 cmdline ="git rev-parse --symbolic " 554if branchesAreInRemotes: 555 cmdline +=" --remotes" 556else: 557 cmdline +=" --branches" 558 559for line inread_pipe_lines(cmdline): 560 line = line.strip() 561 562## only import to p4/ 563if not line.startswith('p4/')or line =="p4/HEAD": 564continue 565 branch = line 566 567# strip off p4 568 branch = re.sub("^p4/","", line) 569 570 branches[branch] =parseRevision(line) 571return branches 572 573deffindUpstreamBranchPoint(head ="HEAD"): 574 branches =p4BranchesInGit() 575# map from depot-path to branch name 576 branchByDepotPath = {} 577for branch in branches.keys(): 578 tip = branches[branch] 579 log =extractLogMessageFromGitCommit(tip) 580 settings =extractSettingsGitLog(log) 581if settings.has_key("depot-paths"): 582 paths =",".join(settings["depot-paths"]) 583 branchByDepotPath[paths] ="remotes/p4/"+ branch 584 585 settings =None 586 parent =0 587while parent <65535: 588 commit = head +"~%s"% parent 589 log =extractLogMessageFromGitCommit(commit) 590 settings =extractSettingsGitLog(log) 591if settings.has_key("depot-paths"): 592 paths =",".join(settings["depot-paths"]) 593if branchByDepotPath.has_key(paths): 594return[branchByDepotPath[paths], settings] 595 596 parent = parent +1 597 598return["", settings] 599 600defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 601if not silent: 602print("Creating/updating branch(es) in%sbased on origin branch(es)" 603% localRefPrefix) 604 605 originPrefix ="origin/p4/" 606 607for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 608 line = line.strip() 609if(not line.startswith(originPrefix))or line.endswith("HEAD"): 610continue 611 612 headName = line[len(originPrefix):] 613 remoteHead = localRefPrefix + headName 614 originHead = line 615 616 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 617if(not original.has_key('depot-paths') 618or not original.has_key('change')): 619continue 620 621 update =False 622if notgitBranchExists(remoteHead): 623if verbose: 624print"creating%s"% remoteHead 625 update =True 626else: 627 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 628if settings.has_key('change') >0: 629if settings['depot-paths'] == original['depot-paths']: 630 originP4Change =int(original['change']) 631 p4Change =int(settings['change']) 632if originP4Change > p4Change: 633print("%s(%s) is newer than%s(%s). " 634"Updating p4 branch from origin." 635% (originHead, originP4Change, 636 remoteHead, p4Change)) 637 update =True 638else: 639print("Ignoring:%swas imported from%swhile " 640"%swas imported from%s" 641% (originHead,','.join(original['depot-paths']), 642 remoteHead,','.join(settings['depot-paths']))) 643 644if update: 645system("git update-ref%s %s"% (remoteHead, originHead)) 646 647deforiginP4BranchesExist(): 648returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 649 650defp4ChangesForPaths(depotPaths, changeRange): 651assert depotPaths 652 cmd = ['changes'] 653for p in depotPaths: 654 cmd += ["%s...%s"% (p, changeRange)] 655 output =p4_read_pipe_lines(cmd) 656 657 changes = {} 658for line in output: 659 changeNum =int(line.split(" ")[1]) 660 changes[changeNum] =True 661 662 changelist = changes.keys() 663 changelist.sort() 664return changelist 665 666defp4PathStartsWith(path, prefix): 667# This method tries to remedy a potential mixed-case issue: 668# 669# If UserA adds //depot/DirA/file1 670# and UserB adds //depot/dira/file2 671# 672# we may or may not have a problem. If you have core.ignorecase=true, 673# we treat DirA and dira as the same directory 674 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 675if ignorecase: 676return path.lower().startswith(prefix.lower()) 677return path.startswith(prefix) 678 679defgetClientSpec(): 680"""Look at the p4 client spec, create a View() object that contains 681 all the mappings, and return it.""" 682 683 specList =p4CmdList("client -o") 684iflen(specList) !=1: 685die('Output from "client -o" is%dlines, expecting 1'% 686len(specList)) 687 688# dictionary of all client parameters 689 entry = specList[0] 690 691# just the keys that start with "View" 692 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 693 694# hold this new View 695 view =View() 696 697# append the lines, in order, to the view 698for view_num inrange(len(view_keys)): 699 k ="View%d"% view_num 700if k not in view_keys: 701die("Expected view key%smissing"% k) 702 view.append(entry[k]) 703 704return view 705 706defgetClientRoot(): 707"""Grab the client directory.""" 708 709 output =p4CmdList("client -o") 710iflen(output) !=1: 711die('Output from "client -o" is%dlines, expecting 1'%len(output)) 712 713 entry = output[0] 714if"Root"not in entry: 715die('Client has no "Root"') 716 717return entry["Root"] 718 719# 720# P4 wildcards are not allowed in filenames. P4 complains 721# if you simply add them, but you can force it with "-f", in 722# which case it translates them into %xx encoding internally. 723# 724defwildcard_decode(path): 725# Search for and fix just these four characters. Do % last so 726# that fixing it does not inadvertently create new %-escapes. 727# Cannot have * in a filename in windows; untested as to 728# what p4 would do in such a case. 729if not platform.system() =="Windows": 730 path = path.replace("%2A","*") 731 path = path.replace("%23","#") \ 732.replace("%40","@") \ 733.replace("%25","%") 734return path 735 736defwildcard_encode(path): 737# do % first to avoid double-encoding the %s introduced here 738 path = path.replace("%","%25") \ 739.replace("*","%2A") \ 740.replace("#","%23") \ 741.replace("@","%40") 742return path 743 744defwildcard_present(path): 745return path.translate(None,"*#@%") != path 746 747class Command: 748def__init__(self): 749 self.usage ="usage: %prog [options]" 750 self.needsGit =True 751 self.verbose =False 752 753class P4UserMap: 754def__init__(self): 755 self.userMapFromPerforceServer =False 756 self.myP4UserId =None 757 758defp4UserId(self): 759if self.myP4UserId: 760return self.myP4UserId 761 762 results =p4CmdList("user -o") 763for r in results: 764if r.has_key('User'): 765 self.myP4UserId = r['User'] 766return r['User'] 767die("Could not find your p4 user id") 768 769defp4UserIsMe(self, p4User): 770# return True if the given p4 user is actually me 771 me = self.p4UserId() 772if not p4User or p4User != me: 773return False 774else: 775return True 776 777defgetUserCacheFilename(self): 778 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 779return home +"/.gitp4-usercache.txt" 780 781defgetUserMapFromPerforceServer(self): 782if self.userMapFromPerforceServer: 783return 784 self.users = {} 785 self.emails = {} 786 787for output inp4CmdList("users"): 788if not output.has_key("User"): 789continue 790 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 791 self.emails[output["Email"]] = output["User"] 792 793 794 s ='' 795for(key, val)in self.users.items(): 796 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 797 798open(self.getUserCacheFilename(),"wb").write(s) 799 self.userMapFromPerforceServer =True 800 801defloadUserMapFromCache(self): 802 self.users = {} 803 self.userMapFromPerforceServer =False 804try: 805 cache =open(self.getUserCacheFilename(),"rb") 806 lines = cache.readlines() 807 cache.close() 808for line in lines: 809 entry = line.strip().split("\t") 810 self.users[entry[0]] = entry[1] 811exceptIOError: 812 self.getUserMapFromPerforceServer() 813 814classP4Debug(Command): 815def__init__(self): 816 Command.__init__(self) 817 self.options = [] 818 self.description ="A tool to debug the output of p4 -G." 819 self.needsGit =False 820 821defrun(self, args): 822 j =0 823for output inp4CmdList(args): 824print'Element:%d'% j 825 j +=1 826print output 827return True 828 829classP4RollBack(Command): 830def__init__(self): 831 Command.__init__(self) 832 self.options = [ 833 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 834] 835 self.description ="A tool to debug the multi-branch import. Don't use :)" 836 self.rollbackLocalBranches =False 837 838defrun(self, args): 839iflen(args) !=1: 840return False 841 maxChange =int(args[0]) 842 843if"p4ExitCode"inp4Cmd("changes -m 1"): 844die("Problems executing p4"); 845 846if self.rollbackLocalBranches: 847 refPrefix ="refs/heads/" 848 lines =read_pipe_lines("git rev-parse --symbolic --branches") 849else: 850 refPrefix ="refs/remotes/" 851 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 852 853for line in lines: 854if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 855 line = line.strip() 856 ref = refPrefix + line 857 log =extractLogMessageFromGitCommit(ref) 858 settings =extractSettingsGitLog(log) 859 860 depotPaths = settings['depot-paths'] 861 change = settings['change'] 862 863 changed =False 864 865iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 866for p in depotPaths]))) ==0: 867print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 868system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 869continue 870 871while change andint(change) > maxChange: 872 changed =True 873if self.verbose: 874print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 875system("git update-ref%s\"%s^\""% (ref, ref)) 876 log =extractLogMessageFromGitCommit(ref) 877 settings =extractSettingsGitLog(log) 878 879 880 depotPaths = settings['depot-paths'] 881 change = settings['change'] 882 883if changed: 884print"%srewound to%s"% (ref, change) 885 886return True 887 888classP4Submit(Command, P4UserMap): 889 890 conflict_behavior_choices = ("ask","skip","quit") 891 892def__init__(self): 893 Command.__init__(self) 894 P4UserMap.__init__(self) 895 self.options = [ 896 optparse.make_option("--origin", dest="origin"), 897 optparse.make_option("-M", dest="detectRenames", action="store_true"), 898# preserve the user, requires relevant p4 permissions 899 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 900 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), 901 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"), 902 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), 903 optparse.make_option("--conflict", dest="conflict_behavior", 904 choices=self.conflict_behavior_choices) 905] 906 self.description ="Submit changes from git to the perforce depot." 907 self.usage +=" [name of git branch to submit into perforce depot]" 908 self.origin ="" 909 self.detectRenames =False 910 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 911 self.dry_run =False 912 self.prepare_p4_only =False 913 self.conflict_behavior =None 914 self.isWindows = (platform.system() =="Windows") 915 self.exportLabels =False 916 self.p4HasMoveCommand =p4_has_move_command() 917 918defcheck(self): 919iflen(p4CmdList("opened ...")) >0: 920die("You have files opened with perforce! Close them before starting the sync.") 921 922defseparate_jobs_from_description(self, message): 923"""Extract and return a possible Jobs field in the commit 924 message. It goes into a separate section in the p4 change 925 specification. 926 927 A jobs line starts with "Jobs:" and looks like a new field 928 in a form. Values are white-space separated on the same 929 line or on following lines that start with a tab. 930 931 This does not parse and extract the full git commit message 932 like a p4 form. It just sees the Jobs: line as a marker 933 to pass everything from then on directly into the p4 form, 934 but outside the description section. 935 936 Return a tuple (stripped log message, jobs string).""" 937 938 m = re.search(r'^Jobs:', message, re.MULTILINE) 939if m is None: 940return(message,None) 941 942 jobtext = message[m.start():] 943 stripped_message = message[:m.start()].rstrip() 944return(stripped_message, jobtext) 945 946defprepareLogMessage(self, template, message, jobs): 947"""Edits the template returned from "p4 change -o" to insert 948 the message in the Description field, and the jobs text in 949 the Jobs field.""" 950 result ="" 951 952 inDescriptionSection =False 953 954for line in template.split("\n"): 955if line.startswith("#"): 956 result += line +"\n" 957continue 958 959if inDescriptionSection: 960if line.startswith("Files:")or line.startswith("Jobs:"): 961 inDescriptionSection =False 962# insert Jobs section 963if jobs: 964 result += jobs +"\n" 965else: 966continue 967else: 968if line.startswith("Description:"): 969 inDescriptionSection =True 970 line +="\n" 971for messageLine in message.split("\n"): 972 line +="\t"+ messageLine +"\n" 973 974 result += line +"\n" 975 976return result 977 978defpatchRCSKeywords(self,file, pattern): 979# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern 980(handle, outFileName) = tempfile.mkstemp(dir='.') 981try: 982 outFile = os.fdopen(handle,"w+") 983 inFile =open(file,"r") 984 regexp = re.compile(pattern, re.VERBOSE) 985for line in inFile.readlines(): 986 line = regexp.sub(r'$\1$', line) 987 outFile.write(line) 988 inFile.close() 989 outFile.close() 990# Forcibly overwrite the original file 991 os.unlink(file) 992 shutil.move(outFileName,file) 993except: 994# cleanup our temporary file 995 os.unlink(outFileName) 996print"Failed to strip RCS keywords in%s"%file 997raise 998 999print"Patched up RCS keywords in%s"%file10001001defp4UserForCommit(self,id):1002# Return the tuple (perforce user,git email) for a given git commit id1003 self.getUserMapFromPerforceServer()1004 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id)1005 gitEmail = gitEmail.strip()1006if not self.emails.has_key(gitEmail):1007return(None,gitEmail)1008else:1009return(self.emails[gitEmail],gitEmail)10101011defcheckValidP4Users(self,commits):1012# check if any git authors cannot be mapped to p4 users1013foridin commits:1014(user,email) = self.p4UserForCommit(id)1015if not user:1016 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1017ifgitConfig('git-p4.allowMissingP4Users').lower() =="true":1018print"%s"% msg1019else:1020die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)10211022deflastP4Changelist(self):1023# Get back the last changelist number submitted in this client spec. This1024# then gets used to patch up the username in the change. If the same1025# client spec is being used by multiple processes then this might go1026# wrong.1027 results =p4CmdList("client -o")# find the current client1028 client =None1029for r in results:1030if r.has_key('Client'):1031 client = r['Client']1032break1033if not client:1034die("could not get client spec")1035 results =p4CmdList(["changes","-c", client,"-m","1"])1036for r in results:1037if r.has_key('change'):1038return r['change']1039die("Could not get changelist number for last submit - cannot patch up user details")10401041defmodifyChangelistUser(self, changelist, newUser):1042# fixup the user field of a changelist after it has been submitted.1043 changes =p4CmdList("change -o%s"% changelist)1044iflen(changes) !=1:1045die("Bad output from p4 change modifying%sto user%s"%1046(changelist, newUser))10471048 c = changes[0]1049if c['User'] == newUser:return# nothing to do1050 c['User'] = newUser1051input= marshal.dumps(c)10521053 result =p4CmdList("change -f -i", stdin=input)1054for r in result:1055if r.has_key('code'):1056if r['code'] =='error':1057die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1058if r.has_key('data'):1059print("Updated user field for changelist%sto%s"% (changelist, newUser))1060return1061die("Could not modify user field of changelist%sto%s"% (changelist, newUser))10621063defcanChangeChangelists(self):1064# check to see if we have p4 admin or super-user permissions, either of1065# which are required to modify changelists.1066 results =p4CmdList(["protects", self.depotPath])1067for r in results:1068if r.has_key('perm'):1069if r['perm'] =='admin':1070return11071if r['perm'] =='super':1072return11073return010741075defprepareSubmitTemplate(self):1076"""Run "p4 change -o" to grab a change specification template.1077 This does not use "p4 -G", as it is nice to keep the submission1078 template in original order, since a human might edit it.10791080 Remove lines in the Files section that show changes to files1081 outside the depot path we're committing into."""10821083 template =""1084 inFilesSection =False1085for line inp4_read_pipe_lines(['change','-o']):1086if line.endswith("\r\n"):1087 line = line[:-2] +"\n"1088if inFilesSection:1089if line.startswith("\t"):1090# path starts and ends with a tab1091 path = line[1:]1092 lastTab = path.rfind("\t")1093if lastTab != -1:1094 path = path[:lastTab]1095if notp4PathStartsWith(path, self.depotPath):1096continue1097else:1098 inFilesSection =False1099else:1100if line.startswith("Files:"):1101 inFilesSection =True11021103 template += line11041105return template11061107defedit_template(self, template_file):1108"""Invoke the editor to let the user change the submission1109 message. Return true if okay to continue with the submit."""11101111# if configured to skip the editing part, just submit1112ifgitConfig("git-p4.skipSubmitEdit") =="true":1113return True11141115# look at the modification time, to check later if the user saved1116# the file1117 mtime = os.stat(template_file).st_mtime11181119# invoke the editor1120if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1121 editor = os.environ.get("P4EDITOR")1122else:1123 editor =read_pipe("git var GIT_EDITOR").strip()1124system(editor +" "+ template_file)11251126# If the file was not saved, prompt to see if this patch should1127# be skipped. But skip this verification step if configured so.1128ifgitConfig("git-p4.skipSubmitEditCheck") =="true":1129return True11301131# modification time updated means user saved the file1132if os.stat(template_file).st_mtime > mtime:1133return True11341135while True:1136 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1137if response =='y':1138return True1139if response =='n':1140return False11411142defapplyCommit(self,id):1143"""Apply one commit, return True if it succeeded."""11441145print"Applying",read_pipe(["git","show","-s",1146"--format=format:%h%s",id])11471148(p4User, gitEmail) = self.p4UserForCommit(id)11491150 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1151 filesToAdd =set()1152 filesToDelete =set()1153 editedFiles =set()1154 pureRenameCopy =set()1155 filesToChangeExecBit = {}11561157for line in diff:1158 diff =parseDiffTreeEntry(line)1159 modifier = diff['status']1160 path = diff['src']1161if modifier =="M":1162p4_edit(path)1163ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1164 filesToChangeExecBit[path] = diff['dst_mode']1165 editedFiles.add(path)1166elif modifier =="A":1167 filesToAdd.add(path)1168 filesToChangeExecBit[path] = diff['dst_mode']1169if path in filesToDelete:1170 filesToDelete.remove(path)1171elif modifier =="D":1172 filesToDelete.add(path)1173if path in filesToAdd:1174 filesToAdd.remove(path)1175elif modifier =="C":1176 src, dest = diff['src'], diff['dst']1177p4_integrate(src, dest)1178 pureRenameCopy.add(dest)1179if diff['src_sha1'] != diff['dst_sha1']:1180p4_edit(dest)1181 pureRenameCopy.discard(dest)1182ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1183p4_edit(dest)1184 pureRenameCopy.discard(dest)1185 filesToChangeExecBit[dest] = diff['dst_mode']1186 os.unlink(dest)1187 editedFiles.add(dest)1188elif modifier =="R":1189 src, dest = diff['src'], diff['dst']1190if self.p4HasMoveCommand:1191p4_edit(src)# src must be open before move1192p4_move(src, dest)# opens for (move/delete, move/add)1193else:1194p4_integrate(src, dest)1195if diff['src_sha1'] != diff['dst_sha1']:1196p4_edit(dest)1197else:1198 pureRenameCopy.add(dest)1199ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1200if not self.p4HasMoveCommand:1201p4_edit(dest)# with move: already open, writable1202 filesToChangeExecBit[dest] = diff['dst_mode']1203if not self.p4HasMoveCommand:1204 os.unlink(dest)1205 filesToDelete.add(src)1206 editedFiles.add(dest)1207else:1208die("unknown modifier%sfor%s"% (modifier, path))12091210 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id)1211 patchcmd = diffcmd +" | git apply "1212 tryPatchCmd = patchcmd +"--check -"1213 applyPatchCmd = patchcmd +"--check --apply -"1214 patch_succeeded =True12151216if os.system(tryPatchCmd) !=0:1217 fixed_rcs_keywords =False1218 patch_succeeded =False1219print"Unfortunately applying the change failed!"12201221# Patch failed, maybe it's just RCS keyword woes. Look through1222# the patch to see if that's possible.1223ifgitConfig("git-p4.attemptRCSCleanup","--bool") =="true":1224file=None1225 pattern =None1226 kwfiles = {}1227forfilein editedFiles | filesToDelete:1228# did this file's delta contain RCS keywords?1229 pattern =p4_keywords_regexp_for_file(file)12301231if pattern:1232# this file is a possibility...look for RCS keywords.1233 regexp = re.compile(pattern, re.VERBOSE)1234for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1235if regexp.search(line):1236if verbose:1237print"got keyword match on%sin%sin%s"% (pattern, line,file)1238 kwfiles[file] = pattern1239break12401241forfilein kwfiles:1242if verbose:1243print"zapping%swith%s"% (line,pattern)1244 self.patchRCSKeywords(file, kwfiles[file])1245 fixed_rcs_keywords =True12461247if fixed_rcs_keywords:1248print"Retrying the patch with RCS keywords cleaned up"1249if os.system(tryPatchCmd) ==0:1250 patch_succeeded =True12511252if not patch_succeeded:1253for f in editedFiles:1254p4_revert(f)1255return False12561257#1258# Apply the patch for real, and do add/delete/+x handling.1259#1260system(applyPatchCmd)12611262for f in filesToAdd:1263p4_add(f)1264for f in filesToDelete:1265p4_revert(f)1266p4_delete(f)12671268# Set/clear executable bits1269for f in filesToChangeExecBit.keys():1270 mode = filesToChangeExecBit[f]1271setP4ExecBit(f, mode)12721273#1274# Build p4 change description, starting with the contents1275# of the git commit message.1276#1277 logMessage =extractLogMessageFromGitCommit(id)1278 logMessage = logMessage.strip()1279(logMessage, jobs) = self.separate_jobs_from_description(logMessage)12801281 template = self.prepareSubmitTemplate()1282 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)12831284if self.preserveUser:1285 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User12861287if self.checkAuthorship and not self.p4UserIsMe(p4User):1288 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1289 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1290 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"12911292 separatorLine ="######## everything below this line is just the diff #######\n"12931294# diff1295if os.environ.has_key("P4DIFF"):1296del(os.environ["P4DIFF"])1297 diff =""1298for editedFile in editedFiles:1299 diff +=p4_read_pipe(['diff','-du',1300wildcard_encode(editedFile)])13011302# new file diff1303 newdiff =""1304for newFile in filesToAdd:1305 newdiff +="==== new file ====\n"1306 newdiff +="--- /dev/null\n"1307 newdiff +="+++%s\n"% newFile1308 f =open(newFile,"r")1309for line in f.readlines():1310 newdiff +="+"+ line1311 f.close()13121313# change description file: submitTemplate, separatorLine, diff, newdiff1314(handle, fileName) = tempfile.mkstemp()1315 tmpFile = os.fdopen(handle,"w+")1316if self.isWindows:1317 submitTemplate = submitTemplate.replace("\n","\r\n")1318 separatorLine = separatorLine.replace("\n","\r\n")1319 newdiff = newdiff.replace("\n","\r\n")1320 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1321 tmpFile.close()13221323if self.prepare_p4_only:1324#1325# Leave the p4 tree prepared, and the submit template around1326# and let the user decide what to do next1327#1328print1329print"P4 workspace prepared for submission."1330print"To submit or revert, go to client workspace"1331print" "+ self.clientPath1332print1333print"To submit, use\"p4 submit\"to write a new description,"1334print"or\"p4 submit -i%s\"to use the one prepared by" \1335"\"git p4\"."% fileName1336print"You can delete the file\"%s\"when finished."% fileName13371338if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1339print"To preserve change ownership by user%s, you must\n" \1340"do\"p4 change -f <change>\"after submitting and\n" \1341"edit the User field."1342if pureRenameCopy:1343print"After submitting, renamed files must be re-synced."1344print"Invoke\"p4 sync -f\"on each of these files:"1345for f in pureRenameCopy:1346print" "+ f13471348print1349print"To revert the changes, use\"p4 revert ...\", and delete"1350print"the submit template file\"%s\""% fileName1351if filesToAdd:1352print"Since the commit adds new files, they must be deleted:"1353for f in filesToAdd:1354print" "+ f1355print1356return True13571358#1359# Let the user edit the change description, then submit it.1360#1361if self.edit_template(fileName):1362# read the edited message and submit1363 ret =True1364 tmpFile =open(fileName,"rb")1365 message = tmpFile.read()1366 tmpFile.close()1367 submitTemplate = message[:message.index(separatorLine)]1368if self.isWindows:1369 submitTemplate = submitTemplate.replace("\r\n","\n")1370p4_write_pipe(['submit','-i'], submitTemplate)13711372if self.preserveUser:1373if p4User:1374# Get last changelist number. Cannot easily get it from1375# the submit command output as the output is1376# unmarshalled.1377 changelist = self.lastP4Changelist()1378 self.modifyChangelistUser(changelist, p4User)13791380# The rename/copy happened by applying a patch that created a1381# new file. This leaves it writable, which confuses p4.1382for f in pureRenameCopy:1383p4_sync(f,"-f")13841385else:1386# skip this patch1387 ret =False1388print"Submission cancelled, undoing p4 changes."1389for f in editedFiles:1390p4_revert(f)1391for f in filesToAdd:1392p4_revert(f)1393 os.remove(f)1394for f in filesToDelete:1395p4_revert(f)13961397 os.remove(fileName)1398return ret13991400# Export git tags as p4 labels. Create a p4 label and then tag1401# with that.1402defexportGitTags(self, gitTags):1403 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1404iflen(validLabelRegexp) ==0:1405 validLabelRegexp = defaultLabelRegexp1406 m = re.compile(validLabelRegexp)14071408for name in gitTags:14091410if not m.match(name):1411if verbose:1412print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1413continue14141415# Get the p4 commit this corresponds to1416 logMessage =extractLogMessageFromGitCommit(name)1417 values =extractSettingsGitLog(logMessage)14181419if not values.has_key('change'):1420# a tag pointing to something not sent to p4; ignore1421if verbose:1422print"git tag%sdoes not give a p4 commit"% name1423continue1424else:1425 changelist = values['change']14261427# Get the tag details.1428 inHeader =True1429 isAnnotated =False1430 body = []1431for l inread_pipe_lines(["git","cat-file","-p", name]):1432 l = l.strip()1433if inHeader:1434if re.match(r'tag\s+', l):1435 isAnnotated =True1436elif re.match(r'\s*$', l):1437 inHeader =False1438continue1439else:1440 body.append(l)14411442if not isAnnotated:1443 body = ["lightweight tag imported by git p4\n"]14441445# Create the label - use the same view as the client spec we are using1446 clientSpec =getClientSpec()14471448 labelTemplate ="Label:%s\n"% name1449 labelTemplate +="Description:\n"1450for b in body:1451 labelTemplate +="\t"+ b +"\n"1452 labelTemplate +="View:\n"1453for mapping in clientSpec.mappings:1454 labelTemplate +="\t%s\n"% mapping.depot_side.path14551456if self.dry_run:1457print"Would create p4 label%sfor tag"% name1458elif self.prepare_p4_only:1459print"Not creating p4 label%sfor tag due to option" \1460" --prepare-p4-only"% name1461else:1462p4_write_pipe(["label","-i"], labelTemplate)14631464# Use the label1465p4_system(["tag","-l", name] +1466["%s@%s"% (mapping.depot_side.path, changelist)for mapping in clientSpec.mappings])14671468if verbose:1469print"created p4 label for tag%s"% name14701471defrun(self, args):1472iflen(args) ==0:1473 self.master =currentGitBranch()1474iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1475die("Detecting current git branch failed!")1476eliflen(args) ==1:1477 self.master = args[0]1478if notbranchExists(self.master):1479die("Branch%sdoes not exist"% self.master)1480else:1481return False14821483 allowSubmit =gitConfig("git-p4.allowSubmit")1484iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1485die("%sis not in git-p4.allowSubmit"% self.master)14861487[upstream, settings] =findUpstreamBranchPoint()1488 self.depotPath = settings['depot-paths'][0]1489iflen(self.origin) ==0:1490 self.origin = upstream14911492if self.preserveUser:1493if not self.canChangeChangelists():1494die("Cannot preserve user names without p4 super-user or admin permissions")14951496# if not set from the command line, try the config file1497if self.conflict_behavior is None:1498 val =gitConfig("git-p4.conflict")1499if val:1500if val not in self.conflict_behavior_choices:1501die("Invalid value '%s' for config git-p4.conflict"% val)1502else:1503 val ="ask"1504 self.conflict_behavior = val15051506if self.verbose:1507print"Origin branch is "+ self.origin15081509iflen(self.depotPath) ==0:1510print"Internal error: cannot locate perforce depot path from existing branches"1511 sys.exit(128)15121513 self.useClientSpec =False1514ifgitConfig("git-p4.useclientspec","--bool") =="true":1515 self.useClientSpec =True1516if self.useClientSpec:1517 self.clientSpecDirs =getClientSpec()15181519if self.useClientSpec:1520# all files are relative to the client spec1521 self.clientPath =getClientRoot()1522else:1523 self.clientPath =p4Where(self.depotPath)15241525if self.clientPath =="":1526die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)15271528print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1529 self.oldWorkingDirectory = os.getcwd()15301531# ensure the clientPath exists1532 new_client_dir =False1533if not os.path.exists(self.clientPath):1534 new_client_dir =True1535 os.makedirs(self.clientPath)15361537chdir(self.clientPath)1538if self.dry_run:1539print"Would synchronize p4 checkout in%s"% self.clientPath1540else:1541print"Synchronizing p4 checkout..."1542if new_client_dir:1543# old one was destroyed, and maybe nobody told p41544p4_sync("...","-f")1545else:1546p4_sync("...")1547 self.check()15481549 commits = []1550for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1551 commits.append(line.strip())1552 commits.reverse()15531554if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1555 self.checkAuthorship =False1556else:1557 self.checkAuthorship =True15581559if self.preserveUser:1560 self.checkValidP4Users(commits)15611562#1563# Build up a set of options to be passed to diff when1564# submitting each commit to p4.1565#1566if self.detectRenames:1567# command-line -M arg1568 self.diffOpts ="-M"1569else:1570# If not explicitly set check the config variable1571 detectRenames =gitConfig("git-p4.detectRenames")15721573if detectRenames.lower() =="false"or detectRenames =="":1574 self.diffOpts =""1575elif detectRenames.lower() =="true":1576 self.diffOpts ="-M"1577else:1578 self.diffOpts ="-M%s"% detectRenames15791580# no command-line arg for -C or --find-copies-harder, just1581# config variables1582 detectCopies =gitConfig("git-p4.detectCopies")1583if detectCopies.lower() =="false"or detectCopies =="":1584pass1585elif detectCopies.lower() =="true":1586 self.diffOpts +=" -C"1587else:1588 self.diffOpts +=" -C%s"% detectCopies15891590ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true":1591 self.diffOpts +=" --find-copies-harder"15921593#1594# Apply the commits, one at a time. On failure, ask if should1595# continue to try the rest of the patches, or quit.1596#1597if self.dry_run:1598print"Would apply"1599 applied = []1600 last =len(commits) -11601for i, commit inenumerate(commits):1602if self.dry_run:1603print" ",read_pipe(["git","show","-s",1604"--format=format:%h%s", commit])1605 ok =True1606else:1607 ok = self.applyCommit(commit)1608if ok:1609 applied.append(commit)1610else:1611if self.prepare_p4_only and i < last:1612print"Processing only the first commit due to option" \1613" --prepare-p4-only"1614break1615if i < last:1616 quit =False1617while True:1618# prompt for what to do, or use the option/variable1619if self.conflict_behavior =="ask":1620print"What do you want to do?"1621 response =raw_input("[s]kip this commit but apply"1622" the rest, or [q]uit? ")1623if not response:1624continue1625elif self.conflict_behavior =="skip":1626 response ="s"1627elif self.conflict_behavior =="quit":1628 response ="q"1629else:1630die("Unknown conflict_behavior '%s'"%1631 self.conflict_behavior)16321633if response[0] =="s":1634print"Skipping this commit, but applying the rest"1635break1636if response[0] =="q":1637print"Quitting"1638 quit =True1639break1640if quit:1641break16421643chdir(self.oldWorkingDirectory)16441645if self.dry_run:1646pass1647elif self.prepare_p4_only:1648pass1649eliflen(commits) ==len(applied):1650print"All commits applied!"16511652 sync =P4Sync()1653 sync.run([])16541655 rebase =P4Rebase()1656 rebase.rebase()16571658else:1659iflen(applied) ==0:1660print"No commits applied."1661else:1662print"Applied only the commits marked with '*':"1663for c in commits:1664if c in applied:1665 star ="*"1666else:1667 star =" "1668print star,read_pipe(["git","show","-s",1669"--format=format:%h%s", c])1670print"You will have to do 'git p4 sync' and rebase."16711672ifgitConfig("git-p4.exportLabels","--bool") =="true":1673 self.exportLabels =True16741675if self.exportLabels:1676 p4Labels =getP4Labels(self.depotPath)1677 gitTags =getGitTags()16781679 missingGitTags = gitTags - p4Labels1680 self.exportGitTags(missingGitTags)16811682# exit with error unless everything applied perfecly1683iflen(commits) !=len(applied):1684 sys.exit(1)16851686return True16871688classView(object):1689"""Represent a p4 view ("p4 help views"), and map files in a1690 repo according to the view."""16911692classPath(object):1693"""A depot or client path, possibly containing wildcards.1694 The only one supported is ... at the end, currently.1695 Initialize with the full path, with //depot or //client."""16961697def__init__(self, path, is_depot):1698 self.path = path1699 self.is_depot = is_depot1700 self.find_wildcards()1701# remember the prefix bit, useful for relative mappings1702 m = re.match("(//[^/]+/)", self.path)1703if not m:1704die("Path%sdoes not start with //prefix/"% self.path)1705 prefix = m.group(1)1706if not self.is_depot:1707# strip //client/ on client paths1708 self.path = self.path[len(prefix):]17091710deffind_wildcards(self):1711"""Make sure wildcards are valid, and set up internal1712 variables."""17131714 self.ends_triple_dot =False1715# There are three wildcards allowed in p4 views1716# (see "p4 help views"). This code knows how to1717# handle "..." (only at the end), but cannot deal with1718# "%%n" or "*". Only check the depot_side, as p4 should1719# validate that the client_side matches too.1720if re.search(r'%%[1-9]', self.path):1721die("Can't handle%%n wildcards in view:%s"% self.path)1722if self.path.find("*") >=0:1723die("Can't handle * wildcards in view:%s"% self.path)1724 triple_dot_index = self.path.find("...")1725if triple_dot_index >=0:1726if triple_dot_index !=len(self.path) -3:1727die("Can handle only single ... wildcard, at end:%s"%1728 self.path)1729 self.ends_triple_dot =True17301731defensure_compatible(self, other_path):1732"""Make sure the wildcards agree."""1733if self.ends_triple_dot != other_path.ends_triple_dot:1734die("Both paths must end with ... if either does;\n"+1735"paths:%s %s"% (self.path, other_path.path))17361737defmatch_wildcards(self, test_path):1738"""See if this test_path matches us, and fill in the value1739 of the wildcards if so. Returns a tuple of1740 (True|False, wildcards[]). For now, only the ... at end1741 is supported, so at most one wildcard."""1742if self.ends_triple_dot:1743 dotless = self.path[:-3]1744if test_path.startswith(dotless):1745 wildcard = test_path[len(dotless):]1746return(True, [ wildcard ])1747else:1748if test_path == self.path:1749return(True, [])1750return(False, [])17511752defmatch(self, test_path):1753"""Just return if it matches; don't bother with the wildcards."""1754 b, _ = self.match_wildcards(test_path)1755return b17561757deffill_in_wildcards(self, wildcards):1758"""Return the relative path, with the wildcards filled in1759 if there are any."""1760if self.ends_triple_dot:1761return self.path[:-3] + wildcards[0]1762else:1763return self.path17641765classMapping(object):1766def__init__(self, depot_side, client_side, overlay, exclude):1767# depot_side is without the trailing /... if it had one1768 self.depot_side = View.Path(depot_side, is_depot=True)1769 self.client_side = View.Path(client_side, is_depot=False)1770 self.overlay = overlay # started with "+"1771 self.exclude = exclude # started with "-"1772assert not(self.overlay and self.exclude)1773 self.depot_side.ensure_compatible(self.client_side)17741775def__str__(self):1776 c =" "1777if self.overlay:1778 c ="+"1779if self.exclude:1780 c ="-"1781return"View.Mapping:%s%s->%s"% \1782(c, self.depot_side.path, self.client_side.path)17831784defmap_depot_to_client(self, depot_path):1785"""Calculate the client path if using this mapping on the1786 given depot path; does not consider the effect of other1787 mappings in a view. Even excluded mappings are returned."""1788 matches, wildcards = self.depot_side.match_wildcards(depot_path)1789if not matches:1790return""1791 client_path = self.client_side.fill_in_wildcards(wildcards)1792return client_path17931794#1795# View methods1796#1797def__init__(self):1798 self.mappings = []17991800defappend(self, view_line):1801"""Parse a view line, splitting it into depot and client1802 sides. Append to self.mappings, preserving order."""18031804# Split the view line into exactly two words. P4 enforces1805# structure on these lines that simplifies this quite a bit.1806#1807# Either or both words may be double-quoted.1808# Single quotes do not matter.1809# Double-quote marks cannot occur inside the words.1810# A + or - prefix is also inside the quotes.1811# There are no quotes unless they contain a space.1812# The line is already white-space stripped.1813# The two words are separated by a single space.1814#1815if view_line[0] =='"':1816# First word is double quoted. Find its end.1817 close_quote_index = view_line.find('"',1)1818if close_quote_index <=0:1819die("No first-word closing quote found:%s"% view_line)1820 depot_side = view_line[1:close_quote_index]1821# skip closing quote and space1822 rhs_index = close_quote_index +1+11823else:1824 space_index = view_line.find(" ")1825if space_index <=0:1826die("No word-splitting space found:%s"% view_line)1827 depot_side = view_line[0:space_index]1828 rhs_index = space_index +118291830if view_line[rhs_index] =='"':1831# Second word is double quoted. Make sure there is a1832# double quote at the end too.1833if not view_line.endswith('"'):1834die("View line with rhs quote should end with one:%s"%1835 view_line)1836# skip the quotes1837 client_side = view_line[rhs_index+1:-1]1838else:1839 client_side = view_line[rhs_index:]18401841# prefix + means overlay on previous mapping1842 overlay =False1843if depot_side.startswith("+"):1844 overlay =True1845 depot_side = depot_side[1:]18461847# prefix - means exclude this path1848 exclude =False1849if depot_side.startswith("-"):1850 exclude =True1851 depot_side = depot_side[1:]18521853 m = View.Mapping(depot_side, client_side, overlay, exclude)1854 self.mappings.append(m)18551856defmap_in_client(self, depot_path):1857"""Return the relative location in the client where this1858 depot file should live. Returns "" if the file should1859 not be mapped in the client."""18601861 paths_filled = []1862 client_path =""18631864# look at later entries first1865for m in self.mappings[::-1]:18661867# see where will this path end up in the client1868 p = m.map_depot_to_client(depot_path)18691870if p =="":1871# Depot path does not belong in client. Must remember1872# this, as previous items should not cause files to1873# exist in this path either. Remember that the list is1874# being walked from the end, which has higher precedence.1875# Overlap mappings do not exclude previous mappings.1876if not m.overlay:1877 paths_filled.append(m.client_side)18781879else:1880# This mapping matched; no need to search any further.1881# But, the mapping could be rejected if the client path1882# has already been claimed by an earlier mapping (i.e.1883# one later in the list, which we are walking backwards).1884 already_mapped_in_client =False1885for f in paths_filled:1886# this is View.Path.match1887if f.match(p):1888 already_mapped_in_client =True1889break1890if not already_mapped_in_client:1891# Include this file, unless it is from a line that1892# explicitly said to exclude it.1893if not m.exclude:1894 client_path = p18951896# a match, even if rejected, always stops the search1897break18981899return client_path19001901classP4Sync(Command, P4UserMap):1902 delete_actions = ("delete","move/delete","purge")19031904def__init__(self):1905 Command.__init__(self)1906 P4UserMap.__init__(self)1907 self.options = [1908 optparse.make_option("--branch", dest="branch"),1909 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1910 optparse.make_option("--changesfile", dest="changesFile"),1911 optparse.make_option("--silent", dest="silent", action="store_true"),1912 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1913 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),1914 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1915help="Import into refs/heads/ , not refs/remotes"),1916 optparse.make_option("--max-changes", dest="maxChanges"),1917 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1918help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1919 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1920help="Only sync files that are included in the Perforce Client Spec")1921]1922 self.description ="""Imports from Perforce into a git repository.\n1923 example:1924 //depot/my/project/ -- to import the current head1925 //depot/my/project/@all -- to import everything1926 //depot/my/project/@1,6 -- to import only from revision 1 to 619271928 (a ... is not needed in the path p4 specification, it's added implicitly)"""19291930 self.usage +=" //depot/path[@revRange]"1931 self.silent =False1932 self.createdBranches =set()1933 self.committedChanges =set()1934 self.branch =""1935 self.detectBranches =False1936 self.detectLabels =False1937 self.importLabels =False1938 self.changesFile =""1939 self.syncWithOrigin =True1940 self.importIntoRemotes =True1941 self.maxChanges =""1942 self.isWindows = (platform.system() =="Windows")1943 self.keepRepoPath =False1944 self.depotPaths =None1945 self.p4BranchesInGit = []1946 self.cloneExclude = []1947 self.useClientSpec =False1948 self.useClientSpec_from_options =False1949 self.clientSpecDirs =None1950 self.tempBranches = []1951 self.tempBranchLocation ="git-p4-tmp"19521953ifgitConfig("git-p4.syncFromOrigin") =="false":1954 self.syncWithOrigin =False19551956# Force a checkpoint in fast-import and wait for it to finish1957defcheckpoint(self):1958 self.gitStream.write("checkpoint\n\n")1959 self.gitStream.write("progress checkpoint\n\n")1960 out = self.gitOutput.readline()1961if self.verbose:1962print"checkpoint finished: "+ out19631964defextractFilesFromCommit(self, commit):1965 self.cloneExclude = [re.sub(r"\.\.\.$","", path)1966for path in self.cloneExclude]1967 files = []1968 fnum =01969while commit.has_key("depotFile%s"% fnum):1970 path = commit["depotFile%s"% fnum]19711972if[p for p in self.cloneExclude1973ifp4PathStartsWith(path, p)]:1974 found =False1975else:1976 found = [p for p in self.depotPaths1977ifp4PathStartsWith(path, p)]1978if not found:1979 fnum = fnum +11980continue19811982file= {}1983file["path"] = path1984file["rev"] = commit["rev%s"% fnum]1985file["action"] = commit["action%s"% fnum]1986file["type"] = commit["type%s"% fnum]1987 files.append(file)1988 fnum = fnum +11989return files19901991defstripRepoPath(self, path, prefixes):1992"""When streaming files, this is called to map a p4 depot path1993 to where it should go in git. The prefixes are either1994 self.depotPaths, or self.branchPrefixes in the case of1995 branch detection."""19961997if self.useClientSpec:1998# branch detection moves files up a level (the branch name)1999# from what client spec interpretation gives2000 path = self.clientSpecDirs.map_in_client(path)2001if self.detectBranches:2002for b in self.knownBranches:2003if path.startswith(b +"/"):2004 path = path[len(b)+1:]20052006elif self.keepRepoPath:2007# Preserve everything in relative path name except leading2008# //depot/; just look at first prefix as they all should2009# be in the same depot.2010 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2011ifp4PathStartsWith(path, depot):2012 path = path[len(depot):]20132014else:2015for p in prefixes:2016ifp4PathStartsWith(path, p):2017 path = path[len(p):]2018break20192020 path =wildcard_decode(path)2021return path20222023defsplitFilesIntoBranches(self, commit):2024"""Look at each depotFile in the commit to figure out to what2025 branch it belongs."""20262027 branches = {}2028 fnum =02029while commit.has_key("depotFile%s"% fnum):2030 path = commit["depotFile%s"% fnum]2031 found = [p for p in self.depotPaths2032ifp4PathStartsWith(path, p)]2033if not found:2034 fnum = fnum +12035continue20362037file= {}2038file["path"] = path2039file["rev"] = commit["rev%s"% fnum]2040file["action"] = commit["action%s"% fnum]2041file["type"] = commit["type%s"% fnum]2042 fnum = fnum +120432044# start with the full relative path where this file would2045# go in a p4 client2046if self.useClientSpec:2047 relPath = self.clientSpecDirs.map_in_client(path)2048else:2049 relPath = self.stripRepoPath(path, self.depotPaths)20502051for branch in self.knownBranches.keys():2052# add a trailing slash so that a commit into qt/4.2foo2053# doesn't end up in qt/4.2, e.g.2054if relPath.startswith(branch +"/"):2055if branch not in branches:2056 branches[branch] = []2057 branches[branch].append(file)2058break20592060return branches20612062# output one file from the P4 stream2063# - helper for streamP4Files20642065defstreamOneP4File(self,file, contents):2066 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2067if verbose:2068 sys.stderr.write("%s\n"% relPath)20692070(type_base, type_mods) =split_p4_type(file["type"])20712072 git_mode ="100644"2073if"x"in type_mods:2074 git_mode ="100755"2075if type_base =="symlink":2076 git_mode ="120000"2077# p4 print on a symlink contains "target\n"; remove the newline2078 data =''.join(contents)2079 contents = [data[:-1]]20802081if type_base =="utf16":2082# p4 delivers different text in the python output to -G2083# than it does when using "print -o", or normal p4 client2084# operations. utf16 is converted to ascii or utf8, perhaps.2085# But ascii text saved as -t utf16 is completely mangled.2086# Invoke print -o to get the real contents.2087 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])2088 contents = [ text ]20892090if type_base =="apple":2091# Apple filetype files will be streamed as a concatenation of2092# its appledouble header and the contents. This is useless2093# on both macs and non-macs. If using "print -q -o xx", it2094# will create "xx" with the data, and "%xx" with the header.2095# This is also not very useful.2096#2097# Ideally, someday, this script can learn how to generate2098# appledouble files directly and import those to git, but2099# non-mac machines can never find a use for apple filetype.2100print"\nIgnoring apple filetype file%s"%file['depotFile']2101return21022103# Perhaps windows wants unicode, utf16 newlines translated too;2104# but this is not doing it.2105if self.isWindows and type_base =="text":2106 mangled = []2107for data in contents:2108 data = data.replace("\r\n","\n")2109 mangled.append(data)2110 contents = mangled21112112# Note that we do not try to de-mangle keywords on utf16 files,2113# even though in theory somebody may want that.2114 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2115if pattern:2116 regexp = re.compile(pattern, re.VERBOSE)2117 text =''.join(contents)2118 text = regexp.sub(r'$\1$', text)2119 contents = [ text ]21202121 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))21222123# total length...2124 length =02125for d in contents:2126 length = length +len(d)21272128 self.gitStream.write("data%d\n"% length)2129for d in contents:2130 self.gitStream.write(d)2131 self.gitStream.write("\n")21322133defstreamOneP4Deletion(self,file):2134 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2135if verbose:2136 sys.stderr.write("delete%s\n"% relPath)2137 self.gitStream.write("D%s\n"% relPath)21382139# handle another chunk of streaming data2140defstreamP4FilesCb(self, marshalled):21412142# catch p4 errors and complain2143 err =None2144if"code"in marshalled:2145if marshalled["code"] =="error":2146if"data"in marshalled:2147 err = marshalled["data"].rstrip()2148if err:2149 f =None2150if self.stream_have_file_info:2151if"depotFile"in self.stream_file:2152 f = self.stream_file["depotFile"]2153# force a failure in fast-import, else an empty2154# commit will be made2155 self.gitStream.write("\n")2156 self.gitStream.write("die-now\n")2157 self.gitStream.close()2158# ignore errors, but make sure it exits first2159 self.importProcess.wait()2160if f:2161die("Error from p4 print for%s:%s"% (f, err))2162else:2163die("Error from p4 print:%s"% err)21642165if marshalled.has_key('depotFile')and self.stream_have_file_info:2166# start of a new file - output the old one first2167 self.streamOneP4File(self.stream_file, self.stream_contents)2168 self.stream_file = {}2169 self.stream_contents = []2170 self.stream_have_file_info =False21712172# pick up the new file information... for the2173# 'data' field we need to append to our array2174for k in marshalled.keys():2175if k =='data':2176 self.stream_contents.append(marshalled['data'])2177else:2178 self.stream_file[k] = marshalled[k]21792180 self.stream_have_file_info =True21812182# Stream directly from "p4 files" into "git fast-import"2183defstreamP4Files(self, files):2184 filesForCommit = []2185 filesToRead = []2186 filesToDelete = []21872188for f in files:2189# if using a client spec, only add the files that have2190# a path in the client2191if self.clientSpecDirs:2192if self.clientSpecDirs.map_in_client(f['path']) =="":2193continue21942195 filesForCommit.append(f)2196if f['action']in self.delete_actions:2197 filesToDelete.append(f)2198else:2199 filesToRead.append(f)22002201# deleted files...2202for f in filesToDelete:2203 self.streamOneP4Deletion(f)22042205iflen(filesToRead) >0:2206 self.stream_file = {}2207 self.stream_contents = []2208 self.stream_have_file_info =False22092210# curry self argument2211defstreamP4FilesCbSelf(entry):2212 self.streamP4FilesCb(entry)22132214 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]22152216p4CmdList(["-x","-","print"],2217 stdin=fileArgs,2218 cb=streamP4FilesCbSelf)22192220# do the last chunk2221if self.stream_file.has_key('depotFile'):2222 self.streamOneP4File(self.stream_file, self.stream_contents)22232224defmake_email(self, userid):2225if userid in self.users:2226return self.users[userid]2227else:2228return"%s<a@b>"% userid22292230# Stream a p4 tag2231defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2232if verbose:2233print"writing tag%sfor commit%s"% (labelName, commit)2234 gitStream.write("tag%s\n"% labelName)2235 gitStream.write("from%s\n"% commit)22362237if labelDetails.has_key('Owner'):2238 owner = labelDetails["Owner"]2239else:2240 owner =None22412242# Try to use the owner of the p4 label, or failing that,2243# the current p4 user id.2244if owner:2245 email = self.make_email(owner)2246else:2247 email = self.make_email(self.p4UserId())2248 tagger ="%s %s %s"% (email, epoch, self.tz)22492250 gitStream.write("tagger%s\n"% tagger)22512252print"labelDetails=",labelDetails2253if labelDetails.has_key('Description'):2254 description = labelDetails['Description']2255else:2256 description ='Label from git p4'22572258 gitStream.write("data%d\n"%len(description))2259 gitStream.write(description)2260 gitStream.write("\n")22612262defcommit(self, details, files, branch, parent =""):2263 epoch = details["time"]2264 author = details["user"]22652266if self.verbose:2267print"commit into%s"% branch22682269# start with reading files; if that fails, we should not2270# create a commit.2271 new_files = []2272for f in files:2273if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2274 new_files.append(f)2275else:2276 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])22772278 self.gitStream.write("commit%s\n"% branch)2279# gitStream.write("mark :%s\n" % details["change"])2280 self.committedChanges.add(int(details["change"]))2281 committer =""2282if author not in self.users:2283 self.getUserMapFromPerforceServer()2284 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)22852286 self.gitStream.write("committer%s\n"% committer)22872288 self.gitStream.write("data <<EOT\n")2289 self.gitStream.write(details["desc"])2290 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2291(','.join(self.branchPrefixes), details["change"]))2292iflen(details['options']) >0:2293 self.gitStream.write(": options =%s"% details['options'])2294 self.gitStream.write("]\nEOT\n\n")22952296iflen(parent) >0:2297if self.verbose:2298print"parent%s"% parent2299 self.gitStream.write("from%s\n"% parent)23002301 self.streamP4Files(new_files)2302 self.gitStream.write("\n")23032304 change =int(details["change"])23052306if self.labels.has_key(change):2307 label = self.labels[change]2308 labelDetails = label[0]2309 labelRevisions = label[1]2310if self.verbose:2311print"Change%sis labelled%s"% (change, labelDetails)23122313 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2314for p in self.branchPrefixes])23152316iflen(files) ==len(labelRevisions):23172318 cleanedFiles = {}2319for info in files:2320if info["action"]in self.delete_actions:2321continue2322 cleanedFiles[info["depotFile"]] = info["rev"]23232324if cleanedFiles == labelRevisions:2325 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)23262327else:2328if not self.silent:2329print("Tag%sdoes not match with change%s: files do not match."2330% (labelDetails["label"], change))23312332else:2333if not self.silent:2334print("Tag%sdoes not match with change%s: file count is different."2335% (labelDetails["label"], change))23362337# Build a dictionary of changelists and labels, for "detect-labels" option.2338defgetLabels(self):2339 self.labels = {}23402341 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2342iflen(l) >0and not self.silent:2343print"Finding files belonging to labels in%s"% `self.depotPaths`23442345for output in l:2346 label = output["label"]2347 revisions = {}2348 newestChange =02349if self.verbose:2350print"Querying files for label%s"% label2351forfileinp4CmdList(["files"] +2352["%s...@%s"% (p, label)2353for p in self.depotPaths]):2354 revisions[file["depotFile"]] =file["rev"]2355 change =int(file["change"])2356if change > newestChange:2357 newestChange = change23582359 self.labels[newestChange] = [output, revisions]23602361if self.verbose:2362print"Label changes:%s"% self.labels.keys()23632364# Import p4 labels as git tags. A direct mapping does not2365# exist, so assume that if all the files are at the same revision2366# then we can use that, or it's something more complicated we should2367# just ignore.2368defimportP4Labels(self, stream, p4Labels):2369if verbose:2370print"import p4 labels: "+' '.join(p4Labels)23712372 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2373 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2374iflen(validLabelRegexp) ==0:2375 validLabelRegexp = defaultLabelRegexp2376 m = re.compile(validLabelRegexp)23772378for name in p4Labels:2379 commitFound =False23802381if not m.match(name):2382if verbose:2383print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2384continue23852386if name in ignoredP4Labels:2387continue23882389 labelDetails =p4CmdList(['label',"-o", name])[0]23902391# get the most recent changelist for each file in this label2392 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2393for p in self.depotPaths])23942395if change.has_key('change'):2396# find the corresponding git commit; take the oldest commit2397 changelist =int(change['change'])2398 gitCommit =read_pipe(["git","rev-list","--max-count=1",2399"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2400iflen(gitCommit) ==0:2401print"could not find git commit for changelist%d"% changelist2402else:2403 gitCommit = gitCommit.strip()2404 commitFound =True2405# Convert from p4 time format2406try:2407 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2408exceptValueError:2409print"Could not convert label time%s"% labelDetails['Update']2410 tmwhen =124112412 when =int(time.mktime(tmwhen))2413 self.streamTag(stream, name, labelDetails, gitCommit, when)2414if verbose:2415print"p4 label%smapped to git commit%s"% (name, gitCommit)2416else:2417if verbose:2418print"Label%shas no changelists - possibly deleted?"% name24192420if not commitFound:2421# We can't import this label; don't try again as it will get very2422# expensive repeatedly fetching all the files for labels that will2423# never be imported. If the label is moved in the future, the2424# ignore will need to be removed manually.2425system(["git","config","--add","git-p4.ignoredP4Labels", name])24262427defguessProjectName(self):2428for p in self.depotPaths:2429if p.endswith("/"):2430 p = p[:-1]2431 p = p[p.strip().rfind("/") +1:]2432if not p.endswith("/"):2433 p +="/"2434return p24352436defgetBranchMapping(self):2437 lostAndFoundBranches =set()24382439 user =gitConfig("git-p4.branchUser")2440iflen(user) >0:2441 command ="branches -u%s"% user2442else:2443 command ="branches"24442445for info inp4CmdList(command):2446 details =p4Cmd(["branch","-o", info["branch"]])2447 viewIdx =02448while details.has_key("View%s"% viewIdx):2449 paths = details["View%s"% viewIdx].split(" ")2450 viewIdx = viewIdx +12451# require standard //depot/foo/... //depot/bar/... mapping2452iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2453continue2454 source = paths[0]2455 destination = paths[1]2456## HACK2457ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2458 source = source[len(self.depotPaths[0]):-4]2459 destination = destination[len(self.depotPaths[0]):-4]24602461if destination in self.knownBranches:2462if not self.silent:2463print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2464print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2465continue24662467 self.knownBranches[destination] = source24682469 lostAndFoundBranches.discard(destination)24702471if source not in self.knownBranches:2472 lostAndFoundBranches.add(source)24732474# Perforce does not strictly require branches to be defined, so we also2475# check git config for a branch list.2476#2477# Example of branch definition in git config file:2478# [git-p4]2479# branchList=main:branchA2480# branchList=main:branchB2481# branchList=branchA:branchC2482 configBranches =gitConfigList("git-p4.branchList")2483for branch in configBranches:2484if branch:2485(source, destination) = branch.split(":")2486 self.knownBranches[destination] = source24872488 lostAndFoundBranches.discard(destination)24892490if source not in self.knownBranches:2491 lostAndFoundBranches.add(source)249224932494for branch in lostAndFoundBranches:2495 self.knownBranches[branch] = branch24962497defgetBranchMappingFromGitBranches(self):2498 branches =p4BranchesInGit(self.importIntoRemotes)2499for branch in branches.keys():2500if branch =="master":2501 branch ="main"2502else:2503 branch = branch[len(self.projectName):]2504 self.knownBranches[branch] = branch25052506deflistExistingP4GitBranches(self):2507# branches holds mapping from name to commit2508 branches =p4BranchesInGit(self.importIntoRemotes)2509 self.p4BranchesInGit = branches.keys()2510for branch in branches.keys():2511 self.initialParents[self.refPrefix + branch] = branches[branch]25122513defupdateOptionDict(self, d):2514 option_keys = {}2515if self.keepRepoPath:2516 option_keys['keepRepoPath'] =125172518 d["options"] =' '.join(sorted(option_keys.keys()))25192520defreadOptions(self, d):2521 self.keepRepoPath = (d.has_key('options')2522and('keepRepoPath'in d['options']))25232524defgitRefForBranch(self, branch):2525if branch =="main":2526return self.refPrefix +"master"25272528iflen(branch) <=0:2529return branch25302531return self.refPrefix + self.projectName + branch25322533defgitCommitByP4Change(self, ref, change):2534if self.verbose:2535print"looking in ref "+ ref +" for change%susing bisect..."% change25362537 earliestCommit =""2538 latestCommit =parseRevision(ref)25392540while True:2541if self.verbose:2542print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2543 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2544iflen(next) ==0:2545if self.verbose:2546print"argh"2547return""2548 log =extractLogMessageFromGitCommit(next)2549 settings =extractSettingsGitLog(log)2550 currentChange =int(settings['change'])2551if self.verbose:2552print"current change%s"% currentChange25532554if currentChange == change:2555if self.verbose:2556print"found%s"% next2557return next25582559if currentChange < change:2560 earliestCommit ="^%s"% next2561else:2562 latestCommit ="%s"% next25632564return""25652566defimportNewBranch(self, branch, maxChange):2567# make fast-import flush all changes to disk and update the refs using the checkpoint2568# command so that we can try to find the branch parent in the git history2569 self.gitStream.write("checkpoint\n\n");2570 self.gitStream.flush();2571 branchPrefix = self.depotPaths[0] + branch +"/"2572range="@1,%s"% maxChange2573#print "prefix" + branchPrefix2574 changes =p4ChangesForPaths([branchPrefix],range)2575iflen(changes) <=0:2576return False2577 firstChange = changes[0]2578#print "first change in branch: %s" % firstChange2579 sourceBranch = self.knownBranches[branch]2580 sourceDepotPath = self.depotPaths[0] + sourceBranch2581 sourceRef = self.gitRefForBranch(sourceBranch)2582#print "source " + sourceBranch25832584 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2585#print "branch parent: %s" % branchParentChange2586 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2587iflen(gitParent) >0:2588 self.initialParents[self.gitRefForBranch(branch)] = gitParent2589#print "parent git commit: %s" % gitParent25902591 self.importChanges(changes)2592return True25932594defsearchParent(self, parent, branch, target):2595 parentFound =False2596for blob inread_pipe_lines(["git","rev-list","--reverse","--no-merges", parent]):2597 blob = blob.strip()2598iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2599 parentFound =True2600if self.verbose:2601print"Found parent of%sin commit%s"% (branch, blob)2602break2603if parentFound:2604return blob2605else:2606return None26072608defimportChanges(self, changes):2609 cnt =12610for change in changes:2611 description =p4_describe(change)2612 self.updateOptionDict(description)26132614if not self.silent:2615 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2616 sys.stdout.flush()2617 cnt = cnt +126182619try:2620if self.detectBranches:2621 branches = self.splitFilesIntoBranches(description)2622for branch in branches.keys():2623## HACK --hwn2624 branchPrefix = self.depotPaths[0] + branch +"/"2625 self.branchPrefixes = [ branchPrefix ]26262627 parent =""26282629 filesForCommit = branches[branch]26302631if self.verbose:2632print"branch is%s"% branch26332634 self.updatedBranches.add(branch)26352636if branch not in self.createdBranches:2637 self.createdBranches.add(branch)2638 parent = self.knownBranches[branch]2639if parent == branch:2640 parent =""2641else:2642 fullBranch = self.projectName + branch2643if fullBranch not in self.p4BranchesInGit:2644if not self.silent:2645print("\nImporting new branch%s"% fullBranch);2646if self.importNewBranch(branch, change -1):2647 parent =""2648 self.p4BranchesInGit.append(fullBranch)2649if not self.silent:2650print("\nResuming with change%s"% change);26512652if self.verbose:2653print"parent determined through known branches:%s"% parent26542655 branch = self.gitRefForBranch(branch)2656 parent = self.gitRefForBranch(parent)26572658if self.verbose:2659print"looking for initial parent for%s; current parent is%s"% (branch, parent)26602661iflen(parent) ==0and branch in self.initialParents:2662 parent = self.initialParents[branch]2663del self.initialParents[branch]26642665 blob =None2666iflen(parent) >0:2667 tempBranch = os.path.join(self.tempBranchLocation,"%d"% (change))2668if self.verbose:2669print"Creating temporary branch: "+ tempBranch2670 self.commit(description, filesForCommit, tempBranch)2671 self.tempBranches.append(tempBranch)2672 self.checkpoint()2673 blob = self.searchParent(parent, branch, tempBranch)2674if blob:2675 self.commit(description, filesForCommit, branch, blob)2676else:2677if self.verbose:2678print"Parent of%snot found. Committing into head of%s"% (branch, parent)2679 self.commit(description, filesForCommit, branch, parent)2680else:2681 files = self.extractFilesFromCommit(description)2682 self.commit(description, files, self.branch,2683 self.initialParent)2684 self.initialParent =""2685exceptIOError:2686print self.gitError.read()2687 sys.exit(1)26882689defimportHeadRevision(self, revision):2690print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)26912692 details = {}2693 details["user"] ="git perforce import user"2694 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2695% (' '.join(self.depotPaths), revision))2696 details["change"] = revision2697 newestRevision =026982699 fileCnt =02700 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]27012702for info inp4CmdList(["files"] + fileArgs):27032704if'code'in info and info['code'] =='error':2705 sys.stderr.write("p4 returned an error:%s\n"2706% info['data'])2707if info['data'].find("must refer to client") >=0:2708 sys.stderr.write("This particular p4 error is misleading.\n")2709 sys.stderr.write("Perhaps the depot path was misspelled.\n");2710 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2711 sys.exit(1)2712if'p4ExitCode'in info:2713 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2714 sys.exit(1)271527162717 change =int(info["change"])2718if change > newestRevision:2719 newestRevision = change27202721if info["action"]in self.delete_actions:2722# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2723#fileCnt = fileCnt + 12724continue27252726for prop in["depotFile","rev","action","type"]:2727 details["%s%s"% (prop, fileCnt)] = info[prop]27282729 fileCnt = fileCnt +127302731 details["change"] = newestRevision27322733# Use time from top-most change so that all git p4 clones of2734# the same p4 repo have the same commit SHA1s.2735 res =p4_describe(newestRevision)2736 details["time"] = res["time"]27372738 self.updateOptionDict(details)2739try:2740 self.commit(details, self.extractFilesFromCommit(details), self.branch)2741exceptIOError:2742print"IO error with git fast-import. Is your git version recent enough?"2743print self.gitError.read()274427452746defrun(self, args):2747 self.depotPaths = []2748 self.changeRange =""2749 self.initialParent =""2750 self.previousDepotPaths = []27512752# map from branch depot path to parent branch2753 self.knownBranches = {}2754 self.initialParents = {}2755 self.hasOrigin =originP4BranchesExist()2756if not self.syncWithOrigin:2757 self.hasOrigin =False27582759if self.importIntoRemotes:2760 self.refPrefix ="refs/remotes/p4/"2761else:2762 self.refPrefix ="refs/heads/p4/"27632764if self.syncWithOrigin and self.hasOrigin:2765if not self.silent:2766print"Syncing with origin first by calling git fetch origin"2767system("git fetch origin")27682769iflen(self.branch) ==0:2770 self.branch = self.refPrefix +"master"2771ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2772system("git update-ref%srefs/heads/p4"% self.branch)2773system("git branch -D p4");2774# create it /after/ importing, when master exists2775if notgitBranchExists(self.refPrefix +"HEAD")and self.importIntoRemotes andgitBranchExists(self.branch):2776system("git symbolic-ref%sHEAD%s"% (self.refPrefix, self.branch))27772778# accept either the command-line option, or the configuration variable2779if self.useClientSpec:2780# will use this after clone to set the variable2781 self.useClientSpec_from_options =True2782else:2783ifgitConfig("git-p4.useclientspec","--bool") =="true":2784 self.useClientSpec =True2785if self.useClientSpec:2786 self.clientSpecDirs =getClientSpec()27872788# TODO: should always look at previous commits,2789# merge with previous imports, if possible.2790if args == []:2791if self.hasOrigin:2792createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)2793 self.listExistingP4GitBranches()27942795iflen(self.p4BranchesInGit) >1:2796if not self.silent:2797print"Importing from/into multiple branches"2798 self.detectBranches =True27992800if self.verbose:2801print"branches:%s"% self.p4BranchesInGit28022803 p4Change =02804for branch in self.p4BranchesInGit:2805 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)28062807 settings =extractSettingsGitLog(logMsg)28082809 self.readOptions(settings)2810if(settings.has_key('depot-paths')2811and settings.has_key('change')):2812 change =int(settings['change']) +12813 p4Change =max(p4Change, change)28142815 depotPaths =sorted(settings['depot-paths'])2816if self.previousDepotPaths == []:2817 self.previousDepotPaths = depotPaths2818else:2819 paths = []2820for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2821 prev_list = prev.split("/")2822 cur_list = cur.split("/")2823for i inrange(0,min(len(cur_list),len(prev_list))):2824if cur_list[i] <> prev_list[i]:2825 i = i -12826break28272828 paths.append("/".join(cur_list[:i +1]))28292830 self.previousDepotPaths = paths28312832if p4Change >0:2833 self.depotPaths =sorted(self.previousDepotPaths)2834 self.changeRange ="@%s,#head"% p4Change2835if not self.detectBranches:2836 self.initialParent =parseRevision(self.branch)2837if not self.silent and not self.detectBranches:2838print"Performing incremental import into%sgit branch"% self.branch28392840if not self.branch.startswith("refs/"):2841 self.branch ="refs/heads/"+ self.branch28422843iflen(args) ==0and self.depotPaths:2844if not self.silent:2845print"Depot paths:%s"%' '.join(self.depotPaths)2846else:2847if self.depotPaths and self.depotPaths != args:2848print("previous import used depot path%sand now%swas specified. "2849"This doesn't work!"% (' '.join(self.depotPaths),2850' '.join(args)))2851 sys.exit(1)28522853 self.depotPaths =sorted(args)28542855 revision =""2856 self.users = {}28572858# Make sure no revision specifiers are used when --changesfile2859# is specified.2860 bad_changesfile =False2861iflen(self.changesFile) >0:2862for p in self.depotPaths:2863if p.find("@") >=0or p.find("#") >=0:2864 bad_changesfile =True2865break2866if bad_changesfile:2867die("Option --changesfile is incompatible with revision specifiers")28682869 newPaths = []2870for p in self.depotPaths:2871if p.find("@") != -1:2872 atIdx = p.index("@")2873 self.changeRange = p[atIdx:]2874if self.changeRange =="@all":2875 self.changeRange =""2876elif','not in self.changeRange:2877 revision = self.changeRange2878 self.changeRange =""2879 p = p[:atIdx]2880elif p.find("#") != -1:2881 hashIdx = p.index("#")2882 revision = p[hashIdx:]2883 p = p[:hashIdx]2884elif self.previousDepotPaths == []:2885# pay attention to changesfile, if given, else import2886# the entire p4 tree at the head revision2887iflen(self.changesFile) ==0:2888 revision ="#head"28892890 p = re.sub("\.\.\.$","", p)2891if not p.endswith("/"):2892 p +="/"28932894 newPaths.append(p)28952896 self.depotPaths = newPaths28972898# --detect-branches may change this for each branch2899 self.branchPrefixes = self.depotPaths29002901 self.loadUserMapFromCache()2902 self.labels = {}2903if self.detectLabels:2904 self.getLabels();29052906if self.detectBranches:2907## FIXME - what's a P4 projectName ?2908 self.projectName = self.guessProjectName()29092910if self.hasOrigin:2911 self.getBranchMappingFromGitBranches()2912else:2913 self.getBranchMapping()2914if self.verbose:2915print"p4-git branches:%s"% self.p4BranchesInGit2916print"initial parents:%s"% self.initialParents2917for b in self.p4BranchesInGit:2918if b !="master":29192920## FIXME2921 b = b[len(self.projectName):]2922 self.createdBranches.add(b)29232924 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))29252926 self.importProcess = subprocess.Popen(["git","fast-import"],2927 stdin=subprocess.PIPE,2928 stdout=subprocess.PIPE,2929 stderr=subprocess.PIPE);2930 self.gitOutput = self.importProcess.stdout2931 self.gitStream = self.importProcess.stdin2932 self.gitError = self.importProcess.stderr29332934if revision:2935 self.importHeadRevision(revision)2936else:2937 changes = []29382939iflen(self.changesFile) >0:2940 output =open(self.changesFile).readlines()2941 changeSet =set()2942for line in output:2943 changeSet.add(int(line))29442945for change in changeSet:2946 changes.append(change)29472948 changes.sort()2949else:2950# catch "git p4 sync" with no new branches, in a repo that2951# does not have any existing p4 branches2952iflen(args) ==0and not self.p4BranchesInGit:2953die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.");2954if self.verbose:2955print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),2956 self.changeRange)2957 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)29582959iflen(self.maxChanges) >0:2960 changes = changes[:min(int(self.maxChanges),len(changes))]29612962iflen(changes) ==0:2963if not self.silent:2964print"No changes to import!"2965else:2966if not self.silent and not self.detectBranches:2967print"Import destination:%s"% self.branch29682969 self.updatedBranches =set()29702971 self.importChanges(changes)29722973if not self.silent:2974print""2975iflen(self.updatedBranches) >0:2976 sys.stdout.write("Updated branches: ")2977for b in self.updatedBranches:2978 sys.stdout.write("%s"% b)2979 sys.stdout.write("\n")29802981ifgitConfig("git-p4.importLabels","--bool") =="true":2982 self.importLabels =True29832984if self.importLabels:2985 p4Labels =getP4Labels(self.depotPaths)2986 gitTags =getGitTags()29872988 missingP4Labels = p4Labels - gitTags2989 self.importP4Labels(self.gitStream, missingP4Labels)29902991 self.gitStream.close()2992if self.importProcess.wait() !=0:2993die("fast-import failed:%s"% self.gitError.read())2994 self.gitOutput.close()2995 self.gitError.close()29962997# Cleanup temporary branches created during import2998if self.tempBranches != []:2999for branch in self.tempBranches:3000read_pipe("git update-ref -d%s"% branch)3001 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))30023003return True30043005classP4Rebase(Command):3006def__init__(self):3007 Command.__init__(self)3008 self.options = [3009 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3010]3011 self.importLabels =False3012 self.description = ("Fetches the latest revision from perforce and "3013+"rebases the current work (branch) against it")30143015defrun(self, args):3016 sync =P4Sync()3017 sync.importLabels = self.importLabels3018 sync.run([])30193020return self.rebase()30213022defrebase(self):3023if os.system("git update-index --refresh") !=0:3024die("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.");3025iflen(read_pipe("git diff-index HEAD --")) >0:3026die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");30273028[upstream, settings] =findUpstreamBranchPoint()3029iflen(upstream) ==0:3030die("Cannot find upstream branchpoint for rebase")30313032# the branchpoint may be p4/foo~3, so strip off the parent3033 upstream = re.sub("~[0-9]+$","", upstream)30343035print"Rebasing the current branch onto%s"% upstream3036 oldHead =read_pipe("git rev-parse HEAD").strip()3037system("git rebase%s"% upstream)3038system("git diff-tree --stat --summary -M%sHEAD"% oldHead)3039return True30403041classP4Clone(P4Sync):3042def__init__(self):3043 P4Sync.__init__(self)3044 self.description ="Creates a new git repository and imports from Perforce into it"3045 self.usage ="usage: %prog [options] //depot/path[@revRange]"3046 self.options += [3047 optparse.make_option("--destination", dest="cloneDestination",3048 action='store', default=None,3049help="where to leave result of the clone"),3050 optparse.make_option("-/", dest="cloneExclude",3051 action="append",type="string",3052help="exclude depot path"),3053 optparse.make_option("--bare", dest="cloneBare",3054 action="store_true", default=False),3055]3056 self.cloneDestination =None3057 self.needsGit =False3058 self.cloneBare =False30593060# This is required for the "append" cloneExclude action3061defensure_value(self, attr, value):3062if nothasattr(self, attr)orgetattr(self, attr)is None:3063setattr(self, attr, value)3064returngetattr(self, attr)30653066defdefaultDestination(self, args):3067## TODO: use common prefix of args?3068 depotPath = args[0]3069 depotDir = re.sub("(@[^@]*)$","", depotPath)3070 depotDir = re.sub("(#[^#]*)$","", depotDir)3071 depotDir = re.sub(r"\.\.\.$","", depotDir)3072 depotDir = re.sub(r"/$","", depotDir)3073return os.path.split(depotDir)[1]30743075defrun(self, args):3076iflen(args) <1:3077return False30783079if self.keepRepoPath and not self.cloneDestination:3080 sys.stderr.write("Must specify destination for --keep-path\n")3081 sys.exit(1)30823083 depotPaths = args30843085if not self.cloneDestination andlen(depotPaths) >1:3086 self.cloneDestination = depotPaths[-1]3087 depotPaths = depotPaths[:-1]30883089 self.cloneExclude = ["/"+p for p in self.cloneExclude]3090for p in depotPaths:3091if not p.startswith("//"):3092return False30933094if not self.cloneDestination:3095 self.cloneDestination = self.defaultDestination(args)30963097print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)30983099if not os.path.exists(self.cloneDestination):3100 os.makedirs(self.cloneDestination)3101chdir(self.cloneDestination)31023103 init_cmd = ["git","init"]3104if self.cloneBare:3105 init_cmd.append("--bare")3106 subprocess.check_call(init_cmd)31073108if not P4Sync.run(self, depotPaths):3109return False3110if self.branch !="master":3111if self.importIntoRemotes:3112 masterbranch ="refs/remotes/p4/master"3113else:3114 masterbranch ="refs/heads/p4/master"3115ifgitBranchExists(masterbranch):3116system("git branch master%s"% masterbranch)3117if not self.cloneBare:3118system("git checkout -f")3119else:3120print"Could not detect main branch. No checkout/master branch created."31213122# auto-set this variable if invoked with --use-client-spec3123if self.useClientSpec_from_options:3124system("git config --bool git-p4.useclientspec true")31253126return True31273128classP4Branches(Command):3129def__init__(self):3130 Command.__init__(self)3131 self.options = [ ]3132 self.description = ("Shows the git branches that hold imports and their "3133+"corresponding perforce depot paths")3134 self.verbose =False31353136defrun(self, args):3137iforiginP4BranchesExist():3138createOrUpdateBranchesFromOrigin()31393140 cmdline ="git rev-parse --symbolic "3141 cmdline +=" --remotes"31423143for line inread_pipe_lines(cmdline):3144 line = line.strip()31453146if not line.startswith('p4/')or line =="p4/HEAD":3147continue3148 branch = line31493150 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3151 settings =extractSettingsGitLog(log)31523153print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3154return True31553156classHelpFormatter(optparse.IndentedHelpFormatter):3157def__init__(self):3158 optparse.IndentedHelpFormatter.__init__(self)31593160defformat_description(self, description):3161if description:3162return description +"\n"3163else:3164return""31653166defprintUsage(commands):3167print"usage:%s<command> [options]"% sys.argv[0]3168print""3169print"valid commands:%s"%", ".join(commands)3170print""3171print"Try%s<command> --help for command specific help."% sys.argv[0]3172print""31733174commands = {3175"debug": P4Debug,3176"submit": P4Submit,3177"commit": P4Submit,3178"sync": P4Sync,3179"rebase": P4Rebase,3180"clone": P4Clone,3181"rollback": P4RollBack,3182"branches": P4Branches3183}318431853186defmain():3187iflen(sys.argv[1:]) ==0:3188printUsage(commands.keys())3189 sys.exit(2)31903191 cmdName = sys.argv[1]3192try:3193 klass = commands[cmdName]3194 cmd =klass()3195exceptKeyError:3196print"unknown command%s"% cmdName3197print""3198printUsage(commands.keys())3199 sys.exit(2)32003201 options = cmd.options3202 cmd.gitdir = os.environ.get("GIT_DIR",None)32033204 args = sys.argv[2:]32053206 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3207if cmd.needsGit:3208 options.append(optparse.make_option("--git-dir", dest="gitdir"))32093210 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3211 options,3212 description = cmd.description,3213 formatter =HelpFormatter())32143215(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3216global verbose3217 verbose = cmd.verbose3218if cmd.needsGit:3219if cmd.gitdir ==None:3220 cmd.gitdir = os.path.abspath(".git")3221if notisValidGitDir(cmd.gitdir):3222 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3223if os.path.exists(cmd.gitdir):3224 cdup =read_pipe("git rev-parse --show-cdup").strip()3225iflen(cdup) >0:3226chdir(cdup);32273228if notisValidGitDir(cmd.gitdir):3229ifisValidGitDir(cmd.gitdir +"/.git"):3230 cmd.gitdir +="/.git"3231else:3232die("fatal: cannot locate git repository at%s"% cmd.gitdir)32333234 os.environ["GIT_DIR"] = cmd.gitdir32353236if not cmd.run(args):3237 parser.print_help()3238 sys.exit(2)323932403241if __name__ =='__main__':3242main()