2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
48 # import functions from Git into our packages, en masse
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
56 *{"${package}::$_"} = \&{"Git::$_"};
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file, $_branch_dest,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
95 my ($_trunk, @_tags, @_branches, $_stdlayout);
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
99 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'destination|d=s' => \$_branch_dest,
145 'dry-run|n' => \$_dry_run,
146 'tag|t' => \$_tag } ],
147 tag => [ sub { $_tag = 1; cmd_branch(@_) },
148 'Create a tag in the SVN repository',
149 { 'message|m=s' => \$_message,
150 'destination|d=s' => \$_branch_dest,
151 'dry-run|n' => \$_dry_run } ],
152 'set-tree' => [ \&cmd_set_tree,
153 "Set an SVN repository to a git tree-ish",
154 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
155 'create-ignore' => [ \&cmd_create_ignore,
156 'Create a .gitignore per svn:ignore',
157 { 'revision|r=i' => \$_revision
159 'propget' => [ \&cmd_propget,
160 'Print the value of a property on a file or directory',
161 { 'revision|r=i' => \$_revision } ],
162 'proplist' => [ \&cmd_proplist,
163 'List all properties of a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
166 { 'revision|r=i' => \$_revision
168 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
169 { 'revision|r=i' => \$_revision
171 'multi-fetch' => [ \&cmd_multi_fetch,
172 "Deprecated alias for $0 fetch --all",
173 { 'revision|r=s' => \$_revision, %fc_opts } ],
174 'migrate' => [ sub { },
175 # no-op, we automatically run this anyways,
176 'Migrate configuration/metadata/layout from
177 previous versions of git-svn',
178 { 'minimize' => \$Git::SVN::Migration::_minimize,
180 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
181 { 'limit=i' => \$Git::SVN::Log::limit,
182 'revision|r=s' => \$_revision,
183 'verbose|v' => \$Git::SVN::Log::verbose,
184 'incremental' => \$Git::SVN::Log::incremental,
185 'oneline' => \$Git::SVN::Log::oneline,
186 'show-commit' => \$Git::SVN::Log::show_commit,
187 'non-recursive' => \$Git::SVN::Log::non_recursive,
188 'authors-file|A=s' => \$_authors,
189 'color' => \$Git::SVN::Log::color,
190 'pager=s' => \$Git::SVN::Log::pager
192 'find-rev' => [ \&cmd_find_rev,
193 "Translate between SVN revision numbers and tree-ish",
195 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
196 { 'merge|m|M' => \$_merge,
197 'verbose|v' => \$_verbose,
198 'strategy|s=s' => \$_strategy,
199 'local|l' => \$_local,
200 'fetch-all|all' => \$_fetch_all,
201 'dry-run|n' => \$_dry_run,
203 'commit-diff' => [ \&cmd_commit_diff,
204 'Commit a diff between two trees',
205 { 'message|m=s' => \$_message,
206 'file|F=s' => \$_file,
207 'revision|r=s' => \$_revision,
209 'info' => [ \&cmd_info,
210 "Show info about the latest SVN revision
211 on the current branch",
212 { 'url' => \$_url, } ],
213 'blame' => [ \&Git::SVN::Log::cmd_blame,
214 "Show what revision and author last modified each line of a file",
215 { 'git-format' => \$_git_format } ],
216 'reset' => [ \&cmd_reset,
217 "Undo fetches back to the specified SVN revision",
218 { 'revision|r=s' => \$_revision,
219 'parent|p' => \$_fetch_parent } ],
223 for (my $i = 0; $i < @ARGV; $i++) {
224 if (defined $cmd{$ARGV[$i]}) {
228 } elsif ($ARGV[$i] eq 'help') {
234 # make sure we're always running at the top-level working directory
235 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
236 unless (-d $ENV{GIT_DIR}) {
237 if ($git_dir_user_set) {
238 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
239 "but it is not a directory\n";
241 my $git_dir = delete $ENV{GIT_DIR};
244 $cdup = command_oneline(qw/rev-parse --show-cdup/);
245 $git_dir = '.' unless ($cdup);
246 chomp $cdup if ($cdup);
247 $cdup = "." unless ($cdup && length $cdup);
248 } "Already at toplevel, but $git_dir not found\n";
249 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
250 unless (-d $git_dir) {
251 die "$git_dir still not found after going to ",
254 $ENV{GIT_DIR} = $git_dir;
256 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
259 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
261 read_repo_config(\%opts);
262 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
263 Getopt::Long::Configure('pass_through');
265 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
266 'minimize-connections' => \$Git::SVN::Migration::_minimize,
267 'id|i=s' => \$Git::SVN::default_ref_id,
268 'svn-remote|remote|R=s' => sub {
269 $Git::SVN::no_reuse_existing = 1;
270 $Git::SVN::default_repo_id = $_[1] });
271 exit 1 if (!$rv && $cmd && $cmd ne 'log');
274 version() if $_version;
275 usage(1) unless defined $cmd;
276 load_authors() if $_authors;
277 if (defined $_authors_prog) {
278 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
281 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
282 Git::SVN::Migration::migration_check();
284 Git::SVN::init_vars();
286 Git::SVN::verify_remotes_sanity();
287 $cmd{$cmd}->[0]->(@ARGV);
290 post_fetch_checkout();
293 ####################### primary functions ######################
295 my $exit = shift || 0;
296 my $fd = $exit ? \*STDERR : \*STDOUT;
298 git-svn - bidirectional operations between a single Subversion tree and git
299 Usage: git svn <command> [options] [arguments]\n
301 print $fd "Available commands:\n" unless $cmd;
303 foreach (sort keys %cmd) {
304 next if $cmd && $cmd ne $_;
305 next if /^multi-/; # don't show deprecated commands
306 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
307 foreach (sort keys %{$cmd{$_}->[2]}) {
308 # mixed-case options are for .git/config only
309 next if /[A-Z]/ && /^[a-z]+$/i;
310 # prints out arguments as they should be passed:
311 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
312 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
314 split /\|/,$_)," $x\n";
318 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
319 arbitrary identifier if you're tracking multiple SVN branches/repositories in
320 one git repository and want to keep them separate. See git-svn(1) for more
327 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
332 unless (-d $ENV{GIT_DIR}) {
333 my @init_db = ('init');
334 push @init_db, "--template=$_template" if defined $_template;
335 if (defined $_shared) {
336 if ($_shared =~ /[a-z]/) {
337 push @init_db, "--shared=$_shared";
339 push @init_db, "--shared";
342 command_noisy(@init_db);
343 $_repository = Git->repository(Repository => ".git");
345 command_noisy('config', 'core.autocrlf', 'false');
347 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
348 foreach my $i (keys %icv) {
349 die "'$set' and '$i' cannot both be set\n" if $set;
350 next unless defined $icv{$i};
351 command_noisy('config', "$pfx.$i", $icv{$i});
354 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
355 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
356 if defined $$ignore_regex;
360 my $repo_path = shift or return;
361 mkpath([$repo_path]) unless -d $repo_path;
362 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
363 $ENV{GIT_DIR} = '.git';
364 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
368 my ($url, $path) = @_;
369 if (!defined $path &&
370 (defined $_trunk || @_branches || @_tags ||
371 defined $_stdlayout) &&
372 $url !~ m#^[a-z\+]+://#) {
375 $path = basename($url) if !defined $path || !length $path;
376 cmd_init($url, $path);
377 Git::SVN::fetch_all($Git::SVN::default_repo_id);
378 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
382 if (defined $_stdlayout) {
383 $_trunk = 'trunk' if (!defined $_trunk);
384 @_tags = 'tags' if (! @_tags);
385 @_branches = 'branches' if (! @_branches);
387 if (defined $_trunk || @_branches || @_tags) {
388 return cmd_multi_init(@_);
390 my $url = shift or die "SVN repository location required ",
391 "as a command-line argument\n";
395 Git::SVN->init($url);
399 if (grep /^\d+=./, @_) {
400 die "'<rev>=<commit>' fetch arguments are ",
401 "no longer supported.\n";
405 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
407 if ($_fetch_parent) {
408 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
410 die "Unable to determine upstream SVN information from ",
411 "working tree history\n";
413 # just fetch, don't checkout.
414 $_no_checkout = 'true';
415 $_fetch_all ? $gs->fetch_all : $gs->fetch;
416 } elsif ($_fetch_all) {
419 $remote ||= $Git::SVN::default_repo_id;
420 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
426 if ($_stdin || !@commits) {
427 print "Reading from stdin...\n";
430 if (/\b($sha1_short)\b/o) {
431 unshift @commits, $1;
436 foreach my $c (@commits) {
437 my @tmp = command('rev-parse',$c);
438 if (scalar @tmp == 1) {
440 } elsif (scalar @tmp > 1) {
441 push @revs, reverse(command('rev-list',@tmp));
443 fatal "Failed to rev-parse $c";
446 my $gs = Git::SVN->new;
447 my ($r_last, $cmt_last) = $gs->last_rev_commit;
449 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
450 fatal "There are new revisions that were fetched ",
451 "and need to be merged (or acknowledged) ",
452 "before committing.\nlast rev: $r_last\n",
453 " current: $gs->{last_rev}";
455 $gs->set_tree($_) foreach @revs;
456 print "Done committing ",scalar @revs," revisions to SVN\n";
462 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
463 'Cannot dcommit with a dirty index. Commit your changes first, '
464 . "or stash them with `git stash'.\n";
468 if ($head ne 'HEAD') {
470 command_oneline([qw/symbolic-ref -q HEAD/])
473 $old_head =~ s{^refs/heads/}{};
475 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
477 command(['checkout', $head], STDERR => 0);
481 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
483 die "Unable to determine upstream SVN information from ",
484 "$head history.\nPerhaps the repository is empty.";
487 if (defined $_commit_url) {
490 $url = eval { command_oneline('config', '--get',
491 "svn-remote.$gs->{repo_id}.commiturl") };
497 my $last_rev = $_revision if defined $_revision;
499 print "Committing to $url ...\n";
501 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
502 if ($_no_rebase && scalar(@$linear_refs) > 1) {
503 warn "Attempting to commit more than one change while ",
504 "--no-rebase is enabled.\n",
505 "If these changes depend on each other, re-running ",
506 "without --no-rebase may be required."
508 my $expect_url = $url;
509 Git::SVN::remove_username($expect_url);
511 my $d = shift @$linear_refs or last;
512 unless (defined $last_rev) {
513 (undef, $last_rev, undef) = cmt_metadata("$d~1");
514 unless (defined $last_rev) {
515 fatal "Unable to extract revision information ",
520 print "diff-tree $d~1 $d\n";
523 my %ed_opts = ( r => $last_rev,
524 log => get_commit_entry($d)->{log},
525 ra => Git::SVN::Ra->new($url),
526 config => SVN::Core::config_get_config(
527 $Git::SVN::Ra::config_dir
532 print "Committed r$_[0]\n";
536 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
537 print "No changes\n$d~1 == $d\n";
538 } elsif ($parents->{$d} && @{$parents->{$d}}) {
539 $gs->{inject_parents_dcommit}->{$cmt_rev} =
542 $_fetch_all ? $gs->fetch_all : $gs->fetch;
543 $last_rev = $cmt_rev;
546 # we always want to rebase against the current HEAD,
547 # not any head that was passed to us
548 my @diff = command('diff-tree', $d,
552 @finish = rebase_cmd();
553 print STDERR "W: $d and ", $gs->refname,
554 " differ, using @finish:\n",
555 join("\n", @diff), "\n";
557 print "No changes between current HEAD and ",
559 "\nResetting to the latest ",
561 @finish = qw/reset --mixed/;
563 command_noisy(@finish, $gs->refname);
566 my ($url_, $rev_, $uuid_, $gs_) =
567 working_head_info('HEAD', \@refs);
568 my ($linear_refs_, $parents_) =
569 linearize_history($gs_, \@refs);
570 if (scalar(@$linear_refs) !=
571 scalar(@$linear_refs_)) {
572 fatal "# of revisions changed ",
574 join("\n", @$linear_refs),
576 join("\n", @$linear_refs_), "\n",
577 'If you are attempting to commit ',
578 "merges, try running:\n\t",
579 'git rebase --interactive',
580 '--preserve-merges ',
582 "\nBefore dcommitting";
584 if ($url_ ne $expect_url) {
585 fatal "URL mismatch after rebase: ",
586 "$url_ != $expect_url";
588 if ($uuid_ ne $uuid) {
589 fatal "uuid mismatch after rebase: ",
594 for ($i = 0; $i < scalar @$linear_refs; $i++) {
595 my $new = $linear_refs_->[$i] or next;
597 $parents->{$linear_refs->[$i]};
607 my $new_head = command_oneline(qw/rev-parse HEAD/);
608 my $new_is_symbolic = eval {
609 command_oneline(qw/symbolic-ref -q HEAD/);
611 if ($new_is_symbolic) {
612 print "dcommitted the branch ", $head, "\n";
614 print "dcommitted on a detached HEAD because you gave ",
615 "a revision argument.\n",
616 "The rewritten commit is: ", $new_head, "\n";
618 command(['checkout', $old_head], STDERR => 0);
625 my ($branch_name, $head) = @_;
627 unless (defined $branch_name && length $branch_name) {
628 die(($_tag ? "tag" : "branch") . " name required\n");
632 my ($src, $rev, undef, $gs) = working_head_info($head);
634 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
635 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
637 if ($#{$allglobs} == 0) {
638 $glob = $allglobs->[0];
640 unless(defined $_branch_dest) {
642 $_tag ? "tag" : "branch",
643 " paths defined for Subversion repository.\n",
644 "You must specify where you want to create the ",
645 $_tag ? "tag" : "branch",
646 " with the --destination argument.\n";
648 foreach my $g (@{$allglobs}) {
649 if ($_branch_dest eq $g->{path}->{left}) {
654 unless (defined $glob) {
656 $_tag ? "tag" : "branch",
657 " destination $_branch_dest\n";
660 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
661 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
663 my $ctx = SVN::Client->new(
664 auth => Git::SVN::Ra::_auth_providers(),
666 ${ $_[0] } = defined $_message
668 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
674 $ctx->ls($dst, 'HEAD', 0);
675 } and die "branch ${branch_name} already exists\n";
677 print "Copying ${src} at r${rev} to ${dst}...\n";
678 $ctx->copy($src, $rev, $dst)
685 my $revision_or_hash = shift or die "SVN or git revision required ",
686 "as a command-line argument\n";
688 if ($revision_or_hash =~ /^r\d+$/) {
692 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
694 die "Unable to determine upstream SVN information from ",
697 my $desired_revision = substr($revision_or_hash, 1);
698 $result = $gs->rev_map_get($desired_revision, $uuid);
700 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
703 print "$result\n" if $result;
707 command_noisy(qw/update-index --refresh/);
708 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
710 die "Unable to determine upstream SVN information from ",
711 "working tree history\n";
714 print "Remote Branch: " . $gs->refname . "\n";
715 print "SVN URL: " . $url . "\n";
718 if (command(qw/diff-index HEAD --/)) {
719 print STDERR "Cannot rebase with uncommited changes:\n";
720 command_noisy('status');
724 # rebase will checkout for us, so no need to do it explicitly
725 $_no_checkout = 'true';
726 $_fetch_all ? $gs->fetch_all : $gs->fetch;
728 command_noisy(rebase_cmd(), $gs->refname);
731 sub cmd_show_ignore {
732 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
733 $gs ||= Git::SVN->new;
734 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
735 $gs->prop_walk($gs->{path}, $r, sub {
736 my ($gs, $path, $props) = @_;
737 print STDOUT "\n# $path\n";
738 my $s = $props->{'svn:ignore'} or return;
739 $s =~ s/[\r\n]+/\n/g;
746 sub cmd_show_externals {
747 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
748 $gs ||= Git::SVN->new;
749 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
750 $gs->prop_walk($gs->{path}, $r, sub {
751 my ($gs, $path, $props) = @_;
752 print STDOUT "\n# $path\n";
753 my $s = $props->{'svn:externals'} or return;
754 $s =~ s/[\r\n]+/\n/g;
761 sub cmd_create_ignore {
762 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
763 $gs ||= Git::SVN->new;
764 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
765 $gs->prop_walk($gs->{path}, $r, sub {
766 my ($gs, $path, $props) = @_;
767 # $path is of the form /path/to/dir/
769 # SVN can have attributes on empty directories,
770 # which git won't track
771 mkpath([$path]) unless -d $path;
772 my $ignore = $path . '.gitignore';
773 my $s = $props->{'svn:ignore'} or return;
774 open(GITIGNORE, '>', $ignore)
775 or fatal("Failed to open `$ignore' for writing: $!");
776 $s =~ s/[\r\n]+/\n/g;
778 # Prefix all patterns so that the ignore doesn't apply
779 # to sub-directories.
781 print GITIGNORE "$s\n";
783 or fatal("Failed to close `$ignore': $!");
784 command_noisy('add', '-f', $ignore);
788 sub canonicalize_path {
790 my $dot_slash_added = 0;
791 if (substr($path, 0, 1) ne "/") {
792 $path = "./" . $path;
793 $dot_slash_added = 1;
795 # File::Spec->canonpath doesn't collapse x/../y into y (for a
796 # good reason), so let's do this manually.
798 $path =~ s#/\.(?:/|$)#/#g;
799 $path =~ s#/[^/]+/\.\.##g;
801 $path =~ s#^\./## if $dot_slash_added;
809 # Helper for cmd_propget and cmd_proplist below.
812 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
813 $gs ||= Git::SVN->new;
815 # prefix THE PATH by the sub-directory from which the user
817 $path = $cmd_dir_prefix . $path;
818 fatal("No such file or directory: $path") unless -e $path;
819 my $is_dir = -d $path ? 1 : 0;
820 $path = $gs->{path} . '/' . $path;
822 # canonicalize the path (otherwise libsvn will abort or fail to
824 $path = canonicalize_path($path);
826 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
829 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
832 (undef, $props) = $gs->ra->get_file($path, $r, undef);
837 # cmd_propget (PROP, PATH)
838 # ------------------------
839 # Print the SVN property PROP for PATH.
841 my ($prop, $path) = @_;
842 $path = '.' if not defined $path;
843 usage(1) if not defined $prop;
844 my $props = get_svnprops($path);
845 if (not defined $props->{$prop}) {
846 fatal("`$path' does not have a `$prop' SVN property.");
848 print $props->{$prop} . "\n";
851 # cmd_proplist (PATH)
852 # -------------------
853 # Print the list of SVN properties for PATH.
856 $path = '.' if not defined $path;
857 my $props = get_svnprops($path);
858 print "Properties on '$path':\n";
859 foreach (sort keys %{$props}) {
866 unless (defined $_trunk || @_branches || @_tags) {
870 # there are currently some bugs that prevent multi-init/multi-fetch
871 # setups from working well without this.
872 $Git::SVN::_minimize_url = 1;
874 $_prefix = '' unless defined $_prefix;
880 if (defined $_trunk) {
881 my $trunk_ref = $_prefix . 'trunk';
882 # try both old-style and new-style lookups:
883 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
885 my ($trunk_url, $trunk_path) =
886 complete_svn_url($url, $_trunk);
887 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
891 return unless @_branches || @_tags;
892 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
893 foreach my $path (@_branches) {
894 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
896 foreach my $path (@_tags) {
897 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
901 sub cmd_multi_fetch {
902 my $remotes = Git::SVN::read_all_remotes();
903 foreach my $repo_id (sort keys %$remotes) {
904 if ($remotes->{$repo_id}->{url}) {
905 Git::SVN::fetch_all($repo_id, $remotes);
910 # this command is special because it requires no metadata
911 sub cmd_commit_diff {
912 my ($ta, $tb, $url) = @_;
913 my $usage = "Usage: $0 commit-diff -r<revision> ".
914 "<tree-ish> <tree-ish> [<URL>]";
915 fatal($usage) if (!defined $ta || !defined $tb);
918 my $gs = eval { Git::SVN->new };
920 fatal("Needed URL or usable git-svn --id in ",
921 "the command-line\n", $usage);
924 $svn_path = $gs->{path};
926 unless (defined $_revision) {
927 fatal("-r|--revision is a required argument\n", $usage);
929 if (defined $_message && defined $_file) {
930 fatal("Both --message/-m and --file/-F specified ",
931 "for the commit message.\n",
932 "I have no idea what you mean");
934 if (defined $_file) {
935 $_message = file_to_s($_file);
937 $_message ||= get_commit_entry($tb)->{log};
939 my $ra ||= Git::SVN::Ra->new($url);
942 $r = $ra->get_latest_revnum;
943 } elsif ($r !~ /^\d+$/) {
944 die "revision argument: $r not understood by git-svn\n";
946 my %ed_opts = ( r => $r,
951 editor_cb => sub { print "Committed r$_[0]\n" },
952 svn_path => $svn_path );
953 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
954 print "No changes\n$ta == $tb\n";
958 sub escape_uri_only {
961 foreach (split m{/}, $uri) {
962 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
970 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
971 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
972 $url = "$scheme://$domain$uri";
978 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
979 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
981 die "Too many arguments specified\n";
984 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
986 if (!$file_type && !$diff_status) {
987 print STDERR "svn: '$path' is not under version control\n";
991 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
993 die "Unable to determine upstream SVN information from ",
994 "working tree history\n";
997 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
998 $path = "." if $path eq "";
1000 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1003 print escape_url($full_url), "\n";
1007 my $result = "Path: $path\n";
1008 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1009 $result .= "URL: " . escape_url($full_url) . "\n";
1012 my $repos_root = $gs->repos_root;
1013 Git::SVN::remove_username($repos_root);
1014 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1017 $result .= "Repository Root: (offline)\n";
1019 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1020 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1021 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1023 $result .= "Node Kind: " .
1024 ($file_type eq "dir" ? "directory" : "file") . "\n";
1026 my $schedule = $diff_status eq "A"
1028 : ($diff_status eq "D" ? "delete" : "normal");
1029 $result .= "Schedule: $schedule\n";
1031 if ($diff_status eq "A") {
1032 print $result, "\n";
1036 my ($lc_author, $lc_rev, $lc_date_utc);
1037 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1038 my $log = command_output_pipe(@args);
1039 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1041 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1043 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1044 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1045 (undef, $lc_rev, undef) = ::extract_metadata($1);
1050 Git::SVN::Log::set_local_timezone();
1052 $result .= "Last Changed Author: $lc_author\n";
1053 $result .= "Last Changed Rev: $lc_rev\n";
1054 $result .= "Last Changed Date: " .
1055 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1057 if ($file_type ne "dir") {
1058 my $text_last_updated_date =
1059 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1061 "Text Last Updated: " .
1062 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1065 if ($diff_status eq "D") {
1067 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1068 if ($file_type eq "link") {
1069 my $file_name = <$fh>;
1070 $checksum = md5sum("link $file_name");
1072 $checksum = md5sum($fh);
1074 command_close_pipe($fh, $ctx);
1075 } elsif ($file_type eq "link") {
1077 command(qw(cat-file blob), "HEAD:$path");
1079 md5sum("link " . $file_name);
1081 open FILE, "<", $path or die $!;
1082 $checksum = md5sum(\*FILE);
1083 close FILE or die $!;
1085 $result .= "Checksum: " . $checksum . "\n";
1088 print $result, "\n";
1092 my $target = shift || $_revision or die "SVN revision required\n";
1093 $target = $1 if $target =~ /^r(\d+)$/;
1094 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1095 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1097 die "Unable to determine upstream SVN information from ".
1100 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1101 $gs->rev_map_set($r, $c, 'reset', $uuid);
1102 print "r$r = $c ($gs->{ref_id})\n";
1105 ########################### utility functions #########################
1108 my @cmd = qw/rebase/;
1109 push @cmd, '-v' if $_verbose;
1110 push @cmd, qw/--merge/ if $_merge;
1111 push @cmd, "--strategy=$_strategy" if $_strategy;
1115 sub post_fetch_checkout {
1116 return if $_no_checkout;
1117 my $gs = $Git::SVN::_head or return;
1118 return if verify_ref('refs/heads/master^0');
1120 my $valid_head = verify_ref('HEAD^0');
1121 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1122 return if ($valid_head || !verify_ref('HEAD^0'));
1124 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1125 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1126 return if -f $index;
1128 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1129 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1130 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1131 print STDERR "Checked out HEAD:\n ",
1132 $gs->full_url, " r", $gs->last_rev, "\n";
1135 sub complete_svn_url {
1136 my ($url, $path) = @_;
1138 if ($path !~ m#^[a-z\+]+://#) {
1139 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1140 fatal("E: '$path' is not a complete URL ",
1141 "and a separate URL is not specified");
1143 return ($url, $path);
1148 sub complete_url_ls_init {
1149 my ($ra, $repo_path, $switch, $pfx) = @_;
1150 unless ($repo_path) {
1151 print STDERR "W: $switch not specified\n";
1154 $repo_path =~ s#/+$##;
1155 if ($repo_path =~ m#^[a-z\+]+://#) {
1156 $ra = Git::SVN::Ra->new($repo_path);
1159 $repo_path =~ s#^/+##;
1161 fatal("E: '$repo_path' is not a complete URL ",
1162 "and a separate URL is not specified");
1165 my $url = $ra->{url};
1166 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1167 my $k = "svn-remote.$gs->{repo_id}.url";
1168 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1169 if ($orig_url && ($orig_url ne $gs->{url})) {
1170 die "$k already set: $orig_url\n",
1171 "wanted to set to: $gs->{url}\n";
1173 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1174 my $remote_path = "$ra->{svn_path}/$repo_path";
1175 $remote_path =~ s#/+#/#g;
1176 $remote_path =~ s#^/##g;
1177 $remote_path .= "/*" if $remote_path !~ /\*/;
1178 my ($n) = ($switch =~ /^--(\w+)/);
1179 if (length $pfx && $pfx !~ m#/$#) {
1180 die "--prefix='$pfx' must have a trailing slash '/'\n";
1182 command_noisy('config',
1184 "svn-remote.$gs->{repo_id}.$n",
1185 "$remote_path:refs/remotes/$pfx*" .
1186 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1191 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1192 { STDERR => 0 }); };
1195 sub get_tree_from_treeish {
1197 # $treeish can be a symbolic ref, too:
1198 my $type = command_oneline(qw/cat-file -t/, $treeish);
1200 while ($type eq 'tag') {
1201 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1203 if ($type eq 'commit') {
1204 $expected = (grep /^tree /, command(qw/cat-file commit/,
1206 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1207 die "Unable to get tree from $treeish\n" unless $expected;
1208 } elsif ($type eq 'tree') {
1209 $expected = $treeish;
1211 die "$treeish is a $type, expected tree, tag or commit\n";
1216 sub get_commit_entry {
1217 my ($treeish) = shift;
1218 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1219 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1220 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1221 open my $log_fh, '>', $commit_editmsg or croak $!;
1223 my $type = command_oneline(qw/cat-file -t/, $treeish);
1224 if ($type eq 'commit' || $type eq 'tag') {
1225 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1233 $in_msg = 1 if (/^\s*$/);
1234 $author = $1 if (/^author (.*>)/);
1235 } elsif (/^git-svn-id: /) {
1236 # skip this for now, we regenerate the
1237 # correct one on re-fetch anyways
1238 # TODO: set *:merge properties or like...
1240 if (/^From:/ || /^Signed-off-by:/) {
1246 $msgbuf =~ s/\s+$//s;
1247 if ($Git::SVN::_add_author_from && defined($author)
1249 $msgbuf .= "\n\nFrom: $author";
1251 print $log_fh $msgbuf or croak $!;
1252 command_close_pipe($msg_fh, $ctx);
1254 close $log_fh or croak $!;
1256 if ($_edit || ($type eq 'tree')) {
1257 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1258 # TODO: strip out spaces, comments, like git-commit.sh
1259 system($editor, $commit_editmsg);
1261 rename $commit_editmsg, $commit_msg or croak $!;
1264 # SVN requires messages to be UTF-8 when entering the repo
1266 open $log_fh, '<', $commit_msg or croak $!;
1268 chomp($log_entry{log} = <$log_fh>);
1270 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1271 my $msg = $log_entry{log};
1273 eval { $msg = Encode::decode($enc, $msg, 1) };
1275 die "Could not decode as $enc:\n", $msg,
1276 "\nPerhaps you need to set i18n.commitencoding\n";
1279 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1280 die "Could not encode as UTF-8:\n$msg\n" if $@;
1282 $log_entry{log} = $msg;
1284 close $log_fh or croak $!;
1291 my ($str, $file, $mode) = @_;
1292 open my $fd,'>',$file or croak $!;
1293 print $fd $str,"\n" or croak $!;
1294 close $fd or croak $!;
1295 chmod ($mode &~ umask, $file) if (defined $mode);
1300 open my $fd,'<',$file or croak "$!: file: $file\n";
1303 close $fd or croak $!;
1308 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1310 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1311 my $log = $cmd eq 'log';
1312 while (<$authors>) {
1314 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1315 my ($user, $name, $email) = ($1, $2, $3);
1317 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1319 $users{$user} = [$name, $email];
1322 close $authors or croak $!;
1325 # convert GetOpt::Long specs for use by git-config
1326 sub read_repo_config {
1327 return unless -d $ENV{GIT_DIR};
1330 foreach my $o (keys %$opts) {
1331 # if we have mixedCase and a long option-only, then
1332 # it's a config-only variable that we don't need for
1334 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1335 my $v = $opts->{$o};
1336 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1338 my $arg = 'git config';
1339 $arg .= ' --int' if ($o =~ /[:=]i$/);
1340 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1341 if (ref $v eq 'ARRAY') {
1342 chomp(my @tmp = `$arg --get-all svn.$key`);
1345 chomp(my $tmp = `$arg --get svn.$key`);
1346 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1351 delete @$opts{@config_only} if @config_only;
1354 sub extract_metadata {
1355 my $id = shift or return (undef, undef, undef);
1356 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1358 if (!defined $rev || !$uuid || !$url) {
1359 # some of the original repositories I made had
1360 # identifiers like this:
1361 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1363 return ($url, $rev, $uuid);
1367 return extract_metadata((grep(/^git-svn-id: /,
1368 command(qw/cat-file commit/, shift)))[-1]);
1371 sub cmt_sha2rev_batch {
1373 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1376 foreach my $sha (@{$list}) {
1379 print $out $sha, "\n";
1381 while (my $line = <$in>) {
1382 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1385 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1389 } elsif ($line =~ /^(git-svn-id: )/) {
1390 my (undef, $rev, undef) =
1391 extract_metadata($line);
1395 $size -= length($line);
1396 last if ($size == 0);
1400 command_close_bidi_pipe($pid, $in, $out, $ctx);
1405 sub working_head_info {
1406 my ($head, $refs) = @_;
1407 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1408 my ($fh, $ctx) = command_output_pipe(@args, $head);
1412 if ( m{^commit ($::sha1)$} ) {
1413 unshift @$refs, $hash if $hash and $refs;
1417 next unless s{^\s*(git-svn-id:)}{$1};
1418 my ($url, $rev, $uuid) = extract_metadata($_);
1419 if (defined $url && defined $rev) {
1420 next if $max{$url} and $max{$url} < $rev;
1421 if (my $gs = Git::SVN->find_by_url($url)) {
1422 my $c = $gs->rev_map_get($rev, $uuid);
1423 if ($c && $c eq $hash) {
1424 close $fh; # break the pipe
1425 return ($url, $rev, $uuid, $gs);
1427 $max{$url} ||= $gs->rev_map_max;
1432 command_close_pipe($fh, $ctx);
1433 (undef, undef, undef, undef);
1436 sub read_commit_parents {
1437 my ($parents, $c) = @_;
1438 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1439 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1440 @{$parents->{$c}} = split(/ /, $p);
1443 sub linearize_history {
1444 my ($gs, $refs) = @_;
1446 foreach my $c (@$refs) {
1447 read_commit_parents(\%parents, $c);
1452 my $last_svn_commit = $gs->last_commit;
1453 foreach my $c (reverse @$refs) {
1454 next if $c eq $last_svn_commit;
1457 unshift @linear_refs, $c;
1460 # we only want the first parent to diff against for linear
1461 # history, we save the rest to inject when we finalize the
1463 my $fp_a = verify_ref("$c~1");
1464 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1465 if (!$fp_a || !$fp_b) {
1467 "has no parent commit, and therefore ",
1468 "nothing to diff against.\n",
1469 "You should be working from a repository ",
1470 "originally created by git-svn\n";
1472 if ($fp_a ne $fp_b) {
1473 die "$c~1 = $fp_a, however parsing commit $c ",
1474 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1477 foreach my $p (@{$parents{$c}}) {
1481 (\@linear_refs, \%parents);
1484 sub find_file_type_and_diff_status {
1486 return ('dir', '') if $path eq '';
1489 command_oneline(qw(diff --cached --name-status --), $path) || "";
1490 my $diff_status = (split(' ', $diff_output))[0] || "";
1492 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1494 return (undef, undef) if !$diff_status && !$ls_tree;
1496 if ($diff_status eq "A") {
1497 return ("link", $diff_status) if -l $path;
1498 return ("dir", $diff_status) if -d $path;
1499 return ("file", $diff_status);
1502 my $mode = (split(' ', $ls_tree))[0] || "";
1504 return ("link", $diff_status) if $mode eq "120000";
1505 return ("dir", $diff_status) if $mode eq "040000";
1506 return ("file", $diff_status);
1512 my $md5 = Digest::MD5->new();
1513 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1514 $md5->addfile($arg) or croak $!;
1515 } elsif ($ref eq 'SCALAR') {
1516 $md5->add($$arg) or croak $!;
1518 $md5->add($arg) or croak $!;
1520 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1522 return $md5->hexdigest();
1528 use Fcntl qw/:DEFAULT :seek/;
1529 use constant rev_map_fmt => 'NH40';
1530 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1531 $_repack $_repack_flags $_use_svm_props $_head
1532 $_use_svnsync_props $no_reuse_existing $_minimize_url
1533 $_use_log_author $_add_author_from $_localtime/;
1535 use File::Path qw/mkpath/;
1536 use File::Copy qw/copy/;
1539 my ($_gc_nr, $_gc_period);
1541 # properties that we do not log:
1544 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1545 svn:special svn:executable
1546 svn:entry:committed-rev
1547 svn:entry:last-author
1549 svn:entry:committed-date/;
1551 # some options are read globally, but can be overridden locally
1552 # per [svn-remote "..."] section. Command-line options will *NOT*
1553 # override options set in an [svn-remote "..."] section
1555 for my $option (qw/follow_parent no_metadata use_svm_props
1556 use_svnsync_props/) {
1559 my $prop = "-$option";
1562 return $self->{$prop} if exists $self->{$prop};
1563 my $k = "svn-remote.$self->{repo_id}.$key";
1564 eval { command_oneline(qw/config --get/, $k) };
1566 $self->{$prop} = ${"Git::SVN::_$option"};
1568 my $v = command_oneline(qw/config --bool/,$k);
1569 $self->{$prop} = $v eq 'false' ? 0 : 1;
1571 return $self->{$prop};
1577 my (%LOCKFILES, %INDEX_FILES);
1579 unlink keys %LOCKFILES if %LOCKFILES;
1580 unlink keys %INDEX_FILES if %INDEX_FILES;
1583 sub resolve_local_globs {
1584 my ($url, $fetch, $glob_spec) = @_;
1585 return unless defined $glob_spec;
1586 my $ref = $glob_spec->{ref};
1587 my $path = $glob_spec->{path};
1588 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1589 next unless m#^refs/remotes/$ref->{regex}$#;
1591 my $pathname = desanitize_refname($path->full_path($p));
1592 my $refname = desanitize_refname($ref->full_path($p));
1593 if (my $existing = $fetch->{$pathname}) {
1594 if ($existing ne $refname) {
1595 die "Refspec conflict:\n",
1596 "existing: refs/remotes/$existing\n",
1597 " globbed: refs/remotes/$refname\n";
1599 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1600 $u =~ s!^\Q$url\E(/|$)!! or die
1601 "refs/remotes/$refname: '$url' not found in '$u'\n";
1602 if ($pathname ne $u) {
1603 warn "W: Refspec glob conflict ",
1604 "(ref: refs/remotes/$refname):\n",
1605 "expected path: $pathname\n",
1607 "Continuing ahead with $u\n";
1611 $fetch->{$pathname} = $refname;
1616 sub parse_revision_argument {
1617 my ($base, $head) = @_;
1618 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1619 return ($base, $head);
1621 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1622 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1623 return ($head, $head) if ($::_revision eq 'HEAD');
1624 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1625 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1626 die "revision argument: $::_revision not understood by git-svn\n";
1630 my ($repo_id, $remotes) = @_;
1634 $repo_id = $gs->{repo_id};
1636 $remotes ||= read_all_remotes();
1637 my $remote = $remotes->{$repo_id} or
1638 die "[svn-remote \"$repo_id\"] unknown\n";
1639 my $fetch = $remote->{fetch};
1640 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1642 my $ra = Git::SVN::Ra->new($url);
1643 my $uuid = $ra->get_uuid;
1644 my $head = $ra->get_latest_revnum;
1645 my $base = defined $fetch ? $head : 0;
1647 # read the max revs for wildcard expansion (branches/*, tags/*)
1648 foreach my $t (qw/branches tags/) {
1649 defined $remote->{$t} or next;
1650 push @globs, @{$remote->{$t}};
1652 my $max_rev = eval { tmp_config(qw/--int --get/,
1653 "svn-remote.$repo_id.${t}-maxRev") };
1654 if (defined $max_rev && ($max_rev < $base)) {
1656 } elsif (!defined $max_rev) {
1662 foreach my $p (sort keys %$fetch) {
1663 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1664 my $lr = $gs->rev_map_max;
1666 $base = $lr if ($lr < $base);
1672 ($base, $head) = parse_revision_argument($base, $head);
1673 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1676 sub read_all_remotes {
1678 my $use_svm_props = eval { command_oneline(qw/config --bool
1679 svn.useSvmProps/) };
1680 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1681 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1682 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1683 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1684 die("svn-remote.$remote: remote ref '$_remote_ref' "
1685 . "must start with 'refs/remotes/'\n")
1686 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1687 my $remote_ref = $1;
1688 $local_ref =~ s{^/}{};
1689 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1690 $r->{$remote}->{svm} = {} if $use_svm_props;
1691 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1692 $r->{$1}->{svm} = {};
1693 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1694 $r->{$1}->{url} = $2;
1695 } elsif (m!^(.+)\.(branches|tags)=
1696 (.*):refs/remotes/(.+)\s*$/!x) {
1697 my ($p, $g) = ($3, $4);
1701 path => Git::SVN::GlobSpec->new($p),
1702 ref => Git::SVN::GlobSpec->new($g) };
1703 if (length($rs->{ref}->{right}) != 0) {
1704 die "The '*' glob character must be the last ",
1705 "character of '$g'\n";
1707 push @{ $r->{$1}->{$2} }, $rs;
1712 if (defined $r->{$_}->{svm}) {
1715 my $section = "svn-remote.$_";
1717 source => tmp_config('--get',
1718 "$section.svm-source"),
1719 replace => tmp_config('--get',
1720 "$section.svm-replace"),
1723 $r->{$_}->{svm} = $svm;
1731 $_gc_nr = $_gc_period = 1000;
1732 if (defined $_repack || defined $_repack_flags) {
1733 warn "Repack options are obsolete; they have no effect.\n";
1737 sub verify_remotes_sanity {
1738 return unless -d $ENV{GIT_DIR};
1740 foreach (command(qw/config -l/)) {
1741 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1743 die "Remote ref refs/remote/$1 is tracked by",
1744 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1745 "Please resolve this ambiguity in ",
1746 "your git configuration file before ",
1754 sub find_existing_remote {
1755 my ($url, $remotes) = @_;
1756 return undef if $no_reuse_existing;
1758 foreach my $repo_id (keys %$remotes) {
1759 my $u = $remotes->{$repo_id}->{url} or next;
1761 $existing = $repo_id;
1767 sub init_remote_config {
1768 my ($self, $url, $no_write) = @_;
1769 $url =~ s!/+$!!; # strip trailing slash
1770 my $r = read_all_remotes();
1771 my $existing = find_existing_remote($url, $r);
1773 unless ($no_write) {
1774 print STDERR "Using existing ",
1775 "[svn-remote \"$existing\"]\n";
1777 $self->{repo_id} = $existing;
1778 } elsif ($_minimize_url) {
1779 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1780 $existing = find_existing_remote($min_url, $r);
1782 unless ($no_write) {
1783 print STDERR "Using existing ",
1784 "[svn-remote \"$existing\"]\n";
1786 $self->{repo_id} = $existing;
1788 if ($min_url ne $url) {
1789 unless ($no_write) {
1790 print STDERR "Using higher level of URL: ",
1791 "$url => $min_url\n";
1793 my $old_path = $self->{path};
1794 $self->{path} = $url;
1795 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1796 if (length $old_path) {
1797 $self->{path} .= "/$old_path";
1804 # verify that we aren't overwriting anything:
1806 command_oneline('config', '--get',
1807 "svn-remote.$self->{repo_id}.url")
1809 if ($orig_url && ($orig_url ne $url)) {
1810 die "svn-remote.$self->{repo_id}.url already set: ",
1811 "$orig_url\nwanted to set to: $url\n";
1814 my ($xrepo_id, $xpath) = find_ref($self->refname);
1815 if (defined $xpath) {
1816 die "svn-remote.$xrepo_id.fetch already set to track ",
1817 "$xpath:refs/remotes/", $self->refname, "\n";
1819 unless ($no_write) {
1820 command_noisy('config',
1821 "svn-remote.$self->{repo_id}.url", $url);
1822 $self->{path} =~ s{^/}{};
1823 command_noisy('config', '--add',
1824 "svn-remote.$self->{repo_id}.fetch",
1825 "$self->{path}:".$self->refname);
1827 $self->{url} = $url;
1830 sub find_by_url { # repos_root and, path are optional
1831 my ($class, $full_url, $repos_root, $path) = @_;
1833 return undef unless defined $full_url;
1834 remove_username($full_url);
1835 remove_username($repos_root) if defined $repos_root;
1836 my $remotes = read_all_remotes();
1837 if (defined $full_url && defined $repos_root && !defined $path) {
1839 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1841 foreach my $repo_id (keys %$remotes) {
1842 my $u = $remotes->{$repo_id}->{url} or next;
1843 remove_username($u);
1844 next if defined $repos_root && $repos_root ne $u;
1846 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1847 foreach my $t (qw/branches tags/) {
1848 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1849 resolve_local_globs($u, $fetch, $globspec);
1853 my $rwr = rewrite_root({repo_id => $repo_id});
1854 my $svm = $remotes->{$repo_id}->{svm}
1855 if defined $remotes->{$repo_id}->{svm};
1856 unless (defined $p) {
1862 remove_username($z);
1863 } elsif (defined $svm) {
1864 $z = $svm->{source};
1865 $prefix = $svm->{replace};
1866 $prefix =~ s#^\Q$u\E(?:/|$)##;
1869 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1871 foreach my $f (keys %$fetch) {
1873 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1880 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1881 my $self = _new($class, $repo_id, $ref_id, $path);
1883 $self->init_remote_config($url, $no_write);
1890 foreach (command(qw/config -l/)) {
1891 next unless m!^svn-remote\.(.+)\.fetch=
1892 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1893 my ($repo_id, $path, $ref) = ($1, $2, $3);
1894 if ($ref eq $ref_id) {
1895 $path = '' if ($path =~ m#^\./?#);
1896 return ($repo_id, $path);
1899 (undef, undef, undef);
1903 my ($class, $ref_id, $repo_id, $path) = @_;
1904 if (defined $ref_id && !defined $repo_id && !defined $path) {
1905 ($repo_id, $path) = find_ref($ref_id);
1906 if (!defined $repo_id) {
1907 die "Could not find a \"svn-remote.*.fetch\" key ",
1908 "in the repository configuration matching: ",
1909 "refs/remotes/$ref_id\n";
1912 my $self = _new($class, $repo_id, $ref_id, $path);
1913 if (!defined $self->{path} || !length $self->{path}) {
1914 my $fetch = command_oneline('config', '--get',
1915 "svn-remote.$repo_id.fetch",
1916 ":refs/remotes/$ref_id\$") or
1917 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1918 "\":refs/remotes/$ref_id\$\" in config\n";
1919 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1921 $self->{url} = command_oneline('config', '--get',
1922 "svn-remote.$repo_id.url") or
1923 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1929 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1931 # It cannot end with a slash /, we'll throw up on this because
1932 # SVN can't have directories with a slash in their name, either:
1933 if ($refname =~ m{/$}) {
1934 die "ref: '$refname' ends with a trailing slash, this is ",
1935 "not permitted by git nor Subversion\n";
1938 # It cannot have ASCII control character space, tilde ~, caret ^,
1939 # colon :, question-mark ?, asterisk *, space, or open bracket [
1942 # Additionally, % must be escaped because it is used for escaping
1943 # and we want our escaped refname to be reversible
1944 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1946 # no slash-separated component can begin with a dot .
1948 $refname =~ s{/\.}{/%2E}g;
1950 # It cannot have two consecutive dots .. anywhere
1952 $refname =~ s{\.\.}{%2E%2E}g;
1957 sub desanitize_refname {
1959 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1965 return $self->{svm}->{uuid} if $self->svm;
1967 unless ($self->{svm}) {
1968 die "SVM UUID not cached, and reading remotely failed\n";
1970 $self->{svm}->{uuid};
1975 return $self->{svm} if $self->{svm};
1977 # see if we have it in our config, first:
1979 my $section = "svn-remote.$self->{repo_id}";
1981 source => tmp_config('--get', "$section.svm-source"),
1982 uuid => tmp_config('--get', "$section.svm-uuid"),
1983 replace => tmp_config('--get', "$section.svm-replace"),
1986 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1987 $self->{svm} = $svm;
1993 my ($self, $ra) = @_;
1994 return $ra if $self->svm;
1996 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1997 "(svm:source, svm:uuid) ",
1998 "from the following URLs:\n" );
1999 sub read_svm_props {
2000 my ($self, $ra, $path, $r) = @_;
2001 my $props = ($ra->get_dir($path, $r))[2];
2002 my $src = $props->{'svm:source'};
2003 my $uuid = $props->{'svm:uuid'};
2004 return undef if (!$src || !$uuid);
2008 $uuid =~ m{^[0-9a-f\-]{30,}$}
2009 or die "doesn't look right - svm:uuid is '$uuid'\n";
2011 # the '!' is used to mark the repos_root!/relative/path
2012 $src =~ s{/?!/?}{/};
2013 $src =~ s{/+$}{}; # no trailing slashes please
2014 # username is of no interest
2015 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2017 my $replace = $ra->{url};
2018 $replace .= "/$path" if length $path;
2020 my $section = "svn-remote.$self->{repo_id}";
2021 tmp_config("$section.svm-source", $src);
2022 tmp_config("$section.svm-replace", $replace);
2023 tmp_config("$section.svm-uuid", $uuid);
2031 my $r = $ra->get_latest_revnum;
2032 my $path = $self->{path};
2034 while (length $path) {
2035 unless ($tried{"$self->{url}/$path"}) {
2036 return $ra if $self->read_svm_props($ra, $path, $r);
2037 $tried{"$self->{url}/$path"} = 1;
2039 $path =~ s#/?[^/]+$##;
2041 die "Path: '$path' should be ''\n" if $path ne '';
2042 return $ra if $self->read_svm_props($ra, $path, $r);
2043 $tried{"$self->{url}/$path"} = 1;
2045 if ($ra->{repos_root} eq $self->{url}) {
2046 die @err, (map { " $_\n" } keys %tried), "\n";
2049 # nope, make sure we're connected to the repository root:
2052 $path = $ra->{svn_path};
2053 $ra = Git::SVN::Ra->new($ra->{repos_root});
2054 while (length $path) {
2055 unless ($tried{"$ra->{url}/$path"}) {
2056 $ok = $self->read_svm_props($ra, $path, $r);
2058 $tried{"$ra->{url}/$path"} = 1;
2060 $path =~ s#/?[^/]+$##;
2062 die "Path: '$path' should be ''\n" if $path ne '';
2063 $ok ||= $self->read_svm_props($ra, $path, $r);
2064 $tried{"$ra->{url}/$path"} = 1;
2066 die @err, (map { " $_\n" } keys %tried), "\n";
2068 Git::SVN::Ra->new($self->{url});
2073 return $self->{svnsync} if $self->{svnsync};
2075 if ($self->no_metadata) {
2076 die "Can't have both 'noMetadata' and ",
2077 "'useSvnsyncProps' options set!\n";
2079 if ($self->rewrite_root) {
2080 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2085 # see if we have it in our config, first:
2087 my $section = "svn-remote.$self->{repo_id}";
2089 my $url = tmp_config('--get', "$section.svnsync-url");
2090 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2091 die "doesn't look right - svn:sync-from-url is '$url'\n";
2093 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2094 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2095 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2097 $svnsync = { url => $url, uuid => $uuid }
2099 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2100 return $self->{svnsync} = $svnsync;
2103 my $err = "useSvnsyncProps set, but failed to read " .
2104 "svnsync property: svn:sync-from-";
2105 my $rp = $self->ra->rev_proplist(0);
2107 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2108 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2109 die "doesn't look right - svn:sync-from-url is '$url'\n";
2111 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2112 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2113 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2115 my $section = "svn-remote.$self->{repo_id}";
2116 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2117 tmp_config('--add', "$section.svnsync-url", $url);
2118 return $self->{svnsync} = { url => $url, uuid => $uuid };
2121 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2122 # remote lookup (useful for 'git svn log').
2125 unless ($self->{ra_uuid}) {
2126 my $key = "svn-remote.$self->{repo_id}.uuid";
2127 my $uuid = eval { tmp_config('--get', $key) };
2128 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2129 $self->{ra_uuid} = $uuid;
2131 die "ra_uuid called without URL\n" unless $self->{url};
2132 $self->{ra_uuid} = $self->ra->get_uuid;
2133 tmp_config('--add', $key, $self->{ra_uuid});
2139 sub _set_repos_root {
2140 my ($self, $repos_root) = @_;
2141 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2142 $repos_root ||= $self->ra->{repos_root};
2143 tmp_config($k, $repos_root);
2149 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2150 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2155 my $ra = Git::SVN::Ra->new($self->{url});
2156 $self->_set_repos_root($ra->{repos_root});
2157 if ($self->use_svm_props && !$self->{svm}) {
2158 if ($self->no_metadata) {
2159 die "Can't have both 'noMetadata' and ",
2160 "'useSvmProps' options set!\n";
2161 } elsif ($self->use_svnsync_props) {
2162 die "Can't have both 'useSvnsyncProps' and ",
2163 "'useSvmProps' options set!\n";
2165 $ra = $self->_set_svm_vars($ra);
2166 $self->{-want_revprops} = 1;
2173 my $repos_root = $self->ra->{repos_root};
2174 return $self->{path} if ($self->{url} eq $repos_root);
2175 my $url = $self->{url} .
2176 (length $self->{path} ? "/$self->{path}" : $self->{path});
2177 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2181 # prop_walk(PATH, REV, SUB)
2182 # -------------------------
2183 # Recursively traverse PATH at revision REV and invoke SUB for each
2184 # directory that contains a SVN property. SUB will be invoked as
2185 # follows: &SUB(gs, path, props); where `gs' is this instance of
2186 # Git::SVN, `path' the path to the directory where the properties
2187 # `props' were found. The `path' will be relative to point of checkout,
2188 # that is, if url://repo/trunk is the current Git branch, and that
2189 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2190 # as `path' (note the trailing `/').
2192 my ($self, $path, $rev, $sub) = @_;
2195 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2198 # Strip the irrelevant part of the path.
2199 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2200 # Ensure the path is terminated by a `/'.
2203 # The properties contain all the internal SVN stuff nobody
2204 # (usually) cares about.
2205 my $interesting_props = 0;
2206 foreach (keys %{$props}) {
2207 # If it doesn't start with `svn:', it must be a
2208 # user-defined property.
2209 ++$interesting_props and next if $_ !~ /^svn:/;
2210 # FIXME: Fragile, if SVN adds new public properties,
2211 # this needs to be updated.
2212 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2213 |eol-style|mime-type
2214 |externals|needs-lock)$/x;
2216 &$sub($self, $p, $props) if $interesting_props;
2218 foreach (sort keys %$dirent) {
2219 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2220 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2224 sub last_rev { ($_[0]->last_rev_commit)[0] }
2225 sub last_commit { ($_[0]->last_rev_commit)[1] }
2227 # returns the newest SVN revision number and newest commit SHA1
2228 sub last_rev_commit {
2230 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2231 return ($self->{last_rev}, $self->{last_commit});
2233 my $c = ::verify_ref($self->refname.'^0');
2234 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2235 my $rev = (::cmt_metadata($c))[1];
2237 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2241 my $map_path = $self->map_path;
2242 unless (-e $map_path) {
2243 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2244 return (undef, undef);
2246 my ($rev, $commit) = $self->rev_map_max(1);
2247 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2248 return ($rev, $commit);
2251 sub get_fetch_range {
2252 my ($self, $min, $max) = @_;
2253 $max ||= $self->ra->get_latest_revnum;
2254 $min ||= $self->rev_map_max;
2260 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2261 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2262 if (! -f $config && -f $old_def_config) {
2263 rename $old_def_config, $config or
2264 die "Failed rename $old_def_config => $config: $!\n";
2266 my $old_config = $ENV{GIT_CONFIG};
2267 $ENV{GIT_CONFIG} = $config;
2270 unless (-f $config) {
2272 open my $fh, '>', $config or
2273 die "Can't open $config: $!\n";
2274 print $fh "; This file is used internally by ",
2276 "Couldn't write to $config: $!\n";
2277 print $fh "; You should not have to edit it\n" or
2278 die "Couldn't write to $config: $!\n";
2279 close $fh or die "Couldn't close $config: $!\n";
2281 command('config', @args);
2284 if (defined $old_config) {
2285 $ENV{GIT_CONFIG} = $old_config;
2287 delete $ENV{GIT_CONFIG};
2290 wantarray ? @ret : $ret[0];
2294 my ($self, $sub) = @_;
2295 my $old_index = $ENV{GIT_INDEX_FILE};
2296 $ENV{GIT_INDEX_FILE} = $self->{index};
2299 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2300 mkpath([$dir]) unless -d $dir;
2304 if (defined $old_index) {
2305 $ENV{GIT_INDEX_FILE} = $old_index;
2307 delete $ENV{GIT_INDEX_FILE};
2310 wantarray ? @ret : $ret[0];
2313 sub assert_index_clean {
2314 my ($self, $treeish) = @_;
2316 $self->tmp_index_do(sub {
2317 command_noisy('read-tree', $treeish) unless -e $self->{index};
2318 my $x = command_oneline('write-tree');
2319 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2320 /^tree ($::sha1)/mo);
2323 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2324 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2325 command_noisy('read-tree', $treeish);
2326 $x = command_oneline('write-tree');
2328 ::fatal "trees ($treeish) $y != $x\n",
2329 "Something is seriously wrong...";
2334 sub get_commit_parents {
2335 my ($self, $log_entry) = @_;
2336 my (%seen, @ret, @tmp);
2337 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2338 if (my $ip = $self->{inject_parents}) {
2339 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2343 if (my $cur = ::verify_ref($self->refname.'^0')) {
2346 if (my $ipd = $self->{inject_parents_dcommit}) {
2347 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2348 push @tmp, @$commit;
2351 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2352 while (my $p = shift @tmp) {
2356 # MAXPARENT is defined to 16 in commit-tree.c:
2360 die "r$log_entry->{revision}: No room for parents:\n\t",
2361 join("\n\t", @tmp), "\n";
2368 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2369 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2370 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2373 if ($rwr !~ m#^[a-z\+]+://#) {
2374 die "$rwr is not a valid URL (key: $k)\n";
2377 $self->{-rewrite_root} = $rwr;
2382 ($self->rewrite_root || $self->{url}) .
2383 (length $self->{path} ? '/' . $self->{path} : '');
2388 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2392 sub set_commit_header_env {
2393 my ($log_entry) = @_;
2395 foreach my $ned (qw/NAME EMAIL DATE/) {
2396 foreach my $ac (qw/AUTHOR COMMITTER/) {
2397 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2401 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2402 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2403 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2405 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2406 ? $log_entry->{commit_name}
2407 : $log_entry->{name};
2408 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2409 ? $log_entry->{commit_email}
2410 : $log_entry->{email};
2414 sub restore_commit_header_env {
2416 foreach my $ned (qw/NAME EMAIL DATE/) {
2417 foreach my $ac (qw/AUTHOR COMMITTER/) {
2418 my $k = "GIT_${ac}_${ned}";
2419 if (defined $env->{$k}) {
2420 $ENV{$k} = $env->{$k};
2429 command_noisy('gc', '--auto');
2433 my ($self, $log_entry) = @_;
2434 my $lr = $self->last_rev;
2435 if (defined $lr && $lr >= $log_entry->{revision}) {
2436 die "Last fetched revision of ", $self->refname,
2437 " was r$lr, but we are about to fetch: ",
2438 "r$log_entry->{revision}!\n";
2440 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2441 croak "$log_entry->{revision} = $c already exists! ",
2442 "Why are we refetching it?\n";
2444 my $old_env = set_commit_header_env($log_entry);
2445 my $tree = $log_entry->{tree};
2446 if (!defined $tree) {
2447 $tree = $self->tmp_index_do(sub {
2448 command_oneline('write-tree') });
2450 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2452 my @exec = ('git', 'commit-tree', $tree);
2453 foreach ($self->get_commit_parents($log_entry)) {
2454 push @exec, '-p', $_;
2456 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2460 # we always get UTF-8 from SVN, but we may want our commits in
2461 # a different encoding.
2462 if (my $enc = Git::config('i18n.commitencoding')) {
2464 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2466 print $msg_fh $log_entry->{log} or croak $!;
2467 restore_commit_header_env($old_env);
2468 unless ($self->no_metadata) {
2469 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2472 $msg_fh->flush == 0 or croak $!;
2473 close $msg_fh or croak $!;
2474 chomp(my $commit = do { local $/; <$out_fh> });
2475 close $out_fh or croak $!;
2478 if ($commit !~ /^$::sha1$/o) {
2479 die "Failed to commit, invalid sha1: $commit\n";
2482 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2484 $self->{last_rev} = $log_entry->{revision};
2485 $self->{last_commit} = $commit;
2486 print "r$log_entry->{revision}" unless $::_q > 1;
2487 if (defined $log_entry->{svm_revision}) {
2488 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2489 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2490 0, $self->svm_uuid);
2492 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2493 if (--$_gc_nr == 0) {
2494 $_gc_nr = $_gc_period;
2501 my ($self, $paths, $r) = @_;
2502 return 1 if $self->{path} eq '';
2503 if (my $path = $paths->{"/$self->{path}"}) {
2504 return ($path->{action} eq 'D') ? 0 : 1;
2506 my $repos_root = $self->ra->{repos_root};
2507 my $extended_path = $self->{url} . '/' . $self->{path};
2508 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2509 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2510 if (grep /$self->{path_regex}/, keys %$paths) {
2514 foreach (split m#/#, $self->{path}) {
2516 next unless ($paths->{$c} &&
2517 ($paths->{$c}->{action} =~ /^[AR]$/));
2518 if ($self->ra->check_path($self->{path}, $r) ==
2526 sub find_parent_branch {
2527 my ($self, $paths, $rev) = @_;
2528 return undef unless $self->follow_parent;
2529 unless (defined $paths) {
2530 my $err_handler = $SVN::Error::handler;
2531 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2532 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2534 Git::SVN::Ra::dup_changed_paths($_[0]) });
2535 $SVN::Error::handler = $err_handler;
2537 return undef unless defined $paths;
2539 # look for a parent from another branch:
2540 my @b_path_components = split m#/#, $self->rel_path;
2541 my @a_path_components;
2543 while (@b_path_components) {
2544 $i = $paths->{'/'.join('/', @b_path_components)};
2545 last if $i && defined $i->{copyfrom_path};
2546 unshift(@a_path_components, pop(@b_path_components));
2548 return undef unless defined $i && defined $i->{copyfrom_path};
2549 my $branch_from = $i->{copyfrom_path};
2550 if (@a_path_components) {
2551 print STDERR "branch_from: $branch_from => ";
2552 $branch_from .= '/'.join('/', @a_path_components);
2553 print STDERR $branch_from, "\n";
2555 my $r = $i->{copyfrom_rev};
2556 my $repos_root = $self->ra->{repos_root};
2557 my $url = $self->ra->{url};
2558 my $new_url = $repos_root . $branch_from;
2559 print STDERR "Found possible branch point: ",
2560 "$new_url => ", $self->full_url, ", $r\n";
2561 $branch_from =~ s#^/##;
2562 my $gs = $self->other_gs($new_url, $url, $repos_root,
2563 $branch_from, $r, $self->{ref_id});
2564 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2567 if (!defined $r0 || !defined $parent) {
2568 ($base, $head) = parse_revision_argument(0, $r);
2571 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2572 0, 1, sub { $base = $_[1] - 1 });
2575 if (defined $base && $base <= $r) {
2576 $gs->fetch($base, $r);
2578 ($r0, $parent) = $gs->find_rev_before($r, 1);
2580 if (defined $r0 && defined $parent) {
2581 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2583 if ($self->ra->can_do_switch) {
2584 $self->assert_index_clean($parent);
2585 print STDERR "Following parent with do_switch\n";
2586 # do_switch works with svn/trunk >= r22312, but that
2587 # is not included with SVN 1.4.3 (the latest version
2588 # at the moment), so we can't rely on it
2589 $self->{last_rev} = $r0;
2590 $self->{last_commit} = $parent;
2591 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2592 $gs->ra->gs_do_switch($r0, $rev, $gs,
2593 $self->full_url, $ed)
2594 or die "SVN connection failed somewhere...\n";
2595 } elsif ($self->ra->trees_match($new_url, $r0,
2596 $self->full_url, $rev)) {
2597 print STDERR "Trees match:\n",
2599 " ${\$self->full_url}\@$rev\n",
2600 "Following parent with no changes\n";
2601 $self->tmp_index_do(sub {
2602 command_noisy('read-tree', $parent);
2604 $self->{last_commit} = $parent;
2606 print STDERR "Following parent with do_update\n";
2607 $ed = SVN::Git::Fetcher->new($self);
2608 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2609 or die "SVN connection failed somewhere...\n";
2611 print STDERR "Successfully followed parent\n";
2612 return $self->make_log_entry($rev, [$parent], $ed);
2618 my ($self, $paths, $rev) = @_;
2620 my ($last_rev, @parents);
2621 if (my $lc = $self->last_commit) {
2622 # we can have a branch that was deleted, then re-added
2623 # under the same name but copied from another path, in
2624 # which case we'll have multiple parents (we don't
2625 # want to break the original ref, nor lose copypath info):
2626 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2627 push @{$log_entry->{parents}}, $lc;
2630 $ed = SVN::Git::Fetcher->new($self);
2631 $last_rev = $self->{last_rev};
2636 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2639 $ed = SVN::Git::Fetcher->new($self);
2641 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2642 die "SVN connection failed somewhere...\n";
2644 $self->make_log_entry($rev, \@parents, $ed);
2648 my ($self, $ed) = @_;
2650 my $h = $ed->{empty};
2651 foreach (sort keys %$h) {
2652 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2653 push @out, " $act: " . uri_encode($_);
2654 warn "W: $act: $_\n";
2656 foreach my $t (qw/dir_prop file_prop/) {
2657 $h = $ed->{$t} or next;
2658 foreach my $path (sort keys %$h) {
2659 my $ppath = $path eq '' ? '.' : $path;
2660 foreach my $prop (sort keys %{$h->{$path}}) {
2661 next if $SKIP_PROP{$prop};
2662 my $v = $h->{$path}->{$prop};
2663 my $t_ppath_prop = "$t: " .
2664 uri_encode($ppath) . ' ' .
2667 push @out, " +$t_ppath_prop " .
2670 push @out, " -$t_ppath_prop";
2675 foreach my $t (qw/absent_file absent_directory/) {
2676 $h = $ed->{$t} or next;
2677 foreach my $parent (sort keys %$h) {
2678 foreach my $path (sort @{$h->{$parent}}) {
2679 push @out, " $t: " .
2680 uri_encode("$parent/$path");
2681 warn "W: $t: $parent/$path ",
2682 "Insufficient permissions?\n";
2689 # parse_svn_date(DATE)
2690 # --------------------
2691 # Given a date (in UTC) from Subversion, return a string in the format
2692 # "<TZ Offset> <local date/time>" that Git will use.
2694 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2695 # is true we'll convert it to the local timezone instead.
2696 sub parse_svn_date {
2697 my $date = shift || return '+0000 1970-01-01 00:00:00';
2698 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2699 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2700 croak "Unable to parse date: $date\n";
2701 my $parsed_date; # Set next.
2703 if ($Git::SVN::_localtime) {
2704 # Translate the Subversion datetime to an epoch time.
2705 # Begin by switching ourselves to $date's timezone, UTC.
2706 my $old_env_TZ = $ENV{TZ};
2710 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2712 # Determine our local timezone (including DST) at the
2713 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2714 # value of TZ, if any, at the time we were run.
2715 if (defined $Git::SVN::Log::TZ) {
2716 $ENV{TZ} = $Git::SVN::Log::TZ;
2722 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2724 # This converts $epoch_in_UTC into our local timezone.
2725 my ($sec, $min, $hour, $mday, $mon, $year,
2726 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2728 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2729 $our_TZ, $year + 1900, $mon + 1,
2730 $mday, $hour, $min, $sec);
2732 # Reset us to the timezone in effect when we entered
2734 if (defined $old_env_TZ) {
2735 $ENV{TZ} = $old_env_TZ;
2740 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2743 return $parsed_date;
2747 my ($self, $new_url, $url, $repos_root,
2748 $branch_from, $r, $old_ref_id) = @_;
2749 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2751 my $ref_id = $old_ref_id;
2752 $ref_id =~ s/\@\d+$//;
2754 # just grow a tail if we're not unique enough :x
2755 $ref_id .= '-' while find_ref($ref_id);
2756 print STDERR "Initializing parent: $ref_id\n";
2757 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2758 if ($u =~ s#^\Q$url\E(/|$)##) {
2761 $repo_id = $self->{repo_id};
2763 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2768 sub call_authors_prog {
2769 my ($orig_author) = @_;
2770 my $author = `$::_authors_prog $orig_author`;
2772 die "$::_authors_prog failed with exit code $?\n"
2774 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2775 my ($name, $email) = ($1, $2);
2776 $email = undef if length $2 == 0;
2777 return [$name, $email];
2779 die "Author: $orig_author: $::_authors_prog returned "
2780 . "invalid author format: $author\n";
2786 if (!defined $author || length $author == 0) {
2787 $author = '(no author)';
2789 if (!defined $::users{$author}) {
2790 if (defined $::_authors_prog) {
2791 $::users{$author} = call_authors_prog($author);
2792 } elsif (defined $::_authors) {
2793 die "Author: $author not defined in $::_authors file\n";
2799 sub make_log_entry {
2800 my ($self, $rev, $parents, $ed) = @_;
2801 my $untracked = $self->get_untracked($ed);
2803 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2804 print $un "r$rev\n" or croak $!;
2805 print $un $_, "\n" foreach @$untracked;
2806 my %log_entry = ( parents => $parents || [], revision => $rev,
2810 my $logged = delete $self->{logged_rev_props};
2811 if (!$logged || $self->{-want_revprops}) {
2812 my $rp = $self->ra->rev_proplist($rev);
2813 foreach (sort keys %$rp) {
2815 if (/^svn:(author|date|log)$/) {
2816 $log_entry{$1} = $v;
2817 } elsif ($_ eq 'svm:headrev') {
2820 print $un " rev_prop: ", uri_encode($_), ' ',
2821 uri_encode($v), "\n";
2825 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2827 close $un or croak $!;
2829 $log_entry{date} = parse_svn_date($log_entry{date});
2830 $log_entry{log} .= "\n";
2831 my $author = $log_entry{author} = check_author($log_entry{author});
2832 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2835 my ($commit_name, $commit_email) = ($name, $email);
2836 if ($_use_log_author) {
2838 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2840 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2843 if (!defined $name_field) {
2844 if (!defined $email) {
2847 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2848 ($name, $email) = ($1, $2);
2849 } elsif ($name_field =~ /(.*)@/) {
2850 ($name, $email) = ($1, $name_field);
2852 ($name, $email) = ($name_field, $name_field);
2855 if (defined $headrev && $self->use_svm_props) {
2856 if ($self->rewrite_root) {
2857 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2860 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2861 # we don't want "SVM: initializing mirror for junk" ...
2862 return undef if $r == 0;
2863 my $svm = $self->svm;
2864 if ($uuid ne $svm->{uuid}) {
2865 die "UUID mismatch on SVM path:\n",
2866 "expected: $svm->{uuid}\n",
2869 my $full_url = $self->full_url;
2870 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2871 die "Failed to replace '$svm->{replace}' with ",
2872 "'$svm->{source}' in $full_url\n";
2873 # throw away username for storing in records
2874 remove_username($full_url);
2875 $log_entry{metadata} = "$full_url\@$r $uuid";
2876 $log_entry{svm_revision} = $r;
2877 $email ||= "$author\@$uuid";
2878 $commit_email ||= "$author\@$uuid";
2879 } elsif ($self->use_svnsync_props) {
2880 my $full_url = $self->svnsync->{url};
2881 $full_url .= "/$self->{path}" if length $self->{path};
2882 remove_username($full_url);
2883 my $uuid = $self->svnsync->{uuid};
2884 $log_entry{metadata} = "$full_url\@$rev $uuid";
2885 $email ||= "$author\@$uuid";
2886 $commit_email ||= "$author\@$uuid";
2888 my $url = $self->metadata_url;
2889 remove_username($url);
2890 $log_entry{metadata} = "$url\@$rev " .
2891 $self->ra->get_uuid;
2892 $email ||= "$author\@" . $self->ra->get_uuid;
2893 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2895 $log_entry{name} = $name;
2896 $log_entry{email} = $email;
2897 $log_entry{commit_name} = $commit_name;
2898 $log_entry{commit_email} = $commit_email;
2903 my ($self, $min_rev, $max_rev, @parents) = @_;
2904 my ($last_rev, $last_commit) = $self->last_rev_commit;
2905 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2906 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2910 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2911 $self->{inject_parents} = { $rev => $tree };
2912 $self->fetch(undef, undef);
2916 my ($self, $tree) = (shift, shift);
2917 my $log_entry = ::get_commit_entry($tree);
2918 unless ($self->{last_rev}) {
2919 ::fatal("Must have an existing revision to commit");
2921 my %ed_opts = ( r => $self->{last_rev},
2922 log => $log_entry->{log},
2924 tree_a => $self->{last_commit},
2927 $self->set_tree_cb($log_entry, $tree, @_) },
2928 svn_path => $self->{path} );
2929 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2930 print "No changes\nr$self->{last_rev} = $tree\n";
2934 sub rebuild_from_rev_db {
2935 my ($self, $path) = @_;
2937 open my $fh, '<', $path or croak "open: $!";
2938 binmode $fh or croak "binmode: $!";
2940 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2943 next if $_ eq ('0' x 40);
2944 $self->rev_map_set($r, $_);
2947 close $fh or croak "close: $!";
2948 unlink $path or croak "unlink: $!";
2953 my $map_path = $self->map_path;
2954 my $partial = (-e $map_path && ! -z $map_path);
2955 return unless ::verify_ref($self->refname.'^0');
2956 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2957 my $rev_db = $self->rev_db_path;
2958 $self->rebuild_from_rev_db($rev_db);
2959 if ($self->use_svm_props) {
2960 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2961 $self->rebuild_from_rev_db($svm_rev_db);
2963 $self->unlink_rev_db_symlink;
2966 print "Rebuilding $map_path ...\n" if (!$partial);
2967 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2970 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2971 ($head ? "$head.." : "") . $self->refname,
2973 my $metadata_url = $self->metadata_url;
2974 remove_username($metadata_url);
2975 my $svn_uuid = $self->ra_uuid;
2978 if ( m{^commit ($::sha1)$} ) {
2982 next unless s{^\s*(git-svn-id:)}{$1};
2983 my ($url, $rev, $uuid) = ::extract_metadata($_);
2984 remove_username($url);
2986 # ignore merges (from set-tree)
2987 next if (!defined $rev || !$uuid);
2989 # if we merged or otherwise started elsewhere, this is
2990 # how we break out of it
2991 if (($uuid ne $svn_uuid) ||
2992 ($metadata_url && $url && ($url ne $metadata_url))) {
2995 if ($partial && $head) {
2996 print "Partial-rebuilding $map_path ...\n";
2997 print "Currently at $base_rev = $head\n";
3001 $self->rev_map_set($rev, $c);
3002 print "r$rev = $c\n";
3004 command_close_pipe($log, $ctx);
3005 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3006 my $rev_db_path = $self->rev_db_path;
3007 if (-f $self->rev_db_path) {
3008 unlink $self->rev_db_path or croak "unlink: $!";
3010 $self->unlink_rev_db_symlink;
3014 # Tie::File seems to be prone to offset errors if revisions get sparse,
3015 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3016 # one of my favorite modules is out :< Next up would be one of the DBM
3017 # modules, but I'm not sure which is most portable...
3019 # This is the replacement for the rev_db format, which was too big
3020 # and inefficient for large repositories with a lot of sparse history
3023 # The format is this:
3024 # - 24 bytes for every record,
3025 # * 4 bytes for the integer representing an SVN revision number
3026 # * 20 bytes representing the sha1 of a git commit
3027 # - No empty padding records like the old format
3028 # (except the last record, which can be overwritten)
3029 # - new records are written append-only since SVN revision numbers
3030 # increase monotonically
3031 # - lookups on SVN revision number are done via a binary search
3032 # - Piping the file to xxd -c24 is a good way of dumping it for
3033 # viewing or editing (piped back through xxd -r), should the need
3035 # - The last record can be padding revision with an all-zero sha1
3036 # This is used to optimize fetch performance when using multiple
3037 # "fetch" directives in .git/config
3039 # These files are disposable unless noMetadata or useSvmProps is set
3042 my ($fh, $rev, $commit) = @_;
3044 binmode $fh or croak "binmode: $!";
3045 my $size = (stat($fh))[7];
3046 ($size % 24) == 0 or croak "inconsistent size: $size";
3050 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3051 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3052 $read == 24 or croak "read only $read bytes (!= 24)";
3053 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3054 if ($last_commit eq ('0' x40)) {
3056 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3057 $read = sysread($fh, $buf, 24) or
3060 croak "read only $read bytes (!= 24)";
3061 ($last_rev, $last_commit) =
3062 unpack(rev_map_fmt, $buf);
3063 if ($last_commit eq ('0' x40)) {
3064 croak "inconsistent .rev_map\n";
3067 if ($last_rev >= $rev) {
3068 croak "last_rev is higher!: $last_rev >= $rev";
3073 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3074 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3078 sub _rev_map_reset {
3079 my ($fh, $rev, $commit) = @_;
3080 my $c = _rev_map_get($fh, $rev);
3081 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3082 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3083 truncate $fh, $offset or croak "truncate: $!";
3089 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3090 mkpath([$dir]) unless -d $dir;
3091 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3092 close $fh or die "Couldn't close (create) $path: $!\n";
3097 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3098 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3099 my $db = $self->map_path($uuid);
3100 my $db_lock = "$db.lock";
3104 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3105 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3109 $LOCKFILES{$db_lock} = 1;
3111 # both of these options make our .rev_db file very, very important
3112 # and we can't afford to lose it because rebuild() won't work
3113 if ($self->use_svm_props || $self->no_metadata) {
3115 copy($db, $db_lock) or die "rev_map_set(@_): ",
3117 "$db => $db_lock ($!)\n";
3119 rename $db, $db_lock or die "rev_map_set(@_): ",
3120 "Failed to rename: ",
3121 "$db => $db_lock ($!)\n";
3124 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3125 or croak "Couldn't open $db_lock: $!\n";
3126 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3127 _rev_map_set($fh, $rev, $commit);
3129 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3130 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3132 close $fh or croak $!;
3136 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3137 command_noisy('update-ref', '-m', "r$rev$note",
3138 $self->refname, $commit);
3140 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3141 "$db_lock => $db ($!)\n";
3142 delete $LOCKFILES{$db_lock};
3144 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3145 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3146 kill $sig, $$ if defined $sig;
3150 # If want_commit, this will return an array of (rev, commit) where
3151 # commit _must_ be a valid commit in the archive.
3152 # Otherwise, it'll return the max revision (whether or not the
3153 # commit is valid or just a 0x40 placeholder).
3155 my ($self, $want_commit) = @_;
3157 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3158 $want_commit ? ($r, $c) : $r;
3161 sub rev_map_max_norebuild {
3162 my ($self, $want_commit) = @_;
3163 my $map_path = $self->map_path;
3164 stat $map_path or return $want_commit ? (0, undef) : 0;
3165 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3166 binmode $fh or croak "binmode: $!";
3167 my $size = (stat($fh))[7];
3168 ($size % 24) == 0 or croak "inconsistent size: $size";
3171 close $fh or croak "close: $!";
3172 return $want_commit ? (0, undef) : 0;
3175 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3176 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3177 my ($r, $c) = unpack(rev_map_fmt, $buf);
3178 if ($want_commit && $c eq ('0' x40)) {
3180 return $want_commit ? (0, undef) : 0;
3182 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3183 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3184 ($r, $c) = unpack(rev_map_fmt, $buf);
3185 if ($c eq ('0'x40)) {
3186 croak "Penultimate record is all-zeroes in $map_path";
3189 close $fh or croak "close: $!";
3190 $want_commit ? ($r, $c) : $r;
3194 my ($self, $rev, $uuid) = @_;
3195 my $map_path = $self->map_path($uuid);
3196 return undef unless -e $map_path;
3198 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3199 my $c = _rev_map_get($fh, $rev);
3200 close($fh) or croak "close: $!";
3205 my ($fh, $rev) = @_;
3207 binmode $fh or croak "binmode: $!";
3208 my $size = (stat($fh))[7];
3209 ($size % 24) == 0 or croak "inconsistent size: $size";
3215 my ($l, $u) = (0, $size - 24);
3219 my $i = int(($l/24 + $u/24) / 2) * 24;
3220 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3221 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3222 my ($r, $c) = unpack('NH40', $buf);
3226 } elsif ($r > $rev) {
3228 } else { # $r == $rev
3229 return $c eq ('0' x 40) ? undef : $c;
3235 # Finds the first svn revision that exists on (if $eq_ok is true) or
3236 # before $rev for the current branch. It will not search any lower
3237 # than $min_rev. Returns the git commit hash and svn revision number
3238 # if found, else (undef, undef).
3239 sub find_rev_before {
3240 my ($self, $rev, $eq_ok, $min_rev) = @_;
3241 --$rev unless $eq_ok;
3243 my $max_rev = $self->rev_map_max;
3244 $rev = $max_rev if ($rev > $max_rev);
3245 while ($rev >= $min_rev) {
3246 if (my $c = $self->rev_map_get($rev)) {
3251 return (undef, undef);
3254 # Finds the first svn revision that exists on (if $eq_ok is true) or
3255 # after $rev for the current branch. It will not search any higher
3256 # than $max_rev. Returns the git commit hash and svn revision number
3257 # if found, else (undef, undef).
3258 sub find_rev_after {
3259 my ($self, $rev, $eq_ok, $max_rev) = @_;
3260 ++$rev unless $eq_ok;
3261 $max_rev ||= $self->rev_map_max;
3262 while ($rev <= $max_rev) {
3263 if (my $c = $self->rev_map_get($rev)) {
3268 return (undef, undef);
3272 my ($class, $repo_id, $ref_id, $path) = @_;
3273 unless (defined $repo_id && length $repo_id) {
3274 $repo_id = $Git::SVN::default_repo_id;
3276 unless (defined $ref_id && length $ref_id) {
3277 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3280 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3281 $_[3] = $path = '' unless (defined $path);
3282 mkpath(["$ENV{GIT_DIR}/svn"]);
3284 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3285 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3286 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3289 # for read-only access of old .rev_db formats
3290 sub unlink_rev_db_symlink {
3292 my $link = $self->rev_db_path;
3293 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3295 unlink $link or croak "unlink: $link failed!";
3300 my ($self, $uuid) = @_;
3301 my $db_path = $self->map_path($uuid);
3302 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3303 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3307 # the new replacement for .rev_db
3309 my ($self, $uuid) = @_;
3310 $uuid ||= $self->ra_uuid;
3311 "$self->{map_root}.$uuid";
3316 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3320 sub remove_username {
3321 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3324 package Git::SVN::Prompt;
3328 use vars qw/$_no_auth_cache $_username/;
3331 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3332 $may_save = undef if $_no_auth_cache;
3333 $default_username = $_username if defined $_username;
3334 if (defined $default_username && length $default_username) {
3335 if (defined $realm && length $realm) {
3336 print STDERR "Authentication realm: $realm\n";
3339 $cred->username($default_username);
3341 username($cred, $realm, $may_save, $pool);
3343 $cred->password(_read_password("Password for '" .
3344 $cred->username . "': ", $realm));
3345 $cred->may_save($may_save);
3346 $SVN::_Core::SVN_NO_ERROR;
3349 sub ssl_server_trust {
3350 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3351 $may_save = undef if $_no_auth_cache;
3352 print STDERR "Error validating server certificate for '$realm':\n";
3355 # All variables SVN::Auth::SSL::* are used only once,
3356 # so we're shutting up Perl warnings about this.
3357 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3358 print STDERR " - The certificate is not issued ",
3359 "by a trusted authority. Use the\n",
3360 " fingerprint to validate ",
3361 "the certificate manually!\n";
3363 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3364 print STDERR " - The certificate hostname ",
3365 "does not match.\n";
3367 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3368 print STDERR " - The certificate is not yet valid.\n";
3370 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3371 print STDERR " - The certificate has expired.\n";
3373 if ($failures & $SVN::Auth::SSL::OTHER) {
3374 print STDERR " - The certificate has ",
3375 "an unknown error.\n";
3377 } # no warnings 'once'
3379 "Certificate information:\n".
3380 " - Hostname: %s\n".
3381 " - Valid: from %s until %s\n".
3383 " - Fingerprint: %s\n",
3384 map $cert_info->$_, qw(hostname valid_from valid_until
3385 issuer_dname fingerprint);
3388 print STDERR $may_save ?
3389 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3390 "(R)eject or accept (t)emporarily? ";
3392 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3393 if ($choice =~ /^t$/i) {
3394 $cred->may_save(undef);
3395 } elsif ($choice =~ /^r$/i) {
3397 } elsif ($may_save && $choice =~ /^p$/i) {
3398 $cred->may_save($may_save);
3402 $cred->accepted_failures($failures);
3403 $SVN::_Core::SVN_NO_ERROR;
3406 sub ssl_client_cert {
3407 my ($cred, $realm, $may_save, $pool) = @_;
3408 $may_save = undef if $_no_auth_cache;
3409 print STDERR "Client certificate filename: ";
3411 chomp(my $filename = <STDIN>);
3412 $cred->cert_file($filename);
3413 $cred->may_save($may_save);
3414 $SVN::_Core::SVN_NO_ERROR;
3417 sub ssl_client_cert_pw {
3418 my ($cred, $realm, $may_save, $pool) = @_;
3419 $may_save = undef if $_no_auth_cache;
3420 $cred->password(_read_password("Password: ", $realm));
3421 $cred->may_save($may_save);
3422 $SVN::_Core::SVN_NO_ERROR;
3426 my ($cred, $realm, $may_save, $pool) = @_;
3427 $may_save = undef if $_no_auth_cache;
3428 if (defined $realm && length $realm) {
3429 print STDERR "Authentication realm: $realm\n";
3432 if (defined $_username) {
3433 $username = $_username;
3435 print STDERR "Username: ";
3437 chomp($username = <STDIN>);
3439 $cred->username($username);
3440 $cred->may_save($may_save);
3441 $SVN::_Core::SVN_NO_ERROR;
3444 sub _read_password {
3445 my ($prompt, $realm) = @_;
3446 print STDERR $prompt;
3448 require Term::ReadKey;
3449 Term::ReadKey::ReadMode('noecho');
3451 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3452 last if $key =~ /[\012\015]/; # \n\r
3455 Term::ReadKey::ReadMode('restore');
3461 package SVN::Git::Fetcher;
3466 use File::Temp qw/tempfile/;
3468 use vars qw/$_ignore_regex/;
3470 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3472 my ($class, $git_svn, $switch_path) = @_;
3473 my $self = SVN::Delta::Editor->new;
3474 bless $self, $class;
3475 if (exists $git_svn->{last_commit}) {
3476 $self->{c} = $git_svn->{last_commit};
3477 $self->{empty_symlinks} =
3478 _mark_empty_symlinks($git_svn, $switch_path);
3480 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3481 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3482 $self->{empty} = {};
3483 $self->{dir_prop} = {};
3484 $self->{file_prop} = {};
3485 $self->{absent_dir} = {};
3486 $self->{absent_file} = {};
3487 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3491 # this uses the Ra object, so it must be called before do_{switch,update},
3492 # not inside them (when the Git::SVN::Fetcher object is passed) to
3493 # do_{switch,update}
3494 sub _mark_empty_symlinks {
3495 my ($git_svn, $switch_path) = @_;
3496 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3497 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3500 my ($rev, $cmt) = $git_svn->last_rev_commit;
3501 return {} unless ($rev && $cmt);
3503 # allow the warning to be printed for each revision we fetch to
3504 # ensure the user sees it. The user can also disable the workaround
3505 # on the repository even while git svn is running and the next
3506 # revision fetched will skip this expensive function.
3507 my $printed_warning;
3508 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3509 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3511 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3512 $pfx .= '/' if length($pfx);
3515 s/\A100644 blob $empty_blob\t//o or next;
3516 unless ($printed_warning) {
3517 print STDERR "Scanning for empty symlinks, ",
3518 "this may take a while if you have ",
3519 "many empty files\n",
3520 "You may disable this with `",
3521 "git config svn.brokenSymlinkWorkaround ",
3523 "This may be done in a different ",
3524 "terminal without restarting ",
3526 $printed_warning = 1;
3529 my (undef, $props) =
3530 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3531 if ($props->{'svn:special'}) {
3535 command_close_pipe($ls, $ctx);
3539 # returns true if a given path is inside a ".git" directory
3541 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3544 # return value: 0 -- don't ignore, 1 -- ignore
3545 sub is_path_ignored {
3546 my ($self, $path) = @_;
3547 return 1 if in_dot_git($path);
3548 return 1 if defined($self->{ignore_regex}) &&
3549 $path =~ m!$self->{ignore_regex}!;
3550 return 0 unless defined($_ignore_regex);
3551 return 1 if $path =~ m!$_ignore_regex!o;
3555 sub set_path_strip {
3556 my ($self, $path) = @_;
3557 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3564 sub open_directory {
3565 my ($self, $path, $pb, $rev) = @_;
3570 my ($self, $path) = @_;
3571 if ($self->{path_strip}) {
3572 $path =~ s!$self->{path_strip}!! or
3573 die "Failed to strip path '$path' ($self->{path_strip})\n";
3579 my ($self, $path, $rev, $pb) = @_;
3580 return undef if $self->is_path_ignored($path);
3582 my $gpath = $self->git_path($path);
3583 return undef if ($gpath eq '');
3585 # remove entire directories.
3586 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3587 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3589 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3595 my $rmpath = "$gpath/$_";
3596 $self->{gii}->remove($rmpath);
3597 print "\tD\t$rmpath\n" unless $::_q;
3599 print "\tD\t$gpath/\n" unless $::_q;
3600 command_close_pipe($ls, $ctx);
3601 $self->{empty}->{$path} = 0
3603 $self->{gii}->remove($gpath);
3604 print "\tD\t$gpath\n" unless $::_q;
3610 my ($self, $path, $pb, $rev) = @_;
3613 goto out if $self->is_path_ignored($path);
3615 my $gpath = $self->git_path($path);
3616 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3617 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3618 unless (defined $mode && defined $blob) {
3619 die "$path was not found in commit $self->{c} (r$rev)\n";
3621 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3625 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3626 pool => SVN::Pool->new, action => 'M' };
3630 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3633 if (!$self->is_path_ignored($path)) {
3634 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3635 delete $self->{empty}->{$dir};
3638 { path => $path, mode_a => $mode, mode_b => $mode,
3639 pool => SVN::Pool->new, action => 'A' };
3643 my ($self, $path, $cp_path, $cp_rev) = @_;
3644 goto out if $self->is_path_ignored($path);
3645 my $gpath = $self->git_path($path);
3647 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3653 $self->{gii}->remove($_);
3654 print "\tD\t$_\n" unless $::_q;
3656 command_close_pipe($ls, $ctx);
3657 $self->{empty}->{$path} = 0;
3659 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3660 delete $self->{empty}->{$dir};
3661 $self->{empty}->{$path} = 1;
3666 sub change_dir_prop {
3667 my ($self, $db, $prop, $value) = @_;
3668 return undef if $self->is_path_ignored($db->{path});
3669 $self->{dir_prop}->{$db->{path}} ||= {};
3670 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3674 sub absent_directory {
3675 my ($self, $path, $pb) = @_;
3676 return undef if $self->is_path_ignored($path);
3677 $self->{absent_dir}->{$pb->{path}} ||= [];
3678 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3683 my ($self, $path, $pb) = @_;
3684 return undef if $self->is_path_ignored($path);
3685 $self->{absent_file}->{$pb->{path}} ||= [];
3686 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3690 sub change_file_prop {
3691 my ($self, $fb, $prop, $value) = @_;
3692 return undef if $self->is_path_ignored($fb->{path});
3693 if ($prop eq 'svn:executable') {
3694 if ($fb->{mode_b} != 120000) {
3695 $fb->{mode_b} = defined $value ? 100755 : 100644;
3697 } elsif ($prop eq 'svn:special') {
3698 $fb->{mode_b} = defined $value ? 120000 : 100644;
3700 $self->{file_prop}->{$fb->{path}} ||= {};
3701 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3706 sub apply_textdelta {
3707 my ($self, $fb, $exp) = @_;
3708 return undef if $self->is_path_ignored($fb->{path});
3709 my $fh = $::_repository->temp_acquire('svn_delta');
3710 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3711 # (but $base does not,) so dup() it for reading in close_file
3712 open my $dup, '<&', $fh or croak $!;
3713 my $base = $::_repository->temp_acquire('git_blob');
3716 my ($base_is_link, $size);
3718 if ($fb->{mode_a} eq '120000' &&
3719 ! $self->{empty_symlinks}->{$fb->{path}}) {
3720 print $base 'link ' or die "print $!\n";
3724 $size = $::_repository->cat_blob($fb->{blob}, $base);
3725 die "Failed to read object $fb->{blob}" if ($size < 0);
3728 seek $base, 0, 0 or croak $!;
3729 my $got = ::md5sum($base);
3731 my $err = "Checksum mismatch: ".
3732 "$fb->{path} $fb->{blob}\n" .
3733 "expected: $exp\n" .
3735 if ($base_is_link) {
3737 "Retrying... (possibly ",
3738 "a bad symlink from SVN)\n";
3739 $::_repository->temp_reset($base);
3747 seek $base, 0, 0 or croak $!;
3749 $fb->{base} = $base;
3750 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3754 my ($self, $fb, $exp) = @_;
3755 return undef if $self->is_path_ignored($fb->{path});
3758 my $path = $self->git_path($fb->{path});
3759 if (my $fh = $fb->{fh}) {
3761 seek($fh, 0, 0) or croak $!;
3762 my $got = ::md5sum($fh);
3764 die "Checksum mismatch: $path\n",
3765 "expected: $exp\n got: $got\n";
3768 if ($fb->{mode_b} == 120000) {
3769 sysseek($fh, 0, 0) or croak $!;
3770 my $rd = sysread($fh, my $buf, 5);
3773 croak "sysread: $!\n";
3774 } elsif ($rd == 0) {
3775 warn "$path has mode 120000",
3776 " but it points to nothing\n",
3777 "converting to an empty file with mode",
3779 $fb->{mode_b} = '100644';
3780 } elsif ($buf ne 'link ') {
3781 warn "$path has mode 120000",
3782 " but is not a link\n";
3784 my $tmp_fh = $::_repository->temp_acquire(
3787 while ($res = sysread($fh, my $str, 1024)) {
3788 my $out = syswrite($tmp_fh, $str, $res);
3789 defined($out) && $out == $res
3791 Git::temp_path($tmp_fh),
3794 defined $res or croak $!;
3796 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3797 Git::temp_release($tmp_fh, 1);
3801 $hash = $::_repository->hash_and_insert_object(
3802 Git::temp_path($fh));
3803 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3805 Git::temp_release($fb->{base}, 1);
3806 Git::temp_release($fh, 1);
3808 $hash = $fb->{blob} or die "no blob information\n";
3811 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3812 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3818 $self->{nr} = $self->{gii}->{nr};
3819 delete $self->{gii};
3820 $self->SUPER::abort_edit(@_);
3825 $self->{git_commit_ok} = 1;
3826 $self->{nr} = $self->{gii}->{nr};
3827 delete $self->{gii};
3828 $self->SUPER::close_edit(@_);
3831 package SVN::Git::Editor;
3832 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3839 my ($class, $opts) = @_;
3840 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3841 die "$_ required!\n" unless (defined $opts->{$_});
3844 my $pool = SVN::Pool->new;
3845 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3846 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3849 # $opts->{ra} functions should not be used after this:
3850 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3851 $opts->{editor_cb}, $pool);
3852 my $self = SVN::Delta::Editor->new(@ce, $pool);
3853 bless $self, $class;
3854 foreach (qw/svn_path r tree_a tree_b/) {
3855 $self->{$_} = $opts->{$_};
3857 $self->{url} = $opts->{ra}->{url};
3858 $self->{mods} = $mods;
3859 $self->{types} = $types;
3860 $self->{pool} = $pool;
3861 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3863 $self->{path_prefix} = length $self->{svn_path} ?
3864 "$self->{svn_path}/" : '';
3865 $self->{config} = $opts->{config};
3870 my ($tree_a, $tree_b) = @_;
3871 my @diff_tree = qw(diff-tree -z -r);
3872 if ($_cp_similarity) {
3873 push @diff_tree, "-C$_cp_similarity";
3875 push @diff_tree, '-C';
3877 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3878 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3879 push @diff_tree, $tree_a, $tree_b;
3880 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3884 while (<$diff_fh>) {
3885 chomp $_; # this gets rid of the trailing "\0"
3886 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3887 ($::sha1)\s($::sha1)\s
3888 ([MTCRAD])\d*$/xo) {
3889 push @mods, { mode_a => $1, mode_b => $2,
3890 sha1_a => $3, sha1_b => $4,
3892 if ($5 =~ /^(?:C|R)$/) {
3897 } elsif ($state eq 'file_a') {
3898 my $x = $mods[$#mods] or croak "Empty array\n";
3899 if ($x->{chg} !~ /^(?:C|R)$/) {
3900 croak "Error parsing $_, $x->{chg}\n";
3904 } elsif ($state eq 'file_b') {
3905 my $x = $mods[$#mods] or croak "Empty array\n";
3906 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3907 croak "Error parsing $_, $x->{chg}\n";
3909 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3910 croak "Error parsing $_, $x->{chg}\n";
3915 croak "Error parsing $_\n";
3918 command_close_pipe($diff_fh, $ctx);
3922 sub check_diff_paths {
3923 my ($ra, $pfx, $rev, $mods) = @_;
3925 $pfx .= '/' if length $pfx;
3927 sub type_diff_paths {
3928 my ($ra, $types, $path, $rev) = @_;
3929 my @p = split m#/+#, $path;
3931 unless (defined $types->{$c}) {
3932 $types->{$c} = $ra->check_path($c, $rev);
3935 $c .= '/' . shift @p;
3936 next if defined $types->{$c};
3937 $types->{$c} = $ra->check_path($c, $rev);
3941 foreach my $m (@$mods) {
3942 foreach my $f (qw/file_a file_b/) {
3943 next unless defined $m->{$f};
3944 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3945 if (length $pfx.$dir && ! defined $types{$dir}) {
3946 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3954 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3958 my ($self, $path) = @_;
3959 $self->{path_prefix}.(defined $path ? $path : '');
3963 my ($self, $path) = @_;
3964 if ($self->{url} =~ m#^https?://#) {
3965 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3967 $self->{url} . '/' . $self->repo_path($path);
3972 my $rm = $self->{rm};
3973 delete $rm->{''}; # we never delete the url we're tracking
3976 foreach (keys %$rm) {
3977 my @d = split m#/#, $_;
3981 $c .= '/' . shift @d;
3985 delete $rm->{$self->{svn_path}};
3986 delete $rm->{''}; # we never delete the url we're tracking
3989 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3994 my @dn = split m#/#, $_;
3996 delete $rm->{join '/', @dn};
4003 command_close_pipe($fh, $ctx);
4005 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4006 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4007 $self->close_directory($bat->{$d}, $p);
4008 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4009 print "\tD+\t$d/\n" unless $::_q;
4010 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4015 sub open_or_add_dir {
4016 my ($self, $full_path, $baton) = @_;
4017 my $t = $self->{types}->{$full_path};
4019 die "$full_path not known in r$self->{r} or we have a bug!\n";
4023 # SVN::Node::none and SVN::Node::file are used only once,
4024 # so we're shutting up Perl's warnings about them.
4025 if ($t == $SVN::Node::none) {
4026 return $self->add_directory($full_path, $baton,
4027 undef, -1, $self->{pool});
4028 } elsif ($t == $SVN::Node::dir) {
4029 return $self->open_directory($full_path, $baton,
4030 $self->{r}, $self->{pool});
4031 } # no warnings 'once'
4032 print STDERR "$full_path already exists in repository at ",
4033 "r$self->{r} and it is not a directory (",
4034 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4035 } # no warnings 'once'
4040 my ($self, $path) = @_;
4041 my $bat = $self->{bat};
4042 my $repo_path = $self->repo_path($path);
4043 return $bat->{''} unless (length $repo_path);
4044 my @p = split m#/+#, $repo_path;
4046 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4049 $c .= '/' . shift @p;
4050 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4055 # Subroutine to convert a globbing pattern to a regular expression.
4056 # From perl cookbook.
4058 my $globstr = shift;
4059 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4060 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4061 return '^' . $globstr . '$';
4064 sub check_autoprop {
4065 my ($self, $pattern, $properties, $file, $fbat) = @_;
4066 # Convert the globbing pattern to a regular expression.
4067 my $regex = glob2pat($pattern);
4068 # Check if the pattern matches the file name.
4069 if($file =~ m/($regex)/) {
4070 # Parse the list of properties to set.
4071 my @props = split(/;/, $properties);
4072 foreach my $prop (@props) {
4073 # Parse 'name=value' syntax and set the property.
4074 if ($prop =~ /([^=]+)=(.*)/) {
4075 my ($n,$v) = ($1,$2);
4079 $self->change_file_prop($fbat, $n, $v);
4085 sub apply_autoprops {
4086 my ($self, $file, $fbat) = @_;
4087 my $conf_t = ${$self->{config}}{'config'};
4089 # Check [miscellany]/enable-auto-props in svn configuration.
4090 if (SVN::_Core::svn_config_get_bool(
4092 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4093 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4095 # Auto-props are enabled. Enumerate them to look for matches.
4096 my $callback = sub {
4097 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4099 SVN::_Core::svn_config_enumerate(
4101 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4107 my ($self, $m) = @_;
4108 my ($dir, $file) = split_path($m->{file_b});
4109 my $pbat = $self->ensure_path($dir);
4110 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4112 print "\tA\t$m->{file_b}\n" unless $::_q;
4113 $self->apply_autoprops($file, $fbat);
4114 $self->chg_file($fbat, $m);
4115 $self->close_file($fbat,undef,$self->{pool});
4119 my ($self, $m) = @_;
4120 my ($dir, $file) = split_path($m->{file_b});
4121 my $pbat = $self->ensure_path($dir);
4122 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4123 $self->url_path($m->{file_a}), $self->{r});
4124 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4125 $self->chg_file($fbat, $m);
4126 $self->close_file($fbat,undef,$self->{pool});
4130 my ($self, $path, $pbat) = @_;
4131 my $rpath = $self->repo_path($path);
4132 my ($dir, $file) = split_path($rpath);
4133 $self->{rm}->{$dir} = 1;
4134 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4138 my ($self, $m) = @_;
4139 my ($dir, $file) = split_path($m->{file_b});
4140 my $pbat = $self->ensure_path($dir);
4141 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4142 $self->url_path($m->{file_a}), $self->{r});
4143 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4144 $self->apply_autoprops($file, $fbat);
4145 $self->chg_file($fbat, $m);
4146 $self->close_file($fbat,undef,$self->{pool});
4148 ($dir, $file) = split_path($m->{file_a});
4149 $pbat = $self->ensure_path($dir);
4150 $self->delete_entry($m->{file_a}, $pbat);
4154 my ($self, $m) = @_;
4155 my ($dir, $file) = split_path($m->{file_b});
4156 my $pbat = $self->ensure_path($dir);
4157 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4158 $pbat,$self->{r},$self->{pool});
4159 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4160 $self->chg_file($fbat, $m);
4161 $self->close_file($fbat,undef,$self->{pool});
4164 sub T { shift->M(@_) }
4166 sub change_file_prop {
4167 my ($self, $fbat, $pname, $pval) = @_;
4168 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4171 sub _chg_file_get_blob ($$$$) {
4172 my ($self, $fbat, $m, $which) = @_;
4173 my $fh = $::_repository->temp_acquire("git_blob_$which");
4174 if ($m->{"mode_$which"} =~ /^120/) {
4175 print $fh 'link ' or croak $!;
4176 $self->change_file_prop($fbat,'svn:special','*');
4177 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4178 $self->change_file_prop($fbat,'svn:special',undef);
4180 my $blob = $m->{"sha1_$which"};
4181 return ($fh,) if ($blob =~ /^0{40}$/);
4182 my $size = $::_repository->cat_blob($blob, $fh);
4183 croak "Failed to read object $blob" if ($size < 0);
4184 $fh->flush == 0 or croak $!;
4185 seek $fh, 0, 0 or croak $!;
4187 my $exp = ::md5sum($fh);
4188 seek $fh, 0, 0 or croak $!;
4193 my ($self, $fbat, $m) = @_;
4194 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4195 $self->change_file_prop($fbat,'svn:executable','*');
4196 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4197 $self->change_file_prop($fbat,'svn:executable',undef);
4199 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4200 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4201 my $pool = SVN::Pool->new;
4202 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4204 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4205 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4207 die "Unexpected result from send_txstream: $res\n",
4208 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4211 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4212 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4213 if ($got ne $exp_b);
4215 Git::temp_release($fh_b, 1);
4216 Git::temp_release($fh_a, 1);
4221 my ($self, $m) = @_;
4222 my ($dir, $file) = split_path($m->{file_b});
4223 my $pbat = $self->ensure_path($dir);
4224 print "\tD\t$m->{file_b}\n" unless $::_q;
4225 $self->delete_entry($m->{file_b}, $pbat);
4230 my ($p,$bat) = ($self->{pool}, $self->{bat});
4231 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4233 $self->close_directory($bat->{$_}, $p);
4235 $self->close_directory($bat->{''}, $p);
4236 $self->SUPER::close_edit($p);
4242 $self->SUPER::abort_edit($self->{pool});
4247 $self->SUPER::DESTROY(@_);
4248 $self->{pool}->clear;
4251 # this drives the editor
4254 my $mods = $self->{mods};
4255 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4256 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4258 if (defined $o{$f}) {
4261 fatal("Invalid change type: $f");
4264 $self->rmdirs if $_rmdir;
4270 return scalar @$mods;
4273 package Git::SVN::Ra;
4274 use vars qw/@ISA $config_dir $_log_window_size/;
4277 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4280 # enforce temporary pool usage for some simple functions
4282 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4284 my $SUPER = "SUPER::$f";
4287 my $pool = SVN::Pool->new;
4288 my @ret = $self->$SUPER(@_,$pool);
4290 wantarray ? @ret : $ret[0];
4295 sub _auth_providers () {
4297 SVN::Client::get_simple_provider(),
4298 SVN::Client::get_ssl_server_trust_file_provider(),
4299 SVN::Client::get_simple_prompt_provider(
4300 \&Git::SVN::Prompt::simple, 2),
4301 SVN::Client::get_ssl_client_cert_file_provider(),
4302 SVN::Client::get_ssl_client_cert_prompt_provider(
4303 \&Git::SVN::Prompt::ssl_client_cert, 2),
4304 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4305 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4306 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4307 SVN::Client::get_username_provider(),
4308 SVN::Client::get_ssl_server_trust_prompt_provider(
4309 \&Git::SVN::Prompt::ssl_server_trust),
4310 SVN::Client::get_username_prompt_provider(
4311 \&Git::SVN::Prompt::username, 2)
4315 sub escape_uri_only {
4318 foreach (split m{/}, $uri) {
4319 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4327 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4328 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4329 $url = "$scheme://$domain$uri";
4335 my ($class, $url) = @_;
4337 return $RA if ($RA && $RA->{url} eq $url);
4339 SVN::_Core::svn_config_ensure($config_dir, undef);
4340 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4341 my $config = SVN::Core::config_get_config($config_dir);
4343 my $dont_store_passwords = 1;
4344 my $conf_t = ${$config}{'config'};
4347 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4348 # produces warnings that variables are used only once.
4349 # I had not found the better way to shut them up, so
4350 # the warnings of type 'once' are disabled in this block.
4351 if (SVN::_Core::svn_config_get_bool($conf_t,
4352 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4353 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4355 SVN::_Core::svn_auth_set_parameter($baton,
4356 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4357 bless (\$dont_store_passwords, "_p_void"));
4359 if (SVN::_Core::svn_config_get_bool($conf_t,
4360 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4361 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4363 $Git::SVN::Prompt::_no_auth_cache = 1;
4365 } # no warnings 'once'
4366 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4368 pool => SVN::Pool->new,
4369 auth_provider_callbacks => $callbacks);
4370 $self->{url} = $url;
4371 $self->{svn_path} = $url;
4372 $self->{repos_root} = $self->get_repos_root;
4373 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4374 $self->{cache} = { check_path => { r => 0, data => {} },
4375 get_dir => { r => 0, data => {} } };
4376 $RA = bless $self, $class;
4380 my ($self, $path, $r) = @_;
4381 my $cache = $self->{cache}->{check_path};
4382 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4383 return $cache->{data}->{$path};
4385 my $pool = SVN::Pool->new;
4386 my $t = $self->SUPER::check_path($path, $r, $pool);
4388 if ($r != $cache->{r}) {
4389 %{$cache->{data}} = ();
4392 $cache->{data}->{$path} = $t;
4396 my ($self, $dir, $r) = @_;
4397 my $cache = $self->{cache}->{get_dir};
4398 if ($r == $cache->{r}) {
4399 if (my $x = $cache->{data}->{$dir}) {
4400 return wantarray ? @$x : $x->[0];
4403 my $pool = SVN::Pool->new;
4404 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4405 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4407 if ($r != $cache->{r}) {
4408 %{$cache->{data}} = ();
4411 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4412 wantarray ? (\%dirents, $r, $props) : \%dirents;
4416 # do not call the real DESTROY since we store ourselves in $RA
4419 # get_log(paths, start, end, limit,
4420 # discover_changed_paths, strict_node_history, receiver)
4422 my ($self, @args) = @_;
4423 my $pool = SVN::Pool->new;
4425 # the limit parameter was not supported in SVN 1.1.x, so we
4426 # drop it. Therefore, the receiver callback passed to it
4427 # is made aware of this limitation by being wrapped if
4428 # the limit passed to is being wrapped.
4429 if ($SVN::Core::VERSION le '1.2.0') {
4430 my $limit = splice(@args, 3, 1);
4432 my $receiver = pop @args;
4433 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4436 my $ret = $self->SUPER::get_log(@args, $pool);
4442 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4443 my $ctx = SVN::Client->new(auth => _auth_providers);
4444 my $out = IO::File->new_tmpfile;
4446 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4447 # $ctx->diff(), so we'll create a default one
4448 my $pool = SVN::Pool->new_default_sub;
4450 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4451 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4453 my $ret = (($out->stat)[7] == 0);
4454 close $out or croak $!;
4459 sub get_commit_editor {
4460 my ($self, $log, $cb, $pool) = @_;
4461 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4462 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4466 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4467 my $new = ($rev_a == $rev_b);
4468 my $path = $gs->{path};
4470 if ($new && -e $gs->{index}) {
4471 unlink $gs->{index} or die
4472 "Couldn't unlink index: $gs->{index}: $!\n";
4474 my $pool = SVN::Pool->new;
4475 $editor->set_path_strip($path);
4476 my (@pc) = split m#/#, $path;
4477 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4479 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4481 # Since we can't rely on svn_ra_reparent being available, we'll
4482 # just have to do some magic with set_path to make it so
4483 # we only want a partial path.
4485 my $final = join('/', @pc);
4487 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4488 $sp .= '/' if length $sp;
4491 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4493 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4495 $reporter->finish_report($pool);
4497 $editor->{git_commit_ok};
4500 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4501 # svn_ra_reparent didn't work before 1.4)
4503 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4504 my $path = $gs->{path};
4505 my $pool = SVN::Pool->new;
4507 my $full_url = $self->{url};
4508 my $old_url = $full_url;
4509 $full_url .= '/' . escape_uri_only($path) if length $path;
4510 my ($ra, $reparented);
4512 if ($old_url =~ m#^svn(\+ssh)?://#) {
4516 $ra = Git::SVN::Ra->new($full_url);
4518 } elsif ($old_url ne $full_url) {
4519 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4520 $self->{url} = $full_url;
4525 $url_b = escape_url($url_b);
4526 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4527 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4528 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4529 $reporter->finish_report($pool);
4532 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4533 $self->{url} = $old_url;
4537 $editor->{git_commit_ok};
4540 sub longest_common_path {
4541 my ($gsv, $globs) = @_;
4543 my $common_max = scalar @$gsv;
4545 foreach my $gs (@$gsv) {
4546 my @tmp = split m#/#, $gs->{path};
4549 $p .= length($p) ? "/$_" : $_;
4555 $common_max += scalar @$globs;
4556 foreach my $glob (@$globs) {
4557 my @tmp = split m#/#, $glob->{path}->{left};
4560 $p .= length($p) ? "/$_" : $_;
4566 my $longest_path = '';
4567 foreach (sort {length $b <=> length $a} keys %common) {
4568 if ($common{$_} == $common_max) {
4576 sub gs_fetch_loop_common {
4577 my ($self, $base, $head, $gsv, $globs) = @_;
4578 return if ($base > $head);
4579 my $inc = $_log_window_size;
4580 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4581 my $longest_path = longest_common_path($gsv, $globs);
4582 my $ra_url = $self->{url};
4583 my $find_trailing_edge;
4587 my $err_handler = $SVN::Error::handler;
4588 $SVN::Error::handler = sub {
4590 skip_unknown_revs($err);
4593 my ($paths, $r, $author, $date, $log) = @_;
4594 [ dup_changed_paths($paths),
4595 { author => $author, date => $date, log => $log } ];
4597 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4598 sub { $revs{$_[1]} = _cb(@_) });
4600 print "Checked through r$max\r";
4602 $find_trailing_edge = 1;
4604 if ($err and $find_trailing_edge) {
4605 print STDERR "Path '$longest_path' ",
4606 "was probably deleted:\n",
4607 $err->expanded_message,
4608 "\nWill attempt to follow ",
4609 "revisions r$min .. r$max ",
4610 "committed before the deletion\n";
4612 while (--$hi >= $min) {
4614 $self->get_log([$longest_path], $min, $hi,
4617 $revs{$_[1]} = _cb(@_) });
4619 print STDERR "r$min .. r$ok OK\n";
4623 $find_trailing_edge = 0;
4625 $SVN::Error::handler = $err_handler;
4627 my %exists = map { $_->{path} => $_ } @$gsv;
4628 foreach my $r (sort {$a <=> $b} keys %revs) {
4629 my ($paths, $logged) = @{$revs{$r}};
4631 foreach my $gs ($self->match_globs(\%exists, $paths,
4633 if ($gs->rev_map_max >= $r) {
4636 next unless $gs->match_paths($paths, $r);
4637 $gs->{logged_rev_props} = $logged;
4638 if (my $last_commit = $gs->last_commit) {
4639 $gs->assert_index_clean($last_commit);
4641 my $log_entry = $gs->do_fetch($paths, $r);
4643 $gs->do_git_commit($log_entry);
4645 $INDEX_FILES{$gs->{index}} = 1;
4647 foreach my $g (@$globs) {
4648 my $k = "svn-remote.$g->{remote}." .
4650 Git::SVN::tmp_config($k, $r);
4656 $self = Git::SVN::Ra->new($ra_url);
4657 $ra_invalid = undef;
4660 # pre-fill the .rev_db since it'll eventually get filled in
4661 # with '0' x40 if something new gets committed
4662 foreach my $gs (@$gsv) {
4663 next if $gs->rev_map_max >= $max;
4664 next if defined $gs->rev_map_get($max);
4665 $gs->rev_map_set($max, 0 x40);
4667 foreach my $g (@$globs) {
4668 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4669 Git::SVN::tmp_config($k, $max);
4671 last if $max >= $head;
4674 $max = $head if ($max > $head);
4679 sub get_dir_globbed {
4680 my ($self, $left, $depth, $r) = @_;
4682 my @x = eval { $self->get_dir($left, $r) };
4683 return unless scalar @x == 3;
4684 my $dirents = $x[0];
4686 foreach my $de (keys %$dirents) {
4687 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4689 my @args = ("$left/$de", $depth - 1, $r);
4690 foreach my $dir ($self->get_dir_globbed(@args)) {
4691 push @finalents, "$de/$dir";
4694 push @finalents, $de;
4701 my ($self, $exists, $paths, $globs, $r) = @_;
4704 my ($self, $exists, $g, $r) = @_;
4706 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4707 $g->{path}->{depth},
4710 foreach my $de (@dirs) {
4711 my $p = $g->{path}->full_path($de);
4712 next if $exists->{$p};
4713 next if (length $g->{path}->{right} &&
4714 ($self->check_path($p, $r) !=
4716 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4717 $g->{ref}->full_path($de), 1);
4720 foreach my $g (@$globs) {
4721 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4722 if ($path->{action} =~ /^[AR]$/) {
4723 get_dir_check($self, $exists, $g, $r);
4726 foreach (keys %$paths) {
4727 if (/$g->{path}->{left_regex}/ &&
4728 !/$g->{path}->{regex}/) {
4729 next if $paths->{$_}->{action} !~ /^[AR]$/;
4730 get_dir_check($self, $exists, $g, $r);
4732 next unless /$g->{path}->{regex}/;
4734 my $pathname = $g->{path}->full_path($p);
4735 next if $exists->{$pathname};
4736 next if ($self->check_path($pathname, $r) !=
4738 $exists->{$pathname} = Git::SVN->init(
4739 $self->{url}, $pathname, undef,
4740 $g->{ref}->full_path($p), 1);
4743 foreach (split m#/#, $g->{path}->{left}) {
4745 next unless ($paths->{$c} &&
4746 ($paths->{$c}->{action} =~ /^[AR]$/));
4747 get_dir_check($self, $exists, $g, $r);
4755 return $self->{url} if ($self->{url} eq $self->{repos_root});
4756 my $url = $self->{repos_root};
4757 my @components = split(m!/!, $self->{svn_path});
4760 $url .= "/$c" if length $c;
4761 eval { (ref $self)->new($url)->get_latest_revnum };
4762 } while ($@ && ($c = shift @components));
4768 unless (defined $can_do_switch) {
4769 my $pool = SVN::Pool->new;
4771 $self->do_switch(1, '', 0, $self->{url},
4772 SVN::Delta::Editor->new, $pool);
4777 $rep->abort_report($pool);
4785 sub skip_unknown_revs {
4787 my $errno = $err->apr_err();
4788 # Maybe the branch we're tracking didn't
4789 # exist when the repo started, so it's
4790 # not an error if it doesn't, just continue
4792 # Wonderfully consistent library, eh?
4793 # 160013 - svn:// and file://
4794 # 175002 - http(s)://
4795 # 175007 - http(s):// (this repo required authorization, too...)
4796 # More codes may be discovered later...
4797 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4798 my $err_key = $err->expanded_message;
4799 # revision numbers change every time, filter them out
4800 $err_key =~ s/\d+/\0/g;
4801 $err_key = "$errno\0$err_key";
4802 unless ($ignored_err{$err_key}) {
4803 warn "W: Ignoring error from SVN, path probably ",
4804 "does not exist: ($errno): ",
4805 $err->expanded_message,"\n";
4806 warn "W: Do not be alarmed at the above message ",
4807 "git-svn is just searching aggressively for ",
4809 "This may take a while on large repositories\n";
4810 $ignored_err{$err_key} = 1;
4814 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4817 # svn_log_changed_path_t objects passed to get_log are likely to be
4818 # overwritten even if only the refs are copied to an external variable,
4819 # so we should dup the structures in their entirety. Using an externally
4820 # passed pool (instead of our temporary and quickly cleared pool in
4821 # Git::SVN::Ra) does not help matters at all...
4822 sub dup_changed_paths {
4824 return undef unless $paths;
4826 foreach my $p (keys %$paths) {
4827 my $i = $paths->{$p};
4828 my %s = map { $_ => $i->$_ }
4829 qw/copyfrom_path copyfrom_rev action/;
4835 package Git::SVN::Log;
4838 use POSIX qw/strftime/;
4840 use constant commit_log_separator => ('-' x 72) . "\n";
4841 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4842 %rusers $show_commit $incremental/;
4847 return 1 if defined $c->{r};
4849 # big commit message got truncated by the 16k pretty buffer in rev-list
4850 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4851 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4853 my @log = command(qw/cat-file commit/, $c->{c});
4855 # shift off the headers
4856 shift @log while ($log[0] ne '');
4859 # TODO: make $c->{l} not have a trailing newline in the future
4860 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4862 (undef, $c->{r}, undef) = ::extract_metadata(
4863 (grep(/^git-svn-id: /, @log))[-1]);
4865 return defined $c->{r};
4869 return $color || Git->repository->get_colorbool('color.diff');
4872 sub git_svn_log_cmd {
4873 my ($r_min, $r_max, @args) = @_;
4875 my (@files, @log_opts);
4876 foreach my $x (@args) {
4877 if ($x eq '--' || @files) {
4880 if (::verify_ref("$x^0")) {
4888 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4889 $gs ||= Git::SVN->_new;
4890 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4892 push @cmd, '-r' unless $non_recursive;
4893 push @cmd, qw/--raw --name-status/ if $verbose;
4894 push @cmd, '--color' if log_use_color();
4895 push @cmd, @log_opts;
4896 if (defined $r_max && $r_max == $r_min) {
4897 push @cmd, '--max-count=1';
4898 if (my $c = $gs->rev_map_get($r_max)) {
4901 } elsif (defined $r_max) {
4902 if ($r_max < $r_min) {
4903 ($r_min, $r_max) = ($r_max, $r_min);
4905 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4906 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4907 # If there are no commits in the range, both $c_max and $c_min
4908 # will be undefined. If there is at least 1 commit in the
4909 # range, both will be defined.
4910 return () if !defined $c_min || !defined $c_max;
4911 if ($c_min eq $c_max) {
4912 push @cmd, '--max-count=1', $c_min;
4914 push @cmd, '--boundary', "$c_min..$c_max";
4917 return (@cmd, @files);
4920 # adapted from pager.c
4922 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4923 if (!defined $pager) {
4925 } elsif (length $pager == 0 || $pager eq 'cat') {
4928 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4932 return unless -t *STDOUT && defined $pager;
4933 pipe my ($rfd, $wfd) or return;
4934 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4936 open STDOUT, '>&', $wfd or
4937 ::fatal "Can't redirect to stdout: $!";
4940 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4941 $ENV{LESS} ||= 'FRSX';
4942 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4945 sub format_svn_date {
4946 # some systmes don't handle or mishandle %z, so be creative.
4947 my $t = shift || time;
4948 my $gm = timelocal(gmtime($t));
4949 my $sign = qw( + + - )[ $t <=> $gm ];
4950 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4951 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4954 sub parse_git_date {
4956 # Date::Parse isn't in the standard Perl distro :(
4957 if ($tz =~ s/^\+//) {
4958 $t += tz_to_s_offset($tz);
4959 } elsif ($tz =~ s/^\-//) {
4960 $t -= tz_to_s_offset($tz);
4965 sub set_local_timezone {
4973 sub tz_to_s_offset {
4976 return ($1 * 60) + ($tz * 3600);
4979 sub get_author_info {
4980 my ($dest, $author, $t, $tz) = @_;
4981 $author =~ s/(?:^\s*|\s*$)//g;
4982 $dest->{a_raw} = $author;
4985 $au = $rusers{$author} || undef;
4988 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4993 $dest->{t_utc} = parse_git_date($t, $tz);
4996 sub process_commit {
4997 my ($c, $r_min, $r_max, $defer) = @_;
4998 if (defined $r_min && defined $r_max) {
4999 if ($r_min == $c->{r} && $r_min == $r_max) {
5003 return 1 if $r_min == $r_max;
5004 if ($r_min < $r_max) {
5005 # we need to reverse the print order
5006 return 0 if (defined $limit && --$limit < 0);
5010 if ($r_min != $r_max) {
5011 return 1 if ($r_min < $c->{r});
5012 return 1 if ($r_max > $c->{r});
5015 return 0 if (defined $limit && --$limit < 0);
5024 if (my $l = $c->{l}) {
5025 while ($l->[0] =~ /^\s*$/) { shift @$l }
5028 $l_fmt ||= 'A' . length($c->{r});
5029 print 'r',pack($l_fmt, $c->{r}),' | ';
5030 print "$c->{c} | " if $show_commit;
5033 show_commit_normal($c);
5037 sub show_commit_changed_paths {
5039 return unless $c->{changed};
5040 print "Changed paths:\n", @{$c->{changed}};
5043 sub show_commit_normal {
5045 print commit_log_separator, "r$c->{r} | ";
5046 print "$c->{c} | " if $show_commit;
5047 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5050 if (my $l = $c->{l}) {
5051 while ($l->[$#$l] eq "\n" && $#$l > 0
5052 && $l->[($#$l - 1)] eq "\n") {
5055 $nr_line = scalar @$l;
5057 print "1 line\n\n\n";
5059 if ($nr_line == 1) {
5060 $nr_line = '1 line';
5062 $nr_line .= ' lines';
5064 print $nr_line, "\n";
5065 show_commit_changed_paths($c);
5067 print $_ foreach @$l;
5071 show_commit_changed_paths($c);
5075 foreach my $x (qw/raw stat diff/) {
5078 print $_ foreach @{$c->{$x}}
5085 my ($r_min, $r_max);
5086 my $r_last = -1; # prevent dupes
5087 set_local_timezone();
5088 if (defined $::_revision) {
5089 if ($::_revision =~ /^(\d+):(\d+)$/) {
5090 ($r_min, $r_max) = ($1, $2);
5091 } elsif ($::_revision =~ /^\d+$/) {
5092 $r_min = $r_max = $::_revision;
5094 ::fatal "-r$::_revision is not supported, use ",
5095 "standard 'git log' arguments instead";
5100 @args = git_svn_log_cmd($r_min, $r_max, @args);
5102 print commit_log_separator unless $incremental || $oneline;
5105 my $log = command_output_pipe(@args);
5107 my (@k, $c, $d, $stat);
5108 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5110 if (/^${esc_color}commit -?($::sha1_short)/o) {
5112 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5114 process_commit($c, $r_min, $r_max, \@k) or
5119 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5120 get_author_info($c, $1, $2, $3);
5121 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5123 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5124 push @{$c->{raw}}, $_;
5125 } elsif (/^${esc_color}[ACRMDT]\t/) {
5126 # we could add $SVN->{svn_path} here, but that requires
5127 # remote access at the moment (repo_path_split)...
5128 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5129 push @{$c->{changed}}, $_;
5130 } elsif (/^${esc_color}diff /o) {
5132 push @{$c->{diff}}, $_;
5134 push @{$c->{diff}}, $_;
5135 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5136 $esc_color*[\+\-]*$esc_color$/x) {
5138 push @{$c->{stat}}, $_;
5139 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5140 push @{$c->{stat}}, $_;
5142 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5143 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5144 } elsif (s/^${esc_color} //o) {
5145 push @{$c->{l}}, $_;
5148 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5150 process_commit($c, $r_min, $r_max, \@k);
5153 ($r_min, $r_max) = ($r_max, $r_min);
5154 process_commit($_, $r_min, $r_max) foreach reverse @k;
5158 print commit_log_separator unless $incremental || $oneline;
5167 my ($fh, $ctx, $rev);
5170 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5171 while (my $line = <$fh>) {
5172 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5173 # Uncommitted edits show up as a rev ID of
5174 # all zeros, which we can't look up with
5177 (undef, $rev, undef) =
5179 $rev = '0' if (!$rev);
5183 $rev = sprintf('%-10s', $rev);
5184 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5189 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5194 my %dsha; #distinct sha keys
5196 while (my $line = <$fh>) {
5197 push @buffer, $line;
5198 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5203 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5205 foreach my $line (@buffer) {
5206 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5208 $rev = '0' if (!$rev)
5210 elsif ($line =~ /^author (.*)/) {
5211 $authors{$rev} = $1;
5212 $authors{$rev} =~ s/\s/_/g;
5214 elsif ($line =~ /^\t(.*)$/) {
5215 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5219 command_close_pipe($fh, $ctx);
5222 package Git::SVN::Migration;
5223 # these version numbers do NOT correspond to actual version numbers
5224 # of git nor git-svn. They are just relative.
5226 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5228 # v1 layout: .git/$id/info/url, refs/remotes/$id
5230 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5232 # v3 layout: .git/svn/$id, refs/remotes/$id
5233 # - info/url may remain for backwards compatibility
5234 # - this is what we migrate up to this layout automatically,
5235 # - this will be used by git svn init on single branches
5236 # v3.1 layout (auto migrated):
5237 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5238 # for backwards compatibility
5240 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5241 # - this is only created for newly multi-init-ed
5242 # repositories. Similar in spirit to the
5243 # --use-separate-remotes option in git-clone (now default)
5244 # - we do not automatically migrate to this (following
5245 # the example set by core git)
5247 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5248 # - newer, more-efficient format that uses 24-bytes per record
5249 # with no filler space.
5250 # - use xxd -c24 < .rev_map.$UUID to view and debug
5251 # - This is a one-way migration, repositories updated to the
5252 # new format will not be able to use old git-svn without
5253 # rebuilding the .rev_db. Rebuilding the rev_db is not
5254 # possible if noMetadata or useSvmProps are set; but should
5255 # be no problem for users that use the (sensible) defaults.
5259 use File::Path qw/mkpath/;
5260 use File::Basename qw/dirname basename/;
5261 use vars qw/$_minimize/;
5263 sub migrate_from_v0 {
5264 my $git_dir = $ENV{GIT_DIR};
5265 return undef unless -d $git_dir;
5266 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5270 my ($id, $orig_ref) = ($_, $_);
5271 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5272 next unless -f "$git_dir/$id/info/url";
5273 my $new_ref = "refs/remotes/$id";
5274 if (::verify_ref("$new_ref^0")) {
5275 print STDERR "W: $orig_ref is probably an old ",
5276 "branch used by an ancient version of ",
5278 "However, $new_ref also exists.\n",
5279 "We will not be able ",
5280 "to use this branch until this ",
5281 "ambiguity is resolved.\n";
5284 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5285 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5286 command_noisy('update-ref', $new_ref, $orig_ref);
5287 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5290 command_close_pipe($fh, $ctx);
5291 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5295 sub migrate_from_v1 {
5296 my $git_dir = $ENV{GIT_DIR};
5298 return $migrated unless -d $git_dir;
5299 my $svn_dir = "$git_dir/svn";
5301 # just in case somebody used 'svn' as their $id at some point...
5302 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5304 print STDERR "Migrating from a git-svn v1 layout...\n";
5306 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5307 "$svn_dir\n\t(required for this version ",
5308 "($::VERSION) of git-svn) does not exist.\n";
5309 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5312 next unless $x =~ s#^refs/remotes/##;
5314 next unless -f "$git_dir/$x/info/url";
5315 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5317 my $dn = dirname("$git_dir/svn/$x");
5318 mkpath([$dn]) unless -d $dn;
5319 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5320 mkpath(["$git_dir/svn/svn"]);
5321 print STDERR " - $git_dir/$x/info => ",
5322 "$git_dir/svn/$x/info\n";
5323 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5325 # don't worry too much about these, they probably
5326 # don't exist with repos this old (save for index,
5327 # and we can easily regenerate that)
5328 foreach my $f (qw/unhandled.log index .rev_db/) {
5329 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5332 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5333 rename "$git_dir/$x", "$git_dir/svn/$x" or
5338 command_close_pipe($fh, $ctx);
5339 print STDERR "Done migrating from a git-svn v1 layout\n";
5344 my ($l_map, $pfx, $path) = @_;
5346 foreach (<$path/*>) {
5347 if (-r "$_/info/url") {
5348 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5349 my $ref_id = $pfx . basename $_;
5350 my $url = ::file_to_s("$_/info/url");
5351 $l_map->{$ref_id} = $url;
5358 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5359 read_old_urls($l_map, $x, $_);
5363 sub migrate_from_v2 {
5364 my @cfg = command(qw/config -l/);
5365 return if grep /^svn-remote\..+\.url=/, @cfg;
5367 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5370 foreach my $ref_id (sort keys %l_map) {
5371 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5373 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5380 sub minimize_connections {
5381 my $r = Git::SVN::read_all_remotes();
5383 my $root_repos = {};
5384 foreach my $repo_id (keys %$r) {
5385 my $url = $r->{$repo_id}->{url} or next;
5386 my $fetch = $r->{$repo_id}->{fetch} or next;
5387 my $ra = Git::SVN::Ra->new($url);
5389 # skip existing cases where we already connect to the root
5390 if (($ra->{url} eq $ra->{repos_root}) ||
5391 ($ra->{repos_root} eq $repo_id)) {
5392 $root_repos->{$ra->{url}} = $repo_id;
5396 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5397 my $root_path = $ra->{url};
5398 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5399 foreach my $path (keys %$fetch) {
5400 my $ref_id = $fetch->{$path};
5401 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5403 # make sure we can read when connecting to
5404 # a higher level of a repository
5405 my ($last_rev, undef) = $gs->last_rev_commit;
5406 if (!defined $last_rev) {
5408 $root_ra->get_latest_revnum;
5412 my $new = $root_path;
5413 $new .= length $path ? "/$path" : '';
5415 $root_ra->get_log([$new], $last_rev, $last_rev,
5419 $new_urls->{$ra->{repos_root}}->{$new} =
5420 { ref_id => $ref_id,
5421 old_repo_id => $repo_id,
5422 old_path => $path };
5427 foreach my $url (keys %$new_urls) {
5428 # see if we can re-use an existing [svn-remote "repo_id"]
5429 # instead of creating a(n ugly) new section:
5430 my $repo_id = $root_repos->{$url} || $url;
5432 my $fetch = $new_urls->{$url};
5433 foreach my $path (keys %$fetch) {
5434 my $x = $fetch->{$path};
5435 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5436 my $pfx = "svn-remote.$x->{old_repo_id}";
5438 my $old_fetch = quotemeta("$x->{old_path}:".
5439 "refs/remotes/$x->{ref_id}");
5440 command_noisy(qw/config --unset/,
5441 "$pfx.fetch", '^'. $old_fetch . '$');
5442 delete $r->{$x->{old_repo_id}}->
5443 {fetch}->{$x->{old_path}};
5444 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5445 command_noisy(qw/config --unset/,
5447 push @emptied, $x->{old_repo_id}
5452 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5454 The following [svn-remote] sections in your config file ($file) are empty
5455 and can be safely removed:
5457 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5461 sub migration_check {
5465 minimize_connections() if $_minimize;
5468 package Git::IndexInfo;
5471 use Git qw/command_input_pipe command_close_pipe/;
5475 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5476 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5480 my ($self, $path) = @_;
5481 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5482 return ++$self->{nr};
5488 my ($self, $mode, $hash, $path) = @_;
5489 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5490 return ++$self->{nr};
5497 command_close_pipe($self->{gui}, $self->{ctx});
5500 package Git::SVN::GlobSpec;
5505 my ($class, $glob) = @_;
5507 $re =~ s!/+$!!g; # no need for trailing slashes
5508 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5510 my ($left, $right) = ($1, $3);
5512 my $depth = $re =~ tr/*/*/;
5513 if ($depth != $temp =~ tr/*/*/) {
5514 die "Only one set of wildcard directories " .
5515 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5518 die "One '*' is needed for glob: '$glob'\n";
5520 $re =~ s!\*!\[^/\]*!g;
5521 $re = quotemeta($left) . "($re)" . quotemeta($right);
5522 if (length $left && !($left =~ s!/+$!!g)) {
5523 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5525 if (length $right && !($right =~ s!^/+!!g)) {
5526 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5528 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5529 bless { left => $left, right => $right, left_regex => $left_re,
5530 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5534 my ($self, $path) = @_;
5535 return (length $self->{left} ? "$self->{left}/" : '') .
5536 $path . (length $self->{right} ? "/$self->{right}" : '');
5544 $remotes = { # returned by read_all_remotes()
5546 # svn-remote.svn.url=https://svn.musicpd.org
5547 url => 'https://svn.musicpd.org',
5548 # svn-remote.svn.fetch=mpd/trunk:trunk
5550 'mpd/trunk' => 'trunk',
5552 # svn-remote.svn.tags=mpd/tags/*:tags/*
5557 regex => qr!mpd/tags/([^/]+)$!,
5563 regex => qr!tags/([^/]+)$!,
5570 $log_entry hashref as returned by libsvn_log_entry()
5572 log => 'whitespace-formatted log entry
5573 ', # trailing newline is preserved
5574 revision => '8', # integer
5575 date => '2004-02-24T17:01:44.108345Z', # commit date
5576 author => 'committer name'
5580 # this is generated by generate_diff();
5581 @mods = array of diff-index line hashes, each element represents one line
5582 of diff-index output
5584 diff-index line ($m hash)
5586 mode_a => first column of diff-index output, no leading ':',
5587 mode_b => second column of diff-index output,
5588 sha1_b => sha1sum of the final blob,
5589 chg => change type [MCRADT],
5590 file_a => original file name of a file (iff chg is 'C' or 'R')
5591 file_b => new/current file name of a file (any chg)
5595 # retval of read_url_paths{,_all}();
5597 # repository root url
5598 'https://svn.musicpd.org' => {
5599 # repository path # GIT_SVN_ID
5600 'mpd/trunk' => 'trunk',
5601 'mpd/tags/0.11.5' => 'tags/0.11.5',
5606 I don't trust the each() function on unless I created %hash myself
5607 because the internal iterator may not have started at base.