1#!/usr/bin/perl 2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net> 3# License: GPL v2 or later 4use5.008; 5use warnings; 6use strict; 7use vars qw/$AUTHOR $VERSION 8$sha1 $sha1_short $_revision $_repository 9$_q $_authors $_authors_prog %users/; 10$AUTHOR='Eric Wong <normalperson@yhbt.net>'; 11$VERSION='@@GIT_VERSION@@'; 12 13# From which subdir have we been invoked? 14my$cmd_dir_prefix=eval{ 15 command_oneline([qw/rev-parse --show-prefix/], STDERR =>0) 16} ||''; 17 18my$git_dir_user_set=1ifdefined$ENV{GIT_DIR}; 19$ENV{GIT_DIR} ||='.git'; 20$Git::SVN::default_repo_id ='svn'; 21$Git::SVN::default_ref_id =$ENV{GIT_SVN_ID} ||'git-svn'; 22$Git::SVN::Ra::_log_window_size =100; 23$Git::SVN::_minimize_url ='unset'; 24 25if(!exists$ENV{SVN_SSH} &&exists$ENV{GIT_SSH}) { 26$ENV{SVN_SSH} =$ENV{GIT_SSH}; 27} 28 29if(exists$ENV{SVN_SSH} &&$^Oeq'msys') { 30$ENV{SVN_SSH} =~s/\\/\\\\/g; 31$ENV{SVN_SSH} =~s/(.*)/"$1"/; 32} 33 34$Git::SVN::Log::TZ =$ENV{TZ}; 35$ENV{TZ} ='UTC'; 36$| =1;# unbuffer STDOUT 37 38sub fatal (@) {print STDERR "@_\n";exit1} 39 40# All SVN commands do it. Otherwise we may die on SIGPIPE when the remote 41# repository decides to close the connection which we expect to be kept alive. 42$SIG{PIPE} ='IGNORE'; 43 44# Given a dot separated version number, "subtract" it from 45# the SVN::Core::VERSION; non-negaitive return means the SVN::Core 46# is at least at the version the caller asked for. 47sub compare_svn_version { 48my(@ours) =split(/\./,$SVN::Core::VERSION); 49my(@theirs) =split(/\./,$_[0]); 50my($i,$diff); 51 52for($i=0;$i<@ours&&$i<@theirs;$i++) { 53$diff=$ours[$i] -$theirs[$i]; 54return$diffif($diff); 55} 56return1if($i<@ours); 57return-1if($i<@theirs); 58return0; 59} 60 61sub _req_svn { 62require SVN::Core;# use()-ing this causes segfaults for me... *shrug* 63require SVN::Ra; 64require SVN::Delta; 65if(::compare_svn_version('1.1.0') <0) { 66 fatal "Need SVN::Core 1.1.0 or better (got$SVN::Core::VERSION)"; 67} 68} 69my$can_compress=eval{require Compress::Zlib;1}; 70use Carp qw/croak/; 71use Digest::MD5; 72use IO::File qw//; 73use File::Basename qw/dirname basename/; 74use File::Path qw/mkpath/; 75use File::Spec; 76use File::Find; 77use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/; 78use IPC::Open3; 79use Git; 80use Git::SVN::Editor qw//; 81use Git::SVN::Fetcher qw//; 82use Git::SVN::Ra qw//; 83use Git::SVN::Prompt qw//; 84use Memoize;# core since 5.8.0, Jul 2002 85 86BEGIN{ 87# import functions from Git into our packages, en masse 88no strict 'refs'; 89foreach(qw/command command_oneline command_noisy command_output_pipe 90 command_input_pipe command_close_pipe 91 command_bidi_pipe command_close_bidi_pipe/) { 92formy$package(qw(Git::SVN::Migration Git::SVN::Log Git::SVN), 93 __PACKAGE__) { 94*{"${package}::$_"} = \&{"Git::$_"}; 95} 96} 97 Memoize::memoize 'Git::config'; 98 Memoize::memoize 'Git::config_bool'; 99} 100 101my($SVN); 102 103$sha1=qr/[a-f\d]{40}/; 104$sha1_short=qr/[a-f\d]{4,40}/; 105my($_stdin,$_help,$_edit, 106$_message,$_file,$_branch_dest, 107$_template,$_shared, 108$_version,$_fetch_all,$_no_rebase,$_fetch_parent, 109$_merge,$_strategy,$_preserve_merges,$_dry_run,$_local, 110$_prefix,$_no_checkout,$_url,$_verbose, 111$_git_format,$_commit_url,$_tag,$_merge_info,$_interactive); 112$Git::SVN::_follow_parent =1; 113$Git::SVN::Fetcher::_placeholder_filename =".gitignore"; 114$_q||=0; 115my%remote_opts= ('username=s'=> \$Git::SVN::Prompt::_username, 116'config-dir=s'=> \$Git::SVN::Ra::config_dir, 117'no-auth-cache'=> \$Git::SVN::Prompt::_no_auth_cache, 118'ignore-paths=s'=> \$Git::SVN::Fetcher::_ignore_regex, 119'ignore-refs=s'=> \$Git::SVN::Ra::_ignore_refs_regex ); 120my%fc_opts= ('follow-parent|follow!'=> \$Git::SVN::_follow_parent, 121'authors-file|A=s'=> \$_authors, 122'authors-prog=s'=> \$_authors_prog, 123'repack:i'=> \$Git::SVN::_repack, 124'noMetadata'=> \$Git::SVN::_no_metadata, 125'useSvmProps'=> \$Git::SVN::_use_svm_props, 126'useSvnsyncProps'=> \$Git::SVN::_use_svnsync_props, 127'log-window-size=i'=> \$Git::SVN::Ra::_log_window_size, 128'no-checkout'=> \$_no_checkout, 129'quiet|q+'=> \$_q, 130'repack-flags|repack-args|repack-opts=s'=> 131 \$Git::SVN::_repack_flags, 132'use-log-author'=> \$Git::SVN::_use_log_author, 133'add-author-from'=> \$Git::SVN::_add_author_from, 134'localtime'=> \$Git::SVN::_localtime, 135%remote_opts); 136 137my($_trunk,@_tags,@_branches,$_stdlayout); 138my%icv; 139my%init_opts= ('template=s'=> \$_template,'shared:s'=> \$_shared, 140'trunk|T=s'=> \$_trunk,'tags|t=s@'=> \@_tags, 141'branches|b=s@'=> \@_branches,'prefix=s'=> \$_prefix, 142'stdlayout|s'=> \$_stdlayout, 143'minimize-url|m!'=> \$Git::SVN::_minimize_url, 144'no-metadata'=>sub{$icv{noMetadata} =1}, 145'use-svm-props'=>sub{$icv{useSvmProps} =1}, 146'use-svnsync-props'=>sub{$icv{useSvnsyncProps} =1}, 147'rewrite-root=s'=>sub{$icv{rewriteRoot} =$_[1] }, 148'rewrite-uuid=s'=>sub{$icv{rewriteUUID} =$_[1] }, 149%remote_opts); 150my%cmt_opts= ('edit|e'=> \$_edit, 151'rmdir'=> \$Git::SVN::Editor::_rmdir, 152'find-copies-harder'=> \$Git::SVN::Editor::_find_copies_harder, 153'l=i'=> \$Git::SVN::Editor::_rename_limit, 154'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity 155); 156 157my%cmd= ( 158 fetch => [ \&cmd_fetch,"Download new revisions from SVN", 159{'revision|r=s'=> \$_revision, 160'fetch-all|all'=> \$_fetch_all, 161'parent|p'=> \$_fetch_parent, 162%fc_opts} ], 163 clone => [ \&cmd_clone,"Initialize and fetch revisions", 164{'revision|r=s'=> \$_revision, 165'preserve-empty-dirs'=> 166 \$Git::SVN::Fetcher::_preserve_empty_dirs, 167'placeholder-filename=s'=> 168 \$Git::SVN::Fetcher::_placeholder_filename, 169%fc_opts,%init_opts} ], 170 init => [ \&cmd_init,"Initialize a repo for tracking". 171" (requires URL argument)", 172 \%init_opts], 173'multi-init'=> [ \&cmd_multi_init, 174"Deprecated alias for ". 175"'$0init -T<trunk> -b<branches> -t<tags>'", 176 \%init_opts], 177 dcommit => [ \&cmd_dcommit, 178'Commit several diffs to merge with upstream', 179{'merge|m|M'=> \$_merge, 180'strategy|s=s'=> \$_strategy, 181'verbose|v'=> \$_verbose, 182'dry-run|n'=> \$_dry_run, 183'fetch-all|all'=> \$_fetch_all, 184'commit-url=s'=> \$_commit_url, 185'revision|r=i'=> \$_revision, 186'no-rebase'=> \$_no_rebase, 187'mergeinfo=s'=> \$_merge_info, 188'interactive|i'=> \$_interactive, 189%cmt_opts,%fc_opts} ], 190 branch => [ \&cmd_branch, 191'Create a branch in the SVN repository', 192{'message|m=s'=> \$_message, 193'destination|d=s'=> \$_branch_dest, 194'dry-run|n'=> \$_dry_run, 195'tag|t'=> \$_tag, 196'username=s'=> \$Git::SVN::Prompt::_username, 197'commit-url=s'=> \$_commit_url} ], 198 tag => [sub{$_tag=1; cmd_branch(@_) }, 199'Create a tag in the SVN repository', 200{'message|m=s'=> \$_message, 201'destination|d=s'=> \$_branch_dest, 202'dry-run|n'=> \$_dry_run, 203'username=s'=> \$Git::SVN::Prompt::_username, 204'commit-url=s'=> \$_commit_url} ], 205'set-tree'=> [ \&cmd_set_tree, 206"Set an SVN repository to a git tree-ish", 207{'stdin'=> \$_stdin,%cmt_opts,%fc_opts, } ], 208'create-ignore'=> [ \&cmd_create_ignore, 209'Create a .gitignore per svn:ignore', 210{'revision|r=i'=> \$_revision 211} ], 212'mkdirs'=> [ \&cmd_mkdirs , 213"recreate empty directories after a checkout", 214{'revision|r=i'=> \$_revision} ], 215'propget'=> [ \&cmd_propget, 216'Print the value of a property on a file or directory', 217{'revision|r=i'=> \$_revision} ], 218'proplist'=> [ \&cmd_proplist, 219'List all properties of a file or directory', 220{'revision|r=i'=> \$_revision} ], 221'show-ignore'=> [ \&cmd_show_ignore,"Show svn:ignore listings", 222{'revision|r=i'=> \$_revision 223} ], 224'show-externals'=> [ \&cmd_show_externals,"Show svn:externals listings", 225{'revision|r=i'=> \$_revision 226} ], 227'multi-fetch'=> [ \&cmd_multi_fetch, 228"Deprecated alias for$0fetch --all", 229{'revision|r=s'=> \$_revision,%fc_opts} ], 230'migrate'=> [sub{ }, 231# no-op, we automatically run this anyways, 232'Migrate configuration/metadata/layout from 233 previous versions of git-svn', 234{'minimize'=> \$Git::SVN::Migration::_minimize, 235%remote_opts} ], 236'log'=> [ \&Git::SVN::Log::cmd_show_log,'Show commit logs', 237{'limit=i'=> \$Git::SVN::Log::limit, 238'revision|r=s'=> \$_revision, 239'verbose|v'=> \$Git::SVN::Log::verbose, 240'incremental'=> \$Git::SVN::Log::incremental, 241'oneline'=> \$Git::SVN::Log::oneline, 242'show-commit'=> \$Git::SVN::Log::show_commit, 243'non-recursive'=> \$Git::SVN::Log::non_recursive, 244'authors-file|A=s'=> \$_authors, 245'color'=> \$Git::SVN::Log::color, 246'pager=s'=> \$Git::SVN::Log::pager 247} ], 248'find-rev'=> [ \&cmd_find_rev, 249"Translate between SVN revision numbers and tree-ish", 250{} ], 251'rebase'=> [ \&cmd_rebase,"Fetch and rebase your working directory", 252{'merge|m|M'=> \$_merge, 253'verbose|v'=> \$_verbose, 254'strategy|s=s'=> \$_strategy, 255'local|l'=> \$_local, 256'fetch-all|all'=> \$_fetch_all, 257'dry-run|n'=> \$_dry_run, 258'preserve-merges|p'=> \$_preserve_merges, 259%fc_opts} ], 260'commit-diff'=> [ \&cmd_commit_diff, 261'Commit a diff between two trees', 262{'message|m=s'=> \$_message, 263'file|F=s'=> \$_file, 264'revision|r=s'=> \$_revision, 265%cmt_opts} ], 266'info'=> [ \&cmd_info, 267"Show info about the latest SVN revision 268 on the current branch", 269{'url'=> \$_url, } ], 270'blame'=> [ \&Git::SVN::Log::cmd_blame, 271"Show what revision and author last modified each line of a file", 272{'git-format'=> \$_git_format} ], 273'reset'=> [ \&cmd_reset, 274"Undo fetches back to the specified SVN revision", 275{'revision|r=s'=> \$_revision, 276'parent|p'=> \$_fetch_parent} ], 277'gc'=> [ \&cmd_gc, 278"Compress unhandled.log files in .git/svn and remove ". 279"index files in .git/svn", 280{} ], 281); 282 283use Term::ReadLine; 284package FakeTerm; 285sub new { 286my($class,$reason) =@_; 287returnbless \$reason,shift; 288} 289subreadline{ 290my$self=shift; 291die"Cannot use readline on FakeTerm:$$self"; 292} 293package main; 294 295my$term=eval{ 296$ENV{"GIT_SVN_NOTTY"} 297? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT 298: new Term::ReadLine 'git-svn'; 299}; 300if($@) { 301$term= new FakeTerm "$@: going non-interactive"; 302} 303 304my$cmd; 305for(my$i=0;$i<@ARGV;$i++) { 306if(defined$cmd{$ARGV[$i]}) { 307$cmd=$ARGV[$i]; 308splice@ARGV,$i,1; 309last; 310}elsif($ARGV[$i]eq'help') { 311$cmd=$ARGV[$i+1]; 312 usage(0); 313} 314}; 315 316# make sure we're always running at the top-level working directory 317unless($cmd&&$cmd=~/(?:clone|init|multi-init)$/) { 318unless(-d $ENV{GIT_DIR}) { 319if($git_dir_user_set) { 320die"GIT_DIR=$ENV{GIT_DIR} explicitly set, ", 321"but it is not a directory\n"; 322} 323my$git_dir=delete$ENV{GIT_DIR}; 324my$cdup=undef; 325 git_cmd_try { 326$cdup= command_oneline(qw/rev-parse --show-cdup/); 327$git_dir='.'unless($cdup); 328chomp$cdupif($cdup); 329$cdup="."unless($cdup&&length$cdup); 330}"Already at toplevel, but$git_dirnot found\n"; 331chdir$cdupor die"Unable to chdir up to '$cdup'\n"; 332unless(-d $git_dir) { 333die"$git_dirstill not found after going to ", 334"'$cdup'\n"; 335} 336$ENV{GIT_DIR} =$git_dir; 337} 338$_repository= Git->repository(Repository =>$ENV{GIT_DIR}); 339} 340 341my%opts= %{$cmd{$cmd}->[2]}if(defined$cmd); 342 343read_git_config(\%opts); 344if($cmd&& ($cmdeq'log'||$cmdeq'blame')) { 345 Getopt::Long::Configure('pass_through'); 346} 347my$rv= GetOptions(%opts,'h|H'=> \$_help,'version|V'=> \$_version, 348'minimize-connections'=> \$Git::SVN::Migration::_minimize, 349'id|i=s'=> \$Git::SVN::default_ref_id, 350'svn-remote|remote|R=s'=>sub{ 351$Git::SVN::no_reuse_existing =1; 352$Git::SVN::default_repo_id =$_[1] }); 353exit1if(!$rv&&$cmd&&$cmdne'log'); 354 355usage(0)if$_help; 356version()if$_version; 357usage(1)unlessdefined$cmd; 358load_authors()if$_authors; 359if(defined$_authors_prog) { 360$_authors_prog="'". File::Spec->rel2abs($_authors_prog) ."'"; 361} 362 363unless($cmd=~/^(?:clone|init|multi-init|commit-diff)$/) { 364 Git::SVN::Migration::migration_check(); 365} 366Git::SVN::init_vars(); 367eval{ 368 Git::SVN::verify_remotes_sanity(); 369$cmd{$cmd}->[0]->(@ARGV); 370 post_fetch_checkout(); 371}; 372fatal $@if$@; 373exit0; 374 375####################### primary functions ###################### 376sub usage { 377my$exit=shift||0; 378my$fd=$exit? \*STDERR : \*STDOUT; 379print$fd<<""; 380git-svn - bidirectional operations between a single Subversion tree and git 381Usage: git svn <command> [options] [arguments]\n 382 383print$fd"Available commands:\n"unless$cmd; 384 385foreach(sort keys%cmd) { 386next if$cmd&&$cmdne$_; 387next if/^multi-/;# don't show deprecated commands 388print$fd' ',pack('A17',$_),$cmd{$_}->[1],"\n"; 389foreach(sort keys%{$cmd{$_}->[2]}) { 390# mixed-case options are for .git/config only 391next if/[A-Z]/&&/^[a-z]+$/i; 392# prints out arguments as they should be passed: 393my$x= s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : ''; 394print$fd' ' x 21,join(', ',map{length$_>1? 395"--$_":"-$_"} 396split/\|/,$_),"$x\n"; 397} 398} 399print$fd<<""; 400\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an 401arbitrary identifier if you're tracking multiple SVN branches/repositories in 402one git repository and want to keep them separate. See git-svn(1) for more 403information. 404 405 exit$exit; 406} 407 408sub version { 409 ::_req_svn(); 410 print "git-svn version$VERSION(svn$SVN::Core::VERSION)\n"; 411 exit 0; 412} 413 414sub ask { 415 my ($prompt,%arg) =@_; 416 my$valid_re=$arg{valid_re}; 417 my$default=$arg{default}; 418 my$resp; 419 my$i= 0; 420 421 if ( !( defined($term->IN) 422 && defined( fileno($term->IN) ) 423 && defined($term->OUT ) 424 && defined( fileno($term->OUT) ) ) ){ 425 return defined($default) ?$default: undef; 426 } 427 428 while ($i++< 10) { 429$resp=$term->readline($prompt); 430 if (!defined$resp) { # EOF 431 print "\n"; 432 return defined$default?$default: undef; 433 } 434 if ($respeq '' and defined$default) { 435 return$default; 436 } 437 if (!defined$valid_reor$resp=~ /$valid_re/) { 438 return$resp; 439 } 440 } 441 return undef; 442} 443 444sub do_git_init_db { 445 unless (-d$ENV{GIT_DIR}) { 446 my@init_db= ('init'); 447 push@init_db, "--template=$_template" if defined$_template; 448 if (defined$_shared) { 449 if ($_shared=~ /[a-z]/) { 450 push@init_db, "--shared=$_shared"; 451 } else { 452 push@init_db, "--shared"; 453 } 454 } 455 command_noisy(@init_db); 456$_repository= Git->repository(Repository => ".git"); 457 } 458 my$set; 459 my$pfx= "svn-remote.$Git::SVN::default_repo_id"; 460 foreach my$i(keys%icv) { 461 die "'$set' and '$i' cannot both be set\n" if$set; 462 next unless defined$icv{$i}; 463 command_noisy('config', "$pfx.$i",$icv{$i}); 464$set=$i; 465 } 466 my$ignore_paths_regex= \$Git::SVN::Fetcher::_ignore_regex; 467 command_noisy('config', "$pfx.ignore-paths",$$ignore_paths_regex) 468 if defined$$ignore_paths_regex; 469 my$ignore_refs_regex= \$Git::SVN::Ra::_ignore_refs_regex; 470 command_noisy('config', "$pfx.ignore-refs",$$ignore_refs_regex) 471 if defined$$ignore_refs_regex; 472 473 if (defined$Git::SVN::Fetcher::_preserve_empty_dirs) { 474 my$fname= \$Git::SVN::Fetcher::_placeholder_filename; 475 command_noisy('config', "$pfx.preserve-empty-dirs", 'true'); 476 command_noisy('config', "$pfx.placeholder-filename",$$fname); 477 } 478} 479 480sub init_subdir { 481 my$repo_path= shift or return; 482 mkpath([$repo_path]) unless -d$repo_path; 483 chdir$repo_pathor die "Couldn't chdir to $repo_path:$!\n"; 484$ENV{GIT_DIR} = '.git'; 485$_repository= Git->repository(Repository =>$ENV{GIT_DIR}); 486} 487 488sub cmd_clone { 489 my ($url,$path) =@_; 490 if (!defined$path&& 491 (defined$_trunk||@_branches||@_tags|| 492 defined$_stdlayout) && 493$url!~ m#^[a-z\+]+://#) { 494$path=$url; 495 } 496$path= basename($url) if !defined$path|| !length$path; 497 my$authors_absolute=$_authors? File::Spec->rel2abs($_authors) : ""; 498 cmd_init($url,$path); 499 command_oneline('config', 'svn.authorsfile',$authors_absolute) 500 if$_authors; 501 Git::SVN::fetch_all($Git::SVN::default_repo_id); 502} 503 504sub cmd_init { 505 if (defined$_stdlayout) { 506$_trunk= 'trunk' if (!defined$_trunk); 507@_tags= 'tags' if (!@_tags); 508@_branches= 'branches' if (!@_branches); 509 } 510 if (defined$_trunk||@_branches||@_tags) { 511 return cmd_multi_init(@_); 512 } 513 my$url= shift or die "SVN repository location required ", 514 "as a command-line argument\n"; 515$url= canonicalize_url($url); 516 init_subdir(@_); 517 do_git_init_db(); 518 519 if ($Git::SVN::_minimize_url eq 'unset') { 520$Git::SVN::_minimize_url = 0; 521 } 522 523 Git::SVN->init($url); 524} 525 526sub cmd_fetch { 527 if (grep /^\d+=./,@_) { 528 die "'<rev>=<commit>' fetch arguments are ", 529 "no longer supported.\n"; 530 } 531 my ($remote) =@_; 532 if (@_> 1) { 533 die "Usage:$0 fetch [--all] [--parent] [svn-remote]\n"; 534 } 535$Git::SVN::no_reuse_existing = undef; 536 if ($_fetch_parent) { 537 my ($url,$rev,$uuid,$gs) = working_head_info('HEAD'); 538 unless ($gs) { 539 die "Unable to determine upstream SVN information from ", 540 "working tree history\n"; 541 } 542 # just fetch, don't checkout. 543$_no_checkout= 'true'; 544$_fetch_all?$gs->fetch_all :$gs->fetch; 545 } elsif ($_fetch_all) { 546 cmd_multi_fetch(); 547 } else { 548$remote||=$Git::SVN::default_repo_id; 549 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes()); 550 } 551} 552 553sub cmd_set_tree { 554 my (@commits) =@_; 555 if ($_stdin|| !@commits) { 556 print "Reading from stdin...\n"; 557@commits= (); 558 while (<STDIN>) { 559 if (/\b($sha1_short)\b/o) { 560 unshift@commits,$1; 561 } 562 } 563 } 564 my@revs; 565 foreach my$c(@commits) { 566 my@tmp= command('rev-parse',$c); 567 if (scalar@tmp== 1) { 568 push@revs,$tmp[0]; 569 } elsif (scalar@tmp> 1) { 570 push@revs, reverse(command('rev-list',@tmp)); 571 } else { 572 fatal "Failed to rev-parse $c"; 573 } 574 } 575 my$gs= Git::SVN->new; 576 my ($r_last,$cmt_last) =$gs->last_rev_commit; 577$gs->fetch; 578 if (defined$gs->{last_rev} &&$r_last!=$gs->{last_rev}) { 579 fatal "There are new revisions that were fetched ", 580 "and need to be merged (or acknowledged)", 581 "before committing.\nlast rev:$r_last\n", 582 " current:$gs->{last_rev}"; 583 } 584$gs->set_tree($_) foreach@revs; 585 print "Done committing ",scalar@revs," revisions to SVN\n"; 586 unlink$gs->{index}; 587} 588 589sub split_merge_info_range { 590 my ($range) =@_; 591 if ($range=~ /(\d+)-(\d+)/) { 592 return (int($1), int($2)); 593 } else { 594 return (int($range), int($range)); 595 } 596} 597 598sub combine_ranges { 599 my ($in) =@_; 600 601 my@fnums= (); 602 my@arr= split(/,/,$in); 603 for my$element(@arr) { 604 my ($start,$end) = split_merge_info_range($element); 605 push@fnums,$start; 606 } 607 608 my@sorted=@arr[ sort { 609$fnums[$a] <=>$fnums[$b] 610 } 0..$#arr]; 611 612 my@return= (); 613 my$last= -1; 614 my$first= -1; 615 for my$element(@sorted) { 616 my ($start,$end) = split_merge_info_range($element); 617 618 if ($last== -1) { 619$first=$start; 620$last=$end; 621 next; 622 } 623 if ($start<=$last+1) { 624 if ($end>$last) { 625$last=$end; 626 } 627 next; 628 } 629 if ($first==$last) { 630 push@return, "$first"; 631 } else { 632 push@return, "$first-$last"; 633 } 634$first=$start; 635$last=$end; 636 } 637 638 if ($first!= -1) { 639 if ($first==$last) { 640 push@return, "$first"; 641 } else { 642 push@return, "$first-$last"; 643 } 644 } 645 646 return join(',',@return); 647} 648 649sub merge_revs_into_hash { 650 my ($hash,$minfo) =@_; 651 my@lines= split(' ',$minfo); 652 653 for my$line(@lines) { 654 my ($branchpath,$revs) = split(/:/,$line); 655 656 if (exists($hash->{$branchpath})) { 657 # Merge the two revision sets 658 my$combined= "$hash->{$branchpath},$revs"; 659$hash->{$branchpath} = combine_ranges($combined); 660 } else { 661 # Just do range combining for consolidation 662$hash->{$branchpath} = combine_ranges($revs); 663 } 664 } 665} 666 667sub merge_merge_info { 668 my ($mergeinfo_one,$mergeinfo_two) =@_; 669 my%result_hash= (); 670 671 merge_revs_into_hash(\%result_hash,$mergeinfo_one); 672 merge_revs_into_hash(\%result_hash,$mergeinfo_two); 673 674 my$result= ''; 675 # Sort below is for consistency's sake 676 for my$branchname(sort keys(%result_hash)) { 677 my$revlist=$result_hash{$branchname}; 678$result.= "$branchname:$revlist\n" 679 } 680 return$result; 681} 682 683sub populate_merge_info { 684 my ($d,$gs,$uuid,$linear_refs,$rewritten_parent) =@_; 685 686 my%parentshash; 687 read_commit_parents(\%parentshash,$d); 688 my@parents= @{$parentshash{$d}}; 689 if ($#parents> 0) { 690 # Merge commit 691 my$all_parents_ok= 1; 692 my$aggregate_mergeinfo= ''; 693 my$rooturl=$gs->repos_root; 694 695 if (defined($rewritten_parent)) { 696 # Replace first parent with newly-rewritten version 697 shift@parents; 698 unshift@parents,$rewritten_parent; 699 } 700 701 foreach my$parent(@parents) { 702 my ($branchurl,$svnrev,$paruuid) = 703 cmt_metadata($parent); 704 705 unless (defined($svnrev)) { 706 # Should have been caught be preflight check 707 fatal "merge commit $dhas ancestor $parent, but that change " 708 ."doesnot have git-svn metadata!"; 709 } 710 unless ($branchurl=~ /^\Q$rooturl\E(.*)/) { 711 fatal "commit $parent git-svn metadata changed mid-run!"; 712 } 713 my$branchpath=$1; 714 715 my$ra= Git::SVN::Ra->new($branchurl); 716 my (undef, undef,$props) = 717$ra->get_dir(canonicalize_path("."),$svnrev); 718 my$par_mergeinfo=$props->{'svn:mergeinfo'}; 719 unless (defined$par_mergeinfo) { 720$par_mergeinfo= ''; 721 } 722 # Merge previous mergeinfo values 723$aggregate_mergeinfo= 724 merge_merge_info($aggregate_mergeinfo, 725$par_mergeinfo, 0); 726 727 next if$parenteq$parents[0]; # Skip first parent 728 # Add new changes being placed in tree by merge 729 my@cmd= (qw/rev-list --reverse/, 730$parent, qw/--not/); 731 foreach my$par(@parents) { 732 unless ($pareq$parent) { 733 push@cmd,$par; 734 } 735 } 736 my@revsin= (); 737 my ($revlist,$ctx) = command_output_pipe(@cmd); 738 while (<$revlist>) { 739 my$irev=$_; 740 chomp$irev; 741 my (undef,$csvnrev, undef) = 742 cmt_metadata($irev); 743 unless (defined$csvnrev) { 744 # A child is missing SVN annotations... 745 # this might be OK, or might not be. 746 warn "W:child $irevis merged into revision " 747 ."$d but doesnot have git-svn metadata." 748 ."This means git-svn cannot determine the " 749 ."svn revision numbers to place into the " 750 ."svn:mergeinfo property. You must ensure " 751 ."a branch is entirely committed to " 752 ."SVN before merging it in order for" 753 ."svn:mergeinfo population to function " 754 ."properly"; 755 } 756 push@revsin,$csvnrev; 757 } 758 command_close_pipe($revlist,$ctx); 759 760 last unless$all_parents_ok; 761 762 # We now have a list of all SVN revnos which are 763 # merged by this particular parent. Integrate them. 764 next if$#revsin== -1; 765 my$newmergeinfo= "$branchpath:" . join(',',@revsin); 766$aggregate_mergeinfo= 767 merge_merge_info($aggregate_mergeinfo, 768$newmergeinfo, 1); 769 } 770 if ($all_parents_okand$aggregate_mergeinfo) { 771 return$aggregate_mergeinfo; 772 } 773 } 774 775 return undef; 776} 777 778sub cmd_dcommit { 779 my$head= shift; 780 command_noisy(qw/update-index --refresh/); 781 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) } 782 'Cannot dcommit with a dirty index. Commit your changes first, ' 783 . "or stash them with `git stash'.\n"; 784$head||= 'HEAD'; 785 786 my$old_head; 787 if ($headne 'HEAD') { 788$old_head= eval { 789 command_oneline([qw/symbolic-ref -q HEAD/]) 790 }; 791 if ($old_head) { 792$old_head=~ s{^refs/heads/}{}; 793 } else { 794$old_head= eval { command_oneline(qw/rev-parse HEAD/) }; 795 } 796 command(['checkout',$head], STDERR => 0); 797 } 798 799 my@refs; 800 my ($url,$rev,$uuid,$gs) = working_head_info('HEAD', \@refs); 801 unless ($gs) { 802 die "Unable to determine upstream SVN information from ", 803 "$headhistory.\nPerhaps the repository is empty."; 804 } 805 806 if (defined$_commit_url) { 807$url=$_commit_url; 808 } else { 809$url= eval { command_oneline('config', '--get', 810 "svn-remote.$gs->{repo_id}.commiturl") }; 811 if (!$url) { 812$url=$gs->full_pushurl 813 } 814 } 815 816 my$last_rev=$_revisionif defined$_revision; 817 if ($url) { 818 print "Committing to$url...\n"; 819 } 820 my ($linear_refs,$parents) = linearize_history($gs, \@refs); 821 if ($_no_rebase&& scalar(@$linear_refs) > 1) { 822 warn "Attempting to commit more than one change while ", 823 "--no-rebase is enabled.\n", 824 "If these changes depend on each other, re-running ", 825 "without --no-rebase may be required." 826 } 827 828 if (defined$_interactive){ 829 my$ask_default= "y"; 830 foreach my$d(@$linear_refs){ 831 my ($fh,$ctx) = command_output_pipe(qw(show --summary),"$d"); 832while(<$fh>){ 833print$_; 834} 835 command_close_pipe($fh,$ctx); 836$_= ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ", 837 valid_re =>qr/^(?:yes|y|no|n|quit|q|all|a)/i, 838default=>$ask_default); 839die"Commit this patch reply required"unlessdefined$_; 840if(/^[nq]/i) { 841exit(0); 842}elsif(/^a/i) { 843last; 844} 845} 846} 847 848my$expect_url=$url; 849 850my$push_merge_info=eval{ 851 command_oneline(qw/config --get svn.pushmergeinfo/) 852}; 853if(not defined($push_merge_info) 854or$push_merge_infoeq"false" 855or$push_merge_infoeq"no" 856or$push_merge_infoeq"never") { 857$push_merge_info=0; 858} 859 860unless(defined($_merge_info) || !$push_merge_info) { 861# Preflight check of changes to ensure no issues with mergeinfo 862# This includes check for uncommitted-to-SVN parents 863# (other than the first parent, which we will handle), 864# information from different SVN repos, and paths 865# which are not underneath this repository root. 866my$rooturl=$gs->repos_root; 867foreachmy$d(@$linear_refs) { 868my%parentshash; 869 read_commit_parents(\%parentshash,$d); 870my@realparents= @{$parentshash{$d}}; 871if($#realparents>0) { 872# Merge commit 873shift@realparents;# Remove/ignore first parent 874foreachmy$parent(@realparents) { 875my($branchurl,$svnrev,$paruuid) = cmt_metadata($parent); 876unless(defined$paruuid) { 877# A parent is missing SVN annotations... 878# abort the whole operation. 879 fatal "$parentis merged into revision$d, " 880."but does not have git-svn metadata. " 881."Either dcommit the branch or use a " 882."local cherry-pick, FF merge, or rebase " 883."instead of an explicit merge commit."; 884} 885 886unless($paruuideq$uuid) { 887# Parent has SVN metadata from different repository 888 fatal "merge parent$parentfor change$dhas " 889."git-svn uuid$paruuid, while current change " 890."has uuid$uuid!"; 891} 892 893unless($branchurl=~/^\Q$rooturl\E(.*)/) { 894# This branch is very strange indeed. 895 fatal "merge parent$parentfor$dis on branch " 896."$branchurl, which is not under the " 897."git-svn root$rooturl!"; 898} 899} 900} 901} 902} 903 904my$rewritten_parent; 905 Git::SVN::remove_username($expect_url); 906if(defined($_merge_info)) { 907$_merge_info=~tr{ }{\n}; 908} 909while(1) { 910my$d=shift@$linear_refsorlast; 911unless(defined$last_rev) { 912(undef,$last_rev,undef) = cmt_metadata("$d~1"); 913unless(defined$last_rev) { 914 fatal "Unable to extract revision information ", 915"from commit$d~1"; 916} 917} 918if($_dry_run) { 919print"diff-tree$d~1$d\n"; 920}else{ 921my$cmt_rev; 922 923unless(defined($_merge_info) || !$push_merge_info) { 924$_merge_info= populate_merge_info($d,$gs, 925$uuid, 926$linear_refs, 927$rewritten_parent); 928} 929 930my%ed_opts= ( r =>$last_rev, 931log=> get_commit_entry($d)->{log}, 932 ra => Git::SVN::Ra->new($url), 933 config => SVN::Core::config_get_config( 934$Git::SVN::Ra::config_dir 935), 936 tree_a =>"$d~1", 937 tree_b =>$d, 938 editor_cb =>sub{ 939print"Committed r$_[0]\n"; 940$cmt_rev=$_[0]; 941}, 942 mergeinfo =>$_merge_info, 943 svn_path =>''); 944if(!Git::SVN::Editor->new(\%ed_opts)->apply_diff) { 945print"No changes\n$d~1==$d\n"; 946}elsif($parents->{$d} && @{$parents->{$d}}) { 947$gs->{inject_parents_dcommit}->{$cmt_rev} = 948$parents->{$d}; 949} 950$_fetch_all?$gs->fetch_all:$gs->fetch; 951$last_rev=$cmt_rev; 952next if$_no_rebase; 953 954# we always want to rebase against the current HEAD, 955# not any head that was passed to us 956my@diff= command('diff-tree',$d, 957$gs->refname,'--'); 958my@finish; 959if(@diff) { 960@finish= rebase_cmd(); 961print STDERR "W:$dand ",$gs->refname, 962" differ, using@finish:\n", 963join("\n",@diff),"\n"; 964}else{ 965print"No changes between current HEAD and ", 966$gs->refname, 967"\nResetting to the latest ", 968$gs->refname,"\n"; 969@finish= qw/reset --mixed/; 970} 971 command_noisy(@finish,$gs->refname); 972 973$rewritten_parent= command_oneline(qw/rev-parse HEAD/); 974 975if(@diff) { 976@refs= (); 977my($url_,$rev_,$uuid_,$gs_) = 978 working_head_info('HEAD', \@refs); 979my($linear_refs_,$parents_) = 980 linearize_history($gs_, \@refs); 981if(scalar(@$linear_refs) != 982scalar(@$linear_refs_)) { 983 fatal "# of revisions changed ", 984"\nbefore:\n", 985join("\n",@$linear_refs), 986"\n\nafter:\n", 987join("\n",@$linear_refs_),"\n", 988'If you are attempting to commit ', 989"merges, try running:\n\t", 990'git rebase --interactive', 991'--preserve-merges ', 992$gs->refname, 993"\nBefore dcommitting"; 994} 995if($url_ne$expect_url) { 996if($url_eq$gs->metadata_url) { 997print 998"Accepting rewritten URL:", 999"$url_\n";1000}else{1001 fatal1002"URL mismatch after rebase:",1003"$url_!=$expect_url";1004}1005}1006if($uuid_ne$uuid) {1007 fatal "uuid mismatch after rebase: ",1008"$uuid_!=$uuid";1009}1010# remap parents1011my(%p,@l,$i);1012for($i=0;$i<scalar@$linear_refs;$i++) {1013my$new=$linear_refs_->[$i]ornext;1014$p{$new} =1015$parents->{$linear_refs->[$i]};1016push@l,$new;1017}1018$parents= \%p;1019$linear_refs= \@l;1020}1021}1022}10231024if($old_head) {1025my$new_head= command_oneline(qw/rev-parse HEAD/);1026my$new_is_symbolic=eval{1027 command_oneline(qw/symbolic-ref -q HEAD/);1028};1029if($new_is_symbolic) {1030print"dcommitted the branch ",$head,"\n";1031}else{1032print"dcommitted on a detached HEAD because you gave ",1033"a revision argument.\n",1034"The rewritten commit is: ",$new_head,"\n";1035}1036 command(['checkout',$old_head], STDERR =>0);1037}10381039unlink$gs->{index};1040}10411042sub cmd_branch {1043my($branch_name,$head) =@_;10441045unless(defined$branch_name&&length$branch_name) {1046die(($_tag?"tag":"branch") ." name required\n");1047}1048$head||='HEAD';10491050my(undef,$rev,undef,$gs) = working_head_info($head);1051my$src=$gs->full_pushurl;10521053my$remote= Git::SVN::read_all_remotes()->{$gs->{repo_id}};1054my$allglobs=$remote->{$_tag?'tags':'branches'};1055my$glob;1056if($#{$allglobs} ==0) {1057$glob=$allglobs->[0];1058}else{1059unless(defined$_branch_dest) {1060die"Multiple ",1061$_tag?"tag":"branch",1062" paths defined for Subversion repository.\n",1063"You must specify where you want to create the ",1064$_tag?"tag":"branch",1065" with the --destination argument.\n";1066}1067foreachmy$g(@{$allglobs}) {1068my$re= Git::SVN::Editor::glob2pat($g->{path}->{left});1069if($_branch_dest=~/$re/) {1070$glob=$g;1071last;1072}1073}1074unless(defined$glob) {1075my$dest_re=qr/\b\Q$_branch_dest\E\b/;1076foreachmy$g(@{$allglobs}) {1077$g->{path}->{left} =~/$dest_re/ornext;1078if(defined$glob) {1079die"Ambiguous destination: ",1080$_branch_dest,"\nmatches both '",1081$glob->{path}->{left},"' and '",1082$g->{path}->{left},"'\n";1083}1084$glob=$g;1085}1086unless(defined$glob) {1087die"Unknown ",1088$_tag?"tag":"branch",1089" destination$_branch_dest\n";1090}1091}1092}1093my($lft,$rgt) = @{$glob->{path} }{qw/left right/};1094my$url;1095if(defined$_commit_url) {1096$url=$_commit_url;1097}else{1098$url=eval{ command_oneline('config','--get',1099"svn-remote.$gs->{repo_id}.commiturl") };1100if(!$url) {1101$url=$remote->{pushurl} ||$remote->{url};1102}1103}1104my$dst=join'/',$url,$lft,$branch_name, ($rgt|| ());11051106if($dst=~/^https:/&&$src=~/^http:/) {1107$src=~s/^http:/https:/;1108}11091110::_req_svn();11111112my$ctx= SVN::Client->new(1113 auth => Git::SVN::Ra::_auth_providers(),1114 log_msg =>sub{1115${$_[0] } =defined$_message1116?$_message1117:'Create '. ($_tag?'tag ':'branch ')1118.$branch_name;1119},1120);11211122eval{1123$ctx->ls($dst,'HEAD',0);1124}and die"branch ${branch_name} already exists\n";11251126print"Copying ${src} at r${rev} to ${dst}...\n";1127$ctx->copy($src,$rev,$dst)1128unless$_dry_run;11291130$gs->fetch_all;1131}11321133sub cmd_find_rev {1134my$revision_or_hash=shift or die"SVN or git revision required ",1135"as a command-line argument\n";1136my$result;1137if($revision_or_hash=~/^r\d+$/) {1138my$head=shift;1139$head||='HEAD';1140my@refs;1141my(undef,undef,$uuid,$gs) = working_head_info($head, \@refs);1142unless($gs) {1143die"Unable to determine upstream SVN information from ",1144"$headhistory\n";1145}1146my$desired_revision=substr($revision_or_hash,1);1147$result=$gs->rev_map_get($desired_revision,$uuid);1148}else{1149my(undef,$rev,undef) = cmt_metadata($revision_or_hash);1150$result=$rev;1151}1152print"$result\n"if$result;1153}11541155sub auto_create_empty_directories {1156my($gs) =@_;1157my$var=eval{ command_oneline('config','--get','--bool',1158"svn-remote.$gs->{repo_id}.automkdirs") };1159# By default, create empty directories by consulting the unhandled log,1160# but allow setting it to 'false' to skip it.1161return!($var&&$vareq'false');1162}11631164sub cmd_rebase {1165 command_noisy(qw/update-index --refresh/);1166my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1167unless($gs) {1168die"Unable to determine upstream SVN information from ",1169"working tree history\n";1170}1171if($_dry_run) {1172print"Remote Branch: ".$gs->refname."\n";1173print"SVN URL: ".$url."\n";1174return;1175}1176if(command(qw/diff-index HEAD --/)) {1177print STDERR "Cannot rebase with uncommited changes:\n";1178 command_noisy('status');1179exit1;1180}1181unless($_local) {1182# rebase will checkout for us, so no need to do it explicitly1183$_no_checkout='true';1184$_fetch_all?$gs->fetch_all:$gs->fetch;1185}1186 command_noisy(rebase_cmd(),$gs->refname);1187if(auto_create_empty_directories($gs)) {1188$gs->mkemptydirs;1189}1190}11911192sub cmd_show_ignore {1193my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1194$gs||= Git::SVN->new;1195my$r= (defined$_revision?$_revision:$gs->ra->get_latest_revnum);1196$gs->prop_walk($gs->{path},$r,sub{1197my($gs,$path,$props) =@_;1198print STDOUT "\n#$path\n";1199my$s=$props->{'svn:ignore'}orreturn;1200$s=~s/[\r\n]+/\n/g;1201$s=~s/^\n+//;1202chomp$s;1203$s=~ s#^#$path#gm;1204print STDOUT "$s\n";1205});1206}12071208sub cmd_show_externals {1209my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1210$gs||= Git::SVN->new;1211my$r= (defined$_revision?$_revision:$gs->ra->get_latest_revnum);1212$gs->prop_walk($gs->{path},$r,sub{1213my($gs,$path,$props) =@_;1214print STDOUT "\n#$path\n";1215my$s=$props->{'svn:externals'}orreturn;1216$s=~s/[\r\n]+/\n/g;1217chomp$s;1218$s=~ s#^#$path#gm;1219print STDOUT "$s\n";1220});1221}12221223sub cmd_create_ignore {1224my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1225$gs||= Git::SVN->new;1226my$r= (defined$_revision?$_revision:$gs->ra->get_latest_revnum);1227$gs->prop_walk($gs->{path},$r,sub{1228my($gs,$path,$props) =@_;1229# $path is of the form /path/to/dir/1230$path='.'.$path;1231# SVN can have attributes on empty directories,1232# which git won't track1233 mkpath([$path])unless-d $path;1234my$ignore=$path.'.gitignore';1235my$s=$props->{'svn:ignore'}orreturn;1236open(GITIGNORE,'>',$ignore)1237or fatal("Failed to open `$ignore' for writing:$!");1238$s=~s/[\r\n]+/\n/g;1239$s=~s/^\n+//;1240chomp$s;1241# Prefix all patterns so that the ignore doesn't apply1242# to sub-directories.1243$s=~ s#^#/#gm;1244print GITIGNORE "$s\n";1245close(GITIGNORE)1246or fatal("Failed to close `$ignore':$!");1247 command_noisy('add','-f',$ignore);1248});1249}12501251sub cmd_mkdirs {1252my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1253$gs||= Git::SVN->new;1254$gs->mkemptydirs($_revision);1255}12561257sub canonicalize_path {1258my($path) =@_;1259my$dot_slash_added=0;1260if(substr($path,0,1)ne"/") {1261$path="./".$path;1262$dot_slash_added=1;1263}1264# File::Spec->canonpath doesn't collapse x/../y into y (for a1265# good reason), so let's do this manually.1266$path=~ s#/+#/#g;1267$path=~ s#/\.(?:/|$)#/#g;1268$path=~ s#/[^/]+/\.\.##g;1269$path=~ s#/$##g;1270$path=~ s#^\./## if $dot_slash_added;1271$path=~ s#^/##;1272$path=~ s#^\.$##;1273return$path;1274}12751276sub canonicalize_url {1277my($url) =@_;1278$url=~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;1279return$url;1280}12811282# get_svnprops(PATH)1283# ------------------1284# Helper for cmd_propget and cmd_proplist below.1285sub get_svnprops {1286my$path=shift;1287my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1288$gs||= Git::SVN->new;12891290# prefix THE PATH by the sub-directory from which the user1291# invoked us.1292$path=$cmd_dir_prefix.$path;1293 fatal("No such file or directory:$path")unless-e $path;1294my$is_dir= -d $path?1:0;1295$path=$gs->{path} .'/'.$path;12961297# canonicalize the path (otherwise libsvn will abort or fail to1298# find the file)1299$path= canonicalize_path($path);13001301my$r= (defined$_revision?$_revision:$gs->ra->get_latest_revnum);1302my$props;1303if($is_dir) {1304(undef,undef,$props) =$gs->ra->get_dir($path,$r);1305}1306else{1307(undef,$props) =$gs->ra->get_file($path,$r,undef);1308}1309return$props;1310}13111312# cmd_propget (PROP, PATH)1313# ------------------------1314# Print the SVN property PROP for PATH.1315sub cmd_propget {1316my($prop,$path) =@_;1317$path='.'ifnot defined$path;1318 usage(1)ifnot defined$prop;1319my$props= get_svnprops($path);1320if(not defined$props->{$prop}) {1321 fatal("`$path' does not have a `$prop' SVN property.");1322}1323print$props->{$prop} ."\n";1324}13251326# cmd_proplist (PATH)1327# -------------------1328# Print the list of SVN properties for PATH.1329sub cmd_proplist {1330my$path=shift;1331$path='.'ifnot defined$path;1332my$props= get_svnprops($path);1333print"Properties on '$path':\n";1334foreach(sort keys%{$props}) {1335print"$_\n";1336}1337}13381339sub cmd_multi_init {1340my$url=shift;1341unless(defined$_trunk||@_branches||@_tags) {1342 usage(1);1343}13441345$_prefix=''unlessdefined$_prefix;1346if(defined$url) {1347$url= canonicalize_url($url);1348 init_subdir(@_);1349}1350 do_git_init_db();1351if(defined$_trunk) {1352$_trunk=~ s#^/+##;1353my$trunk_ref='refs/remotes/'.$_prefix.'trunk';1354# try both old-style and new-style lookups:1355my$gs_trunk=eval{ Git::SVN->new($trunk_ref) };1356unless($gs_trunk) {1357my($trunk_url,$trunk_path) =1358 complete_svn_url($url,$_trunk);1359$gs_trunk= Git::SVN->init($trunk_url,$trunk_path,1360undef,$trunk_ref);1361}1362}1363return unless@_branches||@_tags;1364my$ra=$url? Git::SVN::Ra->new($url) :undef;1365foreachmy$path(@_branches) {1366 complete_url_ls_init($ra,$path,'--branches/-b',$_prefix);1367}1368foreachmy$path(@_tags) {1369 complete_url_ls_init($ra,$path,'--tags/-t',$_prefix.'tags/');1370}1371}13721373sub cmd_multi_fetch {1374$Git::SVN::no_reuse_existing =undef;1375my$remotes= Git::SVN::read_all_remotes();1376foreachmy$repo_id(sort keys%$remotes) {1377if($remotes->{$repo_id}->{url}) {1378 Git::SVN::fetch_all($repo_id,$remotes);1379}1380}1381}13821383# this command is special because it requires no metadata1384sub cmd_commit_diff {1385my($ta,$tb,$url) =@_;1386my$usage="Usage:$0commit-diff -r<revision> ".1387"<tree-ish> <tree-ish> [<URL>]";1388 fatal($usage)if(!defined$ta|| !defined$tb);1389my$svn_path='';1390if(!defined$url) {1391my$gs=eval{ Git::SVN->new};1392if(!$gs) {1393 fatal("Needed URL or usable git-svn --id in ",1394"the command-line\n",$usage);1395}1396$url=$gs->{url};1397$svn_path=$gs->{path};1398}1399unless(defined$_revision) {1400 fatal("-r|--revision is a required argument\n",$usage);1401}1402if(defined$_message&&defined$_file) {1403 fatal("Both --message/-m and --file/-F specified ",1404"for the commit message.\n",1405"I have no idea what you mean");1406}1407if(defined$_file) {1408$_message= file_to_s($_file);1409}else{1410$_message||= get_commit_entry($tb)->{log};1411}1412my$ra||= Git::SVN::Ra->new($url);1413my$r=$_revision;1414if($req'HEAD') {1415$r=$ra->get_latest_revnum;1416}elsif($r!~/^\d+$/) {1417die"revision argument:$rnot understood by git-svn\n";1418}1419my%ed_opts= ( r =>$r,1420log=>$_message,1421 ra =>$ra,1422 tree_a =>$ta,1423 tree_b =>$tb,1424 editor_cb =>sub{print"Committed r$_[0]\n"},1425 svn_path =>$svn_path);1426if(!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {1427print"No changes\n$ta==$tb\n";1428}1429}14301431sub escape_uri_only {1432my($uri) =@_;1433my@tmp;1434foreach(splitm{/},$uri) {1435s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;1436push@tmp,$_;1437}1438join('/',@tmp);1439}14401441sub escape_url {1442my($url) =@_;1443if($url=~ m#^([^:]+)://([^/]*)(.*)$#) {1444my($scheme,$domain,$uri) = ($1,$2, escape_uri_only($3));1445$url="$scheme://$domain$uri";1446}1447$url;1448}14491450sub cmd_info {1451my$path= canonicalize_path(defined($_[0]) ?$_[0] :".");1452my$fullpath= canonicalize_path($cmd_dir_prefix.$path);1453if(exists$_[1]) {1454die"Too many arguments specified\n";1455}14561457my($file_type,$diff_status) = find_file_type_and_diff_status($path);14581459if(!$file_type&& !$diff_status) {1460print STDERR "svn: '$path' is not under version control\n";1461exit1;1462}14631464my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1465unless($gs) {1466die"Unable to determine upstream SVN information from ",1467"working tree history\n";1468}14691470# canonicalize_path() will return "" to make libsvn 1.5.x happy,1471$path="."if$patheq"";14721473my$full_url=$url. ($fullpatheq""?"":"/$fullpath");14741475if($_url) {1476print escape_url($full_url),"\n";1477return;1478}14791480my$result="Path:$path\n";1481$result.="Name: ". basename($path) ."\n"if$file_typene"dir";1482$result.="URL: ". escape_url($full_url) ."\n";14831484eval{1485my$repos_root=$gs->repos_root;1486 Git::SVN::remove_username($repos_root);1487$result.="Repository Root: ". escape_url($repos_root) ."\n";1488};1489if($@) {1490$result.="Repository Root: (offline)\n";1491}1492::_req_svn();1493$result.="Repository UUID:$uuid\n"unless$diff_statuseq"A"&&1494(::compare_svn_version('1.5.4') <=0||$file_typene"dir");1495$result.="Revision: ". ($diff_statuseq"A"?0:$rev) ."\n";14961497$result.="Node Kind: ".1498($file_typeeq"dir"?"directory":"file") ."\n";14991500my$schedule=$diff_statuseq"A"1501?"add"1502: ($diff_statuseq"D"?"delete":"normal");1503$result.="Schedule:$schedule\n";15041505if($diff_statuseq"A") {1506print$result,"\n";1507return;1508}15091510my($lc_author,$lc_rev,$lc_date_utc);1511my@args= Git::SVN::Log::git_svn_log_cmd($rev,$rev,"--",$fullpath);1512my$log= command_output_pipe(@args);1513my$esc_color=qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;1514while(<$log>) {1515if(/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {1516$lc_author=$1;1517$lc_date_utc= Git::SVN::Log::parse_git_date($2,$3);1518}elsif(/^${esc_color} (git-svn-id:.+)$/o) {1519(undef,$lc_rev,undef) = ::extract_metadata($1);1520}1521}1522close$log;15231524 Git::SVN::Log::set_local_timezone();15251526$result.="Last Changed Author:$lc_author\n";1527$result.="Last Changed Rev:$lc_rev\n";1528$result.="Last Changed Date: ".1529 Git::SVN::Log::format_svn_date($lc_date_utc) ."\n";15301531if($file_typene"dir") {1532my$text_last_updated_date=1533($diff_statuseq"D"?$lc_date_utc: (stat$path)[9]);1534$result.=1535"Text Last Updated: ".1536 Git::SVN::Log::format_svn_date($text_last_updated_date) .1537"\n";1538my$checksum;1539if($diff_statuseq"D") {1540my($fh,$ctx) =1541 command_output_pipe(qw(cat-file blob),"HEAD:$path");1542if($file_typeeq"link") {1543my$file_name= <$fh>;1544$checksum= md5sum("link$file_name");1545}else{1546$checksum= md5sum($fh);1547}1548 command_close_pipe($fh,$ctx);1549}elsif($file_typeeq"link") {1550my$file_name=1551 command(qw(cat-file blob),"HEAD:$path");1552$checksum=1553 md5sum("link ".$file_name);1554}else{1555open FILE,"<",$pathor die$!;1556$checksum= md5sum(\*FILE);1557close FILE or die$!;1558}1559$result.="Checksum: ".$checksum."\n";1560}15611562print$result,"\n";1563}15641565sub cmd_reset {1566my$target=shift||$_revisionor die"SVN revision required\n";1567$target=$1if$target=~/^r(\d+)$/;1568$target=~/^\d+$/or die"Numeric SVN revision expected\n";1569my($url,$rev,$uuid,$gs) = working_head_info('HEAD');1570unless($gs) {1571die"Unable to determine upstream SVN information from ".1572"history\n";1573}1574my($r,$c) =$gs->find_rev_before($target,not$_fetch_parent);1575die"Cannot find SVN revision$target\n"unlessdefined($c);1576$gs->rev_map_set($r,$c,'reset',$uuid);1577print"r$r=$c($gs->{ref_id})\n";1578}15791580sub cmd_gc {1581if(!$can_compress) {1582warn"Compress::Zlib could not be found; unhandled.log ".1583"files will not be compressed.\n";1584}1585 find({ wanted => \&gc_directory, no_chdir =>1},"$ENV{GIT_DIR}/svn");1586}15871588########################### utility functions #########################15891590sub rebase_cmd {1591my@cmd= qw/rebase/;1592push@cmd,'-v'if$_verbose;1593push@cmd, qw/--merge/if$_merge;1594push@cmd,"--strategy=$_strategy"if$_strategy;1595push@cmd,"--preserve-merges"if$_preserve_merges;1596@cmd;1597}15981599sub post_fetch_checkout {1600return if$_no_checkout;1601return if verify_ref('HEAD^0');1602my$gs=$Git::SVN::_head orreturn;16031604# look for "trunk" ref if it exists1605my$remote= Git::SVN::read_all_remotes()->{$gs->{repo_id}};1606my$fetch=$remote->{fetch};1607if($fetch) {1608foreachmy$p(keys%$fetch) {1609 basename($fetch->{$p})eq'trunk'ornext;1610$gs= Git::SVN->new($fetch->{$p},$gs->{repo_id},$p);1611last;1612}1613}16141615 command_noisy(qw(update-ref HEAD),$gs->refname);1616return unless verify_ref('HEAD^0');16171618return if$ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;1619my$index=$ENV{GIT_INDEX_FILE} ||"$ENV{GIT_DIR}/index";1620return if-f $index;16211622return if command_oneline(qw/rev-parse --is-inside-work-tree/)eq'false';1623return if command_oneline(qw/rev-parse --is-inside-git-dir/)eq'true';1624 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);1625print STDERR "Checked out HEAD:\n",1626$gs->full_url," r",$gs->last_rev,"\n";1627if(auto_create_empty_directories($gs)) {1628$gs->mkemptydirs($gs->last_rev);1629}1630}16311632sub complete_svn_url {1633my($url,$path) =@_;1634$path=~ s#/+$##;1635if($path!~ m#^[a-z\+]+://#) {1636if(!defined$url||$url!~ m#^[a-z\+]+://#) {1637 fatal("E: '$path' is not a complete URL ",1638"and a separate URL is not specified");1639}1640return($url,$path);1641}1642return($path,'');1643}16441645sub complete_url_ls_init {1646my($ra,$repo_path,$switch,$pfx) =@_;1647unless($repo_path) {1648print STDERR "W:$switchnot specified\n";1649return;1650}1651$repo_path=~ s#/+$##;1652if($repo_path=~ m#^[a-z\+]+://#) {1653$ra= Git::SVN::Ra->new($repo_path);1654$repo_path='';1655}else{1656$repo_path=~ s#^/+##;1657unless($ra) {1658 fatal("E: '$repo_path' is not a complete URL ",1659"and a separate URL is not specified");1660}1661}1662my$url=$ra->{url};1663my$gs= Git::SVN->init($url,undef,undef,undef,1);1664my$k="svn-remote.$gs->{repo_id}.url";1665my$orig_url=eval{ command_oneline(qw/config --get/,$k) };1666if($orig_url&& ($orig_urlne$gs->{url})) {1667die"$kalready set:$orig_url\n",1668"wanted to set to:$gs->{url}\n";1669}1670 command_oneline('config',$k,$gs->{url})unless$orig_url;1671my$remote_path="$gs->{path}/$repo_path";1672$remote_path=~s{%([0-9A-F]{2})}{chr hex($1)}ieg;1673$remote_path=~ s#/+#/#g;1674$remote_path=~ s#^/##g;1675$remote_path.="/*"if$remote_path!~ /\*/;1676my($n) = ($switch=~/^--(\w+)/);1677if(length$pfx&&$pfx!~ m#/$#) {1678die"--prefix='$pfx' must have a trailing slash '/'\n";1679}1680 command_noisy('config',1681'--add',1682"svn-remote.$gs->{repo_id}.$n",1683"$remote_path:refs/remotes/$pfx*".1684('/*' x (($remote_path=~ tr/*/*/) -1)) );1685}16861687sub verify_ref {1688my($ref) =@_;1689eval{ command_oneline(['rev-parse','--verify',$ref],1690{ STDERR =>0}); };1691}16921693sub get_tree_from_treeish {1694my($treeish) =@_;1695# $treeish can be a symbolic ref, too:1696my$type= command_oneline(qw/cat-file -t/,$treeish);1697my$expected;1698while($typeeq'tag') {1699($treeish,$type) = command(qw/cat-file tag/,$treeish);1700}1701if($typeeq'commit') {1702$expected= (grep/^tree /, command(qw/cat-file commit/,1703$treeish))[0];1704($expected) = ($expected=~/^tree ($sha1)$/o);1705die"Unable to get tree from$treeish\n"unless$expected;1706}elsif($typeeq'tree') {1707$expected=$treeish;1708}else{1709die"$treeishis a$type, expected tree, tag or commit\n";1710}1711return$expected;1712}17131714sub get_commit_entry {1715my($treeish) =shift;1716my%log_entry= (log=>'', tree => get_tree_from_treeish($treeish) );1717my$commit_editmsg="$ENV{GIT_DIR}/COMMIT_EDITMSG";1718my$commit_msg="$ENV{GIT_DIR}/COMMIT_MSG";1719open my$log_fh,'>',$commit_editmsgor croak $!;17201721my$type= command_oneline(qw/cat-file -t/,$treeish);1722if($typeeq'commit'||$typeeq'tag') {1723my($msg_fh,$ctx) = command_output_pipe('cat-file',1724$type,$treeish);1725my$in_msg=0;1726my$author;1727my$saw_from=0;1728my$msgbuf="";1729while(<$msg_fh>) {1730if(!$in_msg) {1731$in_msg=1if(/^\s*$/);1732$author=$1if(/^author (.*>)/);1733}elsif(/^git-svn-id: /) {1734# skip this for now, we regenerate the1735# correct one on re-fetch anyways1736# TODO: set *:merge properties or like...1737}else{1738if(/^From:/||/^Signed-off-by:/) {1739$saw_from=1;1740}1741$msgbuf.=$_;1742}1743}1744$msgbuf=~s/\s+$//s;1745if($Git::SVN::_add_author_from &&defined($author)1746&& !$saw_from) {1747$msgbuf.="\n\nFrom:$author";1748}1749print$log_fh $msgbufor croak $!;1750 command_close_pipe($msg_fh,$ctx);1751}1752close$log_fhor croak $!;17531754if($_edit|| ($typeeq'tree')) {1755chomp(my$editor= command_oneline(qw(var GIT_EDITOR)));1756system('sh','-c',$editor.' "$@"',$editor,$commit_editmsg);1757}1758rename$commit_editmsg,$commit_msgor croak $!;1759{1760require Encode;1761# SVN requires messages to be UTF-8 when entering the repo1762local$/;1763open$log_fh,'<',$commit_msgor croak $!;1764binmode$log_fh;1765chomp($log_entry{log} = <$log_fh>);17661767my$enc= Git::config('i18n.commitencoding') ||'UTF-8';1768my$msg=$log_entry{log};17691770eval{$msg= Encode::decode($enc,$msg,1) };1771if($@) {1772die"Could not decode as$enc:\n",$msg,1773"\nPerhaps you need to set i18n.commitencoding\n";1774}17751776eval{$msg= Encode::encode('UTF-8',$msg,1) };1777die"Could not encode as UTF-8:\n$msg\n"if$@;17781779$log_entry{log} =$msg;17801781close$log_fhor croak $!;1782}1783unlink$commit_msg;1784 \%log_entry;1785}17861787sub s_to_file {1788my($str,$file,$mode) =@_;1789open my$fd,'>',$fileor croak $!;1790print$fd $str,"\n"or croak $!;1791close$fdor croak $!;1792chmod($mode&~umask,$file)if(defined$mode);1793}17941795sub file_to_s {1796my$file=shift;1797open my$fd,'<',$fileor croak "$!: file:$file\n";1798local$/;1799my$ret= <$fd>;1800close$fdor croak $!;1801$ret=~s/\s*$//s;1802return$ret;1803}18041805# '<svn username> = real-name <email address>' mapping based on git-svnimport:1806sub load_authors {1807open my$authors,'<',$_authorsor die"Can't open$_authors$!\n";1808my$log=$cmdeq'log';1809while(<$authors>) {1810chomp;1811next unless/^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;1812my($user,$name,$email) = ($1,$2,$3);1813if($log) {1814$Git::SVN::Log::rusers{"$name<$email>"} =$user;1815}else{1816$users{$user} = [$name,$email];1817}1818}1819close$authorsor croak $!;1820}18211822# convert GetOpt::Long specs for use by git-config1823sub read_git_config {1824my$opts=shift;1825my@config_only;1826foreachmy$o(keys%$opts) {1827# if we have mixedCase and a long option-only, then1828# it's a config-only variable that we don't need for1829# the command-line.1830push@config_only,$oif($o=~/[A-Z]/&&$o=~/^[a-z]+$/i);1831my$v=$opts->{$o};1832my($key) = ($o=~/^([a-zA-Z\-]+)/);1833$key=~s/-//g;1834my$arg='git config';1835$arg.=' --int'if($o=~/[:=]i$/);1836$arg.=' --bool'if($o!~/[:=][sfi]$/);1837if(ref$veq'ARRAY') {1838chomp(my@tmp=`$arg--get-all svn.$key`);1839@$v=@tmpif@tmp;1840 } else {1841 chomp(my$tmp= `$arg--get svn.$key`);1842if($tmp&& !($arg=~/ --bool/&&$tmpeq'false')) {1843$$v=$tmp;1844}1845}1846}1847delete@$opts{@config_only}if@config_only;1848}18491850sub extract_metadata {1851my$id=shift orreturn(undef,undef,undef);1852my($url,$rev,$uuid) = ($id=~ /^\s*git-svn-id:\s+(.*)\@(\d+)1853 \s([a-f\d\-]+)$/ix);1854if(!defined$rev|| !$uuid|| !$url) {1855# some of the original repositories I made had1856# identifiers like this:1857($rev,$uuid) = ($id=~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);1858}1859return($url,$rev,$uuid);1860}18611862sub cmt_metadata {1863return extract_metadata((grep(/^git-svn-id: /,1864 command(qw/cat-file commit/,shift)))[-1]);1865}18661867sub cmt_sha2rev_batch {1868my%s2r;1869my($pid,$in,$out,$ctx) = command_bidi_pipe(qw/cat-file --batch/);1870my$list=shift;18711872foreachmy$sha(@{$list}) {1873my$first=1;1874my$size=0;1875print$out $sha,"\n";18761877while(my$line= <$in>) {1878if($first&&$line=~/^[[:xdigit:]]{40}\smissing$/) {1879last;1880}elsif($first&&1881$line=~/^[[:xdigit:]]{40}\scommit\s(\d+)$/) {1882$first=0;1883$size=$1;1884next;1885}elsif($line=~/^(git-svn-id: )/) {1886my(undef,$rev,undef) =1887 extract_metadata($line);1888$s2r{$sha} =$rev;1889}18901891$size-=length($line);1892last if($size==0);1893}1894}18951896 command_close_bidi_pipe($pid,$in,$out,$ctx);18971898return \%s2r;1899}19001901sub working_head_info {1902my($head,$refs) =@_;1903my@args= qw/rev-list --first-parent --pretty=medium/;1904my($fh,$ctx) = command_output_pipe(@args,$head);1905my$hash;1906my%max;1907while(<$fh>) {1908if(m{^commit ($::sha1)$}) {1909unshift@$refs,$hashif$hashand$refs;1910$hash=$1;1911next;1912}1913next unlesss{^\s*(git-svn-id:)}{$1};1914my($url,$rev,$uuid) = extract_metadata($_);1915if(defined$url&&defined$rev) {1916next if$max{$url}and$max{$url} <$rev;1917if(my$gs= Git::SVN->find_by_url($url)) {1918my$c=$gs->rev_map_get($rev,$uuid);1919if($c&&$ceq$hash) {1920close$fh;# break the pipe1921return($url,$rev,$uuid,$gs);1922}else{1923$max{$url} ||=$gs->rev_map_max;1924}1925}1926}1927}1928 command_close_pipe($fh,$ctx);1929(undef,undef,undef,undef);1930}19311932sub read_commit_parents {1933my($parents,$c) =@_;1934chomp(my$p= command_oneline(qw/rev-list --parents -1/,$c));1935$p=~s/^($c)\s*//or die"rev-list --parents -1$cfailed!\n";1936@{$parents->{$c}} =split(/ /,$p);1937}19381939sub linearize_history {1940my($gs,$refs) =@_;1941my%parents;1942foreachmy$c(@$refs) {1943 read_commit_parents(\%parents,$c);1944}19451946my@linear_refs;1947my%skip= ();1948my$last_svn_commit=$gs->last_commit;1949foreachmy$c(reverse@$refs) {1950next if$ceq$last_svn_commit;1951last if$skip{$c};19521953unshift@linear_refs,$c;1954$skip{$c} =1;19551956# we only want the first parent to diff against for linear1957# history, we save the rest to inject when we finalize the1958# svn commit1959my$fp_a= verify_ref("$c~1");1960my$fp_b=shift@{$parents{$c}}if$parents{$c};1961if(!$fp_a|| !$fp_b) {1962die"Commit$c\n",1963"has no parent commit, and therefore ",1964"nothing to diff against.\n",1965"You should be working from a repository ",1966"originally created by git-svn\n";1967}1968if($fp_ane$fp_b) {1969die"$c~1=$fp_a, however parsing commit$c",1970"revealed that:\n$c~1=$fp_b\nBUG!\n";1971}19721973foreachmy$p(@{$parents{$c}}) {1974$skip{$p} =1;1975}1976}1977(\@linear_refs, \%parents);1978}19791980sub find_file_type_and_diff_status {1981my($path) =@_;1982return('dir','')if$patheq'';19831984my$diff_output=1985 command_oneline(qw(diff --cached --name-status --),$path) ||"";1986my$diff_status= (split(' ',$diff_output))[0] ||"";19871988my$ls_tree= command_oneline(qw(ls-tree HEAD),$path) ||"";19891990return(undef,undef)if!$diff_status&& !$ls_tree;19911992if($diff_statuseq"A") {1993return("link",$diff_status)if-l $path;1994return("dir",$diff_status)if-d $path;1995return("file",$diff_status);1996}19971998my$mode= (split(' ',$ls_tree))[0] ||"";19992000return("link",$diff_status)if$modeeq"120000";2001return("dir",$diff_status)if$modeeq"040000";2002return("file",$diff_status);2003}20042005sub md5sum {2006my$arg=shift;2007my$ref=ref$arg;2008my$md5= Digest::MD5->new();2009if($refeq'GLOB'||$refeq'IO::File'||$refeq'File::Temp') {2010$md5->addfile($arg)or croak $!;2011}elsif($refeq'SCALAR') {2012$md5->add($$arg)or croak $!;2013}elsif(!$ref) {2014$md5->add($arg)or croak $!;2015}else{2016::fatal "Can't provide MD5 hash for unknown ref type: '",$ref,"'";2017}2018return$md5->hexdigest();2019}20202021sub gc_directory {2022if($can_compress&& -f $_&& basename($_)eq"unhandled.log") {2023my$out_filename=$_.".gz";2024open my$in_fh,"<",$_or die"Unable to open$_:$!\n";2025binmode$in_fh;2026my$gz= Compress::Zlib::gzopen($out_filename,"ab")or2027die"Unable to open$out_filename:$!\n";20282029my$res;2030while($res=sysread($in_fh,my$str,1024)) {2031$gz->gzwrite($str)or2032die"Unable to write: ".$gz->gzerror()."!\n";2033}2034unlink$_or die"unlink$File::Find::name:$!\n";2035}elsif(-f $_&& basename($_)eq"index") {2036unlink$_or die"unlink$_:$!\n";2037}2038}20392040package Git::SVN;2041use strict;2042use warnings;2043use Fcntl qw/:DEFAULT :seek/;2044useconstant rev_map_fmt =>'NH40';2045use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent2046$_repack $_repack_flags $_use_svm_props $_head2047$_use_svnsync_props $no_reuse_existing $_minimize_url2048$_use_log_author $_add_author_from $_localtime/;2049use Carp qw/croak/;2050use File::Path qw/mkpath/;2051use File::Copy qw/copy/;2052use IPC::Open3;2053use Time::Local;2054use Memoize;# core since 5.8.0, Jul 20022055use Memoize::Storable;2056use POSIX qw(:signal_h);2057my$can_use_yaml;2058BEGIN{2059$can_use_yaml=eval{require Git::SVN::Memoize::YAML;1};2060}20612062my($_gc_nr,$_gc_period);20632064# properties that we do not log:2065my%SKIP_PROP;2066BEGIN{2067%SKIP_PROP=map{$_=>1} qw/svn:wc:ra_dav:version-url2068 svn:special svn:executable2069 svn:entry:committed-rev2070 svn:entry:last-author2071 svn:entry:uuid2072 svn:entry:committed-date/;20732074# some options are read globally, but can be overridden locally2075# per [svn-remote "..."] section. Command-line options will *NOT*2076# override options set in an [svn-remote "..."] section2077no strict 'refs';2078formy$option(qw/follow_parent no_metadata use_svm_props2079 use_svnsync_props/) {2080my$key=$option;2081$key=~tr/_//d;2082my$prop="-$option";2083*$option=sub{2084my($self) =@_;2085return$self->{$prop}ifexists$self->{$prop};2086my$k="svn-remote.$self->{repo_id}.$key";2087eval{ command_oneline(qw/config --get/,$k) };2088if($@) {2089$self->{$prop} = ${"Git::SVN::_$option"};2090}else{2091my$v= command_oneline(qw/config --bool/,$k);2092$self->{$prop} =$veq'false'?0:1;2093}2094return$self->{$prop};2095}2096}2097}209820992100my(%LOCKFILES,%INDEX_FILES);2101END{2102unlink keys%LOCKFILESif%LOCKFILES;2103unlink keys%INDEX_FILESif%INDEX_FILES;2104}21052106sub resolve_local_globs {2107my($url,$fetch,$glob_spec) =@_;2108return unlessdefined$glob_spec;2109my$ref=$glob_spec->{ref};2110my$path=$glob_spec->{path};2111foreach(command(qw#for-each-ref --format=%(refname) refs/#)) {2112next unless m#^$ref->{regex}$#;2113my$p=$1;2114my$pathname= desanitize_refname($path->full_path($p));2115my$refname= desanitize_refname($ref->full_path($p));2116if(my$existing=$fetch->{$pathname}) {2117if($existingne$refname) {2118die"Refspec conflict:\n",2119"existing:$existing\n",2120" globbed:$refname\n";2121}2122my$u= (::cmt_metadata("$refname"))[0];2123$u=~s!^\Q$url\E(/|$)!!or die2124"$refname: '$url' not found in '$u'\n";2125if($pathnamene$u) {2126warn"W: Refspec glob conflict ",2127"(ref:$refname):\n",2128"expected path:$pathname\n",2129" real path:$u\n",2130"Continuing ahead with$u\n";2131next;2132}2133}else{2134$fetch->{$pathname} =$refname;2135}2136}2137}21382139sub parse_revision_argument {2140my($base,$head) =@_;2141if(!defined$::_revision || $::_revision eq'BASE:HEAD') {2142return($base,$head);2143}2144return($1,$2)if($::_revision =~/^(\d+):(\d+)$/);2145return($::_revision, $::_revision)if($::_revision =~/^\d+$/);2146return($head,$head)if($::_revision eq'HEAD');2147return($base,$1)if($::_revision =~/^BASE:(\d+)$/);2148return($1,$head)if($::_revision =~/^(\d+):HEAD$/);2149die"revision argument: $::_revision not understood by git-svn\n";2150}21512152sub fetch_all {2153my($repo_id,$remotes) =@_;2154if(ref$repo_id) {2155my$gs=$repo_id;2156$repo_id=undef;2157$repo_id=$gs->{repo_id};2158}2159$remotes||= read_all_remotes();2160my$remote=$remotes->{$repo_id}or2161die"[svn-remote\"$repo_id\"] unknown\n";2162my$fetch=$remote->{fetch};2163my$url=$remote->{url}or die"svn-remote.$repo_id.url not defined\n";2164my(@gs,@globs);2165my$ra= Git::SVN::Ra->new($url);2166my$uuid=$ra->get_uuid;2167my$head=$ra->get_latest_revnum;21682169# ignore errors, $head revision may not even exist anymore2170eval{$ra->get_log("",$head,0,1,0,1,sub{$head=$_[1] }) };2171warn"W:$@\n"if$@;21722173my$base=defined$fetch?$head:0;21742175# read the max revs for wildcard expansion (branches/*, tags/*)2176foreachmy$t(qw/branches tags/) {2177defined$remote->{$t}ornext;2178push@globs, @{$remote->{$t}};21792180my$max_rev=eval{ tmp_config(qw/--int --get/,2181"svn-remote.$repo_id.${t}-maxRev") };2182if(defined$max_rev&& ($max_rev<$base)) {2183$base=$max_rev;2184}elsif(!defined$max_rev) {2185$base=0;2186}2187}21882189if($fetch) {2190foreachmy$p(sort keys%$fetch) {2191my$gs= Git::SVN->new($fetch->{$p},$repo_id,$p);2192my$lr=$gs->rev_map_max;2193if(defined$lr) {2194$base=$lrif($lr<$base);2195}2196push@gs,$gs;2197}2198}21992200($base,$head) = parse_revision_argument($base,$head);2201$ra->gs_fetch_loop_common($base,$head, \@gs, \@globs);2202}22032204sub read_all_remotes {2205my$r= {};2206my$use_svm_props=eval{ command_oneline(qw/config --bool2207 svn.useSvmProps/) };2208$use_svm_props=$use_svm_propseq'true'if$use_svm_props;2209my$svn_refspec=qr{\s*(.*?)\s*:\s*(.+?)\s*};2210foreach(grep{s/^svn-remote\.//} command(qw/config -l/)) {2211if(m!^(.+)\.fetch=$svn_refspec$!) {2212my($remote,$local_ref,$remote_ref) = ($1,$2,$3);2213die("svn-remote.$remote: remote ref '$remote_ref' "2214."must start with 'refs/'\n")2215unless$remote_ref=~m{^refs/};2216$local_ref= uri_decode($local_ref);2217$r->{$remote}->{fetch}->{$local_ref} =$remote_ref;2218$r->{$remote}->{svm} = {}if$use_svm_props;2219}elsif(m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {2220$r->{$1}->{svm} = {};2221}elsif(m!^(.+)\.url=\s*(.*)\s*$!) {2222$r->{$1}->{url} =$2;2223}elsif(m!^(.+)\.pushurl=\s*(.*)\s*$!) {2224$r->{$1}->{pushurl} =$2;2225}elsif(m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {2226$r->{$1}->{ignore_refs_regex} =$2;2227}elsif(m!^(.+)\.(branches|tags)=$svn_refspec$!) {2228my($remote,$t,$local_ref,$remote_ref) =2229($1,$2,$3,$4);2230die("svn-remote.$remote: remote ref '$remote_ref' ($t) "2231."must start with 'refs/'\n")2232unless$remote_ref=~m{^refs/};2233$local_ref= uri_decode($local_ref);2234my$rs= {2235 t =>$t,2236 remote =>$remote,2237 path => Git::SVN::GlobSpec->new($local_ref,1),2238ref=> Git::SVN::GlobSpec->new($remote_ref,0) };2239if(length($rs->{ref}->{right}) !=0) {2240die"The '*' glob character must be the last ",2241"character of '$remote_ref'\n";2242}2243push@{$r->{$remote}->{$t} },$rs;2244}2245}22462247map{2248if(defined$r->{$_}->{svm}) {2249my$svm;2250eval{2251my$section="svn-remote.$_";2252$svm= {2253 source => tmp_config('--get',2254"$section.svm-source"),2255 replace => tmp_config('--get',2256"$section.svm-replace"),2257}2258};2259$r->{$_}->{svm} =$svm;2260}2261}keys%$r;22622263foreachmy$remote(keys%$r) {2264foreach(grep{defined$_}2265map{$r->{$remote}->{$_} }qw(branches tags)) {2266foreachmy$rs(@$_) {2267$rs->{ignore_refs_regex} =2268$r->{$remote}->{ignore_refs_regex};2269}2270}2271}22722273$r;2274}22752276sub init_vars {2277$_gc_nr=$_gc_period=1000;2278if(defined$_repack||defined$_repack_flags) {2279warn"Repack options are obsolete; they have no effect.\n";2280}2281}22822283sub verify_remotes_sanity {2284return unless-d $ENV{GIT_DIR};2285my%seen;2286foreach(command(qw/config -l/)) {2287if(m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {2288if($seen{$1}) {2289die"Remote ref refs/remote/$1is tracked by",2290"\n \"$_\"\nand\n \"$seen{$1}\"\n",2291"Please resolve this ambiguity in ",2292"your git configuration file before ",2293"continuing\n";2294}2295$seen{$1} =$_;2296}2297}2298}22992300sub find_existing_remote {2301my($url,$remotes) =@_;2302returnundefif$no_reuse_existing;2303my$existing;2304foreachmy$repo_id(keys%$remotes) {2305my$u=$remotes->{$repo_id}->{url}ornext;2306next if$une$url;2307$existing=$repo_id;2308last;2309}2310$existing;2311}23122313sub init_remote_config {2314my($self,$url,$no_write) =@_;2315$url=~s!/+$!!;# strip trailing slash2316my$r= read_all_remotes();2317my$existing= find_existing_remote($url,$r);2318if($existing) {2319unless($no_write) {2320print STDERR "Using existing ",2321"[svn-remote\"$existing\"]\n";2322}2323$self->{repo_id} =$existing;2324}elsif($_minimize_url) {2325my$min_url= Git::SVN::Ra->new($url)->minimize_url;2326$existing= find_existing_remote($min_url,$r);2327if($existing) {2328unless($no_write) {2329print STDERR "Using existing ",2330"[svn-remote\"$existing\"]\n";2331}2332$self->{repo_id} =$existing;2333}2334if($min_urlne$url) {2335unless($no_write) {2336print STDERR "Using higher level of URL: ",2337"$url=>$min_url\n";2338}2339my$old_path=$self->{path};2340$self->{path} =$url;2341$self->{path} =~s!^\Q$min_url\E(/|$)!!;2342if(length$old_path) {2343$self->{path} .="/$old_path";2344}2345$url=$min_url;2346}2347}2348my$orig_url;2349if(!$existing) {2350# verify that we aren't overwriting anything:2351$orig_url=eval{2352 command_oneline('config','--get',2353"svn-remote.$self->{repo_id}.url")2354};2355if($orig_url&& ($orig_urlne$url)) {2356die"svn-remote.$self->{repo_id}.url already set: ",2357"$orig_url\nwanted to set to:$url\n";2358}2359}2360my($xrepo_id,$xpath) = find_ref($self->refname);2361if(!$no_write&&defined$xpath) {2362die"svn-remote.$xrepo_id.fetch already set to track ",2363"$xpath:",$self->refname,"\n";2364}2365unless($no_write) {2366 command_noisy('config',2367"svn-remote.$self->{repo_id}.url",$url);2368$self->{path} =~s{^/}{};2369$self->{path} =~s{%([0-9A-F]{2})}{chr hex($1)}ieg;2370 command_noisy('config','--add',2371"svn-remote.$self->{repo_id}.fetch",2372"$self->{path}:".$self->refname);2373}2374$self->{url} =$url;2375}23762377sub find_by_url {# repos_root and, path are optional2378my($class,$full_url,$repos_root,$path) =@_;23792380returnundefunlessdefined$full_url;2381 remove_username($full_url);2382 remove_username($repos_root)ifdefined$repos_root;2383my$remotes= read_all_remotes();2384if(defined$full_url&&defined$repos_root&& !defined$path) {2385$path=$full_url;2386$path=~ s#^\Q$repos_root\E(?:/|$)##;2387}2388foreachmy$repo_id(keys%$remotes) {2389my$u=$remotes->{$repo_id}->{url}ornext;2390 remove_username($u);2391next ifdefined$repos_root&&$repos_rootne$u;23922393my$fetch=$remotes->{$repo_id}->{fetch} || {};2394foreachmy$t(qw/branches tags/) {2395foreachmy$globspec(@{$remotes->{$repo_id}->{$t}}) {2396 resolve_local_globs($u,$fetch,$globspec);2397}2398}2399my$p=$path;2400my$rwr= rewrite_root({repo_id =>$repo_id});2401my$svm=$remotes->{$repo_id}->{svm}2402ifdefined$remotes->{$repo_id}->{svm};2403unless(defined$p) {2404$p=$full_url;2405my$z=$u;2406my$prefix='';2407if($rwr) {2408$z=$rwr;2409 remove_username($z);2410}elsif(defined$svm) {2411$z=$svm->{source};2412$prefix=$svm->{replace};2413$prefix=~ s#^\Q$u\E(?:/|$)##;2414$prefix=~ s#/$##;2415}2416$p=~ s#^\Q$z\E(?:/|$)#$prefix# or next;2417}2418foreachmy$f(keys%$fetch) {2419next if$fne$p;2420return Git::SVN->new($fetch->{$f},$repo_id,$f);2421}2422}2423undef;2424}24252426sub init {2427my($class,$url,$path,$repo_id,$ref_id,$no_write) =@_;2428my$self= _new($class,$repo_id,$ref_id,$path);2429if(defined$url) {2430$self->init_remote_config($url,$no_write);2431}2432$self;2433}24342435sub find_ref {2436my($ref_id) =@_;2437foreach(command(qw/config -l/)) {2438next unless m!^svn-remote\.(.+)\.fetch=2439 \s*(.*?)\s*:\s*(.+?)\s*$!x;2440my($repo_id,$path,$ref) = ($1,$2,$3);2441if($refeq$ref_id) {2442$path=''if($path=~ m#^\./?#);2443return($repo_id,$path);2444}2445}2446(undef,undef,undef);2447}24482449sub new {2450my($class,$ref_id,$repo_id,$path) =@_;2451if(defined$ref_id&& !defined$repo_id&& !defined$path) {2452($repo_id,$path) = find_ref($ref_id);2453if(!defined$repo_id) {2454die"Could not find a\"svn-remote.*.fetch\"key ",2455"in the repository configuration matching: ",2456"$ref_id\n";2457}2458}2459my$self= _new($class,$repo_id,$ref_id,$path);2460if(!defined$self->{path} || !length$self->{path}) {2461my$fetch= command_oneline('config','--get',2462"svn-remote.$repo_id.fetch",2463":$ref_id\$")or2464die"Failed to read\"svn-remote.$repo_id.fetch\"",2465"\":$ref_id\$\"in config\n";2466($self->{path},undef) =split(/\s*:\s*/,$fetch);2467}2468$self->{path} =~s{/+}{/}g;2469$self->{path} =~s{\A/}{};2470$self->{path} =~s{/\z}{};2471$self->{url} = command_oneline('config','--get',2472"svn-remote.$repo_id.url")or2473die"Failed to read\"svn-remote.$repo_id.url\"in config\n";2474$self->{pushurl} =eval{ command_oneline('config','--get',2475"svn-remote.$repo_id.pushurl") };2476$self->rebuild;2477$self;2478}24792480sub refname {2481my($refname) =$_[0]->{ref_id} ;24822483# It cannot end with a slash /, we'll throw up on this because2484# SVN can't have directories with a slash in their name, either:2485if($refname=~m{/$}) {2486die"ref: '$refname' ends with a trailing slash, this is ",2487"not permitted by git nor Subversion\n";2488}24892490# It cannot have ASCII control character space, tilde ~, caret ^,2491# colon :, question-mark ?, asterisk *, space, or open bracket [2492# anywhere.2493#2494# Additionally, % must be escaped because it is used for escaping2495# and we want our escaped refname to be reversible2496$refname=~s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;24972498# no slash-separated component can begin with a dot .2499# /.* becomes /%2E*2500$refname=~s{/\.}{/%2E}g;25012502# It cannot have two consecutive dots .. anywhere2503# .. becomes %2E%2E2504$refname=~s{\.\.}{%2E%2E}g;25052506# trailing dots and .lock are not allowed2507# .$ becomes %2E and .lock becomes %2Elock2508$refname=~s{\.(?=$|lock$)}{%2E};25092510# the sequence @{ is used to access the reflog2511# @{ becomes %40{2512$refname=~s{\@\{}{%40\{}g;25132514return$refname;2515}25162517sub desanitize_refname {2518my($refname) =@_;2519$refname=~s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;2520return$refname;2521}25222523sub svm_uuid {2524my($self) =@_;2525return$self->{svm}->{uuid}if$self->svm;2526$self->ra;2527unless($self->{svm}) {2528die"SVM UUID not cached, and reading remotely failed\n";2529}2530$self->{svm}->{uuid};2531}25322533sub svm {2534my($self) =@_;2535return$self->{svm}if$self->{svm};2536my$svm;2537# see if we have it in our config, first:2538eval{2539my$section="svn-remote.$self->{repo_id}";2540$svm= {2541 source => tmp_config('--get',"$section.svm-source"),2542 uuid => tmp_config('--get',"$section.svm-uuid"),2543 replace => tmp_config('--get',"$section.svm-replace"),2544}2545};2546if($svm&&$svm->{source} &&$svm->{uuid} &&$svm->{replace}) {2547$self->{svm} =$svm;2548}2549$self->{svm};2550}25512552sub _set_svm_vars {2553my($self,$ra) =@_;2554return$raif$self->svm;25552556my@err= ("useSvmProps set, but failed to read SVM properties\n",2557"(svm:source, svm:uuid) ",2558"from the following URLs:\n");2559sub read_svm_props {2560my($self,$ra,$path,$r) =@_;2561my$props= ($ra->get_dir($path,$r))[2];2562my$src=$props->{'svm:source'};2563my$uuid=$props->{'svm:uuid'};2564returnundefif(!$src|| !$uuid);25652566chomp($src,$uuid);25672568$uuid=~m{^[0-9a-f\-]{30,}$}i2569or die"doesn't look right - svm:uuid is '$uuid'\n";25702571# the '!' is used to mark the repos_root!/relative/path2572$src=~s{/?!/?}{/};2573$src=~s{/+$}{};# no trailing slashes please2574# username is of no interest2575$src=~s{(^[a-z\+]*://)[^/@]*@}{$1};25762577my$replace=$ra->{url};2578$replace.="/$path"iflength$path;25792580my$section="svn-remote.$self->{repo_id}";2581 tmp_config("$section.svm-source",$src);2582 tmp_config("$section.svm-replace",$replace);2583 tmp_config("$section.svm-uuid",$uuid);2584$self->{svm} = {2585 source =>$src,2586 uuid =>$uuid,2587 replace =>$replace2588};2589}25902591my$r=$ra->get_latest_revnum;2592my$path=$self->{path};2593my%tried;2594while(length$path) {2595unless($tried{"$self->{url}/$path"}) {2596return$raif$self->read_svm_props($ra,$path,$r);2597$tried{"$self->{url}/$path"} =1;2598}2599$path=~ s#/?[^/]+$##;2600}2601die"Path: '$path' should be ''\n"if$pathne'';2602return$raif$self->read_svm_props($ra,$path,$r);2603$tried{"$self->{url}/$path"} =1;26042605if($ra->{repos_root}eq$self->{url}) {2606die@err, (map{"$_\n"}keys%tried),"\n";2607}26082609# nope, make sure we're connected to the repository root:2610my$ok;2611my@tried_b;2612$path=$ra->{svn_path};2613$ra= Git::SVN::Ra->new($ra->{repos_root});2614while(length$path) {2615unless($tried{"$ra->{url}/$path"}) {2616$ok=$self->read_svm_props($ra,$path,$r);2617last if$ok;2618$tried{"$ra->{url}/$path"} =1;2619}2620$path=~ s#/?[^/]+$##;2621}2622die"Path: '$path' should be ''\n"if$pathne'';2623$ok||=$self->read_svm_props($ra,$path,$r);2624$tried{"$ra->{url}/$path"} =1;2625if(!$ok) {2626die@err, (map{"$_\n"}keys%tried),"\n";2627}2628 Git::SVN::Ra->new($self->{url});2629}26302631sub svnsync {2632my($self) =@_;2633return$self->{svnsync}if$self->{svnsync};26342635if($self->no_metadata) {2636die"Can't have both 'noMetadata' and ",2637"'useSvnsyncProps' options set!\n";2638}2639if($self->rewrite_root) {2640die"Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",2641"options set!\n";2642}2643if($self->rewrite_uuid) {2644die"Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",2645"options set!\n";2646}26472648my$svnsync;2649# see if we have it in our config, first:2650eval{2651my$section="svn-remote.$self->{repo_id}";26522653my$url= tmp_config('--get',"$section.svnsync-url");2654($url) = ($url=~m{^([a-z\+]+://\S+)$})or2655die"doesn't look right - svn:sync-from-url is '$url'\n";26562657my$uuid= tmp_config('--get',"$section.svnsync-uuid");2658($uuid) = ($uuid=~m{^([0-9a-f\-]{30,})$}i)or2659die"doesn't look right - svn:sync-from-uuid is '$uuid'\n";26602661$svnsync= { url =>$url, uuid =>$uuid}2662};2663if($svnsync&&$svnsync->{url} &&$svnsync->{uuid}) {2664return$self->{svnsync} =$svnsync;2665}26662667my$err="useSvnsyncProps set, but failed to read ".2668"svnsync property: svn:sync-from-";2669my$rp=$self->ra->rev_proplist(0);26702671my$url=$rp->{'svn:sync-from-url'}or die$err."url\n";2672($url) = ($url=~m{^([a-z\+]+://\S+)$})or2673die"doesn't look right - svn:sync-from-url is '$url'\n";26742675my$uuid=$rp->{'svn:sync-from-uuid'}or die$err."uuid\n";2676($uuid) = ($uuid=~m{^([0-9a-f\-]{30,})$}i)or2677die"doesn't look right - svn:sync-from-uuid is '$uuid'\n";26782679my$section="svn-remote.$self->{repo_id}";2680 tmp_config('--add',"$section.svnsync-uuid",$uuid);2681 tmp_config('--add',"$section.svnsync-url",$url);2682return$self->{svnsync} = { url =>$url, uuid =>$uuid};2683}26842685# this allows us to memoize our SVN::Ra UUID locally and avoid a2686# remote lookup (useful for 'git svn log').2687sub ra_uuid {2688my($self) =@_;2689unless($self->{ra_uuid}) {2690my$key="svn-remote.$self->{repo_id}.uuid";2691my$uuid=eval{ tmp_config('--get',$key) };2692if(!$@&&$uuid&&$uuid=~/^([a-f\d\-]{30,})$/i) {2693$self->{ra_uuid} =$uuid;2694}else{2695die"ra_uuid called without URL\n"unless$self->{url};2696$self->{ra_uuid} =$self->ra->get_uuid;2697 tmp_config('--add',$key,$self->{ra_uuid});2698}2699}2700$self->{ra_uuid};2701}27022703sub _set_repos_root {2704my($self,$repos_root) =@_;2705my$k="svn-remote.$self->{repo_id}.reposRoot";2706$repos_root||=$self->ra->{repos_root};2707 tmp_config($k,$repos_root);2708$repos_root;2709}27102711sub repos_root {2712my($self) =@_;2713my$k="svn-remote.$self->{repo_id}.reposRoot";2714eval{ tmp_config('--get',$k) } ||$self->_set_repos_root;2715}27162717sub ra {2718my($self) =shift;2719my$ra= Git::SVN::Ra->new($self->{url});2720$self->_set_repos_root($ra->{repos_root});2721if($self->use_svm_props&& !$self->{svm}) {2722if($self->no_metadata) {2723die"Can't have both 'noMetadata' and ",2724"'useSvmProps' options set!\n";2725}elsif($self->use_svnsync_props) {2726die"Can't have both 'useSvnsyncProps' and ",2727"'useSvmProps' options set!\n";2728}2729$ra=$self->_set_svm_vars($ra);2730$self->{-want_revprops} =1;2731}2732$ra;2733}27342735# prop_walk(PATH, REV, SUB)2736# -------------------------2737# Recursively traverse PATH at revision REV and invoke SUB for each2738# directory that contains a SVN property. SUB will be invoked as2739# follows: &SUB(gs, path, props); where `gs' is this instance of2740# Git::SVN, `path' the path to the directory where the properties2741# `props' were found. The `path' will be relative to point of checkout,2742# that is, if url://repo/trunk is the current Git branch, and that2743# directory contains a sub-directory `d', SUB will be invoked with `/d/'2744# as `path' (note the trailing `/').2745sub prop_walk {2746my($self,$path,$rev,$sub) =@_;27472748$path=~ s#^/##;2749my($dirent,undef,$props) =$self->ra->get_dir($path,$rev);2750$path=~ s#^/*#/#g;2751my$p=$path;2752# Strip the irrelevant part of the path.2753$p=~ s#^/+\Q$self->{path}\E(/|$)#/#;2754# Ensure the path is terminated by a `/'.2755$p=~ s#/*$#/#;27562757# The properties contain all the internal SVN stuff nobody2758# (usually) cares about.2759my$interesting_props=0;2760foreach(keys%{$props}) {2761# If it doesn't start with `svn:', it must be a2762# user-defined property.2763++$interesting_propsandnext if$_!~/^svn:/;2764# FIXME: Fragile, if SVN adds new public properties,2765# this needs to be updated.2766++$interesting_propsif/^svn:(?:ignore|keywords|executable2767|eol-style|mime-type2768|externals|needs-lock)$/x;2769}2770&$sub($self,$p,$props)if$interesting_props;27712772foreach(sort keys%$dirent) {2773next if$dirent->{$_}->{kind} !=$SVN::Node::dir;2774$self->prop_walk($self->{path} .$p.$_,$rev,$sub);2775}2776}27772778sub last_rev { ($_[0]->last_rev_commit)[0] }2779sub last_commit { ($_[0]->last_rev_commit)[1] }27802781# returns the newest SVN revision number and newest commit SHA12782sub last_rev_commit {2783my($self) =@_;2784if(defined$self->{last_rev} &&defined$self->{last_commit}) {2785return($self->{last_rev},$self->{last_commit});2786}2787my$c= ::verify_ref($self->refname.'^0');2788if($c&& !$self->use_svm_props&& !$self->no_metadata) {2789my$rev= (::cmt_metadata($c))[1];2790if(defined$rev) {2791($self->{last_rev},$self->{last_commit}) = ($rev,$c);2792return($rev,$c);2793}2794}2795my$map_path=$self->map_path;2796unless(-e $map_path) {2797($self->{last_rev},$self->{last_commit}) = (undef,undef);2798return(undef,undef);2799}2800my($rev,$commit) =$self->rev_map_max(1);2801($self->{last_rev},$self->{last_commit}) = ($rev,$commit);2802return($rev,$commit);2803}28042805sub get_fetch_range {2806my($self,$min,$max) =@_;2807$max||=$self->ra->get_latest_revnum;2808$min||=$self->rev_map_max;2809(++$min,$max);2810}28112812sub tmp_config {2813my(@args) =@_;2814my$old_def_config="$ENV{GIT_DIR}/svn/config";2815my$config="$ENV{GIT_DIR}/svn/.metadata";2816if(! -f $config&& -f $old_def_config) {2817rename$old_def_config,$configor2818die"Failed rename$old_def_config=>$config:$!\n";2819}2820my$old_config=$ENV{GIT_CONFIG};2821$ENV{GIT_CONFIG} =$config;2822$@=undef;2823my@ret=eval{2824unless(-f $config) {2825 mkfile($config);2826open my$fh,'>',$configor2827die"Can't open$config:$!\n";2828print$fh"; This file is used internally by ",2829"git-svn\n"or die2830"Couldn't write to$config:$!\n";2831print$fh"; You should not have to edit it\n"or2832die"Couldn't write to$config:$!\n";2833close$fhor die"Couldn't close$config:$!\n";2834}2835 command('config',@args);2836};2837my$err=$@;2838if(defined$old_config) {2839$ENV{GIT_CONFIG} =$old_config;2840}else{2841delete$ENV{GIT_CONFIG};2842}2843die$errif$err;2844wantarray?@ret:$ret[0];2845}28462847sub tmp_index_do {2848my($self,$sub) =@_;2849my$old_index=$ENV{GIT_INDEX_FILE};2850$ENV{GIT_INDEX_FILE} =$self->{index};2851$@=undef;2852my@ret=eval{2853my($dir,$base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);2854 mkpath([$dir])unless-d $dir;2855&$sub;2856};2857my$err=$@;2858if(defined$old_index) {2859$ENV{GIT_INDEX_FILE} =$old_index;2860}else{2861delete$ENV{GIT_INDEX_FILE};2862}2863die$errif$err;2864wantarray?@ret:$ret[0];2865}28662867sub assert_index_clean {2868my($self,$treeish) =@_;28692870$self->tmp_index_do(sub{2871 command_noisy('read-tree',$treeish)unless-e $self->{index};2872my$x= command_oneline('write-tree');2873my($y) = (command(qw/cat-file commit/,$treeish) =~2874/^tree ($::sha1)/mo);2875return if$yeq$x;28762877warn"Index mismatch:$y!=$x\nrereading$treeish\n";2878unlink$self->{index}or die"unlink$self->{index}:$!\n";2879 command_noisy('read-tree',$treeish);2880$x= command_oneline('write-tree');2881if($yne$x) {2882::fatal "trees ($treeish)$y!=$x\n",2883"Something is seriously wrong...";2884}2885});2886}28872888sub get_commit_parents {2889my($self,$log_entry) =@_;2890my(%seen,@ret,@tmp);2891# legacy support for 'set-tree'; this is only used by set_tree_cb:2892if(my$ip=$self->{inject_parents}) {2893if(my$commit=delete$ip->{$log_entry->{revision}}) {2894push@tmp,$commit;2895}2896}2897if(my$cur= ::verify_ref($self->refname.'^0')) {2898push@tmp,$cur;2899}2900if(my$ipd=$self->{inject_parents_dcommit}) {2901if(my$commit=delete$ipd->{$log_entry->{revision}}) {2902push@tmp,@$commit;2903}2904}2905push@tmp,$_foreach(@{$log_entry->{parents}},@tmp);2906while(my$p=shift@tmp) {2907next if$seen{$p};2908$seen{$p} =1;2909push@ret,$p;2910}2911@ret;2912}29132914sub rewrite_root {2915my($self) =@_;2916return$self->{-rewrite_root}ifexists$self->{-rewrite_root};2917my$k="svn-remote.$self->{repo_id}.rewriteRoot";2918my$rwr=eval{ command_oneline(qw/config --get/,$k) };2919if($rwr) {2920$rwr=~ s#/+$##;2921if($rwr!~ m#^[a-z\+]+://#) {2922die"$rwris not a valid URL (key:$k)\n";2923}2924}2925$self->{-rewrite_root} =$rwr;2926}29272928sub rewrite_uuid {2929my($self) =@_;2930return$self->{-rewrite_uuid}ifexists$self->{-rewrite_uuid};2931my$k="svn-remote.$self->{repo_id}.rewriteUUID";2932my$rwid=eval{ command_oneline(qw/config --get/,$k) };2933if($rwid) {2934$rwid=~ s#/+$##;2935if($rwid!~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {2936die"$rwidis not a valid UUID (key:$k)\n";2937}2938}2939$self->{-rewrite_uuid} =$rwid;2940}29412942sub metadata_url {2943my($self) =@_;2944($self->rewrite_root||$self->{url}) .2945(length$self->{path} ?'/'.$self->{path} :'');2946}29472948sub full_url {2949my($self) =@_;2950$self->{url} . (length$self->{path} ?'/'.$self->{path} :'');2951}29522953sub full_pushurl {2954my($self) =@_;2955if($self->{pushurl}) {2956return$self->{pushurl} . (length$self->{path} ?'/'.2957$self->{path} :'');2958}else{2959return$self->full_url;2960}2961}29622963sub set_commit_header_env {2964my($log_entry) =@_;2965my%env;2966foreachmy$ned(qw/NAME EMAIL DATE/) {2967foreachmy$ac(qw/AUTHOR COMMITTER/) {2968$env{"GIT_${ac}_${ned}"} =$ENV{"GIT_${ac}_${ned}"};2969}2970}29712972$ENV{GIT_AUTHOR_NAME} =$log_entry->{name};2973$ENV{GIT_AUTHOR_EMAIL} =$log_entry->{email};2974$ENV{GIT_AUTHOR_DATE} =$ENV{GIT_COMMITTER_DATE} =$log_entry->{date};29752976$ENV{GIT_COMMITTER_NAME} = (defined$log_entry->{commit_name})2977?$log_entry->{commit_name}2978:$log_entry->{name};2979$ENV{GIT_COMMITTER_EMAIL} = (defined$log_entry->{commit_email})2980?$log_entry->{commit_email}2981:$log_entry->{email};2982 \%env;2983}29842985sub restore_commit_header_env {2986my($env) =@_;2987foreachmy$ned(qw/NAME EMAIL DATE/) {2988foreachmy$ac(qw/AUTHOR COMMITTER/) {2989my$k="GIT_${ac}_${ned}";2990if(defined$env->{$k}) {2991$ENV{$k} =$env->{$k};2992}else{2993delete$ENV{$k};2994}2995}2996}2997}29982999sub gc {3000 command_noisy('gc','--auto');3001};30023003sub do_git_commit {3004my($self,$log_entry) =@_;3005my$lr=$self->last_rev;3006if(defined$lr&&$lr>=$log_entry->{revision}) {3007die"Last fetched revision of ",$self->refname,3008" was r$lr, but we are about to fetch: ",3009"r$log_entry->{revision}!\n";3010}3011if(my$c=$self->rev_map_get($log_entry->{revision})) {3012 croak "$log_entry->{revision} =$calready exists! ",3013"Why are we refetching it?\n";3014}3015my$old_env= set_commit_header_env($log_entry);3016my$tree=$log_entry->{tree};3017if(!defined$tree) {3018$tree=$self->tmp_index_do(sub{3019 command_oneline('write-tree') });3020}3021die"Tree is not a valid sha1:$tree\n"if$tree!~/^$::sha1$/o;30223023my@exec= ('git','commit-tree',$tree);3024foreach($self->get_commit_parents($log_entry)) {3025push@exec,'-p',$_;3026}3027defined(my$pid= open3(my$msg_fh,my$out_fh,'>&STDERR',@exec))3028or croak $!;3029binmode$msg_fh;30303031# we always get UTF-8 from SVN, but we may want our commits in3032# a different encoding.3033if(my$enc= Git::config('i18n.commitencoding')) {3034require Encode;3035 Encode::from_to($log_entry->{log},'UTF-8',$enc);3036}3037print$msg_fh $log_entry->{log}or croak $!;3038 restore_commit_header_env($old_env);3039unless($self->no_metadata) {3040print$msg_fh"\ngit-svn-id:$log_entry->{metadata}\n"3041or croak $!;3042}3043$msg_fh->flush==0or croak $!;3044close$msg_fhor croak $!;3045chomp(my$commit=do{local$/; <$out_fh> });3046close$out_fhor croak $!;3047waitpid$pid,0;3048 croak $?if$?;3049if($commit!~/^$::sha1$/o) {3050die"Failed to commit, invalid sha1:$commit\n";3051}30523053$self->rev_map_set($log_entry->{revision},$commit,1);30543055$self->{last_rev} =$log_entry->{revision};3056$self->{last_commit} =$commit;3057print"r$log_entry->{revision}"unless$::_q >1;3058if(defined$log_entry->{svm_revision}) {3059print" (\@$log_entry->{svm_revision})"unless$::_q >1;3060$self->rev_map_set($log_entry->{svm_revision},$commit,30610,$self->svm_uuid);3062}3063print" =$commit($self->{ref_id})\n"unless$::_q >1;3064if(--$_gc_nr==0) {3065$_gc_nr=$_gc_period;3066 gc();3067}3068return$commit;3069}30703071sub match_paths {3072my($self,$paths,$r) =@_;3073return1if$self->{path}eq'';3074if(my$path=$paths->{"/$self->{path}"}) {3075return($path->{action}eq'D') ?0:1;3076}3077$self->{path_regex} ||=qr/^\/\Q$self->{path}\E\//;3078if(grep/$self->{path_regex}/,keys%$paths) {3079return1;3080}3081my$c='';3082foreach(split m#/#, $self->{path}) {3083$c.="/$_";3084next unless($paths->{$c} &&3085($paths->{$c}->{action} =~/^[AR]$/));3086if($self->ra->check_path($self->{path},$r) ==3087$SVN::Node::dir) {3088return1;3089}3090}3091return0;3092}30933094sub find_parent_branch {3095my($self,$paths,$rev) =@_;3096returnundefunless$self->follow_parent;3097unless(defined$paths) {3098my$err_handler=$SVN::Error::handler;3099$SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;3100$self->ra->get_log([$self->{path}],$rev,$rev,0,1,1,3101sub{$paths=$_[0] });3102$SVN::Error::handler =$err_handler;3103}3104returnundefunlessdefined$paths;31053106# look for a parent from another branch:3107my@b_path_components=split m#/#, $self->{path};3108my@a_path_components;3109my$i;3110while(@b_path_components) {3111$i=$paths->{'/'.join('/',@b_path_components)};3112last if$i&&defined$i->{copyfrom_path};3113unshift(@a_path_components,pop(@b_path_components));3114}3115returnundefunlessdefined$i&&defined$i->{copyfrom_path};3116my$branch_from=$i->{copyfrom_path};3117if(@a_path_components) {3118print STDERR "branch_from:$branch_from=> ";3119$branch_from.='/'.join('/',@a_path_components);3120print STDERR $branch_from,"\n";3121}3122my$r=$i->{copyfrom_rev};3123my$repos_root=$self->ra->{repos_root};3124my$url=$self->ra->{url};3125my$new_url=$url.$branch_from;3126print STDERR "Found possible branch point: ",3127"$new_url=> ",$self->full_url,",$r\n"3128unless$::_q >1;3129$branch_from=~ s#^/##;3130my$gs=$self->other_gs($new_url,$url,3131$branch_from,$r,$self->{ref_id});3132my($r0,$parent) =$gs->find_rev_before($r,1);3133{3134my($base,$head);3135if(!defined$r0|| !defined$parent) {3136($base,$head) = parse_revision_argument(0,$r);3137}else{3138if($r0<$r) {3139$gs->ra->get_log([$gs->{path}],$r0+1,$r,1,31400,1,sub{$base=$_[1] -1});3141}3142}3143if(defined$base&&$base<=$r) {3144$gs->fetch($base,$r);3145}3146($r0,$parent) =$gs->find_rev_before($r,1);3147}3148if(defined$r0&&defined$parent) {3149print STDERR "Found branch parent: ($self->{ref_id})$parent\n"3150unless$::_q >1;3151my$ed;3152if($self->ra->can_do_switch) {3153$self->assert_index_clean($parent);3154print STDERR "Following parent with do_switch\n"3155unless$::_q >1;3156# do_switch works with svn/trunk >= r22312, but that3157# is not included with SVN 1.4.3 (the latest version3158# at the moment), so we can't rely on it3159$self->{last_rev} =$r0;3160$self->{last_commit} =$parent;3161$ed= Git::SVN::Fetcher->new($self,$gs->{path});3162$gs->ra->gs_do_switch($r0,$rev,$gs,3163$self->full_url,$ed)3164or die"SVN connection failed somewhere...\n";3165}elsif($self->ra->trees_match($new_url,$r0,3166$self->full_url,$rev)) {3167print STDERR "Trees match:\n",3168"$new_url\@$r0\n",3169" ${\$self->full_url}\@$rev\n",3170"Following parent with no changes\n"3171unless$::_q >1;3172$self->tmp_index_do(sub{3173 command_noisy('read-tree',$parent);3174});3175$self->{last_commit} =$parent;3176}else{3177print STDERR "Following parent with do_update\n"3178unless$::_q >1;3179$ed= Git::SVN::Fetcher->new($self);3180$self->ra->gs_do_update($rev,$rev,$self,$ed)3181or die"SVN connection failed somewhere...\n";3182}3183print STDERR "Successfully followed parent\n"unless$::_q >1;3184return$self->make_log_entry($rev, [$parent],$ed);3185}3186returnundef;3187}31883189sub do_fetch {3190my($self,$paths,$rev) =@_;3191my$ed;3192my($last_rev,@parents);3193if(my$lc=$self->last_commit) {3194# we can have a branch that was deleted, then re-added3195# under the same name but copied from another path, in3196# which case we'll have multiple parents (we don't3197# want to break the original ref, nor lose copypath info):3198if(my$log_entry=$self->find_parent_branch($paths,$rev)) {3199push@{$log_entry->{parents}},$lc;3200return$log_entry;3201}3202$ed= Git::SVN::Fetcher->new($self);3203$last_rev=$self->{last_rev};3204$ed->{c} =$lc;3205@parents= ($lc);3206}else{3207$last_rev=$rev;3208if(my$log_entry=$self->find_parent_branch($paths,$rev)) {3209return$log_entry;3210}3211$ed= Git::SVN::Fetcher->new($self);3212}3213unless($self->ra->gs_do_update($last_rev,$rev,$self,$ed)) {3214die"SVN connection failed somewhere...\n";3215}3216$self->make_log_entry($rev, \@parents,$ed);3217}32183219sub mkemptydirs {3220my($self,$r) =@_;32213222sub scan {3223my($r,$empty_dirs,$line) =@_;3224if(defined$r&&$line=~/^r(\d+)$/) {3225return0if$1>$r;3226}elsif($line=~/^ \+empty_dir: (.+)$/) {3227$empty_dirs->{$1} =1;3228}elsif($line=~/^ \-empty_dir: (.+)$/) {3229my@d=grep{m[^\Q$1\E(/|$)]} (keys%$empty_dirs);3230delete@$empty_dirs{@d};3231}32321;# continue3233};32343235my%empty_dirs= ();3236my$gz_file="$self->{dir}/unhandled.log.gz";3237if(-f $gz_file) {3238if(!$can_compress) {3239warn"Compress::Zlib could not be found; ",3240"empty directories in$gz_filewill not be read\n";3241}else{3242my$gz= Compress::Zlib::gzopen($gz_file,"rb")or3243die"Unable to open$gz_file:$!\n";3244my$line;3245while($gz->gzreadline($line) >0) {3246 scan($r, \%empty_dirs,$line)orlast;3247}3248$gz->gzclose;3249}3250}32513252if(open my$fh,'<',"$self->{dir}/unhandled.log") {3253binmode$fhor croak "binmode:$!";3254while(<$fh>) {3255 scan($r, \%empty_dirs,$_)orlast;3256}3257close$fh;3258}32593260my$strip=qr/\A\Q$self->{path}\E(?:\/|$)/;3261foreachmy$d(sort keys%empty_dirs) {3262$d= uri_decode($d);3263$d=~s/$strip//;3264next unlesslength($d);3265next if-d $d;3266if(-e $d) {3267warn"$dexists but is not a directory\n";3268}else{3269print"creating empty directory:$d\n";3270 mkpath([$d]);3271}3272}3273}32743275sub get_untracked {3276my($self,$ed) =@_;3277my@out;3278my$h=$ed->{empty};3279foreach(sort keys%$h) {3280my$act=$h->{$_} ?'+empty_dir':'-empty_dir';3281push@out,"$act: ". uri_encode($_);3282warn"W:$act:$_\n";3283}3284foreachmy$t(qw/dir_prop file_prop/) {3285$h=$ed->{$t}ornext;3286foreachmy$path(sort keys%$h) {3287my$ppath=$patheq''?'.':$path;3288foreachmy$prop(sort keys%{$h->{$path}}) {3289next if$SKIP_PROP{$prop};3290my$v=$h->{$path}->{$prop};3291my$t_ppath_prop="$t: ".3292 uri_encode($ppath) .' '.3293 uri_encode($prop);3294if(defined$v) {3295push@out," +$t_ppath_prop".3296 uri_encode($v);3297}else{3298push@out," -$t_ppath_prop";3299}3300}3301}3302}3303foreachmy$t(qw/absent_file absent_directory/) {3304$h=$ed->{$t}ornext;3305foreachmy$parent(sort keys%$h) {3306foreachmy$path(sort@{$h->{$parent}}) {3307push@out,"$t: ".3308 uri_encode("$parent/$path");3309warn"W:$t:$parent/$path",3310"Insufficient permissions?\n";3311}3312}3313}3314 \@out;3315}33163317sub get_tz {3318# some systmes don't handle or mishandle %z, so be creative.3319my$t=shift||time;3320my$gm= timelocal(gmtime($t));3321my$sign=qw( + + - )[$t<=>$gm];3322returnsprintf("%s%02d%02d",$sign, (gmtime(abs($t-$gm)))[2,1]);3323}33243325# parse_svn_date(DATE)3326# --------------------3327# Given a date (in UTC) from Subversion, return a string in the format3328# "<TZ Offset> <local date/time>" that Git will use.3329#3330# By default the parsed date will be in UTC; if $Git::SVN::_localtime3331# is true we'll convert it to the local timezone instead.3332sub parse_svn_date {3333my$date=shift||return'+0000 1970-01-01 00:00:00';3334my($Y,$m,$d,$H,$M,$S) = ($date=~ /^(\d{4})\-(\d\d)\-(\d\d)T3335(\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x)or3336 croak "Unable to parse date:$date\n";3337my$parsed_date;# Set next.33383339if($Git::SVN::_localtime) {3340# Translate the Subversion datetime to an epoch time.3341# Begin by switching ourselves to $date's timezone, UTC.3342my$old_env_TZ=$ENV{TZ};3343$ENV{TZ} ='UTC';33443345my$epoch_in_UTC=3346 POSIX::strftime('%s',$S,$M,$H,$d,$m-1,$Y-1900);33473348# Determine our local timezone (including DST) at the3349# time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the3350# value of TZ, if any, at the time we were run.3351if(defined$Git::SVN::Log::TZ) {3352$ENV{TZ} =$Git::SVN::Log::TZ;3353}else{3354delete$ENV{TZ};3355}33563357my$our_TZ= get_tz();33583359# This converts $epoch_in_UTC into our local timezone.3360my($sec,$min,$hour,$mday,$mon,$year,3361$wday,$yday,$isdst) =localtime($epoch_in_UTC);33623363$parsed_date=sprintf('%s%04d-%02d-%02d%02d:%02d:%02d',3364$our_TZ,$year+1900,$mon+1,3365$mday,$hour,$min,$sec);33663367# Reset us to the timezone in effect when we entered3368# this routine.3369if(defined$old_env_TZ) {3370$ENV{TZ} =$old_env_TZ;3371}else{3372delete$ENV{TZ};3373}3374}else{3375$parsed_date="+0000$Y-$m-$d$H:$M:$S";3376}33773378return$parsed_date;3379}33803381sub other_gs {3382my($self,$new_url,$url,3383$branch_from,$r,$old_ref_id) =@_;3384my$gs= Git::SVN->find_by_url($new_url,$url,$branch_from);3385unless($gs) {3386my$ref_id=$old_ref_id;3387$ref_id=~s/\@\d+-*$//;3388$ref_id.="\@$r";3389# just grow a tail if we're not unique enough :x3390$ref_id.='-'while find_ref($ref_id);3391my($u,$p,$repo_id) = ($new_url,'',$ref_id);3392if($u=~ s#^\Q$url\E(/|$)##) {3393$p=$u;3394$u=$url;3395$repo_id=$self->{repo_id};3396}3397while(1) {3398# It is possible to tag two different subdirectories at3399# the same revision. If the url for an existing ref3400# does not match, we must either find a ref with a3401# matching url or create a new ref by growing a tail.3402$gs= Git::SVN->init($u,$p,$repo_id,$ref_id,1);3403my(undef,$max_commit) =$gs->rev_map_max(1);3404last if(!$max_commit);3405my($url) = ::cmt_metadata($max_commit);3406last if($urleq$gs->metadata_url);3407$ref_id.='-';3408}3409print STDERR "Initializing parent:$ref_id\n"unless$::_q >1;3410}3411$gs3412}34133414sub call_authors_prog {3415my($orig_author) =@_;3416$orig_author= command_oneline('rev-parse','--sq-quote',$orig_author);3417my$author=`$::_authors_prog$orig_author`;3418 if ($?!= 0) {3419 die "$::_authors_prog failed with exit code$?\n"3420 }3421 if ($author=~ /^\s*(.+?)\s*<(.*)>\s*$/) {3422 my ($name,$email) = ($1,$2);3423$email= undef if length$2== 0;3424 return [$name,$email];3425 } else {3426 die "Author:$orig_author: $::_authors_prog returned "3427 . "invalid author format:$author\n";3428 }3429}34303431sub check_author {3432 my ($author) =@_;3433 if (!defined$author|| length$author== 0) {3434$author= '(no author)';3435 }3436 if (!defined $::users{$author}) {3437 if (defined $::_authors_prog) {3438 $::users{$author} = call_authors_prog($author);3439 } elsif (defined $::_authors) {3440 die "Author:$authornot defined in $::_authors file\n";3441 }3442 }3443$author;3444}34453446sub find_extra_svk_parents {3447 my ($self,$ed,$tickets,$parents) =@_;3448 # aha! svk:merge property changed...3449 my@tickets= split "\n",$tickets;3450 my@known_parents;3451 for my$ticket(@tickets) {3452 my ($uuid,$path,$rev) = split /:/,$ticket;3453 if ($uuideq$self->ra_uuid ) {3454 my$url=$self->{url};3455 my$repos_root=$url;3456 my$branch_from=$path;3457$branch_from=~ s{^/}{};3458 my$gs=$self->other_gs($repos_root."/".$branch_from,3459$url,3460$branch_from,3461$rev,3462$self->{ref_id});3463 if ( my$commit=$gs->rev_map_get($rev,$uuid) ) {3464 # wahey! we found it, but it might be3465 # an old one (!)3466 push@known_parents, [$rev,$commit];3467 }3468 }3469 }3470 # Ordering matters; highest-numbered commit merge tickets3471 # first, as they may account for later merge ticket additions3472 # or changes.3473@known_parents= map {$_->[1]} sort {$b->[0] <=>$a->[0]}@known_parents;3474 for my$parent(@known_parents) {3475 my@cmd= ('rev-list',$parent, map { "^$_" }@$parents);3476 my ($msg_fh,$ctx) = command_output_pipe(@cmd);3477 my$new;3478 while ( <$msg_fh> ) {3479$new=1;last;3480 }3481 command_close_pipe($msg_fh,$ctx);3482 if ($new) {3483 print STDERR3484 "Found merge parent (svk:merge ticket):$parent\n";3485 push@$parents,$parent;3486 }3487 }3488}34893490sub lookup_svn_merge {3491 my$uuid= shift;3492 my$url= shift;3493 my$merge= shift;34943495 my ($source,$revs) = split ":",$merge;3496 my$path=$source;3497$path=~ s{^/}{};3498 my$gs= Git::SVN->find_by_url($url.$source,$url,$path);3499 if ( !$gs) {3500 warn "Couldn't find revmap for$url$source\n";3501 return;3502 }3503 my@ranges= split ",",$revs;3504 my ($tip,$tip_commit);3505 my@merged_commit_ranges;3506 # find the tip3507 for my$range(@ranges) {3508 my ($bottom,$top) = split "-",$range;3509$top||=$bottom;3510 my$bottom_commit=$gs->find_rev_after($bottom, 1,$top);3511 my$top_commit=$gs->find_rev_before($top, 1,$bottom);35123513 unless ($top_commitand$bottom_commit) {3514 warn "W:unknown path/rev in svn:mergeinfo "3515 ."dirprop:$source:$range\n";3516 next;3517 }35183519 if (scalar(command('rev-parse', "$bottom_commit^@"))) {3520 push@merged_commit_ranges,3521 "$bottom_commit^..$top_commit";3522 } else {3523 push@merged_commit_ranges, "$top_commit";3524 }35253526 if ( !defined$tipor$top>$tip) {3527$tip=$top;3528$tip_commit=$top_commit;3529 }3530 }3531 return ($tip_commit,@merged_commit_ranges);3532}35333534sub _rev_list {3535 my ($msg_fh,$ctx) = command_output_pipe(3536 "rev-list",@_,3537 );3538 my@rv;3539 while ( <$msg_fh> ) {3540 chomp;3541 push@rv,$_;3542 }3543 command_close_pipe($msg_fh,$ctx);3544@rv;3545}35463547sub check_cherry_pick {3548 my$base= shift;3549 my$tip= shift;3550 my$parents= shift;3551 my@ranges=@_;3552 my%commits= map {$_=> 1 }3553 _rev_list("--no-merges",$tip, "--not",$base,@$parents, "--");3554 for my$range(@ranges) {3555 delete@commits{_rev_list($range, "--")};3556 }3557 for my$commit(keys%commits) {3558 if (has_no_changes($commit)) {3559 delete$commits{$commit};3560 }3561 }3562 return (keys%commits);3563}35643565sub has_no_changes {3566 my$commit= shift;35673568 my@revs= split / /, command_oneline(3569 qw(rev-list --parents -1 -m),$commit);35703571# Commits with no parents, e.g. the start of a partial branch,3572# have changes by definition.3573return1if(@revs<2);35743575# Commits with multiple parents, e.g a merge, have no changes3576# by definition.3577return0if(@revs>2);35783579return(command_oneline("rev-parse","$commit^{tree}")eq3580 command_oneline("rev-parse","$commit~1^{tree}"));3581}35823583sub tie_for_persistent_memoization {3584my$hash=shift;3585my$path=shift;35863587if($can_use_yaml) {3588 tie %$hash=>'Git::SVN::Memoize::YAML',"$path.yaml";3589}else{3590 tie %$hash=>'Memoize::Storable',"$path.db",'nstore';3591}3592}35933594# The GIT_DIR environment variable is not always set until after the command3595# line arguments are processed, so we can't memoize in a BEGIN block.3596{3597my$memoized=0;35983599sub memoize_svn_mergeinfo_functions {3600return if$memoized;3601$memoized=1;36023603my$cache_path="$ENV{GIT_DIR}/svn/.caches/";3604 mkpath([$cache_path])unless-d $cache_path;36053606my%lookup_svn_merge_cache;3607my%check_cherry_pick_cache;3608my%has_no_changes_cache;36093610 tie_for_persistent_memoization(\%lookup_svn_merge_cache,3611"$cache_path/lookup_svn_merge");3612 memoize 'lookup_svn_merge',3613 SCALAR_CACHE =>'FAULT',3614 LIST_CACHE => ['HASH'=> \%lookup_svn_merge_cache],3615;36163617 tie_for_persistent_memoization(\%check_cherry_pick_cache,3618"$cache_path/check_cherry_pick");3619 memoize 'check_cherry_pick',3620 SCALAR_CACHE =>'FAULT',3621 LIST_CACHE => ['HASH'=> \%check_cherry_pick_cache],3622;36233624 tie_for_persistent_memoization(\%has_no_changes_cache,3625"$cache_path/has_no_changes");3626 memoize 'has_no_changes',3627 SCALAR_CACHE => ['HASH'=> \%has_no_changes_cache],3628 LIST_CACHE =>'FAULT',3629;3630}36313632sub unmemoize_svn_mergeinfo_functions {3633return ifnot$memoized;3634$memoized=0;36353636 Memoize::unmemoize 'lookup_svn_merge';3637 Memoize::unmemoize 'check_cherry_pick';3638 Memoize::unmemoize 'has_no_changes';3639}36403641 Memoize::memoize 'Git::SVN::repos_root';3642}36433644END{3645# Force cache writeout explicitly instead of waiting for3646# global destruction to avoid segfault in Storable:3647# http://rt.cpan.org/Public/Bug/Display.html?id=360873648 unmemoize_svn_mergeinfo_functions();3649}36503651sub parents_exclude {3652my$parents=shift;3653my@commits=@_;3654return unless@commits;36553656my@excluded;3657my$excluded;3658do{3659my@cmd= ('rev-list',"-1",@commits,"--not",@$parents);3660$excluded= command_oneline(@cmd);3661if($excluded) {3662my@new;3663my$found;3664formy$commit(@commits) {3665if($commiteq$excluded) {3666push@excluded,$commit;3667$found++;3668last;3669}3670else{3671push@new,$commit;3672}3673}3674die"saw commit '$excluded' in rev-list output, "3675."but we didn't ask for that commit (wanted:@commits--not@$parents)"3676unless$found;3677@commits=@new;3678}3679}3680while($excludedand@commits);36813682return@excluded;3683}368436853686# note: this function should only be called if the various dirprops3687# have actually changed3688sub find_extra_svn_parents {3689my($self,$ed,$mergeinfo,$parents) =@_;3690# aha! svk:merge property changed...36913692 memoize_svn_mergeinfo_functions();36933694# We first search for merged tips which are not in our3695# history. Then, we figure out which git revisions are in3696# that tip, but not this revision. If all of those revisions3697# are now marked as merge, we can add the tip as a parent.3698my@merges=split"\n",$mergeinfo;3699my@merge_tips;3700my$url=$self->{url};3701my$uuid=$self->ra_uuid;3702my%ranges;3703formy$merge(@merges) {3704my($tip_commit,@ranges) =3705 lookup_svn_merge($uuid,$url,$merge);3706unless(!$tip_commitor3707grep{$_eq$tip_commit}@$parents) {3708push@merge_tips,$tip_commit;3709$ranges{$tip_commit} = \@ranges;3710}else{3711push@merge_tips,undef;3712}3713}37143715my%excluded=map{$_=>1}3716 parents_exclude($parents,grep{defined}@merge_tips);37173718# check merge tips for new parents3719my@new_parents;3720formy$merge_tip(@merge_tips) {3721my$spec=shift@merges;3722next unless$merge_tipand$excluded{$merge_tip};37233724my$ranges=$ranges{$merge_tip};37253726# check out 'new' tips3727my$merge_base;3728eval{3729$merge_base= command_oneline(3730"merge-base",3731@$parents,$merge_tip,3732);3733};3734if($@) {3735die"An error occurred during merge-base"3736unless$@->isa("Git::Error::Command");37373738warn"W: Cannot find common ancestor between ".3739"@$parentsand$merge_tip. Ignoring merge info.\n";3740next;3741}37423743# double check that there are no missing non-merge commits3744my(@incomplete) = check_cherry_pick(3745$merge_base,$merge_tip,3746$parents,3747@$ranges,3748);37493750if(@incomplete) {3751warn"W:svn cherry-pick ignored ($spec) - missing "3752.@incomplete." commit(s) (eg$incomplete[0])\n";3753}else{3754warn3755"Found merge parent (svn:mergeinfo prop): ",3756$merge_tip,"\n";3757push@new_parents,$merge_tip;3758}3759}37603761# cater for merges which merge commits from multiple branches3762if(@new_parents>1) {3763for(my$i=0;$i<=$#new_parents;$i++) {3764for(my$j=0;$j<=$#new_parents;$j++) {3765next if$i==$j;3766next unless$new_parents[$i];3767next unless$new_parents[$j];3768my$revs= command_oneline(3769"rev-list","-1",3770"$new_parents[$i]..$new_parents[$j]",3771);3772if( !$revs) {3773undef($new_parents[$j]);3774}3775}3776}3777}3778push@$parents,grep{defined}@new_parents;3779}37803781sub make_log_entry {3782my($self,$rev,$parents,$ed) =@_;3783my$untracked=$self->get_untracked($ed);37843785my@parents=@$parents;3786my$ps=$ed->{path_strip} ||"";3787formy$path(grep{m/$ps/} %{$ed->{dir_prop}} ) {3788my$props=$ed->{dir_prop}{$path};3789if($props->{"svk:merge"} ) {3790$self->find_extra_svk_parents3791($ed,$props->{"svk:merge"}, \@parents);3792}3793if($props->{"svn:mergeinfo"} ) {3794$self->find_extra_svn_parents3795($ed,3796$props->{"svn:mergeinfo"},3797 \@parents);3798}3799}38003801open my$un,'>>',"$self->{dir}/unhandled.log"or croak $!;3802print$un"r$rev\n"or croak $!;3803print$un $_,"\n"foreach@$untracked;3804my%log_entry= ( parents => \@parents, revision =>$rev,3805log=>'');38063807my$headrev;3808my$logged=delete$self->{logged_rev_props};3809if(!$logged||$self->{-want_revprops}) {3810my$rp=$self->ra->rev_proplist($rev);3811foreach(sort keys%$rp) {3812my$v=$rp->{$_};3813if(/^svn:(author|date|log)$/) {3814$log_entry{$1} =$v;3815}elsif($_eq'svm:headrev') {3816$headrev=$v;3817}else{3818print$un" rev_prop: ", uri_encode($_),' ',3819 uri_encode($v),"\n";3820}3821}3822}else{3823map{$log_entry{$_} =$logged->{$_} }keys%$logged;3824}3825close$unor croak $!;38263827$log_entry{date} = parse_svn_date($log_entry{date});3828$log_entry{log} .="\n";3829my$author=$log_entry{author} = check_author($log_entry{author});3830my($name,$email) =defined$::users{$author} ? @{$::users{$author}}3831: ($author,undef);38323833my($commit_name,$commit_email) = ($name,$email);3834if($_use_log_author) {3835my$name_field;3836if($log_entry{log} =~/From:\s+(.*\S)\s*\n/i) {3837$name_field=$1;3838}elsif($log_entry{log} =~/Signed-off-by:\s+(.*\S)\s*\n/i) {3839$name_field=$1;3840}3841if(!defined$name_field) {3842if(!defined$email) {3843$email=$name;3844}3845}elsif($name_field=~/(.*?)\s+<(.*)>/) {3846($name,$email) = ($1,$2);3847}elsif($name_field=~/(.*)@/) {3848($name,$email) = ($1,$name_field);3849}else{3850($name,$email) = ($name_field,$name_field);3851}3852}3853if(defined$headrev&&$self->use_svm_props) {3854if($self->rewrite_root) {3855die"Can't have both 'useSvmProps' and 'rewriteRoot' ",3856"options set!\n";3857}3858if($self->rewrite_uuid) {3859die"Can't have both 'useSvmProps' and 'rewriteUUID' ",3860"options set!\n";3861}3862my($uuid,$r) =$headrev=~m{^([a-f\d\-]{30,}):(\d+)$}i;3863# we don't want "SVM: initializing mirror for junk" ...3864returnundefif$r==0;3865my$svm=$self->svm;3866if($uuidne$svm->{uuid}) {3867die"UUID mismatch on SVM path:\n",3868"expected:$svm->{uuid}\n",3869" got:$uuid\n";3870}3871my$full_url=$self->full_url;3872$full_url=~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or3873die"Failed to replace '$svm->{replace}' with ",3874"'$svm->{source}' in$full_url\n";3875# throw away username for storing in records3876 remove_username($full_url);3877$log_entry{metadata} ="$full_url\@$r$uuid";3878$log_entry{svm_revision} =$r;3879$email||="$author\@$uuid";3880$commit_email||="$author\@$uuid";3881}elsif($self->use_svnsync_props) {3882my$full_url=$self->svnsync->{url};3883$full_url.="/$self->{path}"iflength$self->{path};3884 remove_username($full_url);3885my$uuid=$self->svnsync->{uuid};3886$log_entry{metadata} ="$full_url\@$rev$uuid";3887$email||="$author\@$uuid";3888$commit_email||="$author\@$uuid";3889}else{3890my$url=$self->metadata_url;3891 remove_username($url);3892my$uuid=$self->rewrite_uuid||$self->ra->get_uuid;3893$log_entry{metadata} ="$url\@$rev".$uuid;3894$email||="$author\@".$uuid;3895$commit_email||="$author\@".$uuid;3896}3897$log_entry{name} =$name;3898$log_entry{email} =$email;3899$log_entry{commit_name} =$commit_name;3900$log_entry{commit_email} =$commit_email;3901 \%log_entry;3902}39033904sub fetch {3905my($self,$min_rev,$max_rev,@parents) =@_;3906my($last_rev,$last_commit) =$self->last_rev_commit;3907my($base,$head) =$self->get_fetch_range($min_rev,$max_rev);3908$self->ra->gs_fetch_loop_common($base,$head, [$self]);3909}39103911sub set_tree_cb {3912my($self,$log_entry,$tree,$rev,$date,$author) =@_;3913$self->{inject_parents} = {$rev=>$tree};3914$self->fetch(undef,undef);3915}39163917sub set_tree {3918my($self,$tree) = (shift,shift);3919my$log_entry= ::get_commit_entry($tree);3920unless($self->{last_rev}) {3921::fatal("Must have an existing revision to commit");3922}3923my%ed_opts= ( r =>$self->{last_rev},3924log=>$log_entry->{log},3925 ra =>$self->ra,3926 tree_a =>$self->{last_commit},3927 tree_b =>$tree,3928 editor_cb =>sub{3929$self->set_tree_cb($log_entry,$tree,@_) },3930 svn_path =>$self->{path} );3931if(!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {3932print"No changes\nr$self->{last_rev} =$tree\n";3933}3934}39353936sub rebuild_from_rev_db {3937my($self,$path) =@_;3938my$r= -1;3939open my$fh,'<',$pathor croak "open:$!";3940binmode$fhor croak "binmode:$!";3941while(<$fh>) {3942length($_) ==41or croak "inconsistent size in ($_) != 41";3943chomp($_);3944++$r;3945next if$_eq('0' x 40);3946$self->rev_map_set($r,$_);3947print"r$r=$_\n";3948}3949close$fhor croak "close:$!";3950unlink$pathor croak "unlink:$!";3951}39523953sub rebuild {3954my($self) =@_;3955my$map_path=$self->map_path;3956my$partial= (-e $map_path&& ! -z $map_path);3957return unless::verify_ref($self->refname.'^0');3958if(!$partial&& ($self->use_svm_props||$self->no_metadata)) {3959my$rev_db=$self->rev_db_path;3960$self->rebuild_from_rev_db($rev_db);3961if($self->use_svm_props) {3962my$svm_rev_db=$self->rev_db_path($self->svm_uuid);3963$self->rebuild_from_rev_db($svm_rev_db);3964}3965$self->unlink_rev_db_symlink;3966return;3967}3968print"Rebuilding$map_path...\n"if(!$partial);3969my($base_rev,$head) = ($partial?$self->rev_map_max_norebuild(1) :3970(undef,undef));3971my($log,$ctx) =3972 command_output_pipe(qw/rev-list --pretty=raw --reverse/,3973($head?"$head..":"") .$self->refname,3974'--');3975my$metadata_url=$self->metadata_url;3976 remove_username($metadata_url);3977my$svn_uuid=$self->rewrite_uuid||$self->ra_uuid;3978my$c;3979while(<$log>) {3980if(m{^commit ($::sha1)$}) {3981$c=$1;3982next;3983}3984next unlesss{^\s*(git-svn-id:)}{$1};3985my($url,$rev,$uuid) = ::extract_metadata($_);3986 remove_username($url);39873988# ignore merges (from set-tree)3989next if(!defined$rev|| !$uuid);39903991# if we merged or otherwise started elsewhere, this is3992# how we break out of it3993if(($uuidne$svn_uuid) ||3994($metadata_url&&$url&& ($urlne$metadata_url))) {3995next;3996}3997if($partial&&$head) {3998print"Partial-rebuilding$map_path...\n";3999print"Currently at$base_rev=$head\n";4000$head=undef;4001}40024003$self->rev_map_set($rev,$c);4004print"r$rev=$c\n";4005}4006 command_close_pipe($log,$ctx);4007print"Done rebuilding$map_path\n"if(!$partial|| !$head);4008my$rev_db_path=$self->rev_db_path;4009if(-f $self->rev_db_path) {4010unlink$self->rev_db_pathor croak "unlink:$!";4011}4012$self->unlink_rev_db_symlink;4013}40144015# rev_map:4016# Tie::File seems to be prone to offset errors if revisions get sparse,4017# it's not that fast, either. Tie::File is also not in Perl 5.6. So4018# one of my favorite modules is out :< Next up would be one of the DBM4019# modules, but I'm not sure which is most portable...4020#4021# This is the replacement for the rev_db format, which was too big4022# and inefficient for large repositories with a lot of sparse history4023# (mainly tags)4024#4025# The format is this:4026# - 24 bytes for every record,4027# * 4 bytes for the integer representing an SVN revision number4028# * 20 bytes representing the sha1 of a git commit4029# - No empty padding records like the old format4030# (except the last record, which can be overwritten)4031# - new records are written append-only since SVN revision numbers4032# increase monotonically4033# - lookups on SVN revision number are done via a binary search4034# - Piping the file to xxd -c24 is a good way of dumping it for4035# viewing or editing (piped back through xxd -r), should the need4036# ever arise.4037# - The last record can be padding revision with an all-zero sha14038# This is used to optimize fetch performance when using multiple4039# "fetch" directives in .git/config4040#4041# These files are disposable unless noMetadata or useSvmProps is set40424043sub _rev_map_set {4044my($fh,$rev,$commit) =@_;40454046binmode$fhor croak "binmode:$!";4047my$size= (stat($fh))[7];4048($size%24) ==0or croak "inconsistent size:$size";40494050my$wr_offset=0;4051if($size>0) {4052sysseek($fh, -24, SEEK_END)or croak "seek:$!";4053my$read=sysread($fh,my$buf,24)or croak "read:$!";4054$read==24or croak "read only$readbytes (!= 24)";4055my($last_rev,$last_commit) =unpack(rev_map_fmt,$buf);4056if($last_commiteq('0' x40)) {4057if($size>=48) {4058sysseek($fh, -48, SEEK_END)or croak "seek:$!";4059$read=sysread($fh,$buf,24)or4060 croak "read:$!";4061$read==24or4062 croak "read only$readbytes (!= 24)";4063($last_rev,$last_commit) =4064unpack(rev_map_fmt,$buf);4065if($last_commiteq('0' x40)) {4066 croak "inconsistent .rev_map\n";4067}4068}4069if($last_rev>=$rev) {4070 croak "last_rev is higher!:$last_rev>=$rev";4071}4072$wr_offset= -24;4073}4074}4075sysseek($fh,$wr_offset, SEEK_END)or croak "seek:$!";4076syswrite($fh,pack(rev_map_fmt,$rev,$commit),24) ==24or4077 croak "write:$!";4078}40794080sub _rev_map_reset {4081my($fh,$rev,$commit) =@_;4082my$c= _rev_map_get($fh,$rev);4083$ceq$commitor die"_rev_map_reset(@_) commit$cdoes not match!\n";4084my$offset=sysseek($fh,0, SEEK_CUR)or croak "seek:$!";4085truncate$fh,$offsetor croak "truncate:$!";4086}40874088sub mkfile {4089my($path) =@_;4090unless(-e $path) {4091my($dir,$base) = ($path=~ m#^(.*?)/?([^/]+)$#);4092 mkpath([$dir])unless-d $dir;4093open my$fh,'>>',$pathor die"Couldn't create$path:$!\n";4094close$fhor die"Couldn't close (create)$path:$!\n";4095}4096}40974098sub rev_map_set {4099my($self,$rev,$commit,$update_ref,$uuid) =@_;4100defined$commitor die"missing arg3\n";4101length$commit==40or die"arg3 must be a full SHA1 hexsum\n";4102my$db=$self->map_path($uuid);4103my$db_lock="$db.lock";4104my$sigmask;4105$update_ref||=0;4106if($update_ref) {4107$sigmask= POSIX::SigSet->new();4108my$signew= POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,4109 SIGALRM, SIGUSR1, SIGUSR2);4110 sigprocmask(SIG_BLOCK,$signew,$sigmask)or4111 croak "Can't block signals:$!";4112}4113 mkfile($db);41144115$LOCKFILES{$db_lock} =1;4116my$sync;4117# both of these options make our .rev_db file very, very important4118# and we can't afford to lose it because rebuild() won't work4119if($self->use_svm_props||$self->no_metadata) {4120$sync=1;4121 copy($db,$db_lock)or die"rev_map_set(@_): ",4122"Failed to copy: ",4123"$db=>$db_lock($!)\n";4124}else{4125rename$db,$db_lockor die"rev_map_set(@_): ",4126"Failed to rename: ",4127"$db=>$db_lock($!)\n";4128}41294130sysopen(my$fh,$db_lock, O_RDWR | O_CREAT)4131or croak "Couldn't open$db_lock:$!\n";4132$update_refeq'reset'? _rev_map_reset($fh,$rev,$commit) :4133 _rev_map_set($fh,$rev,$commit);4134if($sync) {4135$fh->flushor die"Couldn't flush$db_lock:$!\n";4136$fh->syncor die"Couldn't sync$db_lock:$!\n";4137}4138close$fhor croak $!;4139if($update_ref) {4140$_head=$self;4141my$note="";4142$note=" ($update_ref)"if($update_ref!~/^\d*$/);4143 command_noisy('update-ref','-m',"r$rev$note",4144$self->refname,$commit);4145}4146rename$db_lock,$dbor die"rev_map_set(@_): ","Failed to rename: ",4147"$db_lock=>$db($!)\n";4148delete$LOCKFILES{$db_lock};4149if($update_ref) {4150 sigprocmask(SIG_SETMASK,$sigmask)or4151 croak "Can't restore signal mask:$!";4152}4153}41544155# If want_commit, this will return an array of (rev, commit) where4156# commit _must_ be a valid commit in the archive.4157# Otherwise, it'll return the max revision (whether or not the4158# commit is valid or just a 0x40 placeholder).4159sub rev_map_max {4160my($self,$want_commit) =@_;4161$self->rebuild;4162my($r,$c) =$self->rev_map_max_norebuild($want_commit);4163$want_commit? ($r,$c) :$r;4164}41654166sub rev_map_max_norebuild {4167my($self,$want_commit) =@_;4168my$map_path=$self->map_path;4169stat$map_pathorreturn$want_commit? (0,undef) :0;4170sysopen(my$fh,$map_path, O_RDONLY)or croak "open:$!";4171binmode$fhor croak "binmode:$!";4172my$size= (stat($fh))[7];4173($size%24) ==0or croak "inconsistent size:$size";41744175if($size==0) {4176close$fhor croak "close:$!";4177return$want_commit? (0,undef) :0;4178}41794180sysseek($fh, -24, SEEK_END)or croak "seek:$!";4181sysread($fh,my$buf,24) ==24or croak "read:$!";4182my($r,$c) =unpack(rev_map_fmt,$buf);4183if($want_commit&&$ceq('0' x40)) {4184if($size<48) {4185return$want_commit? (0,undef) :0;4186}4187sysseek($fh, -48, SEEK_END)or croak "seek:$!";4188sysread($fh,$buf,24) ==24or croak "read:$!";4189($r,$c) =unpack(rev_map_fmt,$buf);4190if($ceq('0'x40)) {4191 croak "Penultimate record is all-zeroes in$map_path";4192}4193}4194close$fhor croak "close:$!";4195$want_commit? ($r,$c) :$r;4196}41974198sub rev_map_get {4199my($self,$rev,$uuid) =@_;4200my$map_path=$self->map_path($uuid);4201returnundefunless-e $map_path;42024203sysopen(my$fh,$map_path, O_RDONLY)or croak "open:$!";4204my$c= _rev_map_get($fh,$rev);4205close($fh)or croak "close:$!";4206$c4207}42084209sub _rev_map_get {4210my($fh,$rev) =@_;42114212binmode$fhor croak "binmode:$!";4213my$size= (stat($fh))[7];4214($size%24) ==0or croak "inconsistent size:$size";42154216if($size==0) {4217returnundef;4218}42194220my($l,$u) = (0,$size-24);4221my($r,$c,$buf);42224223while($l<=$u) {4224my$i=int(($l/24+$u/24) /2) *24;4225sysseek($fh,$i, SEEK_SET)or croak "seek:$!";4226sysread($fh,my$buf,24) ==24or croak "read:$!";4227my($r,$c) =unpack(rev_map_fmt,$buf);42284229if($r<$rev) {4230$l=$i+24;4231}elsif($r>$rev) {4232$u=$i-24;4233}else{# $r == $rev4234return$ceq('0' x 40) ?undef:$c;4235}4236}4237undef;4238}42394240# Finds the first svn revision that exists on (if $eq_ok is true) or4241# before $rev for the current branch. It will not search any lower4242# than $min_rev. Returns the git commit hash and svn revision number4243# if found, else (undef, undef).4244sub find_rev_before {4245my($self,$rev,$eq_ok,$min_rev) =@_;4246--$revunless$eq_ok;4247$min_rev||=1;4248my$max_rev=$self->rev_map_max;4249$rev=$max_revif($rev>$max_rev);4250while($rev>=$min_rev) {4251if(my$c=$self->rev_map_get($rev)) {4252return($rev,$c);4253}4254--$rev;4255}4256return(undef,undef);4257}42584259# Finds the first svn revision that exists on (if $eq_ok is true) or4260# after $rev for the current branch. It will not search any higher4261# than $max_rev. Returns the git commit hash and svn revision number4262# if found, else (undef, undef).4263sub find_rev_after {4264my($self,$rev,$eq_ok,$max_rev) =@_;4265++$revunless$eq_ok;4266$max_rev||=$self->rev_map_max;4267while($rev<=$max_rev) {4268if(my$c=$self->rev_map_get($rev)) {4269return($rev,$c);4270}4271++$rev;4272}4273return(undef,undef);4274}42754276sub _new {4277my($class,$repo_id,$ref_id,$path) =@_;4278unless(defined$repo_id&&length$repo_id) {4279$repo_id=$Git::SVN::default_repo_id;4280}4281unless(defined$ref_id&&length$ref_id) {4282$_prefix=''unlessdefined($_prefix);4283$_[2] =$ref_id=4284"refs/remotes/$_prefix$Git::SVN::default_ref_id";4285}4286$_[1] =$repo_id;4287my$dir="$ENV{GIT_DIR}/svn/$ref_id";42884289# Older repos imported by us used $GIT_DIR/svn/foo instead of4290# $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo4291if($ref_id=~m{^refs/remotes/(.*)}) {4292my$old_dir="$ENV{GIT_DIR}/svn/$1";4293if(-d $old_dir&& ! -d $dir) {4294$dir=$old_dir;4295}4296}42974298$_[3] =$path=''unless(defined$path);4299 mkpath([$dir]);4300bless{4301 ref_id =>$ref_id, dir =>$dir,index=>"$dir/index",4302 path =>$path, config =>"$ENV{GIT_DIR}/svn/config",4303 map_root =>"$dir/.rev_map", repo_id =>$repo_id},$class;4304}43054306# for read-only access of old .rev_db formats4307sub unlink_rev_db_symlink {4308my($self) =@_;4309my$link=$self->rev_db_path;4310$link=~s/\.[\w-]+$//or croak "missing UUID at the end of$link";4311if(-l $link) {4312unlink$linkor croak "unlink:$linkfailed!";4313}4314}43154316sub rev_db_path {4317my($self,$uuid) =@_;4318my$db_path=$self->map_path($uuid);4319$db_path=~s{/\.rev_map\.}{/\.rev_db\.}4320or croak "map_path:$db_pathdoes not contain '/.rev_map.' !";4321$db_path;4322}43234324# the new replacement for .rev_db4325sub map_path {4326my($self,$uuid) =@_;4327$uuid||=$self->ra_uuid;4328"$self->{map_root}.$uuid";4329}43304331sub uri_encode {4332my($f) =@_;4333$f=~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;4334$f4335}43364337sub uri_decode {4338my($f) =@_;4339$f=~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;4340$f4341}43424343sub remove_username {4344$_[0] =~s{^([^:]*://)[^@]+@}{$1};4345}43464347package Git::SVN::Log;4348use strict;4349use warnings;4350use POSIX qw/strftime/;4351useconstant commit_log_separator => ('-' x 72) ."\n";4352use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline4353%rusers $show_commit $incremental/;4354my$l_fmt;43554356sub cmt_showable {4357my($c) =@_;4358return1ifdefined$c->{r};43594360# big commit message got truncated by the 16k pretty buffer in rev-list4361if($c->{l} &&$c->{l}->[-1]eq"...\n"&&4362$c->{a_raw} =~/\@([a-f\d\-]+)>$/) {4363@{$c->{l}} = ();4364my@log= command(qw/cat-file commit/,$c->{c});43654366# shift off the headers4367shift@logwhile($log[0]ne'');4368shift@log;43694370# TODO: make $c->{l} not have a trailing newline in the future4371@{$c->{l}} =map{"$_\n"}grep!/^git-svn-id: /,@log;43724373(undef,$c->{r},undef) = ::extract_metadata(4374(grep(/^git-svn-id: /,@log))[-1]);4375}4376returndefined$c->{r};4377}43784379sub log_use_color {4380return$color|| Git->repository->get_colorbool('color.diff');4381}43824383sub git_svn_log_cmd {4384my($r_min,$r_max,@args) =@_;4385my$head='HEAD';4386my(@files,@log_opts);4387foreachmy$x(@args) {4388if($xeq'--'||@files) {4389push@files,$x;4390}else{4391if(::verify_ref("$x^0")) {4392$head=$x;4393}else{4394push@log_opts,$x;4395}4396}4397}43984399my($url,$rev,$uuid,$gs) = ::working_head_info($head);4400$gs||= Git::SVN->_new;4401my@cmd= (qw/log --abbrev-commit --pretty=raw --default/,4402$gs->refname);4403push@cmd,'-r'unless$non_recursive;4404push@cmd, qw/--raw --name-status/if$verbose;4405push@cmd,'--color'if log_use_color();4406push@cmd,@log_opts;4407if(defined$r_max&&$r_max==$r_min) {4408push@cmd,'--max-count=1';4409if(my$c=$gs->rev_map_get($r_max)) {4410push@cmd,$c;4411}4412}elsif(defined$r_max) {4413if($r_max<$r_min) {4414($r_min,$r_max) = ($r_max,$r_min);4415}4416my(undef,$c_max) =$gs->find_rev_before($r_max,1,$r_min);4417my(undef,$c_min) =$gs->find_rev_after($r_min,1,$r_max);4418# If there are no commits in the range, both $c_max and $c_min4419# will be undefined. If there is at least 1 commit in the4420# range, both will be defined.4421return()if!defined$c_min|| !defined$c_max;4422if($c_mineq$c_max) {4423push@cmd,'--max-count=1',$c_min;4424}else{4425push@cmd,'--boundary',"$c_min..$c_max";4426}4427}4428return(@cmd,@files);4429}44304431# adapted from pager.c4432sub config_pager {4433if(! -t *STDOUT) {4434$ENV{GIT_PAGER_IN_USE} ='false';4435$pager=undef;4436return;4437}4438chomp($pager= command_oneline(qw(var GIT_PAGER)));4439if($pagereq'cat') {4440$pager=undef;4441}4442$ENV{GIT_PAGER_IN_USE} =defined($pager);4443}44444445sub run_pager {4446return unlessdefined$pager;4447pipe my($rfd,$wfd)orreturn;4448defined(my$pid=fork)or::fatal "Can't fork:$!";4449if(!$pid) {4450open STDOUT,'>&',$wfdor4451::fatal "Can't redirect to stdout:$!";4452return;4453}4454open STDIN,'<&',$rfdor::fatal "Can't redirect stdin:$!";4455$ENV{LESS} ||='FRSX';4456exec$pageror::fatal "Can't run pager:$!($pager)";4457}44584459sub format_svn_date {4460my$t=shift||time;4461my$gmoff= Git::SVN::get_tz($t);4462return strftime("%Y-%m-%d%H:%M:%S$gmoff(%a,%d%b%Y)",localtime($t));4463}44644465sub parse_git_date {4466my($t,$tz) =@_;4467# Date::Parse isn't in the standard Perl distro :(4468if($tz=~s/^\+//) {4469$t+= tz_to_s_offset($tz);4470}elsif($tz=~s/^\-//) {4471$t-= tz_to_s_offset($tz);4472}4473return$t;4474}44754476sub set_local_timezone {4477if(defined$TZ) {4478$ENV{TZ} =$TZ;4479}else{4480delete$ENV{TZ};4481}4482}44834484sub tz_to_s_offset {4485my($tz) =@_;4486$tz=~s/(\d\d)$//;4487return($1*60) + ($tz*3600);4488}44894490sub get_author_info {4491my($dest,$author,$t,$tz) =@_;4492$author=~s/(?:^\s*|\s*$)//g;4493$dest->{a_raw} =$author;4494my$au;4495if($::_authors) {4496$au=$rusers{$author} ||undef;4497}4498if(!$au) {4499($au) = ($author=~/<([^>]+)\@[^>]+>$/);4500}4501$dest->{t} =$t;4502$dest->{tz} =$tz;4503$dest->{a} =$au;4504$dest->{t_utc} = parse_git_date($t,$tz);4505}45064507sub process_commit {4508my($c,$r_min,$r_max,$defer) =@_;4509if(defined$r_min&&defined$r_max) {4510if($r_min==$c->{r} &&$r_min==$r_max) {4511 show_commit($c);4512return0;4513}4514return1if$r_min==$r_max;4515if($r_min<$r_max) {4516# we need to reverse the print order4517return0if(defined$limit&& --$limit<0);4518push@$defer,$c;4519return1;4520}4521if($r_min!=$r_max) {4522return1if($r_min<$c->{r});4523return1if($r_max>$c->{r});4524}4525}4526return0if(defined$limit&& --$limit<0);4527 show_commit($c);4528return1;4529}45304531sub show_commit {4532my$c=shift;4533if($oneline) {4534my$x="\n";4535if(my$l=$c->{l}) {4536while($l->[0] =~/^\s*$/) {shift@$l}4537$x=$l->[0];4538}4539$l_fmt||='A'.length($c->{r});4540print'r',pack($l_fmt,$c->{r}),' | ';4541print"$c->{c} | "if$show_commit;4542print$x;4543}else{4544 show_commit_normal($c);4545}4546}45474548sub show_commit_changed_paths {4549my($c) =@_;4550return unless$c->{changed};4551print"Changed paths:\n", @{$c->{changed}};4552}45534554sub show_commit_normal {4555my($c) =@_;4556print commit_log_separator,"r$c->{r} | ";4557print"$c->{c} | "if$show_commit;4558print"$c->{a} | ", format_svn_date($c->{t_utc}),' | ';4559my$nr_line=0;45604561if(my$l=$c->{l}) {4562while($l->[$#$l]eq"\n"&&$#$l>04563&&$l->[($#$l-1)]eq"\n") {4564pop@$l;4565}4566$nr_line=scalar@$l;4567if(!$nr_line) {4568print"1 line\n\n\n";4569}else{4570if($nr_line==1) {4571$nr_line='1 line';4572}else{4573$nr_line.=' lines';4574}4575print$nr_line,"\n";4576 show_commit_changed_paths($c);4577print"\n";4578print$_foreach@$l;4579}4580}else{4581print"1 line\n";4582 show_commit_changed_paths($c);4583print"\n";45844585}4586foreachmy$x(qw/raw stat diff/) {4587if($c->{$x}) {4588print"\n";4589print$_foreach@{$c->{$x}}4590}4591}4592}45934594sub cmd_show_log {4595my(@args) =@_;4596my($r_min,$r_max);4597my$r_last= -1;# prevent dupes4598 set_local_timezone();4599if(defined$::_revision) {4600if($::_revision =~/^(\d+):(\d+)$/) {4601($r_min,$r_max) = ($1,$2);4602}elsif($::_revision =~/^\d+$/) {4603$r_min=$r_max= $::_revision;4604}else{4605::fatal "-r$::_revision is not supported, use ",4606"standard 'git log' arguments instead";4607}4608}46094610 config_pager();4611@args= git_svn_log_cmd($r_min,$r_max,@args);4612if(!@args) {4613print commit_log_separator unless$incremental||$oneline;4614return;4615}4616my$log= command_output_pipe(@args);4617 run_pager();4618my(@k,$c,$d,$stat);4619my$esc_color=qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;4620while(<$log>) {4621if(/^${esc_color}commit (?:- )?($::sha1_short)/o) {4622my$cmt=$1;4623if($c&& cmt_showable($c) &&$c->{r} !=$r_last) {4624$r_last=$c->{r};4625 process_commit($c,$r_min,$r_max, \@k)or4626goto out;4627}4628$d=undef;4629$c= { c =>$cmt};4630}elsif(/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {4631 get_author_info($c,$1,$2,$3);4632}elsif(/^${esc_color}(?:tree|parent|committer) /o) {4633# ignore4634}elsif(/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {4635push@{$c->{raw}},$_;4636}elsif(/^${esc_color}[ACRMDT]\t/) {4637# we could add $SVN->{svn_path} here, but that requires4638# remote access at the moment (repo_path_split)...4639 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;4640push@{$c->{changed}},$_;4641}elsif(/^${esc_color}diff /o) {4642$d=1;4643push@{$c->{diff}},$_;4644}elsif($d) {4645push@{$c->{diff}},$_;4646}elsif(/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*4647$esc_color*[\+\-]*$esc_color$/x) {4648$stat=1;4649push@{$c->{stat}},$_;4650}elsif($stat&&/^ \d+ files changed, \d+ insertions/) {4651push@{$c->{stat}},$_;4652$stat=undef;4653}elsif(/^${esc_color} (git-svn-id:.+)$/o) {4654($c->{url},$c->{r},undef) = ::extract_metadata($1);4655}elsif(s/^${esc_color} //o) {4656push@{$c->{l}},$_;4657}4658}4659if($c&&defined$c->{r} &&$c->{r} !=$r_last) {4660$r_last=$c->{r};4661 process_commit($c,$r_min,$r_max, \@k);4662}4663if(@k) {4664($r_min,$r_max) = ($r_max,$r_min);4665 process_commit($_,$r_min,$r_max)foreachreverse@k;4666}4667out:4668close$log;4669print commit_log_separator unless$incremental||$oneline;4670}46714672sub cmd_blame {4673my$path=pop;46744675 config_pager();4676 run_pager();46774678my($fh,$ctx,$rev);46794680if($_git_format) {4681($fh,$ctx) = command_output_pipe('blame',@_,$path);4682while(my$line= <$fh>) {4683if($line=~/^\^?([[:xdigit:]]+)\s/) {4684# Uncommitted edits show up as a rev ID of4685# all zeros, which we can't look up with4686# cmt_metadata4687if($1!~/^0+$/) {4688(undef,$rev,undef) =4689::cmt_metadata($1);4690$rev='0'if(!$rev);4691}else{4692$rev='0';4693}4694$rev=sprintf('%-10s',$rev);4695$line=~s/^\^?[[:xdigit:]]+(\s)/$rev$1/;4696}4697print$line;4698}4699}else{4700($fh,$ctx) = command_output_pipe('blame','-p',@_,'HEAD',4701'--',$path);4702my($sha1);4703my%authors;4704my@buffer;4705my%dsha;#distinct sha keys47064707while(my$line= <$fh>) {4708push@buffer,$line;4709if($line=~/^([[:xdigit:]]{40})\s\d+\s\d+/) {4710$dsha{$1} =1;4711}4712}47134714my$s2r= ::cmt_sha2rev_batch([keys%dsha]);47154716foreachmy$line(@buffer) {4717if($line=~/^([[:xdigit:]]{40})\s\d+\s\d+/) {4718$rev=$s2r->{$1};4719$rev='0'if(!$rev)4720}4721elsif($line=~/^author (.*)/) {4722$authors{$rev} =$1;4723$authors{$rev} =~s/\s/_/g;4724}4725elsif($line=~/^\t(.*)$/) {4726printf("%6s%10s%s\n",$rev,$authors{$rev},$1);4727}4728}4729}4730 command_close_pipe($fh,$ctx);4731}47324733package Git::SVN::Migration;4734# these version numbers do NOT correspond to actual version numbers4735# of git nor git-svn. They are just relative.4736#4737# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD4738#4739# v1 layout: .git/$id/info/url, refs/remotes/$id4740#4741# v2 layout: .git/svn/$id/info/url, refs/remotes/$id4742#4743# v3 layout: .git/svn/$id, refs/remotes/$id4744# - info/url may remain for backwards compatibility4745# - this is what we migrate up to this layout automatically,4746# - this will be used by git svn init on single branches4747# v3.1 layout (auto migrated):4748# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink4749# for backwards compatibility4750#4751# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id4752# - this is only created for newly multi-init-ed4753# repositories. Similar in spirit to the4754# --use-separate-remotes option in git-clone (now default)4755# - we do not automatically migrate to this (following4756# the example set by core git)4757#4758# v5 layout: .rev_db.$UUID => .rev_map.$UUID4759# - newer, more-efficient format that uses 24-bytes per record4760# with no filler space.4761# - use xxd -c24 < .rev_map.$UUID to view and debug4762# - This is a one-way migration, repositories updated to the4763# new format will not be able to use old git-svn without4764# rebuilding the .rev_db. Rebuilding the rev_db is not4765# possible if noMetadata or useSvmProps are set; but should4766# be no problem for users that use the (sensible) defaults.4767use strict;4768use warnings;4769use Carp qw/croak/;4770use File::Path qw/mkpath/;4771use File::Basename qw/dirname basename/;4772use vars qw/$_minimize/;47734774sub migrate_from_v0 {4775my$git_dir=$ENV{GIT_DIR};4776returnundefunless-d $git_dir;4777my($fh,$ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);4778my$migrated=0;4779while(<$fh>) {4780chomp;4781my($id,$orig_ref) = ($_,$_);4782next unless$id=~ s#^refs/heads/(.+)-HEAD$#$1#;4783next unless-f "$git_dir/$id/info/url";4784my$new_ref="refs/remotes/$id";4785if(::verify_ref("$new_ref^0")) {4786print STDERR "W:$orig_refis probably an old ",4787"branch used by an ancient version of ",4788"git-svn.\n",4789"However,$new_refalso exists.\n",4790"We will not be able ",4791"to use this branch until this ",4792"ambiguity is resolved.\n";4793next;4794}4795print STDERR "Migrating from v0 layout...\n"if!$migrated;4796print STDERR "Renaming ref:$orig_ref=>$new_ref\n";4797 command_noisy('update-ref',$new_ref,$orig_ref);4798 command_noisy('update-ref','-d',$orig_ref,$orig_ref);4799$migrated++;4800}4801 command_close_pipe($fh,$ctx);4802print STDERR "Done migrating from v0 layout...\n"if$migrated;4803$migrated;4804}48054806sub migrate_from_v1 {4807my$git_dir=$ENV{GIT_DIR};4808my$migrated=0;4809return$migratedunless-d $git_dir;4810my$svn_dir="$git_dir/svn";48114812# just in case somebody used 'svn' as their $id at some point...4813return$migratedif-d $svn_dir&& ! -f "$svn_dir/info/url";48144815print STDERR "Migrating from a git-svn v1 layout...\n";4816 mkpath([$svn_dir]);4817print STDERR "Data from a previous version of git-svn exists, but\n\t",4818"$svn_dir\n\t(required for this version ",4819"($::VERSION) of git-svn) does not exist.\n";4820my($fh,$ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);4821while(<$fh>) {4822my$x=$_;4823next unless$x=~ s#^refs/remotes/##;4824chomp$x;4825next unless-f "$git_dir/$x/info/url";4826my$u=eval{ ::file_to_s("$git_dir/$x/info/url") };4827next unless$u;4828my$dn= dirname("$git_dir/svn/$x");4829 mkpath([$dn])unless-d $dn;4830if($xeq'svn') {# they used 'svn' as GIT_SVN_ID:4831 mkpath(["$git_dir/svn/svn"]);4832print STDERR " -$git_dir/$x/info=> ",4833"$git_dir/svn/$x/info\n";4834rename"$git_dir/$x/info","$git_dir/svn/$x/info"or4835 croak "$!:$x";4836# don't worry too much about these, they probably4837# don't exist with repos this old (save for index,4838# and we can easily regenerate that)4839foreachmy$f(qw/unhandled.log index .rev_db/) {4840rename"$git_dir/$x/$f","$git_dir/svn/$x/$f";4841}4842}else{4843print STDERR " -$git_dir/$x=>$git_dir/svn/$x\n";4844rename"$git_dir/$x","$git_dir/svn/$x"or4845 croak "$!:$x";4846}4847$migrated++;4848}4849 command_close_pipe($fh,$ctx);4850print STDERR "Done migrating from a git-svn v1 layout\n";4851$migrated;4852}48534854sub read_old_urls {4855my($l_map,$pfx,$path) =@_;4856my@dir;4857foreach(<$path/*>) {4858if(-r "$_/info/url") {4859$pfx.='/'if$pfx&&$pfx!~ m!/$!;4860my$ref_id=$pfx. basename $_;4861my$url= ::file_to_s("$_/info/url");4862$l_map->{$ref_id} =$url;4863}elsif(-d $_) {4864push@dir,$_;4865}4866}4867foreach(@dir) {4868my$x=$_;4869$x=~s!^\Q$ENV{GIT_DIR}\E/svn/!!o;4870 read_old_urls($l_map,$x,$_);4871}4872}48734874sub migrate_from_v2 {4875my@cfg= command(qw/config -l/);4876return ifgrep/^svn-remote\..+\.url=/,@cfg;4877my%l_map;4878 read_old_urls(\%l_map,'',"$ENV{GIT_DIR}/svn");4879my$migrated=0;48804881foreachmy$ref_id(sort keys%l_map) {4882eval{ Git::SVN->init($l_map{$ref_id},'',undef,$ref_id) };4883if($@) {4884 Git::SVN->init($l_map{$ref_id},'',$ref_id,$ref_id);4885}4886$migrated++;4887}4888$migrated;4889}48904891sub minimize_connections {4892my$r= Git::SVN::read_all_remotes();4893my$new_urls= {};4894my$root_repos= {};4895foreachmy$repo_id(keys%$r) {4896my$url=$r->{$repo_id}->{url}ornext;4897my$fetch=$r->{$repo_id}->{fetch}ornext;4898my$ra= Git::SVN::Ra->new($url);48994900# skip existing cases where we already connect to the root4901if(($ra->{url}eq$ra->{repos_root}) ||4902($ra->{repos_root}eq$repo_id)) {4903$root_repos->{$ra->{url}} =$repo_id;4904next;4905}49064907my$root_ra= Git::SVN::Ra->new($ra->{repos_root});4908my$root_path=$ra->{url};4909$root_path=~ s#^\Q$ra->{repos_root}\E(/|$)##;4910foreachmy$path(keys%$fetch) {4911my$ref_id=$fetch->{$path};4912my$gs= Git::SVN->new($ref_id,$repo_id,$path);49134914# make sure we can read when connecting to4915# a higher level of a repository4916my($last_rev,undef) =$gs->last_rev_commit;4917if(!defined$last_rev) {4918$last_rev=eval{4919$root_ra->get_latest_revnum;4920};4921next if$@;4922}4923my$new=$root_path;4924$new.=length$path?"/$path":'';4925eval{4926$root_ra->get_log([$new],$last_rev,$last_rev,49270,0,1,sub{ });4928};4929next if$@;4930$new_urls->{$ra->{repos_root}}->{$new} =4931{ ref_id =>$ref_id,4932 old_repo_id =>$repo_id,4933 old_path =>$path};4934}4935}49364937my@emptied;4938foreachmy$url(keys%$new_urls) {4939# see if we can re-use an existing [svn-remote "repo_id"]4940# instead of creating a(n ugly) new section:4941my$repo_id=$root_repos->{$url} ||$url;49424943my$fetch=$new_urls->{$url};4944foreachmy$path(keys%$fetch) {4945my$x=$fetch->{$path};4946 Git::SVN->init($url,$path,$repo_id,$x->{ref_id});4947my$pfx="svn-remote.$x->{old_repo_id}";49484949my$old_fetch=quotemeta("$x->{old_path}:".4950"$x->{ref_id}");4951 command_noisy(qw/config --unset/,4952"$pfx.fetch",'^'.$old_fetch.'$');4953delete$r->{$x->{old_repo_id}}->4954{fetch}->{$x->{old_path}};4955if(!keys%{$r->{$x->{old_repo_id}}->{fetch}}) {4956 command_noisy(qw/config --unset/,4957"$pfx.url");4958push@emptied,$x->{old_repo_id}4959}4960}4961}4962if(@emptied) {4963my$file=$ENV{GIT_CONFIG} ||"$ENV{GIT_DIR}/config";4964print STDERR <<EOF;4965The following [svn-remote] sections in your config file ($file) are empty4966and can be safely removed:4967EOF4968print STDERR "[svn-remote\"$_\"]\n"foreach@emptied;4969}4970}49714972sub migration_check {4973 migrate_from_v0();4974 migrate_from_v1();4975 migrate_from_v2();4976 minimize_connections()if$_minimize;4977}49784979package Git::IndexInfo;4980use strict;4981use warnings;4982use Git qw/command_input_pipe command_close_pipe/;49834984sub new {4985my($class) =@_;4986my($gui,$ctx) = command_input_pipe(qw/update-index -z --index-info/);4987bless{ gui =>$gui, ctx =>$ctx, nr =>0},$class;4988}49894990sub remove {4991my($self,$path) =@_;4992if(print{$self->{gui} }'0 ',0 x 40,"\t",$path,"\0") {4993return++$self->{nr};4994}4995undef;4996}49974998sub update {4999my($self,$mode,$hash,$path) =@_;5000if(print{$self->{gui} }$mode,' ',$hash,"\t",$path,"\0") {5001return++$self->{nr};5002}5003undef;5004}50055006sub DESTROY {5007my($self) =@_;5008 command_close_pipe($self->{gui},$self->{ctx});5009}50105011package Git::SVN::GlobSpec;5012use strict;5013use warnings;50145015sub new {5016my($class,$glob,$pattern_ok) =@_;5017my$re=$glob;5018$re=~s!/+$!!g;# no need for trailing slashes5019my(@left,@right,@patterns);5020my$state="left";5021my$die_msg="Only one set of wildcard directories ".5022"(e.g. '*' or '*/*/*') is supported: '$glob'\n";5023formy$part(split(m|/|,$glob)) {5024if($part=~/\*/&&$partne"*") {5025die"Invalid pattern in '$glob':$part\n";5026}elsif($pattern_ok&&$part=~/[{}]/&&5027$part!~/^\{[^{}]+\}/) {5028die"Invalid pattern in '$glob':$part\n";5029}5030if($parteq"*") {5031die$die_msgif$stateeq"right";5032$state="pattern";5033push(@patterns,"[^/]*");5034}elsif($pattern_ok&&$part=~/^\{(.*)\}$/) {5035die$die_msgif$stateeq"right";5036$state="pattern";5037my$p=quotemeta($1);5038$p=~s/\\,/|/g;5039push(@patterns,"(?:$p)");5040}else{5041if($stateeq"left") {5042push(@left,$part);5043}else{5044push(@right,$part);5045$state="right";5046}5047}5048}5049my$depth=@patterns;5050if($depth==0) {5051die"One '*' is needed in glob: '$glob'\n";5052}5053my$left=join('/',@left);5054my$right=join('/',@right);5055$re=join('/',@patterns);5056$re=join('\/',5057grep(length,quotemeta($left),"($re)",quotemeta($right)));5058my$left_re=qr/^\/\Q$left\E(\/|$)/;5059bless{ left =>$left, right =>$right, left_regex =>$left_re,5060 regex =>qr/$re/,glob=>$glob, depth =>$depth},$class;5061}50625063sub full_path {5064my($self,$path) =@_;5065return(length$self->{left} ?"$self->{left}/":'') .5066$path. (length$self->{right} ?"/$self->{right}":'');5067}50685069__END__50705071Data structures:507250735074$remotes= {# returned by read_all_remotes()5075'svn'=> {5076# svn-remote.svn.url=https://svn.musicpd.org5077 url =>'https://svn.musicpd.org',5078# svn-remote.svn.fetch=mpd/trunk:trunk5079 fetch => {5080'mpd/trunk'=>'trunk',5081},5082# svn-remote.svn.tags=mpd/tags/*:tags/*5083 tags => {5084 path => {5085 left =>'mpd/tags',5086 right =>'',5087 regex =>qr!mpd/tags/([^/]+)$!,5088glob=>'tags/*',5089},5090ref=> {5091 left =>'tags',5092 right =>'',5093 regex =>qr!tags/([^/]+)$!,5094glob=>'tags/*',5095},5096}5097}5098};50995100$log_entry hashref as returned by libsvn_log_entry()5101{5102log=>'whitespace-formatted log entry5103',# trailing newline is preserved5104 revision =>'8',# integer5105 date =>'2004-02-24T17:01:44.108345Z',# commit date5106 author =>'committer name'5107};510851095110# this is generated by generate_diff();5111@mods= array of diff-index line hashes,each element represents one line5112 of diff-index output51135114diff-index line ($m hash)5115{5116 mode_a => first column of diff-index output,no leading ':',5117 mode_b => second column of diff-index output,5118 sha1_b => sha1sum of the final blob,5119 chg => change type [MCRADT],5120 file_a => original file name of a file (iff chg is'C'or'R')5121 file_b => new/current file name of a file (any chg)5122}5123;51245125# retval of read_url_paths{,_all}();5126$l_map= {5127# repository root url5128'https://svn.musicpd.org'=> {5129# repository path # GIT_SVN_ID5130'mpd/trunk'=>'trunk',5131'mpd/tags/0.11.5'=>'tags/0.11.5',5132},5133}51345135Notes:5136 I don't trust the each() function on unless I created%hashmyself5137 because the internal iterator may not have started at base.