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}; 371fatal $@if$@; 372post_fetch_checkout(); 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;1601my$gs=$Git::SVN::_head orreturn;1602return if verify_ref('refs/heads/master^0');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}16141615my$valid_head= verify_ref('HEAD^0');1616 command_noisy(qw(update-ref refs/heads/master),$gs->refname);1617return if($valid_head|| !verify_ref('HEAD^0'));16181619return if$ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;1620my$index=$ENV{GIT_INDEX_FILE} ||"$ENV{GIT_DIR}/index";1621return if-f $index;16221623return if command_oneline(qw/rev-parse --is-inside-work-tree/)eq'false';1624return if command_oneline(qw/rev-parse --is-inside-git-dir/)eq'true';1625 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);1626print STDERR "Checked out HEAD:\n",1627$gs->full_url," r",$gs->last_rev,"\n";1628if(auto_create_empty_directories($gs)) {1629$gs->mkemptydirs($gs->last_rev);1630}1631}16321633sub complete_svn_url {1634my($url,$path) =@_;1635$path=~ s#/+$##;1636if($path!~ m#^[a-z\+]+://#) {1637if(!defined$url||$url!~ m#^[a-z\+]+://#) {1638 fatal("E: '$path' is not a complete URL ",1639"and a separate URL is not specified");1640}1641return($url,$path);1642}1643return($path,'');1644}16451646sub complete_url_ls_init {1647my($ra,$repo_path,$switch,$pfx) =@_;1648unless($repo_path) {1649print STDERR "W:$switchnot specified\n";1650return;1651}1652$repo_path=~ s#/+$##;1653if($repo_path=~ m#^[a-z\+]+://#) {1654$ra= Git::SVN::Ra->new($repo_path);1655$repo_path='';1656}else{1657$repo_path=~ s#^/+##;1658unless($ra) {1659 fatal("E: '$repo_path' is not a complete URL ",1660"and a separate URL is not specified");1661}1662}1663my$url=$ra->{url};1664my$gs= Git::SVN->init($url,undef,undef,undef,1);1665my$k="svn-remote.$gs->{repo_id}.url";1666my$orig_url=eval{ command_oneline(qw/config --get/,$k) };1667if($orig_url&& ($orig_urlne$gs->{url})) {1668die"$kalready set:$orig_url\n",1669"wanted to set to:$gs->{url}\n";1670}1671 command_oneline('config',$k,$gs->{url})unless$orig_url;1672my$remote_path="$gs->{path}/$repo_path";1673$remote_path=~s{%([0-9A-F]{2})}{chr hex($1)}ieg;1674$remote_path=~ s#/+#/#g;1675$remote_path=~ s#^/##g;1676$remote_path.="/*"if$remote_path!~ /\*/;1677my($n) = ($switch=~/^--(\w+)/);1678if(length$pfx&&$pfx!~ m#/$#) {1679die"--prefix='$pfx' must have a trailing slash '/'\n";1680}1681 command_noisy('config',1682'--add',1683"svn-remote.$gs->{repo_id}.$n",1684"$remote_path:refs/remotes/$pfx*".1685('/*' x (($remote_path=~ tr/*/*/) -1)) );1686}16871688sub verify_ref {1689my($ref) =@_;1690eval{ command_oneline(['rev-parse','--verify',$ref],1691{ STDERR =>0}); };1692}16931694sub get_tree_from_treeish {1695my($treeish) =@_;1696# $treeish can be a symbolic ref, too:1697my$type= command_oneline(qw/cat-file -t/,$treeish);1698my$expected;1699while($typeeq'tag') {1700($treeish,$type) = command(qw/cat-file tag/,$treeish);1701}1702if($typeeq'commit') {1703$expected= (grep/^tree /, command(qw/cat-file commit/,1704$treeish))[0];1705($expected) = ($expected=~/^tree ($sha1)$/o);1706die"Unable to get tree from$treeish\n"unless$expected;1707}elsif($typeeq'tree') {1708$expected=$treeish;1709}else{1710die"$treeishis a$type, expected tree, tag or commit\n";1711}1712return$expected;1713}17141715sub get_commit_entry {1716my($treeish) =shift;1717my%log_entry= (log=>'', tree => get_tree_from_treeish($treeish) );1718my$commit_editmsg="$ENV{GIT_DIR}/COMMIT_EDITMSG";1719my$commit_msg="$ENV{GIT_DIR}/COMMIT_MSG";1720open my$log_fh,'>',$commit_editmsgor croak $!;17211722my$type= command_oneline(qw/cat-file -t/,$treeish);1723if($typeeq'commit'||$typeeq'tag') {1724my($msg_fh,$ctx) = command_output_pipe('cat-file',1725$type,$treeish);1726my$in_msg=0;1727my$author;1728my$saw_from=0;1729my$msgbuf="";1730while(<$msg_fh>) {1731if(!$in_msg) {1732$in_msg=1if(/^\s*$/);1733$author=$1if(/^author (.*>)/);1734}elsif(/^git-svn-id: /) {1735# skip this for now, we regenerate the1736# correct one on re-fetch anyways1737# TODO: set *:merge properties or like...1738}else{1739if(/^From:/||/^Signed-off-by:/) {1740$saw_from=1;1741}1742$msgbuf.=$_;1743}1744}1745$msgbuf=~s/\s+$//s;1746if($Git::SVN::_add_author_from &&defined($author)1747&& !$saw_from) {1748$msgbuf.="\n\nFrom:$author";1749}1750print$log_fh $msgbufor croak $!;1751 command_close_pipe($msg_fh,$ctx);1752}1753close$log_fhor croak $!;17541755if($_edit|| ($typeeq'tree')) {1756chomp(my$editor= command_oneline(qw(var GIT_EDITOR)));1757system('sh','-c',$editor.' "$@"',$editor,$commit_editmsg);1758}1759rename$commit_editmsg,$commit_msgor croak $!;1760{1761require Encode;1762# SVN requires messages to be UTF-8 when entering the repo1763local$/;1764open$log_fh,'<',$commit_msgor croak $!;1765binmode$log_fh;1766chomp($log_entry{log} = <$log_fh>);17671768my$enc= Git::config('i18n.commitencoding') ||'UTF-8';1769my$msg=$log_entry{log};17701771eval{$msg= Encode::decode($enc,$msg,1) };1772if($@) {1773die"Could not decode as$enc:\n",$msg,1774"\nPerhaps you need to set i18n.commitencoding\n";1775}17761777eval{$msg= Encode::encode('UTF-8',$msg,1) };1778die"Could not encode as UTF-8:\n$msg\n"if$@;17791780$log_entry{log} =$msg;17811782close$log_fhor croak $!;1783}1784unlink$commit_msg;1785 \%log_entry;1786}17871788sub s_to_file {1789my($str,$file,$mode) =@_;1790open my$fd,'>',$fileor croak $!;1791print$fd $str,"\n"or croak $!;1792close$fdor croak $!;1793chmod($mode&~umask,$file)if(defined$mode);1794}17951796sub file_to_s {1797my$file=shift;1798open my$fd,'<',$fileor croak "$!: file:$file\n";1799local$/;1800my$ret= <$fd>;1801close$fdor croak $!;1802$ret=~s/\s*$//s;1803return$ret;1804}18051806# '<svn username> = real-name <email address>' mapping based on git-svnimport:1807sub load_authors {1808open my$authors,'<',$_authorsor die"Can't open$_authors$!\n";1809my$log=$cmdeq'log';1810while(<$authors>) {1811chomp;1812next unless/^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;1813my($user,$name,$email) = ($1,$2,$3);1814if($log) {1815$Git::SVN::Log::rusers{"$name<$email>"} =$user;1816}else{1817$users{$user} = [$name,$email];1818}1819}1820close$authorsor croak $!;1821}18221823# convert GetOpt::Long specs for use by git-config1824sub read_git_config {1825my$opts=shift;1826my@config_only;1827foreachmy$o(keys%$opts) {1828# if we have mixedCase and a long option-only, then1829# it's a config-only variable that we don't need for1830# the command-line.1831push@config_only,$oif($o=~/[A-Z]/&&$o=~/^[a-z]+$/i);1832my$v=$opts->{$o};1833my($key) = ($o=~/^([a-zA-Z\-]+)/);1834$key=~s/-//g;1835my$arg='git config';1836$arg.=' --int'if($o=~/[:=]i$/);1837$arg.=' --bool'if($o!~/[:=][sfi]$/);1838if(ref$veq'ARRAY') {1839chomp(my@tmp=`$arg--get-all svn.$key`);1840@$v=@tmpif@tmp;1841 } else {1842 chomp(my$tmp= `$arg--get svn.$key`);1843if($tmp&& !($arg=~/ --bool/&&$tmpeq'false')) {1844$$v=$tmp;1845}1846}1847}1848delete@$opts{@config_only}if@config_only;1849}18501851sub extract_metadata {1852my$id=shift orreturn(undef,undef,undef);1853my($url,$rev,$uuid) = ($id=~ /^\s*git-svn-id:\s+(.*)\@(\d+)1854 \s([a-f\d\-]+)$/ix);1855if(!defined$rev|| !$uuid|| !$url) {1856# some of the original repositories I made had1857# identifiers like this:1858($rev,$uuid) = ($id=~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);1859}1860return($url,$rev,$uuid);1861}18621863sub cmt_metadata {1864return extract_metadata((grep(/^git-svn-id: /,1865 command(qw/cat-file commit/,shift)))[-1]);1866}18671868sub cmt_sha2rev_batch {1869my%s2r;1870my($pid,$in,$out,$ctx) = command_bidi_pipe(qw/cat-file --batch/);1871my$list=shift;18721873foreachmy$sha(@{$list}) {1874my$first=1;1875my$size=0;1876print$out $sha,"\n";18771878while(my$line= <$in>) {1879if($first&&$line=~/^[[:xdigit:]]{40}\smissing$/) {1880last;1881}elsif($first&&1882$line=~/^[[:xdigit:]]{40}\scommit\s(\d+)$/) {1883$first=0;1884$size=$1;1885next;1886}elsif($line=~/^(git-svn-id: )/) {1887my(undef,$rev,undef) =1888 extract_metadata($line);1889$s2r{$sha} =$rev;1890}18911892$size-=length($line);1893last if($size==0);1894}1895}18961897 command_close_bidi_pipe($pid,$in,$out,$ctx);18981899return \%s2r;1900}19011902sub working_head_info {1903my($head,$refs) =@_;1904my@args= qw/rev-list --first-parent --pretty=medium/;1905my($fh,$ctx) = command_output_pipe(@args,$head);1906my$hash;1907my%max;1908while(<$fh>) {1909if(m{^commit ($::sha1)$}) {1910unshift@$refs,$hashif$hashand$refs;1911$hash=$1;1912next;1913}1914next unlesss{^\s*(git-svn-id:)}{$1};1915my($url,$rev,$uuid) = extract_metadata($_);1916if(defined$url&&defined$rev) {1917next if$max{$url}and$max{$url} <$rev;1918if(my$gs= Git::SVN->find_by_url($url)) {1919my$c=$gs->rev_map_get($rev,$uuid);1920if($c&&$ceq$hash) {1921close$fh;# break the pipe1922return($url,$rev,$uuid,$gs);1923}else{1924$max{$url} ||=$gs->rev_map_max;1925}1926}1927}1928}1929 command_close_pipe($fh,$ctx);1930(undef,undef,undef,undef);1931}19321933sub read_commit_parents {1934my($parents,$c) =@_;1935chomp(my$p= command_oneline(qw/rev-list --parents -1/,$c));1936$p=~s/^($c)\s*//or die"rev-list --parents -1$cfailed!\n";1937@{$parents->{$c}} =split(/ /,$p);1938}19391940sub linearize_history {1941my($gs,$refs) =@_;1942my%parents;1943foreachmy$c(@$refs) {1944 read_commit_parents(\%parents,$c);1945}19461947my@linear_refs;1948my%skip= ();1949my$last_svn_commit=$gs->last_commit;1950foreachmy$c(reverse@$refs) {1951next if$ceq$last_svn_commit;1952last if$skip{$c};19531954unshift@linear_refs,$c;1955$skip{$c} =1;19561957# we only want the first parent to diff against for linear1958# history, we save the rest to inject when we finalize the1959# svn commit1960my$fp_a= verify_ref("$c~1");1961my$fp_b=shift@{$parents{$c}}if$parents{$c};1962if(!$fp_a|| !$fp_b) {1963die"Commit$c\n",1964"has no parent commit, and therefore ",1965"nothing to diff against.\n",1966"You should be working from a repository ",1967"originally created by git-svn\n";1968}1969if($fp_ane$fp_b) {1970die"$c~1=$fp_a, however parsing commit$c",1971"revealed that:\n$c~1=$fp_b\nBUG!\n";1972}19731974foreachmy$p(@{$parents{$c}}) {1975$skip{$p} =1;1976}1977}1978(\@linear_refs, \%parents);1979}19801981sub find_file_type_and_diff_status {1982my($path) =@_;1983return('dir','')if$patheq'';19841985my$diff_output=1986 command_oneline(qw(diff --cached --name-status --),$path) ||"";1987my$diff_status= (split(' ',$diff_output))[0] ||"";19881989my$ls_tree= command_oneline(qw(ls-tree HEAD),$path) ||"";19901991return(undef,undef)if!$diff_status&& !$ls_tree;19921993if($diff_statuseq"A") {1994return("link",$diff_status)if-l $path;1995return("dir",$diff_status)if-d $path;1996return("file",$diff_status);1997}19981999my$mode= (split(' ',$ls_tree))[0] ||"";20002001return("link",$diff_status)if$modeeq"120000";2002return("dir",$diff_status)if$modeeq"040000";2003return("file",$diff_status);2004}20052006sub md5sum {2007my$arg=shift;2008my$ref=ref$arg;2009my$md5= Digest::MD5->new();2010if($refeq'GLOB'||$refeq'IO::File'||$refeq'File::Temp') {2011$md5->addfile($arg)or croak $!;2012}elsif($refeq'SCALAR') {2013$md5->add($$arg)or croak $!;2014}elsif(!$ref) {2015$md5->add($arg)or croak $!;2016}else{2017::fatal "Can't provide MD5 hash for unknown ref type: '",$ref,"'";2018}2019return$md5->hexdigest();2020}20212022sub gc_directory {2023if($can_compress&& -f $_&& basename($_)eq"unhandled.log") {2024my$out_filename=$_.".gz";2025open my$in_fh,"<",$_or die"Unable to open$_:$!\n";2026binmode$in_fh;2027my$gz= Compress::Zlib::gzopen($out_filename,"ab")or2028die"Unable to open$out_filename:$!\n";20292030my$res;2031while($res=sysread($in_fh,my$str,1024)) {2032$gz->gzwrite($str)or2033die"Unable to write: ".$gz->gzerror()."!\n";2034}2035unlink$_or die"unlink$File::Find::name:$!\n";2036}elsif(-f $_&& basename($_)eq"index") {2037unlink$_or die"unlink$_:$!\n";2038}2039}20402041package Git::SVN;2042use strict;2043use warnings;2044use Fcntl qw/:DEFAULT :seek/;2045useconstant rev_map_fmt =>'NH40';2046use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent2047$_repack $_repack_flags $_use_svm_props $_head2048$_use_svnsync_props $no_reuse_existing $_minimize_url2049$_use_log_author $_add_author_from $_localtime/;2050use Carp qw/croak/;2051use File::Path qw/mkpath/;2052use File::Copy qw/copy/;2053use IPC::Open3;2054use Time::Local;2055use Memoize;# core since 5.8.0, Jul 20022056use Memoize::Storable;2057use POSIX qw(:signal_h);2058my$can_use_yaml;2059BEGIN{2060$can_use_yaml=eval{require Git::SVN::Memoize::YAML;1};2061}20622063my($_gc_nr,$_gc_period);20642065# properties that we do not log:2066my%SKIP_PROP;2067BEGIN{2068%SKIP_PROP=map{$_=>1} qw/svn:wc:ra_dav:version-url2069 svn:special svn:executable2070 svn:entry:committed-rev2071 svn:entry:last-author2072 svn:entry:uuid2073 svn:entry:committed-date/;20742075# some options are read globally, but can be overridden locally2076# per [svn-remote "..."] section. Command-line options will *NOT*2077# override options set in an [svn-remote "..."] section2078no strict 'refs';2079formy$option(qw/follow_parent no_metadata use_svm_props2080 use_svnsync_props/) {2081my$key=$option;2082$key=~tr/_//d;2083my$prop="-$option";2084*$option=sub{2085my($self) =@_;2086return$self->{$prop}ifexists$self->{$prop};2087my$k="svn-remote.$self->{repo_id}.$key";2088eval{ command_oneline(qw/config --get/,$k) };2089if($@) {2090$self->{$prop} = ${"Git::SVN::_$option"};2091}else{2092my$v= command_oneline(qw/config --bool/,$k);2093$self->{$prop} =$veq'false'?0:1;2094}2095return$self->{$prop};2096}2097}2098}209921002101my(%LOCKFILES,%INDEX_FILES);2102END{2103unlink keys%LOCKFILESif%LOCKFILES;2104unlink keys%INDEX_FILESif%INDEX_FILES;2105}21062107sub resolve_local_globs {2108my($url,$fetch,$glob_spec) =@_;2109return unlessdefined$glob_spec;2110my$ref=$glob_spec->{ref};2111my$path=$glob_spec->{path};2112foreach(command(qw#for-each-ref --format=%(refname) refs/#)) {2113next unless m#^$ref->{regex}$#;2114my$p=$1;2115my$pathname= desanitize_refname($path->full_path($p));2116my$refname= desanitize_refname($ref->full_path($p));2117if(my$existing=$fetch->{$pathname}) {2118if($existingne$refname) {2119die"Refspec conflict:\n",2120"existing:$existing\n",2121" globbed:$refname\n";2122}2123my$u= (::cmt_metadata("$refname"))[0];2124$u=~s!^\Q$url\E(/|$)!!or die2125"$refname: '$url' not found in '$u'\n";2126if($pathnamene$u) {2127warn"W: Refspec glob conflict ",2128"(ref:$refname):\n",2129"expected path:$pathname\n",2130" real path:$u\n",2131"Continuing ahead with$u\n";2132next;2133}2134}else{2135$fetch->{$pathname} =$refname;2136}2137}2138}21392140sub parse_revision_argument {2141my($base,$head) =@_;2142if(!defined$::_revision || $::_revision eq'BASE:HEAD') {2143return($base,$head);2144}2145return($1,$2)if($::_revision =~/^(\d+):(\d+)$/);2146return($::_revision, $::_revision)if($::_revision =~/^\d+$/);2147return($head,$head)if($::_revision eq'HEAD');2148return($base,$1)if($::_revision =~/^BASE:(\d+)$/);2149return($1,$head)if($::_revision =~/^(\d+):HEAD$/);2150die"revision argument: $::_revision not understood by git-svn\n";2151}21522153sub fetch_all {2154my($repo_id,$remotes) =@_;2155if(ref$repo_id) {2156my$gs=$repo_id;2157$repo_id=undef;2158$repo_id=$gs->{repo_id};2159}2160$remotes||= read_all_remotes();2161my$remote=$remotes->{$repo_id}or2162die"[svn-remote\"$repo_id\"] unknown\n";2163my$fetch=$remote->{fetch};2164my$url=$remote->{url}or die"svn-remote.$repo_id.url not defined\n";2165my(@gs,@globs);2166my$ra= Git::SVN::Ra->new($url);2167my$uuid=$ra->get_uuid;2168my$head=$ra->get_latest_revnum;21692170# ignore errors, $head revision may not even exist anymore2171eval{$ra->get_log("",$head,0,1,0,1,sub{$head=$_[1] }) };2172warn"W:$@\n"if$@;21732174my$base=defined$fetch?$head:0;21752176# read the max revs for wildcard expansion (branches/*, tags/*)2177foreachmy$t(qw/branches tags/) {2178defined$remote->{$t}ornext;2179push@globs, @{$remote->{$t}};21802181my$max_rev=eval{ tmp_config(qw/--int --get/,2182"svn-remote.$repo_id.${t}-maxRev") };2183if(defined$max_rev&& ($max_rev<$base)) {2184$base=$max_rev;2185}elsif(!defined$max_rev) {2186$base=0;2187}2188}21892190if($fetch) {2191foreachmy$p(sort keys%$fetch) {2192my$gs= Git::SVN->new($fetch->{$p},$repo_id,$p);2193my$lr=$gs->rev_map_max;2194if(defined$lr) {2195$base=$lrif($lr<$base);2196}2197push@gs,$gs;2198}2199}22002201($base,$head) = parse_revision_argument($base,$head);2202$ra->gs_fetch_loop_common($base,$head, \@gs, \@globs);2203}22042205sub read_all_remotes {2206my$r= {};2207my$use_svm_props=eval{ command_oneline(qw/config --bool2208 svn.useSvmProps/) };2209$use_svm_props=$use_svm_propseq'true'if$use_svm_props;2210my$svn_refspec=qr{\s*(.*?)\s*:\s*(.+?)\s*};2211foreach(grep{s/^svn-remote\.//} command(qw/config -l/)) {2212if(m!^(.+)\.fetch=$svn_refspec$!) {2213my($remote,$local_ref,$remote_ref) = ($1,$2,$3);2214die("svn-remote.$remote: remote ref '$remote_ref' "2215."must start with 'refs/'\n")2216unless$remote_ref=~m{^refs/};2217$local_ref= uri_decode($local_ref);2218$r->{$remote}->{fetch}->{$local_ref} =$remote_ref;2219$r->{$remote}->{svm} = {}if$use_svm_props;2220}elsif(m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {2221$r->{$1}->{svm} = {};2222}elsif(m!^(.+)\.url=\s*(.*)\s*$!) {2223$r->{$1}->{url} =$2;2224}elsif(m!^(.+)\.pushurl=\s*(.*)\s*$!) {2225$r->{$1}->{pushurl} =$2;2226}elsif(m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {2227$r->{$1}->{ignore_refs_regex} =$2;2228}elsif(m!^(.+)\.(branches|tags)=$svn_refspec$!) {2229my($remote,$t,$local_ref,$remote_ref) =2230($1,$2,$3,$4);2231die("svn-remote.$remote: remote ref '$remote_ref' ($t) "2232."must start with 'refs/'\n")2233unless$remote_ref=~m{^refs/};2234$local_ref= uri_decode($local_ref);2235my$rs= {2236 t =>$t,2237 remote =>$remote,2238 path => Git::SVN::GlobSpec->new($local_ref,1),2239ref=> Git::SVN::GlobSpec->new($remote_ref,0) };2240if(length($rs->{ref}->{right}) !=0) {2241die"The '*' glob character must be the last ",2242"character of '$remote_ref'\n";2243}2244push@{$r->{$remote}->{$t} },$rs;2245}2246}22472248map{2249if(defined$r->{$_}->{svm}) {2250my$svm;2251eval{2252my$section="svn-remote.$_";2253$svm= {2254 source => tmp_config('--get',2255"$section.svm-source"),2256 replace => tmp_config('--get',2257"$section.svm-replace"),2258}2259};2260$r->{$_}->{svm} =$svm;2261}2262}keys%$r;22632264foreachmy$remote(keys%$r) {2265foreach(grep{defined$_}2266map{$r->{$remote}->{$_} }qw(branches tags)) {2267foreachmy$rs(@$_) {2268$rs->{ignore_refs_regex} =2269$r->{$remote}->{ignore_refs_regex};2270}2271}2272}22732274$r;2275}22762277sub init_vars {2278$_gc_nr=$_gc_period=1000;2279if(defined$_repack||defined$_repack_flags) {2280warn"Repack options are obsolete; they have no effect.\n";2281}2282}22832284sub verify_remotes_sanity {2285return unless-d $ENV{GIT_DIR};2286my%seen;2287foreach(command(qw/config -l/)) {2288if(m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {2289if($seen{$1}) {2290die"Remote ref refs/remote/$1is tracked by",2291"\n \"$_\"\nand\n \"$seen{$1}\"\n",2292"Please resolve this ambiguity in ",2293"your git configuration file before ",2294"continuing\n";2295}2296$seen{$1} =$_;2297}2298}2299}23002301sub find_existing_remote {2302my($url,$remotes) =@_;2303returnundefif$no_reuse_existing;2304my$existing;2305foreachmy$repo_id(keys%$remotes) {2306my$u=$remotes->{$repo_id}->{url}ornext;2307next if$une$url;2308$existing=$repo_id;2309last;2310}2311$existing;2312}23132314sub init_remote_config {2315my($self,$url,$no_write) =@_;2316$url=~s!/+$!!;# strip trailing slash2317my$r= read_all_remotes();2318my$existing= find_existing_remote($url,$r);2319if($existing) {2320unless($no_write) {2321print STDERR "Using existing ",2322"[svn-remote\"$existing\"]\n";2323}2324$self->{repo_id} =$existing;2325}elsif($_minimize_url) {2326my$min_url= Git::SVN::Ra->new($url)->minimize_url;2327$existing= find_existing_remote($min_url,$r);2328if($existing) {2329unless($no_write) {2330print STDERR "Using existing ",2331"[svn-remote\"$existing\"]\n";2332}2333$self->{repo_id} =$existing;2334}2335if($min_urlne$url) {2336unless($no_write) {2337print STDERR "Using higher level of URL: ",2338"$url=>$min_url\n";2339}2340my$old_path=$self->{path};2341$self->{path} =$url;2342$self->{path} =~s!^\Q$min_url\E(/|$)!!;2343if(length$old_path) {2344$self->{path} .="/$old_path";2345}2346$url=$min_url;2347}2348}2349my$orig_url;2350if(!$existing) {2351# verify that we aren't overwriting anything:2352$orig_url=eval{2353 command_oneline('config','--get',2354"svn-remote.$self->{repo_id}.url")2355};2356if($orig_url&& ($orig_urlne$url)) {2357die"svn-remote.$self->{repo_id}.url already set: ",2358"$orig_url\nwanted to set to:$url\n";2359}2360}2361my($xrepo_id,$xpath) = find_ref($self->refname);2362if(!$no_write&&defined$xpath) {2363die"svn-remote.$xrepo_id.fetch already set to track ",2364"$xpath:",$self->refname,"\n";2365}2366unless($no_write) {2367 command_noisy('config',2368"svn-remote.$self->{repo_id}.url",$url);2369$self->{path} =~s{^/}{};2370$self->{path} =~s{%([0-9A-F]{2})}{chr hex($1)}ieg;2371 command_noisy('config','--add',2372"svn-remote.$self->{repo_id}.fetch",2373"$self->{path}:".$self->refname);2374}2375$self->{url} =$url;2376}23772378sub find_by_url {# repos_root and, path are optional2379my($class,$full_url,$repos_root,$path) =@_;23802381returnundefunlessdefined$full_url;2382 remove_username($full_url);2383 remove_username($repos_root)ifdefined$repos_root;2384my$remotes= read_all_remotes();2385if(defined$full_url&&defined$repos_root&& !defined$path) {2386$path=$full_url;2387$path=~ s#^\Q$repos_root\E(?:/|$)##;2388}2389foreachmy$repo_id(keys%$remotes) {2390my$u=$remotes->{$repo_id}->{url}ornext;2391 remove_username($u);2392next ifdefined$repos_root&&$repos_rootne$u;23932394my$fetch=$remotes->{$repo_id}->{fetch} || {};2395foreachmy$t(qw/branches tags/) {2396foreachmy$globspec(@{$remotes->{$repo_id}->{$t}}) {2397 resolve_local_globs($u,$fetch,$globspec);2398}2399}2400my$p=$path;2401my$rwr= rewrite_root({repo_id =>$repo_id});2402my$svm=$remotes->{$repo_id}->{svm}2403ifdefined$remotes->{$repo_id}->{svm};2404unless(defined$p) {2405$p=$full_url;2406my$z=$u;2407my$prefix='';2408if($rwr) {2409$z=$rwr;2410 remove_username($z);2411}elsif(defined$svm) {2412$z=$svm->{source};2413$prefix=$svm->{replace};2414$prefix=~ s#^\Q$u\E(?:/|$)##;2415$prefix=~ s#/$##;2416}2417$p=~ s#^\Q$z\E(?:/|$)#$prefix# or next;2418}2419foreachmy$f(keys%$fetch) {2420next if$fne$p;2421return Git::SVN->new($fetch->{$f},$repo_id,$f);2422}2423}2424undef;2425}24262427sub init {2428my($class,$url,$path,$repo_id,$ref_id,$no_write) =@_;2429my$self= _new($class,$repo_id,$ref_id,$path);2430if(defined$url) {2431$self->init_remote_config($url,$no_write);2432}2433$self;2434}24352436sub find_ref {2437my($ref_id) =@_;2438foreach(command(qw/config -l/)) {2439next unless m!^svn-remote\.(.+)\.fetch=2440 \s*(.*?)\s*:\s*(.+?)\s*$!x;2441my($repo_id,$path,$ref) = ($1,$2,$3);2442if($refeq$ref_id) {2443$path=''if($path=~ m#^\./?#);2444return($repo_id,$path);2445}2446}2447(undef,undef,undef);2448}24492450sub new {2451my($class,$ref_id,$repo_id,$path) =@_;2452if(defined$ref_id&& !defined$repo_id&& !defined$path) {2453($repo_id,$path) = find_ref($ref_id);2454if(!defined$repo_id) {2455die"Could not find a\"svn-remote.*.fetch\"key ",2456"in the repository configuration matching: ",2457"$ref_id\n";2458}2459}2460my$self= _new($class,$repo_id,$ref_id,$path);2461if(!defined$self->{path} || !length$self->{path}) {2462my$fetch= command_oneline('config','--get',2463"svn-remote.$repo_id.fetch",2464":$ref_id\$")or2465die"Failed to read\"svn-remote.$repo_id.fetch\"",2466"\":$ref_id\$\"in config\n";2467($self->{path},undef) =split(/\s*:\s*/,$fetch);2468}2469$self->{path} =~s{/+}{/}g;2470$self->{path} =~s{\A/}{};2471$self->{path} =~s{/\z}{};2472$self->{url} = command_oneline('config','--get',2473"svn-remote.$repo_id.url")or2474die"Failed to read\"svn-remote.$repo_id.url\"in config\n";2475$self->{pushurl} =eval{ command_oneline('config','--get',2476"svn-remote.$repo_id.pushurl") };2477$self->rebuild;2478$self;2479}24802481sub refname {2482my($refname) =$_[0]->{ref_id} ;24832484# It cannot end with a slash /, we'll throw up on this because2485# SVN can't have directories with a slash in their name, either:2486if($refname=~m{/$}) {2487die"ref: '$refname' ends with a trailing slash, this is ",2488"not permitted by git nor Subversion\n";2489}24902491# It cannot have ASCII control character space, tilde ~, caret ^,2492# colon :, question-mark ?, asterisk *, space, or open bracket [2493# anywhere.2494#2495# Additionally, % must be escaped because it is used for escaping2496# and we want our escaped refname to be reversible2497$refname=~s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;24982499# no slash-separated component can begin with a dot .2500# /.* becomes /%2E*2501$refname=~s{/\.}{/%2E}g;25022503# It cannot have two consecutive dots .. anywhere2504# .. becomes %2E%2E2505$refname=~s{\.\.}{%2E%2E}g;25062507# trailing dots and .lock are not allowed2508# .$ becomes %2E and .lock becomes %2Elock2509$refname=~s{\.(?=$|lock$)}{%2E};25102511# the sequence @{ is used to access the reflog2512# @{ becomes %40{2513$refname=~s{\@\{}{%40\{}g;25142515return$refname;2516}25172518sub desanitize_refname {2519my($refname) =@_;2520$refname=~s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;2521return$refname;2522}25232524sub svm_uuid {2525my($self) =@_;2526return$self->{svm}->{uuid}if$self->svm;2527$self->ra;2528unless($self->{svm}) {2529die"SVM UUID not cached, and reading remotely failed\n";2530}2531$self->{svm}->{uuid};2532}25332534sub svm {2535my($self) =@_;2536return$self->{svm}if$self->{svm};2537my$svm;2538# see if we have it in our config, first:2539eval{2540my$section="svn-remote.$self->{repo_id}";2541$svm= {2542 source => tmp_config('--get',"$section.svm-source"),2543 uuid => tmp_config('--get',"$section.svm-uuid"),2544 replace => tmp_config('--get',"$section.svm-replace"),2545}2546};2547if($svm&&$svm->{source} &&$svm->{uuid} &&$svm->{replace}) {2548$self->{svm} =$svm;2549}2550$self->{svm};2551}25522553sub _set_svm_vars {2554my($self,$ra) =@_;2555return$raif$self->svm;25562557my@err= ("useSvmProps set, but failed to read SVM properties\n",2558"(svm:source, svm:uuid) ",2559"from the following URLs:\n");2560sub read_svm_props {2561my($self,$ra,$path,$r) =@_;2562my$props= ($ra->get_dir($path,$r))[2];2563my$src=$props->{'svm:source'};2564my$uuid=$props->{'svm:uuid'};2565returnundefif(!$src|| !$uuid);25662567chomp($src,$uuid);25682569$uuid=~m{^[0-9a-f\-]{30,}$}i2570or die"doesn't look right - svm:uuid is '$uuid'\n";25712572# the '!' is used to mark the repos_root!/relative/path2573$src=~s{/?!/?}{/};2574$src=~s{/+$}{};# no trailing slashes please2575# username is of no interest2576$src=~s{(^[a-z\+]*://)[^/@]*@}{$1};25772578my$replace=$ra->{url};2579$replace.="/$path"iflength$path;25802581my$section="svn-remote.$self->{repo_id}";2582 tmp_config("$section.svm-source",$src);2583 tmp_config("$section.svm-replace",$replace);2584 tmp_config("$section.svm-uuid",$uuid);2585$self->{svm} = {2586 source =>$src,2587 uuid =>$uuid,2588 replace =>$replace2589};2590}25912592my$r=$ra->get_latest_revnum;2593my$path=$self->{path};2594my%tried;2595while(length$path) {2596unless($tried{"$self->{url}/$path"}) {2597return$raif$self->read_svm_props($ra,$path,$r);2598$tried{"$self->{url}/$path"} =1;2599}2600$path=~ s#/?[^/]+$##;2601}2602die"Path: '$path' should be ''\n"if$pathne'';2603return$raif$self->read_svm_props($ra,$path,$r);2604$tried{"$self->{url}/$path"} =1;26052606if($ra->{repos_root}eq$self->{url}) {2607die@err, (map{"$_\n"}keys%tried),"\n";2608}26092610# nope, make sure we're connected to the repository root:2611my$ok;2612my@tried_b;2613$path=$ra->{svn_path};2614$ra= Git::SVN::Ra->new($ra->{repos_root});2615while(length$path) {2616unless($tried{"$ra->{url}/$path"}) {2617$ok=$self->read_svm_props($ra,$path,$r);2618last if$ok;2619$tried{"$ra->{url}/$path"} =1;2620}2621$path=~ s#/?[^/]+$##;2622}2623die"Path: '$path' should be ''\n"if$pathne'';2624$ok||=$self->read_svm_props($ra,$path,$r);2625$tried{"$ra->{url}/$path"} =1;2626if(!$ok) {2627die@err, (map{"$_\n"}keys%tried),"\n";2628}2629 Git::SVN::Ra->new($self->{url});2630}26312632sub svnsync {2633my($self) =@_;2634return$self->{svnsync}if$self->{svnsync};26352636if($self->no_metadata) {2637die"Can't have both 'noMetadata' and ",2638"'useSvnsyncProps' options set!\n";2639}2640if($self->rewrite_root) {2641die"Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",2642"options set!\n";2643}2644if($self->rewrite_uuid) {2645die"Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",2646"options set!\n";2647}26482649my$svnsync;2650# see if we have it in our config, first:2651eval{2652my$section="svn-remote.$self->{repo_id}";26532654my$url= tmp_config('--get',"$section.svnsync-url");2655($url) = ($url=~m{^([a-z\+]+://\S+)$})or2656die"doesn't look right - svn:sync-from-url is '$url'\n";26572658my$uuid= tmp_config('--get',"$section.svnsync-uuid");2659($uuid) = ($uuid=~m{^([0-9a-f\-]{30,})$}i)or2660die"doesn't look right - svn:sync-from-uuid is '$uuid'\n";26612662$svnsync= { url =>$url, uuid =>$uuid}2663};2664if($svnsync&&$svnsync->{url} &&$svnsync->{uuid}) {2665return$self->{svnsync} =$svnsync;2666}26672668my$err="useSvnsyncProps set, but failed to read ".2669"svnsync property: svn:sync-from-";2670my$rp=$self->ra->rev_proplist(0);26712672my$url=$rp->{'svn:sync-from-url'}or die$err."url\n";2673($url) = ($url=~m{^([a-z\+]+://\S+)$})or2674die"doesn't look right - svn:sync-from-url is '$url'\n";26752676my$uuid=$rp->{'svn:sync-from-uuid'}or die$err."uuid\n";2677($uuid) = ($uuid=~m{^([0-9a-f\-]{30,})$}i)or2678die"doesn't look right - svn:sync-from-uuid is '$uuid'\n";26792680my$section="svn-remote.$self->{repo_id}";2681 tmp_config('--add',"$section.svnsync-uuid",$uuid);2682 tmp_config('--add',"$section.svnsync-url",$url);2683return$self->{svnsync} = { url =>$url, uuid =>$uuid};2684}26852686# this allows us to memoize our SVN::Ra UUID locally and avoid a2687# remote lookup (useful for 'git svn log').2688sub ra_uuid {2689my($self) =@_;2690unless($self->{ra_uuid}) {2691my$key="svn-remote.$self->{repo_id}.uuid";2692my$uuid=eval{ tmp_config('--get',$key) };2693if(!$@&&$uuid&&$uuid=~/^([a-f\d\-]{30,})$/i) {2694$self->{ra_uuid} =$uuid;2695}else{2696die"ra_uuid called without URL\n"unless$self->{url};2697$self->{ra_uuid} =$self->ra->get_uuid;2698 tmp_config('--add',$key,$self->{ra_uuid});2699}2700}2701$self->{ra_uuid};2702}27032704sub _set_repos_root {2705my($self,$repos_root) =@_;2706my$k="svn-remote.$self->{repo_id}.reposRoot";2707$repos_root||=$self->ra->{repos_root};2708 tmp_config($k,$repos_root);2709$repos_root;2710}27112712sub repos_root {2713my($self) =@_;2714my$k="svn-remote.$self->{repo_id}.reposRoot";2715eval{ tmp_config('--get',$k) } ||$self->_set_repos_root;2716}27172718sub ra {2719my($self) =shift;2720my$ra= Git::SVN::Ra->new($self->{url});2721$self->_set_repos_root($ra->{repos_root});2722if($self->use_svm_props&& !$self->{svm}) {2723if($self->no_metadata) {2724die"Can't have both 'noMetadata' and ",2725"'useSvmProps' options set!\n";2726}elsif($self->use_svnsync_props) {2727die"Can't have both 'useSvnsyncProps' and ",2728"'useSvmProps' options set!\n";2729}2730$ra=$self->_set_svm_vars($ra);2731$self->{-want_revprops} =1;2732}2733$ra;2734}27352736# prop_walk(PATH, REV, SUB)2737# -------------------------2738# Recursively traverse PATH at revision REV and invoke SUB for each2739# directory that contains a SVN property. SUB will be invoked as2740# follows: &SUB(gs, path, props); where `gs' is this instance of2741# Git::SVN, `path' the path to the directory where the properties2742# `props' were found. The `path' will be relative to point of checkout,2743# that is, if url://repo/trunk is the current Git branch, and that2744# directory contains a sub-directory `d', SUB will be invoked with `/d/'2745# as `path' (note the trailing `/').2746sub prop_walk {2747my($self,$path,$rev,$sub) =@_;27482749$path=~ s#^/##;2750my($dirent,undef,$props) =$self->ra->get_dir($path,$rev);2751$path=~ s#^/*#/#g;2752my$p=$path;2753# Strip the irrelevant part of the path.2754$p=~ s#^/+\Q$self->{path}\E(/|$)#/#;2755# Ensure the path is terminated by a `/'.2756$p=~ s#/*$#/#;27572758# The properties contain all the internal SVN stuff nobody2759# (usually) cares about.2760my$interesting_props=0;2761foreach(keys%{$props}) {2762# If it doesn't start with `svn:', it must be a2763# user-defined property.2764++$interesting_propsandnext if$_!~/^svn:/;2765# FIXME: Fragile, if SVN adds new public properties,2766# this needs to be updated.2767++$interesting_propsif/^svn:(?:ignore|keywords|executable2768|eol-style|mime-type2769|externals|needs-lock)$/x;2770}2771&$sub($self,$p,$props)if$interesting_props;27722773foreach(sort keys%$dirent) {2774next if$dirent->{$_}->{kind} !=$SVN::Node::dir;2775$self->prop_walk($self->{path} .$p.$_,$rev,$sub);2776}2777}27782779sub last_rev { ($_[0]->last_rev_commit)[0] }2780sub last_commit { ($_[0]->last_rev_commit)[1] }27812782# returns the newest SVN revision number and newest commit SHA12783sub last_rev_commit {2784my($self) =@_;2785if(defined$self->{last_rev} &&defined$self->{last_commit}) {2786return($self->{last_rev},$self->{last_commit});2787}2788my$c= ::verify_ref($self->refname.'^0');2789if($c&& !$self->use_svm_props&& !$self->no_metadata) {2790my$rev= (::cmt_metadata($c))[1];2791if(defined$rev) {2792($self->{last_rev},$self->{last_commit}) = ($rev,$c);2793return($rev,$c);2794}2795}2796my$map_path=$self->map_path;2797unless(-e $map_path) {2798($self->{last_rev},$self->{last_commit}) = (undef,undef);2799return(undef,undef);2800}2801my($rev,$commit) =$self->rev_map_max(1);2802($self->{last_rev},$self->{last_commit}) = ($rev,$commit);2803return($rev,$commit);2804}28052806sub get_fetch_range {2807my($self,$min,$max) =@_;2808$max||=$self->ra->get_latest_revnum;2809$min||=$self->rev_map_max;2810(++$min,$max);2811}28122813sub tmp_config {2814my(@args) =@_;2815my$old_def_config="$ENV{GIT_DIR}/svn/config";2816my$config="$ENV{GIT_DIR}/svn/.metadata";2817if(! -f $config&& -f $old_def_config) {2818rename$old_def_config,$configor2819die"Failed rename$old_def_config=>$config:$!\n";2820}2821my$old_config=$ENV{GIT_CONFIG};2822$ENV{GIT_CONFIG} =$config;2823$@=undef;2824my@ret=eval{2825unless(-f $config) {2826 mkfile($config);2827open my$fh,'>',$configor2828die"Can't open$config:$!\n";2829print$fh"; This file is used internally by ",2830"git-svn\n"or die2831"Couldn't write to$config:$!\n";2832print$fh"; You should not have to edit it\n"or2833die"Couldn't write to$config:$!\n";2834close$fhor die"Couldn't close$config:$!\n";2835}2836 command('config',@args);2837};2838my$err=$@;2839if(defined$old_config) {2840$ENV{GIT_CONFIG} =$old_config;2841}else{2842delete$ENV{GIT_CONFIG};2843}2844die$errif$err;2845wantarray?@ret:$ret[0];2846}28472848sub tmp_index_do {2849my($self,$sub) =@_;2850my$old_index=$ENV{GIT_INDEX_FILE};2851$ENV{GIT_INDEX_FILE} =$self->{index};2852$@=undef;2853my@ret=eval{2854my($dir,$base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);2855 mkpath([$dir])unless-d $dir;2856&$sub;2857};2858my$err=$@;2859if(defined$old_index) {2860$ENV{GIT_INDEX_FILE} =$old_index;2861}else{2862delete$ENV{GIT_INDEX_FILE};2863}2864die$errif$err;2865wantarray?@ret:$ret[0];2866}28672868sub assert_index_clean {2869my($self,$treeish) =@_;28702871$self->tmp_index_do(sub{2872 command_noisy('read-tree',$treeish)unless-e $self->{index};2873my$x= command_oneline('write-tree');2874my($y) = (command(qw/cat-file commit/,$treeish) =~2875/^tree ($::sha1)/mo);2876return if$yeq$x;28772878warn"Index mismatch:$y!=$x\nrereading$treeish\n";2879unlink$self->{index}or die"unlink$self->{index}:$!\n";2880 command_noisy('read-tree',$treeish);2881$x= command_oneline('write-tree');2882if($yne$x) {2883::fatal "trees ($treeish)$y!=$x\n",2884"Something is seriously wrong...";2885}2886});2887}28882889sub get_commit_parents {2890my($self,$log_entry) =@_;2891my(%seen,@ret,@tmp);2892# legacy support for 'set-tree'; this is only used by set_tree_cb:2893if(my$ip=$self->{inject_parents}) {2894if(my$commit=delete$ip->{$log_entry->{revision}}) {2895push@tmp,$commit;2896}2897}2898if(my$cur= ::verify_ref($self->refname.'^0')) {2899push@tmp,$cur;2900}2901if(my$ipd=$self->{inject_parents_dcommit}) {2902if(my$commit=delete$ipd->{$log_entry->{revision}}) {2903push@tmp,@$commit;2904}2905}2906push@tmp,$_foreach(@{$log_entry->{parents}},@tmp);2907while(my$p=shift@tmp) {2908next if$seen{$p};2909$seen{$p} =1;2910push@ret,$p;2911}2912@ret;2913}29142915sub rewrite_root {2916my($self) =@_;2917return$self->{-rewrite_root}ifexists$self->{-rewrite_root};2918my$k="svn-remote.$self->{repo_id}.rewriteRoot";2919my$rwr=eval{ command_oneline(qw/config --get/,$k) };2920if($rwr) {2921$rwr=~ s#/+$##;2922if($rwr!~ m#^[a-z\+]+://#) {2923die"$rwris not a valid URL (key:$k)\n";2924}2925}2926$self->{-rewrite_root} =$rwr;2927}29282929sub rewrite_uuid {2930my($self) =@_;2931return$self->{-rewrite_uuid}ifexists$self->{-rewrite_uuid};2932my$k="svn-remote.$self->{repo_id}.rewriteUUID";2933my$rwid=eval{ command_oneline(qw/config --get/,$k) };2934if($rwid) {2935$rwid=~ s#/+$##;2936if($rwid!~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {2937die"$rwidis not a valid UUID (key:$k)\n";2938}2939}2940$self->{-rewrite_uuid} =$rwid;2941}29422943sub metadata_url {2944my($self) =@_;2945($self->rewrite_root||$self->{url}) .2946(length$self->{path} ?'/'.$self->{path} :'');2947}29482949sub full_url {2950my($self) =@_;2951$self->{url} . (length$self->{path} ?'/'.$self->{path} :'');2952}29532954sub full_pushurl {2955my($self) =@_;2956if($self->{pushurl}) {2957return$self->{pushurl} . (length$self->{path} ?'/'.2958$self->{path} :'');2959}else{2960return$self->full_url;2961}2962}29632964sub set_commit_header_env {2965my($log_entry) =@_;2966my%env;2967foreachmy$ned(qw/NAME EMAIL DATE/) {2968foreachmy$ac(qw/AUTHOR COMMITTER/) {2969$env{"GIT_${ac}_${ned}"} =$ENV{"GIT_${ac}_${ned}"};2970}2971}29722973$ENV{GIT_AUTHOR_NAME} =$log_entry->{name};2974$ENV{GIT_AUTHOR_EMAIL} =$log_entry->{email};2975$ENV{GIT_AUTHOR_DATE} =$ENV{GIT_COMMITTER_DATE} =$log_entry->{date};29762977$ENV{GIT_COMMITTER_NAME} = (defined$log_entry->{commit_name})2978?$log_entry->{commit_name}2979:$log_entry->{name};2980$ENV{GIT_COMMITTER_EMAIL} = (defined$log_entry->{commit_email})2981?$log_entry->{commit_email}2982:$log_entry->{email};2983 \%env;2984}29852986sub restore_commit_header_env {2987my($env) =@_;2988foreachmy$ned(qw/NAME EMAIL DATE/) {2989foreachmy$ac(qw/AUTHOR COMMITTER/) {2990my$k="GIT_${ac}_${ned}";2991if(defined$env->{$k}) {2992$ENV{$k} =$env->{$k};2993}else{2994delete$ENV{$k};2995}2996}2997}2998}29993000sub gc {3001 command_noisy('gc','--auto');3002};30033004sub do_git_commit {3005my($self,$log_entry) =@_;3006my$lr=$self->last_rev;3007if(defined$lr&&$lr>=$log_entry->{revision}) {3008die"Last fetched revision of ",$self->refname,3009" was r$lr, but we are about to fetch: ",3010"r$log_entry->{revision}!\n";3011}3012if(my$c=$self->rev_map_get($log_entry->{revision})) {3013 croak "$log_entry->{revision} =$calready exists! ",3014"Why are we refetching it?\n";3015}3016my$old_env= set_commit_header_env($log_entry);3017my$tree=$log_entry->{tree};3018if(!defined$tree) {3019$tree=$self->tmp_index_do(sub{3020 command_oneline('write-tree') });3021}3022die"Tree is not a valid sha1:$tree\n"if$tree!~/^$::sha1$/o;30233024my@exec= ('git','commit-tree',$tree);3025foreach($self->get_commit_parents($log_entry)) {3026push@exec,'-p',$_;3027}3028defined(my$pid= open3(my$msg_fh,my$out_fh,'>&STDERR',@exec))3029or croak $!;3030binmode$msg_fh;30313032# we always get UTF-8 from SVN, but we may want our commits in3033# a different encoding.3034if(my$enc= Git::config('i18n.commitencoding')) {3035require Encode;3036 Encode::from_to($log_entry->{log},'UTF-8',$enc);3037}3038print$msg_fh $log_entry->{log}or croak $!;3039 restore_commit_header_env($old_env);3040unless($self->no_metadata) {3041print$msg_fh"\ngit-svn-id:$log_entry->{metadata}\n"3042or croak $!;3043}3044$msg_fh->flush==0or croak $!;3045close$msg_fhor croak $!;3046chomp(my$commit=do{local$/; <$out_fh> });3047close$out_fhor croak $!;3048waitpid$pid,0;3049 croak $?if$?;3050if($commit!~/^$::sha1$/o) {3051die"Failed to commit, invalid sha1:$commit\n";3052}30533054$self->rev_map_set($log_entry->{revision},$commit,1);30553056$self->{last_rev} =$log_entry->{revision};3057$self->{last_commit} =$commit;3058print"r$log_entry->{revision}"unless$::_q >1;3059if(defined$log_entry->{svm_revision}) {3060print" (\@$log_entry->{svm_revision})"unless$::_q >1;3061$self->rev_map_set($log_entry->{svm_revision},$commit,30620,$self->svm_uuid);3063}3064print" =$commit($self->{ref_id})\n"unless$::_q >1;3065if(--$_gc_nr==0) {3066$_gc_nr=$_gc_period;3067 gc();3068}3069return$commit;3070}30713072sub match_paths {3073my($self,$paths,$r) =@_;3074return1if$self->{path}eq'';3075if(my$path=$paths->{"/$self->{path}"}) {3076return($path->{action}eq'D') ?0:1;3077}3078$self->{path_regex} ||=qr/^\/\Q$self->{path}\E\//;3079if(grep/$self->{path_regex}/,keys%$paths) {3080return1;3081}3082my$c='';3083foreach(split m#/#, $self->{path}) {3084$c.="/$_";3085next unless($paths->{$c} &&3086($paths->{$c}->{action} =~/^[AR]$/));3087if($self->ra->check_path($self->{path},$r) ==3088$SVN::Node::dir) {3089return1;3090}3091}3092return0;3093}30943095sub find_parent_branch {3096my($self,$paths,$rev) =@_;3097returnundefunless$self->follow_parent;3098unless(defined$paths) {3099my$err_handler=$SVN::Error::handler;3100$SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;3101$self->ra->get_log([$self->{path}],$rev,$rev,0,1,1,3102sub{$paths=$_[0] });3103$SVN::Error::handler =$err_handler;3104}3105returnundefunlessdefined$paths;31063107# look for a parent from another branch:3108my@b_path_components=split m#/#, $self->{path};3109my@a_path_components;3110my$i;3111while(@b_path_components) {3112$i=$paths->{'/'.join('/',@b_path_components)};3113last if$i&&defined$i->{copyfrom_path};3114unshift(@a_path_components,pop(@b_path_components));3115}3116returnundefunlessdefined$i&&defined$i->{copyfrom_path};3117my$branch_from=$i->{copyfrom_path};3118if(@a_path_components) {3119print STDERR "branch_from:$branch_from=> ";3120$branch_from.='/'.join('/',@a_path_components);3121print STDERR $branch_from,"\n";3122}3123my$r=$i->{copyfrom_rev};3124my$repos_root=$self->ra->{repos_root};3125my$url=$self->ra->{url};3126my$new_url=$url.$branch_from;3127print STDERR "Found possible branch point: ",3128"$new_url=> ",$self->full_url,",$r\n"3129unless$::_q >1;3130$branch_from=~ s#^/##;3131my$gs=$self->other_gs($new_url,$url,3132$branch_from,$r,$self->{ref_id});3133my($r0,$parent) =$gs->find_rev_before($r,1);3134{3135my($base,$head);3136if(!defined$r0|| !defined$parent) {3137($base,$head) = parse_revision_argument(0,$r);3138}else{3139if($r0<$r) {3140$gs->ra->get_log([$gs->{path}],$r0+1,$r,1,31410,1,sub{$base=$_[1] -1});3142}3143}3144if(defined$base&&$base<=$r) {3145$gs->fetch($base,$r);3146}3147($r0,$parent) =$gs->find_rev_before($r,1);3148}3149if(defined$r0&&defined$parent) {3150print STDERR "Found branch parent: ($self->{ref_id})$parent\n"3151unless$::_q >1;3152my$ed;3153if($self->ra->can_do_switch) {3154$self->assert_index_clean($parent);3155print STDERR "Following parent with do_switch\n"3156unless$::_q >1;3157# do_switch works with svn/trunk >= r22312, but that3158# is not included with SVN 1.4.3 (the latest version3159# at the moment), so we can't rely on it3160$self->{last_rev} =$r0;3161$self->{last_commit} =$parent;3162$ed= Git::SVN::Fetcher->new($self,$gs->{path});3163$gs->ra->gs_do_switch($r0,$rev,$gs,3164$self->full_url,$ed)3165or die"SVN connection failed somewhere...\n";3166}elsif($self->ra->trees_match($new_url,$r0,3167$self->full_url,$rev)) {3168print STDERR "Trees match:\n",3169"$new_url\@$r0\n",3170" ${\$self->full_url}\@$rev\n",3171"Following parent with no changes\n"3172unless$::_q >1;3173$self->tmp_index_do(sub{3174 command_noisy('read-tree',$parent);3175});3176$self->{last_commit} =$parent;3177}else{3178print STDERR "Following parent with do_update\n"3179unless$::_q >1;3180$ed= Git::SVN::Fetcher->new($self);3181$self->ra->gs_do_update($rev,$rev,$self,$ed)3182or die"SVN connection failed somewhere...\n";3183}3184print STDERR "Successfully followed parent\n"unless$::_q >1;3185return$self->make_log_entry($rev, [$parent],$ed);3186}3187returnundef;3188}31893190sub do_fetch {3191my($self,$paths,$rev) =@_;3192my$ed;3193my($last_rev,@parents);3194if(my$lc=$self->last_commit) {3195# we can have a branch that was deleted, then re-added3196# under the same name but copied from another path, in3197# which case we'll have multiple parents (we don't3198# want to break the original ref, nor lose copypath info):3199if(my$log_entry=$self->find_parent_branch($paths,$rev)) {3200push@{$log_entry->{parents}},$lc;3201return$log_entry;3202}3203$ed= Git::SVN::Fetcher->new($self);3204$last_rev=$self->{last_rev};3205$ed->{c} =$lc;3206@parents= ($lc);3207}else{3208$last_rev=$rev;3209if(my$log_entry=$self->find_parent_branch($paths,$rev)) {3210return$log_entry;3211}3212$ed= Git::SVN::Fetcher->new($self);3213}3214unless($self->ra->gs_do_update($last_rev,$rev,$self,$ed)) {3215die"SVN connection failed somewhere...\n";3216}3217$self->make_log_entry($rev, \@parents,$ed);3218}32193220sub mkemptydirs {3221my($self,$r) =@_;32223223sub scan {3224my($r,$empty_dirs,$line) =@_;3225if(defined$r&&$line=~/^r(\d+)$/) {3226return0if$1>$r;3227}elsif($line=~/^ \+empty_dir: (.+)$/) {3228$empty_dirs->{$1} =1;3229}elsif($line=~/^ \-empty_dir: (.+)$/) {3230my@d=grep{m[^\Q$1\E(/|$)]} (keys%$empty_dirs);3231delete@$empty_dirs{@d};3232}32331;# continue3234};32353236my%empty_dirs= ();3237my$gz_file="$self->{dir}/unhandled.log.gz";3238if(-f $gz_file) {3239if(!$can_compress) {3240warn"Compress::Zlib could not be found; ",3241"empty directories in$gz_filewill not be read\n";3242}else{3243my$gz= Compress::Zlib::gzopen($gz_file,"rb")or3244die"Unable to open$gz_file:$!\n";3245my$line;3246while($gz->gzreadline($line) >0) {3247 scan($r, \%empty_dirs,$line)orlast;3248}3249$gz->gzclose;3250}3251}32523253if(open my$fh,'<',"$self->{dir}/unhandled.log") {3254binmode$fhor croak "binmode:$!";3255while(<$fh>) {3256 scan($r, \%empty_dirs,$_)orlast;3257}3258close$fh;3259}32603261my$strip=qr/\A\Q$self->{path}\E(?:\/|$)/;3262foreachmy$d(sort keys%empty_dirs) {3263$d= uri_decode($d);3264$d=~s/$strip//;3265next unlesslength($d);3266next if-d $d;3267if(-e $d) {3268warn"$dexists but is not a directory\n";3269}else{3270print"creating empty directory:$d\n";3271 mkpath([$d]);3272}3273}3274}32753276sub get_untracked {3277my($self,$ed) =@_;3278my@out;3279my$h=$ed->{empty};3280foreach(sort keys%$h) {3281my$act=$h->{$_} ?'+empty_dir':'-empty_dir';3282push@out,"$act: ". uri_encode($_);3283warn"W:$act:$_\n";3284}3285foreachmy$t(qw/dir_prop file_prop/) {3286$h=$ed->{$t}ornext;3287foreachmy$path(sort keys%$h) {3288my$ppath=$patheq''?'.':$path;3289foreachmy$prop(sort keys%{$h->{$path}}) {3290next if$SKIP_PROP{$prop};3291my$v=$h->{$path}->{$prop};3292my$t_ppath_prop="$t: ".3293 uri_encode($ppath) .' '.3294 uri_encode($prop);3295if(defined$v) {3296push@out," +$t_ppath_prop".3297 uri_encode($v);3298}else{3299push@out," -$t_ppath_prop";3300}3301}3302}3303}3304foreachmy$t(qw/absent_file absent_directory/) {3305$h=$ed->{$t}ornext;3306foreachmy$parent(sort keys%$h) {3307foreachmy$path(sort@{$h->{$parent}}) {3308push@out,"$t: ".3309 uri_encode("$parent/$path");3310warn"W:$t:$parent/$path",3311"Insufficient permissions?\n";3312}3313}3314}3315 \@out;3316}33173318sub get_tz {3319# some systmes don't handle or mishandle %z, so be creative.3320my$t=shift||time;3321my$gm= timelocal(gmtime($t));3322my$sign=qw( + + - )[$t<=>$gm];3323returnsprintf("%s%02d%02d",$sign, (gmtime(abs($t-$gm)))[2,1]);3324}33253326# parse_svn_date(DATE)3327# --------------------3328# Given a date (in UTC) from Subversion, return a string in the format3329# "<TZ Offset> <local date/time>" that Git will use.3330#3331# By default the parsed date will be in UTC; if $Git::SVN::_localtime3332# is true we'll convert it to the local timezone instead.3333sub parse_svn_date {3334my$date=shift||return'+0000 1970-01-01 00:00:00';3335my($Y,$m,$d,$H,$M,$S) = ($date=~ /^(\d{4})\-(\d\d)\-(\d\d)T3336(\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x)or3337 croak "Unable to parse date:$date\n";3338my$parsed_date;# Set next.33393340if($Git::SVN::_localtime) {3341# Translate the Subversion datetime to an epoch time.3342# Begin by switching ourselves to $date's timezone, UTC.3343my$old_env_TZ=$ENV{TZ};3344$ENV{TZ} ='UTC';33453346my$epoch_in_UTC=3347 POSIX::strftime('%s',$S,$M,$H,$d,$m-1,$Y-1900);33483349# Determine our local timezone (including DST) at the3350# time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the3351# value of TZ, if any, at the time we were run.3352if(defined$Git::SVN::Log::TZ) {3353$ENV{TZ} =$Git::SVN::Log::TZ;3354}else{3355delete$ENV{TZ};3356}33573358my$our_TZ= get_tz();33593360# This converts $epoch_in_UTC into our local timezone.3361my($sec,$min,$hour,$mday,$mon,$year,3362$wday,$yday,$isdst) =localtime($epoch_in_UTC);33633364$parsed_date=sprintf('%s%04d-%02d-%02d%02d:%02d:%02d',3365$our_TZ,$year+1900,$mon+1,3366$mday,$hour,$min,$sec);33673368# Reset us to the timezone in effect when we entered3369# this routine.3370if(defined$old_env_TZ) {3371$ENV{TZ} =$old_env_TZ;3372}else{3373delete$ENV{TZ};3374}3375}else{3376$parsed_date="+0000$Y-$m-$d$H:$M:$S";3377}33783379return$parsed_date;3380}33813382sub other_gs {3383my($self,$new_url,$url,3384$branch_from,$r,$old_ref_id) =@_;3385my$gs= Git::SVN->find_by_url($new_url,$url,$branch_from);3386unless($gs) {3387my$ref_id=$old_ref_id;3388$ref_id=~s/\@\d+-*$//;3389$ref_id.="\@$r";3390# just grow a tail if we're not unique enough :x3391$ref_id.='-'while find_ref($ref_id);3392my($u,$p,$repo_id) = ($new_url,'',$ref_id);3393if($u=~ s#^\Q$url\E(/|$)##) {3394$p=$u;3395$u=$url;3396$repo_id=$self->{repo_id};3397}3398while(1) {3399# It is possible to tag two different subdirectories at3400# the same revision. If the url for an existing ref3401# does not match, we must either find a ref with a3402# matching url or create a new ref by growing a tail.3403$gs= Git::SVN->init($u,$p,$repo_id,$ref_id,1);3404my(undef,$max_commit) =$gs->rev_map_max(1);3405last if(!$max_commit);3406my($url) = ::cmt_metadata($max_commit);3407last if($urleq$gs->metadata_url);3408$ref_id.='-';3409}3410print STDERR "Initializing parent:$ref_id\n"unless$::_q >1;3411}3412$gs3413}34143415sub call_authors_prog {3416my($orig_author) =@_;3417$orig_author= command_oneline('rev-parse','--sq-quote',$orig_author);3418my$author=`$::_authors_prog$orig_author`;3419 if ($?!= 0) {3420 die "$::_authors_prog failed with exit code$?\n"3421 }3422 if ($author=~ /^\s*(.+?)\s*<(.*)>\s*$/) {3423 my ($name,$email) = ($1,$2);3424$email= undef if length$2== 0;3425 return [$name,$email];3426 } else {3427 die "Author:$orig_author: $::_authors_prog returned "3428 . "invalid author format:$author\n";3429 }3430}34313432sub check_author {3433 my ($author) =@_;3434 if (!defined$author|| length$author== 0) {3435$author= '(no author)';3436 }3437 if (!defined $::users{$author}) {3438 if (defined $::_authors_prog) {3439 $::users{$author} = call_authors_prog($author);3440 } elsif (defined $::_authors) {3441 die "Author:$authornot defined in $::_authors file\n";3442 }3443 }3444$author;3445}34463447sub find_extra_svk_parents {3448 my ($self,$ed,$tickets,$parents) =@_;3449 # aha! svk:merge property changed...3450 my@tickets= split "\n",$tickets;3451 my@known_parents;3452 for my$ticket(@tickets) {3453 my ($uuid,$path,$rev) = split /:/,$ticket;3454 if ($uuideq$self->ra_uuid ) {3455 my$url=$self->{url};3456 my$repos_root=$url;3457 my$branch_from=$path;3458$branch_from=~ s{^/}{};3459 my$gs=$self->other_gs($repos_root."/".$branch_from,3460$url,3461$branch_from,3462$rev,3463$self->{ref_id});3464 if ( my$commit=$gs->rev_map_get($rev,$uuid) ) {3465 # wahey! we found it, but it might be3466 # an old one (!)3467 push@known_parents, [$rev,$commit];3468 }3469 }3470 }3471 # Ordering matters; highest-numbered commit merge tickets3472 # first, as they may account for later merge ticket additions3473 # or changes.3474@known_parents= map {$_->[1]} sort {$b->[0] <=>$a->[0]}@known_parents;3475 for my$parent(@known_parents) {3476 my@cmd= ('rev-list',$parent, map { "^$_" }@$parents);3477 my ($msg_fh,$ctx) = command_output_pipe(@cmd);3478 my$new;3479 while ( <$msg_fh> ) {3480$new=1;last;3481 }3482 command_close_pipe($msg_fh,$ctx);3483 if ($new) {3484 print STDERR3485 "Found merge parent (svk:merge ticket):$parent\n";3486 push@$parents,$parent;3487 }3488 }3489}34903491sub lookup_svn_merge {3492 my$uuid= shift;3493 my$url= shift;3494 my$merge= shift;34953496 my ($source,$revs) = split ":",$merge;3497 my$path=$source;3498$path=~ s{^/}{};3499 my$gs= Git::SVN->find_by_url($url.$source,$url,$path);3500 if ( !$gs) {3501 warn "Couldn't find revmap for$url$source\n";3502 return;3503 }3504 my@ranges= split ",",$revs;3505 my ($tip,$tip_commit);3506 my@merged_commit_ranges;3507 # find the tip3508 for my$range(@ranges) {3509 my ($bottom,$top) = split "-",$range;3510$top||=$bottom;3511 my$bottom_commit=$gs->find_rev_after($bottom, 1,$top);3512 my$top_commit=$gs->find_rev_before($top, 1,$bottom);35133514 unless ($top_commitand$bottom_commit) {3515 warn "W:unknown path/rev in svn:mergeinfo "3516 ."dirprop:$source:$range\n";3517 next;3518 }35193520 if (scalar(command('rev-parse', "$bottom_commit^@"))) {3521 push@merged_commit_ranges,3522 "$bottom_commit^..$top_commit";3523 } else {3524 push@merged_commit_ranges, "$top_commit";3525 }35263527 if ( !defined$tipor$top>$tip) {3528$tip=$top;3529$tip_commit=$top_commit;3530 }3531 }3532 return ($tip_commit,@merged_commit_ranges);3533}35343535sub _rev_list {3536 my ($msg_fh,$ctx) = command_output_pipe(3537 "rev-list",@_,3538 );3539 my@rv;3540 while ( <$msg_fh> ) {3541 chomp;3542 push@rv,$_;3543 }3544 command_close_pipe($msg_fh,$ctx);3545@rv;3546}35473548sub check_cherry_pick {3549 my$base= shift;3550 my$tip= shift;3551 my$parents= shift;3552 my@ranges=@_;3553 my%commits= map {$_=> 1 }3554 _rev_list("--no-merges",$tip, "--not",$base,@$parents, "--");3555 for my$range(@ranges) {3556 delete@commits{_rev_list($range, "--")};3557 }3558 for my$commit(keys%commits) {3559 if (has_no_changes($commit)) {3560 delete$commits{$commit};3561 }3562 }3563 return (keys%commits);3564}35653566sub has_no_changes {3567 my$commit= shift;35683569 my@revs= split / /, command_oneline(3570 qw(rev-list --parents -1 -m),$commit);35713572# Commits with no parents, e.g. the start of a partial branch,3573# have changes by definition.3574return1if(@revs<2);35753576# Commits with multiple parents, e.g a merge, have no changes3577# by definition.3578return0if(@revs>2);35793580return(command_oneline("rev-parse","$commit^{tree}")eq3581 command_oneline("rev-parse","$commit~1^{tree}"));3582}35833584sub tie_for_persistent_memoization {3585my$hash=shift;3586my$path=shift;35873588if($can_use_yaml) {3589 tie %$hash=>'Git::SVN::Memoize::YAML',"$path.yaml";3590}else{3591 tie %$hash=>'Memoize::Storable',"$path.db",'nstore';3592}3593}35943595# The GIT_DIR environment variable is not always set until after the command3596# line arguments are processed, so we can't memoize in a BEGIN block.3597{3598my$memoized=0;35993600sub memoize_svn_mergeinfo_functions {3601return if$memoized;3602$memoized=1;36033604my$cache_path="$ENV{GIT_DIR}/svn/.caches/";3605 mkpath([$cache_path])unless-d $cache_path;36063607my%lookup_svn_merge_cache;3608my%check_cherry_pick_cache;3609my%has_no_changes_cache;36103611 tie_for_persistent_memoization(\%lookup_svn_merge_cache,3612"$cache_path/lookup_svn_merge");3613 memoize 'lookup_svn_merge',3614 SCALAR_CACHE =>'FAULT',3615 LIST_CACHE => ['HASH'=> \%lookup_svn_merge_cache],3616;36173618 tie_for_persistent_memoization(\%check_cherry_pick_cache,3619"$cache_path/check_cherry_pick");3620 memoize 'check_cherry_pick',3621 SCALAR_CACHE =>'FAULT',3622 LIST_CACHE => ['HASH'=> \%check_cherry_pick_cache],3623;36243625 tie_for_persistent_memoization(\%has_no_changes_cache,3626"$cache_path/has_no_changes");3627 memoize 'has_no_changes',3628 SCALAR_CACHE => ['HASH'=> \%has_no_changes_cache],3629 LIST_CACHE =>'FAULT',3630;3631}36323633sub unmemoize_svn_mergeinfo_functions {3634return ifnot$memoized;3635$memoized=0;36363637 Memoize::unmemoize 'lookup_svn_merge';3638 Memoize::unmemoize 'check_cherry_pick';3639 Memoize::unmemoize 'has_no_changes';3640}36413642 Memoize::memoize 'Git::SVN::repos_root';3643}36443645END{3646# Force cache writeout explicitly instead of waiting for3647# global destruction to avoid segfault in Storable:3648# http://rt.cpan.org/Public/Bug/Display.html?id=360873649 unmemoize_svn_mergeinfo_functions();3650}36513652sub parents_exclude {3653my$parents=shift;3654my@commits=@_;3655return unless@commits;36563657my@excluded;3658my$excluded;3659do{3660my@cmd= ('rev-list',"-1",@commits,"--not",@$parents);3661$excluded= command_oneline(@cmd);3662if($excluded) {3663my@new;3664my$found;3665formy$commit(@commits) {3666if($commiteq$excluded) {3667push@excluded,$commit;3668$found++;3669last;3670}3671else{3672push@new,$commit;3673}3674}3675die"saw commit '$excluded' in rev-list output, "3676."but we didn't ask for that commit (wanted:@commits--not@$parents)"3677unless$found;3678@commits=@new;3679}3680}3681while($excludedand@commits);36823683return@excluded;3684}368536863687# note: this function should only be called if the various dirprops3688# have actually changed3689sub find_extra_svn_parents {3690my($self,$ed,$mergeinfo,$parents) =@_;3691# aha! svk:merge property changed...36923693 memoize_svn_mergeinfo_functions();36943695# We first search for merged tips which are not in our3696# history. Then, we figure out which git revisions are in3697# that tip, but not this revision. If all of those revisions3698# are now marked as merge, we can add the tip as a parent.3699my@merges=split"\n",$mergeinfo;3700my@merge_tips;3701my$url=$self->{url};3702my$uuid=$self->ra_uuid;3703my%ranges;3704formy$merge(@merges) {3705my($tip_commit,@ranges) =3706 lookup_svn_merge($uuid,$url,$merge);3707unless(!$tip_commitor3708grep{$_eq$tip_commit}@$parents) {3709push@merge_tips,$tip_commit;3710$ranges{$tip_commit} = \@ranges;3711}else{3712push@merge_tips,undef;3713}3714}37153716my%excluded=map{$_=>1}3717 parents_exclude($parents,grep{defined}@merge_tips);37183719# check merge tips for new parents3720my@new_parents;3721formy$merge_tip(@merge_tips) {3722my$spec=shift@merges;3723next unless$merge_tipand$excluded{$merge_tip};37243725my$ranges=$ranges{$merge_tip};37263727# check out 'new' tips3728my$merge_base;3729eval{3730$merge_base= command_oneline(3731"merge-base",3732@$parents,$merge_tip,3733);3734};3735if($@) {3736die"An error occurred during merge-base"3737unless$@->isa("Git::Error::Command");37383739warn"W: Cannot find common ancestor between ".3740"@$parentsand$merge_tip. Ignoring merge info.\n";3741next;3742}37433744# double check that there are no missing non-merge commits3745my(@incomplete) = check_cherry_pick(3746$merge_base,$merge_tip,3747$parents,3748@$ranges,3749);37503751if(@incomplete) {3752warn"W:svn cherry-pick ignored ($spec) - missing "3753.@incomplete." commit(s) (eg$incomplete[0])\n";3754}else{3755warn3756"Found merge parent (svn:mergeinfo prop): ",3757$merge_tip,"\n";3758push@new_parents,$merge_tip;3759}3760}37613762# cater for merges which merge commits from multiple branches3763if(@new_parents>1) {3764for(my$i=0;$i<=$#new_parents;$i++) {3765for(my$j=0;$j<=$#new_parents;$j++) {3766next if$i==$j;3767next unless$new_parents[$i];3768next unless$new_parents[$j];3769my$revs= command_oneline(3770"rev-list","-1",3771"$new_parents[$i]..$new_parents[$j]",3772);3773if( !$revs) {3774undef($new_parents[$j]);3775}3776}3777}3778}3779push@$parents,grep{defined}@new_parents;3780}37813782sub make_log_entry {3783my($self,$rev,$parents,$ed) =@_;3784my$untracked=$self->get_untracked($ed);37853786my@parents=@$parents;3787my$ps=$ed->{path_strip} ||"";3788formy$path(grep{m/$ps/} %{$ed->{dir_prop}} ) {3789my$props=$ed->{dir_prop}{$path};3790if($props->{"svk:merge"} ) {3791$self->find_extra_svk_parents3792($ed,$props->{"svk:merge"}, \@parents);3793}3794if($props->{"svn:mergeinfo"} ) {3795$self->find_extra_svn_parents3796($ed,3797$props->{"svn:mergeinfo"},3798 \@parents);3799}3800}38013802open my$un,'>>',"$self->{dir}/unhandled.log"or croak $!;3803print$un"r$rev\n"or croak $!;3804print$un $_,"\n"foreach@$untracked;3805my%log_entry= ( parents => \@parents, revision =>$rev,3806log=>'');38073808my$headrev;3809my$logged=delete$self->{logged_rev_props};3810if(!$logged||$self->{-want_revprops}) {3811my$rp=$self->ra->rev_proplist($rev);3812foreach(sort keys%$rp) {3813my$v=$rp->{$_};3814if(/^svn:(author|date|log)$/) {3815$log_entry{$1} =$v;3816}elsif($_eq'svm:headrev') {3817$headrev=$v;3818}else{3819print$un" rev_prop: ", uri_encode($_),' ',3820 uri_encode($v),"\n";3821}3822}3823}else{3824map{$log_entry{$_} =$logged->{$_} }keys%$logged;3825}3826close$unor croak $!;38273828$log_entry{date} = parse_svn_date($log_entry{date});3829$log_entry{log} .="\n";3830my$author=$log_entry{author} = check_author($log_entry{author});3831my($name,$email) =defined$::users{$author} ? @{$::users{$author}}3832: ($author,undef);38333834my($commit_name,$commit_email) = ($name,$email);3835if($_use_log_author) {3836my$name_field;3837if($log_entry{log} =~/From:\s+(.*\S)\s*\n/i) {3838$name_field=$1;3839}elsif($log_entry{log} =~/Signed-off-by:\s+(.*\S)\s*\n/i) {3840$name_field=$1;3841}3842if(!defined$name_field) {3843if(!defined$email) {3844$email=$name;3845}3846}elsif($name_field=~/(.*?)\s+<(.*)>/) {3847($name,$email) = ($1,$2);3848}elsif($name_field=~/(.*)@/) {3849($name,$email) = ($1,$name_field);3850}else{3851($name,$email) = ($name_field,$name_field);3852}3853}3854if(defined$headrev&&$self->use_svm_props) {3855if($self->rewrite_root) {3856die"Can't have both 'useSvmProps' and 'rewriteRoot' ",3857"options set!\n";3858}3859if($self->rewrite_uuid) {3860die"Can't have both 'useSvmProps' and 'rewriteUUID' ",3861"options set!\n";3862}3863my($uuid,$r) =$headrev=~m{^([a-f\d\-]{30,}):(\d+)$}i;3864# we don't want "SVM: initializing mirror for junk" ...3865returnundefif$r==0;3866my$svm=$self->svm;3867if($uuidne$svm->{uuid}) {3868die"UUID mismatch on SVM path:\n",3869"expected:$svm->{uuid}\n",3870" got:$uuid\n";3871}3872my$full_url=$self->full_url;3873$full_url=~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or3874die"Failed to replace '$svm->{replace}' with ",3875"'$svm->{source}' in$full_url\n";3876# throw away username for storing in records3877 remove_username($full_url);3878$log_entry{metadata} ="$full_url\@$r$uuid";3879$log_entry{svm_revision} =$r;3880$email||="$author\@$uuid";3881$commit_email||="$author\@$uuid";3882}elsif($self->use_svnsync_props) {3883my$full_url=$self->svnsync->{url};3884$full_url.="/$self->{path}"iflength$self->{path};3885 remove_username($full_url);3886my$uuid=$self->svnsync->{uuid};3887$log_entry{metadata} ="$full_url\@$rev$uuid";3888$email||="$author\@$uuid";3889$commit_email||="$author\@$uuid";3890}else{3891my$url=$self->metadata_url;3892 remove_username($url);3893my$uuid=$self->rewrite_uuid||$self->ra->get_uuid;3894$log_entry{metadata} ="$url\@$rev".$uuid;3895$email||="$author\@".$uuid;3896$commit_email||="$author\@".$uuid;3897}3898$log_entry{name} =$name;3899$log_entry{email} =$email;3900$log_entry{commit_name} =$commit_name;3901$log_entry{commit_email} =$commit_email;3902 \%log_entry;3903}39043905sub fetch {3906my($self,$min_rev,$max_rev,@parents) =@_;3907my($last_rev,$last_commit) =$self->last_rev_commit;3908my($base,$head) =$self->get_fetch_range($min_rev,$max_rev);3909$self->ra->gs_fetch_loop_common($base,$head, [$self]);3910}39113912sub set_tree_cb {3913my($self,$log_entry,$tree,$rev,$date,$author) =@_;3914$self->{inject_parents} = {$rev=>$tree};3915$self->fetch(undef,undef);3916}39173918sub set_tree {3919my($self,$tree) = (shift,shift);3920my$log_entry= ::get_commit_entry($tree);3921unless($self->{last_rev}) {3922::fatal("Must have an existing revision to commit");3923}3924my%ed_opts= ( r =>$self->{last_rev},3925log=>$log_entry->{log},3926 ra =>$self->ra,3927 tree_a =>$self->{last_commit},3928 tree_b =>$tree,3929 editor_cb =>sub{3930$self->set_tree_cb($log_entry,$tree,@_) },3931 svn_path =>$self->{path} );3932if(!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {3933print"No changes\nr$self->{last_rev} =$tree\n";3934}3935}39363937sub rebuild_from_rev_db {3938my($self,$path) =@_;3939my$r= -1;3940open my$fh,'<',$pathor croak "open:$!";3941binmode$fhor croak "binmode:$!";3942while(<$fh>) {3943length($_) ==41or croak "inconsistent size in ($_) != 41";3944chomp($_);3945++$r;3946next if$_eq('0' x 40);3947$self->rev_map_set($r,$_);3948print"r$r=$_\n";3949}3950close$fhor croak "close:$!";3951unlink$pathor croak "unlink:$!";3952}39533954sub rebuild {3955my($self) =@_;3956my$map_path=$self->map_path;3957my$partial= (-e $map_path&& ! -z $map_path);3958return unless::verify_ref($self->refname.'^0');3959if(!$partial&& ($self->use_svm_props||$self->no_metadata)) {3960my$rev_db=$self->rev_db_path;3961$self->rebuild_from_rev_db($rev_db);3962if($self->use_svm_props) {3963my$svm_rev_db=$self->rev_db_path($self->svm_uuid);3964$self->rebuild_from_rev_db($svm_rev_db);3965}3966$self->unlink_rev_db_symlink;3967return;3968}3969print"Rebuilding$map_path...\n"if(!$partial);3970my($base_rev,$head) = ($partial?$self->rev_map_max_norebuild(1) :3971(undef,undef));3972my($log,$ctx) =3973 command_output_pipe(qw/rev-list --pretty=raw --reverse/,3974($head?"$head..":"") .$self->refname,3975'--');3976my$metadata_url=$self->metadata_url;3977 remove_username($metadata_url);3978my$svn_uuid=$self->rewrite_uuid||$self->ra_uuid;3979my$c;3980while(<$log>) {3981if(m{^commit ($::sha1)$}) {3982$c=$1;3983next;3984}3985next unlesss{^\s*(git-svn-id:)}{$1};3986my($url,$rev,$uuid) = ::extract_metadata($_);3987 remove_username($url);39883989# ignore merges (from set-tree)3990next if(!defined$rev|| !$uuid);39913992# if we merged or otherwise started elsewhere, this is3993# how we break out of it3994if(($uuidne$svn_uuid) ||3995($metadata_url&&$url&& ($urlne$metadata_url))) {3996next;3997}3998if($partial&&$head) {3999print"Partial-rebuilding$map_path...\n";4000print"Currently at$base_rev=$head\n";4001$head=undef;4002}40034004$self->rev_map_set($rev,$c);4005print"r$rev=$c\n";4006}4007 command_close_pipe($log,$ctx);4008print"Done rebuilding$map_path\n"if(!$partial|| !$head);4009my$rev_db_path=$self->rev_db_path;4010if(-f $self->rev_db_path) {4011unlink$self->rev_db_pathor croak "unlink:$!";4012}4013$self->unlink_rev_db_symlink;4014}40154016# rev_map:4017# Tie::File seems to be prone to offset errors if revisions get sparse,4018# it's not that fast, either. Tie::File is also not in Perl 5.6. So4019# one of my favorite modules is out :< Next up would be one of the DBM4020# modules, but I'm not sure which is most portable...4021#4022# This is the replacement for the rev_db format, which was too big4023# and inefficient for large repositories with a lot of sparse history4024# (mainly tags)4025#4026# The format is this:4027# - 24 bytes for every record,4028# * 4 bytes for the integer representing an SVN revision number4029# * 20 bytes representing the sha1 of a git commit4030# - No empty padding records like the old format4031# (except the last record, which can be overwritten)4032# - new records are written append-only since SVN revision numbers4033# increase monotonically4034# - lookups on SVN revision number are done via a binary search4035# - Piping the file to xxd -c24 is a good way of dumping it for4036# viewing or editing (piped back through xxd -r), should the need4037# ever arise.4038# - The last record can be padding revision with an all-zero sha14039# This is used to optimize fetch performance when using multiple4040# "fetch" directives in .git/config4041#4042# These files are disposable unless noMetadata or useSvmProps is set40434044sub _rev_map_set {4045my($fh,$rev,$commit) =@_;40464047binmode$fhor croak "binmode:$!";4048my$size= (stat($fh))[7];4049($size%24) ==0or croak "inconsistent size:$size";40504051my$wr_offset=0;4052if($size>0) {4053sysseek($fh, -24, SEEK_END)or croak "seek:$!";4054my$read=sysread($fh,my$buf,24)or croak "read:$!";4055$read==24or croak "read only$readbytes (!= 24)";4056my($last_rev,$last_commit) =unpack(rev_map_fmt,$buf);4057if($last_commiteq('0' x40)) {4058if($size>=48) {4059sysseek($fh, -48, SEEK_END)or croak "seek:$!";4060$read=sysread($fh,$buf,24)or4061 croak "read:$!";4062$read==24or4063 croak "read only$readbytes (!= 24)";4064($last_rev,$last_commit) =4065unpack(rev_map_fmt,$buf);4066if($last_commiteq('0' x40)) {4067 croak "inconsistent .rev_map\n";4068}4069}4070if($last_rev>=$rev) {4071 croak "last_rev is higher!:$last_rev>=$rev";4072}4073$wr_offset= -24;4074}4075}4076sysseek($fh,$wr_offset, SEEK_END)or croak "seek:$!";4077syswrite($fh,pack(rev_map_fmt,$rev,$commit),24) ==24or4078 croak "write:$!";4079}40804081sub _rev_map_reset {4082my($fh,$rev,$commit) =@_;4083my$c= _rev_map_get($fh,$rev);4084$ceq$commitor die"_rev_map_reset(@_) commit$cdoes not match!\n";4085my$offset=sysseek($fh,0, SEEK_CUR)or croak "seek:$!";4086truncate$fh,$offsetor croak "truncate:$!";4087}40884089sub mkfile {4090my($path) =@_;4091unless(-e $path) {4092my($dir,$base) = ($path=~ m#^(.*?)/?([^/]+)$#);4093 mkpath([$dir])unless-d $dir;4094open my$fh,'>>',$pathor die"Couldn't create$path:$!\n";4095close$fhor die"Couldn't close (create)$path:$!\n";4096}4097}40984099sub rev_map_set {4100my($self,$rev,$commit,$update_ref,$uuid) =@_;4101defined$commitor die"missing arg3\n";4102length$commit==40or die"arg3 must be a full SHA1 hexsum\n";4103my$db=$self->map_path($uuid);4104my$db_lock="$db.lock";4105my$sigmask;4106$update_ref||=0;4107if($update_ref) {4108$sigmask= POSIX::SigSet->new();4109my$signew= POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,4110 SIGALRM, SIGUSR1, SIGUSR2);4111 sigprocmask(SIG_BLOCK,$signew,$sigmask)or4112 croak "Can't block signals:$!";4113}4114 mkfile($db);41154116$LOCKFILES{$db_lock} =1;4117my$sync;4118# both of these options make our .rev_db file very, very important4119# and we can't afford to lose it because rebuild() won't work4120if($self->use_svm_props||$self->no_metadata) {4121$sync=1;4122 copy($db,$db_lock)or die"rev_map_set(@_): ",4123"Failed to copy: ",4124"$db=>$db_lock($!)\n";4125}else{4126rename$db,$db_lockor die"rev_map_set(@_): ",4127"Failed to rename: ",4128"$db=>$db_lock($!)\n";4129}41304131sysopen(my$fh,$db_lock, O_RDWR | O_CREAT)4132or croak "Couldn't open$db_lock:$!\n";4133$update_refeq'reset'? _rev_map_reset($fh,$rev,$commit) :4134 _rev_map_set($fh,$rev,$commit);4135if($sync) {4136$fh->flushor die"Couldn't flush$db_lock:$!\n";4137$fh->syncor die"Couldn't sync$db_lock:$!\n";4138}4139close$fhor croak $!;4140if($update_ref) {4141$_head=$self;4142my$note="";4143$note=" ($update_ref)"if($update_ref!~/^\d*$/);4144 command_noisy('update-ref','-m',"r$rev$note",4145$self->refname,$commit);4146}4147rename$db_lock,$dbor die"rev_map_set(@_): ","Failed to rename: ",4148"$db_lock=>$db($!)\n";4149delete$LOCKFILES{$db_lock};4150if($update_ref) {4151 sigprocmask(SIG_SETMASK,$sigmask)or4152 croak "Can't restore signal mask:$!";4153}4154}41554156# If want_commit, this will return an array of (rev, commit) where4157# commit _must_ be a valid commit in the archive.4158# Otherwise, it'll return the max revision (whether or not the4159# commit is valid or just a 0x40 placeholder).4160sub rev_map_max {4161my($self,$want_commit) =@_;4162$self->rebuild;4163my($r,$c) =$self->rev_map_max_norebuild($want_commit);4164$want_commit? ($r,$c) :$r;4165}41664167sub rev_map_max_norebuild {4168my($self,$want_commit) =@_;4169my$map_path=$self->map_path;4170stat$map_pathorreturn$want_commit? (0,undef) :0;4171sysopen(my$fh,$map_path, O_RDONLY)or croak "open:$!";4172binmode$fhor croak "binmode:$!";4173my$size= (stat($fh))[7];4174($size%24) ==0or croak "inconsistent size:$size";41754176if($size==0) {4177close$fhor croak "close:$!";4178return$want_commit? (0,undef) :0;4179}41804181sysseek($fh, -24, SEEK_END)or croak "seek:$!";4182sysread($fh,my$buf,24) ==24or croak "read:$!";4183my($r,$c) =unpack(rev_map_fmt,$buf);4184if($want_commit&&$ceq('0' x40)) {4185if($size<48) {4186return$want_commit? (0,undef) :0;4187}4188sysseek($fh, -48, SEEK_END)or croak "seek:$!";4189sysread($fh,$buf,24) ==24or croak "read:$!";4190($r,$c) =unpack(rev_map_fmt,$buf);4191if($ceq('0'x40)) {4192 croak "Penultimate record is all-zeroes in$map_path";4193}4194}4195close$fhor croak "close:$!";4196$want_commit? ($r,$c) :$r;4197}41984199sub rev_map_get {4200my($self,$rev,$uuid) =@_;4201my$map_path=$self->map_path($uuid);4202returnundefunless-e $map_path;42034204sysopen(my$fh,$map_path, O_RDONLY)or croak "open:$!";4205my$c= _rev_map_get($fh,$rev);4206close($fh)or croak "close:$!";4207$c4208}42094210sub _rev_map_get {4211my($fh,$rev) =@_;42124213binmode$fhor croak "binmode:$!";4214my$size= (stat($fh))[7];4215($size%24) ==0or croak "inconsistent size:$size";42164217if($size==0) {4218returnundef;4219}42204221my($l,$u) = (0,$size-24);4222my($r,$c,$buf);42234224while($l<=$u) {4225my$i=int(($l/24+$u/24) /2) *24;4226sysseek($fh,$i, SEEK_SET)or croak "seek:$!";4227sysread($fh,my$buf,24) ==24or croak "read:$!";4228my($r,$c) =unpack(rev_map_fmt,$buf);42294230if($r<$rev) {4231$l=$i+24;4232}elsif($r>$rev) {4233$u=$i-24;4234}else{# $r == $rev4235return$ceq('0' x 40) ?undef:$c;4236}4237}4238undef;4239}42404241# Finds the first svn revision that exists on (if $eq_ok is true) or4242# before $rev for the current branch. It will not search any lower4243# than $min_rev. Returns the git commit hash and svn revision number4244# if found, else (undef, undef).4245sub find_rev_before {4246my($self,$rev,$eq_ok,$min_rev) =@_;4247--$revunless$eq_ok;4248$min_rev||=1;4249my$max_rev=$self->rev_map_max;4250$rev=$max_revif($rev>$max_rev);4251while($rev>=$min_rev) {4252if(my$c=$self->rev_map_get($rev)) {4253return($rev,$c);4254}4255--$rev;4256}4257return(undef,undef);4258}42594260# Finds the first svn revision that exists on (if $eq_ok is true) or4261# after $rev for the current branch. It will not search any higher4262# than $max_rev. Returns the git commit hash and svn revision number4263# if found, else (undef, undef).4264sub find_rev_after {4265my($self,$rev,$eq_ok,$max_rev) =@_;4266++$revunless$eq_ok;4267$max_rev||=$self->rev_map_max;4268while($rev<=$max_rev) {4269if(my$c=$self->rev_map_get($rev)) {4270return($rev,$c);4271}4272++$rev;4273}4274return(undef,undef);4275}42764277sub _new {4278my($class,$repo_id,$ref_id,$path) =@_;4279unless(defined$repo_id&&length$repo_id) {4280$repo_id=$Git::SVN::default_repo_id;4281}4282unless(defined$ref_id&&length$ref_id) {4283$_prefix=''unlessdefined($_prefix);4284$_[2] =$ref_id=4285"refs/remotes/$_prefix$Git::SVN::default_ref_id";4286}4287$_[1] =$repo_id;4288my$dir="$ENV{GIT_DIR}/svn/$ref_id";42894290# Older repos imported by us used $GIT_DIR/svn/foo instead of4291# $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo4292if($ref_id=~m{^refs/remotes/(.*)}) {4293my$old_dir="$ENV{GIT_DIR}/svn/$1";4294if(-d $old_dir&& ! -d $dir) {4295$dir=$old_dir;4296}4297}42984299$_[3] =$path=''unless(defined$path);4300 mkpath([$dir]);4301bless{4302 ref_id =>$ref_id, dir =>$dir,index=>"$dir/index",4303 path =>$path, config =>"$ENV{GIT_DIR}/svn/config",4304 map_root =>"$dir/.rev_map", repo_id =>$repo_id},$class;4305}43064307# for read-only access of old .rev_db formats4308sub unlink_rev_db_symlink {4309my($self) =@_;4310my$link=$self->rev_db_path;4311$link=~s/\.[\w-]+$//or croak "missing UUID at the end of$link";4312if(-l $link) {4313unlink$linkor croak "unlink:$linkfailed!";4314}4315}43164317sub rev_db_path {4318my($self,$uuid) =@_;4319my$db_path=$self->map_path($uuid);4320$db_path=~s{/\.rev_map\.}{/\.rev_db\.}4321or croak "map_path:$db_pathdoes not contain '/.rev_map.' !";4322$db_path;4323}43244325# the new replacement for .rev_db4326sub map_path {4327my($self,$uuid) =@_;4328$uuid||=$self->ra_uuid;4329"$self->{map_root}.$uuid";4330}43314332sub uri_encode {4333my($f) =@_;4334$f=~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;4335$f4336}43374338sub uri_decode {4339my($f) =@_;4340$f=~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;4341$f4342}43434344sub remove_username {4345$_[0] =~s{^([^:]*://)[^@]+@}{$1};4346}43474348package Git::SVN::Log;4349use strict;4350use warnings;4351use POSIX qw/strftime/;4352useconstant commit_log_separator => ('-' x 72) ."\n";4353use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline4354%rusers $show_commit $incremental/;4355my$l_fmt;43564357sub cmt_showable {4358my($c) =@_;4359return1ifdefined$c->{r};43604361# big commit message got truncated by the 16k pretty buffer in rev-list4362if($c->{l} &&$c->{l}->[-1]eq"...\n"&&4363$c->{a_raw} =~/\@([a-f\d\-]+)>$/) {4364@{$c->{l}} = ();4365my@log= command(qw/cat-file commit/,$c->{c});43664367# shift off the headers4368shift@logwhile($log[0]ne'');4369shift@log;43704371# TODO: make $c->{l} not have a trailing newline in the future4372@{$c->{l}} =map{"$_\n"}grep!/^git-svn-id: /,@log;43734374(undef,$c->{r},undef) = ::extract_metadata(4375(grep(/^git-svn-id: /,@log))[-1]);4376}4377returndefined$c->{r};4378}43794380sub log_use_color {4381return$color|| Git->repository->get_colorbool('color.diff');4382}43834384sub git_svn_log_cmd {4385my($r_min,$r_max,@args) =@_;4386my$head='HEAD';4387my(@files,@log_opts);4388foreachmy$x(@args) {4389if($xeq'--'||@files) {4390push@files,$x;4391}else{4392if(::verify_ref("$x^0")) {4393$head=$x;4394}else{4395push@log_opts,$x;4396}4397}4398}43994400my($url,$rev,$uuid,$gs) = ::working_head_info($head);4401$gs||= Git::SVN->_new;4402my@cmd= (qw/log --abbrev-commit --pretty=raw --default/,4403$gs->refname);4404push@cmd,'-r'unless$non_recursive;4405push@cmd, qw/--raw --name-status/if$verbose;4406push@cmd,'--color'if log_use_color();4407push@cmd,@log_opts;4408if(defined$r_max&&$r_max==$r_min) {4409push@cmd,'--max-count=1';4410if(my$c=$gs->rev_map_get($r_max)) {4411push@cmd,$c;4412}4413}elsif(defined$r_max) {4414if($r_max<$r_min) {4415($r_min,$r_max) = ($r_max,$r_min);4416}4417my(undef,$c_max) =$gs->find_rev_before($r_max,1,$r_min);4418my(undef,$c_min) =$gs->find_rev_after($r_min,1,$r_max);4419# If there are no commits in the range, both $c_max and $c_min4420# will be undefined. If there is at least 1 commit in the4421# range, both will be defined.4422return()if!defined$c_min|| !defined$c_max;4423if($c_mineq$c_max) {4424push@cmd,'--max-count=1',$c_min;4425}else{4426push@cmd,'--boundary',"$c_min..$c_max";4427}4428}4429return(@cmd,@files);4430}44314432# adapted from pager.c4433sub config_pager {4434if(! -t *STDOUT) {4435$ENV{GIT_PAGER_IN_USE} ='false';4436$pager=undef;4437return;4438}4439chomp($pager= command_oneline(qw(var GIT_PAGER)));4440if($pagereq'cat') {4441$pager=undef;4442}4443$ENV{GIT_PAGER_IN_USE} =defined($pager);4444}44454446sub run_pager {4447return unlessdefined$pager;4448pipe my($rfd,$wfd)orreturn;4449defined(my$pid=fork)or::fatal "Can't fork:$!";4450if(!$pid) {4451open STDOUT,'>&',$wfdor4452::fatal "Can't redirect to stdout:$!";4453return;4454}4455open STDIN,'<&',$rfdor::fatal "Can't redirect stdin:$!";4456$ENV{LESS} ||='FRSX';4457exec$pageror::fatal "Can't run pager:$!($pager)";4458}44594460sub format_svn_date {4461my$t=shift||time;4462my$gmoff= Git::SVN::get_tz($t);4463return strftime("%Y-%m-%d%H:%M:%S$gmoff(%a,%d%b%Y)",localtime($t));4464}44654466sub parse_git_date {4467my($t,$tz) =@_;4468# Date::Parse isn't in the standard Perl distro :(4469if($tz=~s/^\+//) {4470$t+= tz_to_s_offset($tz);4471}elsif($tz=~s/^\-//) {4472$t-= tz_to_s_offset($tz);4473}4474return$t;4475}44764477sub set_local_timezone {4478if(defined$TZ) {4479$ENV{TZ} =$TZ;4480}else{4481delete$ENV{TZ};4482}4483}44844485sub tz_to_s_offset {4486my($tz) =@_;4487$tz=~s/(\d\d)$//;4488return($1*60) + ($tz*3600);4489}44904491sub get_author_info {4492my($dest,$author,$t,$tz) =@_;4493$author=~s/(?:^\s*|\s*$)//g;4494$dest->{a_raw} =$author;4495my$au;4496if($::_authors) {4497$au=$rusers{$author} ||undef;4498}4499if(!$au) {4500($au) = ($author=~/<([^>]+)\@[^>]+>$/);4501}4502$dest->{t} =$t;4503$dest->{tz} =$tz;4504$dest->{a} =$au;4505$dest->{t_utc} = parse_git_date($t,$tz);4506}45074508sub process_commit {4509my($c,$r_min,$r_max,$defer) =@_;4510if(defined$r_min&&defined$r_max) {4511if($r_min==$c->{r} &&$r_min==$r_max) {4512 show_commit($c);4513return0;4514}4515return1if$r_min==$r_max;4516if($r_min<$r_max) {4517# we need to reverse the print order4518return0if(defined$limit&& --$limit<0);4519push@$defer,$c;4520return1;4521}4522if($r_min!=$r_max) {4523return1if($r_min<$c->{r});4524return1if($r_max>$c->{r});4525}4526}4527return0if(defined$limit&& --$limit<0);4528 show_commit($c);4529return1;4530}45314532sub show_commit {4533my$c=shift;4534if($oneline) {4535my$x="\n";4536if(my$l=$c->{l}) {4537while($l->[0] =~/^\s*$/) {shift@$l}4538$x=$l->[0];4539}4540$l_fmt||='A'.length($c->{r});4541print'r',pack($l_fmt,$c->{r}),' | ';4542print"$c->{c} | "if$show_commit;4543print$x;4544}else{4545 show_commit_normal($c);4546}4547}45484549sub show_commit_changed_paths {4550my($c) =@_;4551return unless$c->{changed};4552print"Changed paths:\n", @{$c->{changed}};4553}45544555sub show_commit_normal {4556my($c) =@_;4557print commit_log_separator,"r$c->{r} | ";4558print"$c->{c} | "if$show_commit;4559print"$c->{a} | ", format_svn_date($c->{t_utc}),' | ';4560my$nr_line=0;45614562if(my$l=$c->{l}) {4563while($l->[$#$l]eq"\n"&&$#$l>04564&&$l->[($#$l-1)]eq"\n") {4565pop@$l;4566}4567$nr_line=scalar@$l;4568if(!$nr_line) {4569print"1 line\n\n\n";4570}else{4571if($nr_line==1) {4572$nr_line='1 line';4573}else{4574$nr_line.=' lines';4575}4576print$nr_line,"\n";4577 show_commit_changed_paths($c);4578print"\n";4579print$_foreach@$l;4580}4581}else{4582print"1 line\n";4583 show_commit_changed_paths($c);4584print"\n";45854586}4587foreachmy$x(qw/raw stat diff/) {4588if($c->{$x}) {4589print"\n";4590print$_foreach@{$c->{$x}}4591}4592}4593}45944595sub cmd_show_log {4596my(@args) =@_;4597my($r_min,$r_max);4598my$r_last= -1;# prevent dupes4599 set_local_timezone();4600if(defined$::_revision) {4601if($::_revision =~/^(\d+):(\d+)$/) {4602($r_min,$r_max) = ($1,$2);4603}elsif($::_revision =~/^\d+$/) {4604$r_min=$r_max= $::_revision;4605}else{4606::fatal "-r$::_revision is not supported, use ",4607"standard 'git log' arguments instead";4608}4609}46104611 config_pager();4612@args= git_svn_log_cmd($r_min,$r_max,@args);4613if(!@args) {4614print commit_log_separator unless$incremental||$oneline;4615return;4616}4617my$log= command_output_pipe(@args);4618 run_pager();4619my(@k,$c,$d,$stat);4620my$esc_color=qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;4621while(<$log>) {4622if(/^${esc_color}commit (?:- )?($::sha1_short)/o) {4623my$cmt=$1;4624if($c&& cmt_showable($c) &&$c->{r} !=$r_last) {4625$r_last=$c->{r};4626 process_commit($c,$r_min,$r_max, \@k)or4627goto out;4628}4629$d=undef;4630$c= { c =>$cmt};4631}elsif(/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {4632 get_author_info($c,$1,$2,$3);4633}elsif(/^${esc_color}(?:tree|parent|committer) /o) {4634# ignore4635}elsif(/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {4636push@{$c->{raw}},$_;4637}elsif(/^${esc_color}[ACRMDT]\t/) {4638# we could add $SVN->{svn_path} here, but that requires4639# remote access at the moment (repo_path_split)...4640 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;4641push@{$c->{changed}},$_;4642}elsif(/^${esc_color}diff /o) {4643$d=1;4644push@{$c->{diff}},$_;4645}elsif($d) {4646push@{$c->{diff}},$_;4647}elsif(/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*4648$esc_color*[\+\-]*$esc_color$/x) {4649$stat=1;4650push@{$c->{stat}},$_;4651}elsif($stat&&/^ \d+ files changed, \d+ insertions/) {4652push@{$c->{stat}},$_;4653$stat=undef;4654}elsif(/^${esc_color} (git-svn-id:.+)$/o) {4655($c->{url},$c->{r},undef) = ::extract_metadata($1);4656}elsif(s/^${esc_color} //o) {4657push@{$c->{l}},$_;4658}4659}4660if($c&&defined$c->{r} &&$c->{r} !=$r_last) {4661$r_last=$c->{r};4662 process_commit($c,$r_min,$r_max, \@k);4663}4664if(@k) {4665($r_min,$r_max) = ($r_max,$r_min);4666 process_commit($_,$r_min,$r_max)foreachreverse@k;4667}4668out:4669close$log;4670print commit_log_separator unless$incremental||$oneline;4671}46724673sub cmd_blame {4674my$path=pop;46754676 config_pager();4677 run_pager();46784679my($fh,$ctx,$rev);46804681if($_git_format) {4682($fh,$ctx) = command_output_pipe('blame',@_,$path);4683while(my$line= <$fh>) {4684if($line=~/^\^?([[:xdigit:]]+)\s/) {4685# Uncommitted edits show up as a rev ID of4686# all zeros, which we can't look up with4687# cmt_metadata4688if($1!~/^0+$/) {4689(undef,$rev,undef) =4690::cmt_metadata($1);4691$rev='0'if(!$rev);4692}else{4693$rev='0';4694}4695$rev=sprintf('%-10s',$rev);4696$line=~s/^\^?[[:xdigit:]]+(\s)/$rev$1/;4697}4698print$line;4699}4700}else{4701($fh,$ctx) = command_output_pipe('blame','-p',@_,'HEAD',4702'--',$path);4703my($sha1);4704my%authors;4705my@buffer;4706my%dsha;#distinct sha keys47074708while(my$line= <$fh>) {4709push@buffer,$line;4710if($line=~/^([[:xdigit:]]{40})\s\d+\s\d+/) {4711$dsha{$1} =1;4712}4713}47144715my$s2r= ::cmt_sha2rev_batch([keys%dsha]);47164717foreachmy$line(@buffer) {4718if($line=~/^([[:xdigit:]]{40})\s\d+\s\d+/) {4719$rev=$s2r->{$1};4720$rev='0'if(!$rev)4721}4722elsif($line=~/^author (.*)/) {4723$authors{$rev} =$1;4724$authors{$rev} =~s/\s/_/g;4725}4726elsif($line=~/^\t(.*)$/) {4727printf("%6s%10s%s\n",$rev,$authors{$rev},$1);4728}4729}4730}4731 command_close_pipe($fh,$ctx);4732}47334734package Git::SVN::Migration;4735# these version numbers do NOT correspond to actual version numbers4736# of git nor git-svn. They are just relative.4737#4738# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD4739#4740# v1 layout: .git/$id/info/url, refs/remotes/$id4741#4742# v2 layout: .git/svn/$id/info/url, refs/remotes/$id4743#4744# v3 layout: .git/svn/$id, refs/remotes/$id4745# - info/url may remain for backwards compatibility4746# - this is what we migrate up to this layout automatically,4747# - this will be used by git svn init on single branches4748# v3.1 layout (auto migrated):4749# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink4750# for backwards compatibility4751#4752# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id4753# - this is only created for newly multi-init-ed4754# repositories. Similar in spirit to the4755# --use-separate-remotes option in git-clone (now default)4756# - we do not automatically migrate to this (following4757# the example set by core git)4758#4759# v5 layout: .rev_db.$UUID => .rev_map.$UUID4760# - newer, more-efficient format that uses 24-bytes per record4761# with no filler space.4762# - use xxd -c24 < .rev_map.$UUID to view and debug4763# - This is a one-way migration, repositories updated to the4764# new format will not be able to use old git-svn without4765# rebuilding the .rev_db. Rebuilding the rev_db is not4766# possible if noMetadata or useSvmProps are set; but should4767# be no problem for users that use the (sensible) defaults.4768use strict;4769use warnings;4770use Carp qw/croak/;4771use File::Path qw/mkpath/;4772use File::Basename qw/dirname basename/;4773use vars qw/$_minimize/;47744775sub migrate_from_v0 {4776my$git_dir=$ENV{GIT_DIR};4777returnundefunless-d $git_dir;4778my($fh,$ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);4779my$migrated=0;4780while(<$fh>) {4781chomp;4782my($id,$orig_ref) = ($_,$_);4783next unless$id=~ s#^refs/heads/(.+)-HEAD$#$1#;4784next unless-f "$git_dir/$id/info/url";4785my$new_ref="refs/remotes/$id";4786if(::verify_ref("$new_ref^0")) {4787print STDERR "W:$orig_refis probably an old ",4788"branch used by an ancient version of ",4789"git-svn.\n",4790"However,$new_refalso exists.\n",4791"We will not be able ",4792"to use this branch until this ",4793"ambiguity is resolved.\n";4794next;4795}4796print STDERR "Migrating from v0 layout...\n"if!$migrated;4797print STDERR "Renaming ref:$orig_ref=>$new_ref\n";4798 command_noisy('update-ref',$new_ref,$orig_ref);4799 command_noisy('update-ref','-d',$orig_ref,$orig_ref);4800$migrated++;4801}4802 command_close_pipe($fh,$ctx);4803print STDERR "Done migrating from v0 layout...\n"if$migrated;4804$migrated;4805}48064807sub migrate_from_v1 {4808my$git_dir=$ENV{GIT_DIR};4809my$migrated=0;4810return$migratedunless-d $git_dir;4811my$svn_dir="$git_dir/svn";48124813# just in case somebody used 'svn' as their $id at some point...4814return$migratedif-d $svn_dir&& ! -f "$svn_dir/info/url";48154816print STDERR "Migrating from a git-svn v1 layout...\n";4817 mkpath([$svn_dir]);4818print STDERR "Data from a previous version of git-svn exists, but\n\t",4819"$svn_dir\n\t(required for this version ",4820"($::VERSION) of git-svn) does not exist.\n";4821my($fh,$ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);4822while(<$fh>) {4823my$x=$_;4824next unless$x=~ s#^refs/remotes/##;4825chomp$x;4826next unless-f "$git_dir/$x/info/url";4827my$u=eval{ ::file_to_s("$git_dir/$x/info/url") };4828next unless$u;4829my$dn= dirname("$git_dir/svn/$x");4830 mkpath([$dn])unless-d $dn;4831if($xeq'svn') {# they used 'svn' as GIT_SVN_ID:4832 mkpath(["$git_dir/svn/svn"]);4833print STDERR " -$git_dir/$x/info=> ",4834"$git_dir/svn/$x/info\n";4835rename"$git_dir/$x/info","$git_dir/svn/$x/info"or4836 croak "$!:$x";4837# don't worry too much about these, they probably4838# don't exist with repos this old (save for index,4839# and we can easily regenerate that)4840foreachmy$f(qw/unhandled.log index .rev_db/) {4841rename"$git_dir/$x/$f","$git_dir/svn/$x/$f";4842}4843}else{4844print STDERR " -$git_dir/$x=>$git_dir/svn/$x\n";4845rename"$git_dir/$x","$git_dir/svn/$x"or4846 croak "$!:$x";4847}4848$migrated++;4849}4850 command_close_pipe($fh,$ctx);4851print STDERR "Done migrating from a git-svn v1 layout\n";4852$migrated;4853}48544855sub read_old_urls {4856my($l_map,$pfx,$path) =@_;4857my@dir;4858foreach(<$path/*>) {4859if(-r "$_/info/url") {4860$pfx.='/'if$pfx&&$pfx!~ m!/$!;4861my$ref_id=$pfx. basename $_;4862my$url= ::file_to_s("$_/info/url");4863$l_map->{$ref_id} =$url;4864}elsif(-d $_) {4865push@dir,$_;4866}4867}4868foreach(@dir) {4869my$x=$_;4870$x=~s!^\Q$ENV{GIT_DIR}\E/svn/!!o;4871 read_old_urls($l_map,$x,$_);4872}4873}48744875sub migrate_from_v2 {4876my@cfg= command(qw/config -l/);4877return ifgrep/^svn-remote\..+\.url=/,@cfg;4878my%l_map;4879 read_old_urls(\%l_map,'',"$ENV{GIT_DIR}/svn");4880my$migrated=0;48814882foreachmy$ref_id(sort keys%l_map) {4883eval{ Git::SVN->init($l_map{$ref_id},'',undef,$ref_id) };4884if($@) {4885 Git::SVN->init($l_map{$ref_id},'',$ref_id,$ref_id);4886}4887$migrated++;4888}4889$migrated;4890}48914892sub minimize_connections {4893my$r= Git::SVN::read_all_remotes();4894my$new_urls= {};4895my$root_repos= {};4896foreachmy$repo_id(keys%$r) {4897my$url=$r->{$repo_id}->{url}ornext;4898my$fetch=$r->{$repo_id}->{fetch}ornext;4899my$ra= Git::SVN::Ra->new($url);49004901# skip existing cases where we already connect to the root4902if(($ra->{url}eq$ra->{repos_root}) ||4903($ra->{repos_root}eq$repo_id)) {4904$root_repos->{$ra->{url}} =$repo_id;4905next;4906}49074908my$root_ra= Git::SVN::Ra->new($ra->{repos_root});4909my$root_path=$ra->{url};4910$root_path=~ s#^\Q$ra->{repos_root}\E(/|$)##;4911foreachmy$path(keys%$fetch) {4912my$ref_id=$fetch->{$path};4913my$gs= Git::SVN->new($ref_id,$repo_id,$path);49144915# make sure we can read when connecting to4916# a higher level of a repository4917my($last_rev,undef) =$gs->last_rev_commit;4918if(!defined$last_rev) {4919$last_rev=eval{4920$root_ra->get_latest_revnum;4921};4922next if$@;4923}4924my$new=$root_path;4925$new.=length$path?"/$path":'';4926eval{4927$root_ra->get_log([$new],$last_rev,$last_rev,49280,0,1,sub{ });4929};4930next if$@;4931$new_urls->{$ra->{repos_root}}->{$new} =4932{ ref_id =>$ref_id,4933 old_repo_id =>$repo_id,4934 old_path =>$path};4935}4936}49374938my@emptied;4939foreachmy$url(keys%$new_urls) {4940# see if we can re-use an existing [svn-remote "repo_id"]4941# instead of creating a(n ugly) new section:4942my$repo_id=$root_repos->{$url} ||$url;49434944my$fetch=$new_urls->{$url};4945foreachmy$path(keys%$fetch) {4946my$x=$fetch->{$path};4947 Git::SVN->init($url,$path,$repo_id,$x->{ref_id});4948my$pfx="svn-remote.$x->{old_repo_id}";49494950my$old_fetch=quotemeta("$x->{old_path}:".4951"$x->{ref_id}");4952 command_noisy(qw/config --unset/,4953"$pfx.fetch",'^'.$old_fetch.'$');4954delete$r->{$x->{old_repo_id}}->4955{fetch}->{$x->{old_path}};4956if(!keys%{$r->{$x->{old_repo_id}}->{fetch}}) {4957 command_noisy(qw/config --unset/,4958"$pfx.url");4959push@emptied,$x->{old_repo_id}4960}4961}4962}4963if(@emptied) {4964my$file=$ENV{GIT_CONFIG} ||"$ENV{GIT_DIR}/config";4965print STDERR <<EOF;4966The following [svn-remote] sections in your config file ($file) are empty4967and can be safely removed:4968EOF4969print STDERR "[svn-remote\"$_\"]\n"foreach@emptied;4970}4971}49724973sub migration_check {4974 migrate_from_v0();4975 migrate_from_v1();4976 migrate_from_v2();4977 minimize_connections()if$_minimize;4978}49794980package Git::IndexInfo;4981use strict;4982use warnings;4983use Git qw/command_input_pipe command_close_pipe/;49844985sub new {4986my($class) =@_;4987my($gui,$ctx) = command_input_pipe(qw/update-index -z --index-info/);4988bless{ gui =>$gui, ctx =>$ctx, nr =>0},$class;4989}49904991sub remove {4992my($self,$path) =@_;4993if(print{$self->{gui} }'0 ',0 x 40,"\t",$path,"\0") {4994return++$self->{nr};4995}4996undef;4997}49984999sub update {5000my($self,$mode,$hash,$path) =@_;5001if(print{$self->{gui} }$mode,' ',$hash,"\t",$path,"\0") {5002return++$self->{nr};5003}5004undef;5005}50065007sub DESTROY {5008my($self) =@_;5009 command_close_pipe($self->{gui},$self->{ctx});5010}50115012package Git::SVN::GlobSpec;5013use strict;5014use warnings;50155016sub new {5017my($class,$glob,$pattern_ok) =@_;5018my$re=$glob;5019$re=~s!/+$!!g;# no need for trailing slashes5020my(@left,@right,@patterns);5021my$state="left";5022my$die_msg="Only one set of wildcard directories ".5023"(e.g. '*' or '*/*/*') is supported: '$glob'\n";5024formy$part(split(m|/|,$glob)) {5025if($part=~/\*/&&$partne"*") {5026die"Invalid pattern in '$glob':$part\n";5027}elsif($pattern_ok&&$part=~/[{}]/&&5028$part!~/^\{[^{}]+\}/) {5029die"Invalid pattern in '$glob':$part\n";5030}5031if($parteq"*") {5032die$die_msgif$stateeq"right";5033$state="pattern";5034push(@patterns,"[^/]*");5035}elsif($pattern_ok&&$part=~/^\{(.*)\}$/) {5036die$die_msgif$stateeq"right";5037$state="pattern";5038my$p=quotemeta($1);5039$p=~s/\\,/|/g;5040push(@patterns,"(?:$p)");5041}else{5042if($stateeq"left") {5043push(@left,$part);5044}else{5045push(@right,$part);5046$state="right";5047}5048}5049}5050my$depth=@patterns;5051if($depth==0) {5052die"One '*' is needed in glob: '$glob'\n";5053}5054my$left=join('/',@left);5055my$right=join('/',@right);5056$re=join('/',@patterns);5057$re=join('\/',5058grep(length,quotemeta($left),"($re)",quotemeta($right)));5059my$left_re=qr/^\/\Q$left\E(\/|$)/;5060bless{ left =>$left, right =>$right, left_regex =>$left_re,5061 regex =>qr/$re/,glob=>$glob, depth =>$depth},$class;5062}50635064sub full_path {5065my($self,$path) =@_;5066return(length$self->{left} ?"$self->{left}/":'') .5067$path. (length$self->{right} ?"/$self->{right}":'');5068}50695070__END__50715072Data structures:507350745075$remotes= {# returned by read_all_remotes()5076'svn'=> {5077# svn-remote.svn.url=https://svn.musicpd.org5078 url =>'https://svn.musicpd.org',5079# svn-remote.svn.fetch=mpd/trunk:trunk5080 fetch => {5081'mpd/trunk'=>'trunk',5082},5083# svn-remote.svn.tags=mpd/tags/*:tags/*5084 tags => {5085 path => {5086 left =>'mpd/tags',5087 right =>'',5088 regex =>qr!mpd/tags/([^/]+)$!,5089glob=>'tags/*',5090},5091ref=> {5092 left =>'tags',5093 right =>'',5094 regex =>qr!tags/([^/]+)$!,5095glob=>'tags/*',5096},5097}5098}5099};51005101$log_entry hashref as returned by libsvn_log_entry()5102{5103log=>'whitespace-formatted log entry5104',# trailing newline is preserved5105 revision =>'8',# integer5106 date =>'2004-02-24T17:01:44.108345Z',# commit date5107 author =>'committer name'5108};510951105111# this is generated by generate_diff();5112@mods= array of diff-index line hashes,each element represents one line5113 of diff-index output51145115diff-index line ($m hash)5116{5117 mode_a => first column of diff-index output,no leading ':',5118 mode_b => second column of diff-index output,5119 sha1_b => sha1sum of the final blob,5120 chg => change type [MCRADT],5121 file_a => original file name of a file (iff chg is'C'or'R')5122 file_b => new/current file name of a file (any chg)5123}5124;51255126# retval of read_url_paths{,_all}();5127$l_map= {5128# repository root url5129'https://svn.musicpd.org'=> {5130# repository path # GIT_SVN_ID5131'mpd/trunk'=>'trunk',5132'mpd/tags/0.11.5'=>'tags/0.11.5',5133},5134}51355136Notes:5137 I don't trust the each() function on unless I created%hashmyself5138 because the internal iterator may not have started at base.