Code

6657e100fbbc3bd83e805b2440b1a7b61780c5f4
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision
8                 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
28 }
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41         my $s;
42         foreach (qw/command command_oneline command_noisy command_output_pipe
43                     command_input_pipe command_close_pipe/) {
44                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
45                       "*Git::SVN::Migration::$_ = ".
46                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
47         }
48         eval $s;
49 }
51 my ($SVN);
53 $sha1 = qr/[a-f\d]{40}/;
54 $sha1_short = qr/[a-f\d]{4,40}/;
55 my ($_stdin, $_help, $_edit,
56         $_message, $_file,
57         $_template, $_shared,
58         $_version, $_fetch_all,
59         $_merge, $_strategy, $_dry_run, $_local,
60         $_prefix, $_no_checkout, $_verbose);
61 $Git::SVN::_follow_parent = 1;
62 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
64                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
65 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
66                 'authors-file|A=s' => \$_authors,
67                 'repack:i' => \$Git::SVN::_repack,
68                 'noMetadata' => \$Git::SVN::_no_metadata,
69                 'useSvmProps' => \$Git::SVN::_use_svm_props,
70                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
71                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
72                 'no-checkout' => \$_no_checkout,
73                 'quiet|q' => \$_q,
74                 'repack-flags|repack-args|repack-opts=s' =>
75                    \$Git::SVN::_repack_flags,
76                 %remote_opts );
78 my ($_trunk, $_tags, $_branches);
79 my %icv;
80 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81                   'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82                   'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
83                   'no-metadata' => sub { $icv{noMetadata} = 1 },
84                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
85                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
86                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
87                   %remote_opts );
88 my %cmt_opts = ( 'edit|e' => \$_edit,
89                 'rmdir' => \$SVN::Git::Editor::_rmdir,
90                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
91                 'l=i' => \$SVN::Git::Editor::_rename_limit,
92                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
93 );
95 my %cmd = (
96         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
97                         { 'revision|r=s' => \$_revision,
98                           'fetch-all|all' => \$_fetch_all,
99                            %fc_opts } ],
100         clone => [ \&cmd_clone, "Initialize and fetch revisions",
101                         { 'revision|r=s' => \$_revision,
102                            %fc_opts, %init_opts } ],
103         init => [ \&cmd_init, "Initialize a repo for tracking" .
104                           " (requires URL argument)",
105                           \%init_opts ],
106         'multi-init' => [ \&cmd_multi_init,
107                           "Deprecated alias for ".
108                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
109                           \%init_opts ],
110         dcommit => [ \&cmd_dcommit,
111                      'Commit several diffs to merge with upstream',
112                         { 'merge|m|M' => \$_merge,
113                           'strategy|s=s' => \$_strategy,
114                           'verbose|v' => \$_verbose,
115                           'dry-run|n' => \$_dry_run,
116                           'fetch-all|all' => \$_fetch_all,
117                         %cmt_opts, %fc_opts } ],
118         'set-tree' => [ \&cmd_set_tree,
119                         "Set an SVN repository to a git tree-ish",
120                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
121         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
122                         { 'revision|r=i' => \$_revision } ],
123         'multi-fetch' => [ \&cmd_multi_fetch,
124                            "Deprecated alias for $0 fetch --all",
125                            { 'revision|r=s' => \$_revision, %fc_opts } ],
126         'migrate' => [ sub { },
127                        # no-op, we automatically run this anyways,
128                        'Migrate configuration/metadata/layout from
129                         previous versions of git-svn',
130                        { 'minimize' => \$Git::SVN::Migration::_minimize,
131                          %remote_opts } ],
132         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
133                         { 'limit=i' => \$Git::SVN::Log::limit,
134                           'revision|r=s' => \$_revision,
135                           'verbose|v' => \$Git::SVN::Log::verbose,
136                           'incremental' => \$Git::SVN::Log::incremental,
137                           'oneline' => \$Git::SVN::Log::oneline,
138                           'show-commit' => \$Git::SVN::Log::show_commit,
139                           'non-recursive' => \$Git::SVN::Log::non_recursive,
140                           'authors-file|A=s' => \$_authors,
141                           'color' => \$Git::SVN::Log::color,
142                           'pager=s' => \$Git::SVN::Log::pager,
143                         } ],
144         'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
145                         { } ],
146         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
147                         { 'merge|m|M' => \$_merge,
148                           'verbose|v' => \$_verbose,
149                           'strategy|s=s' => \$_strategy,
150                           'local|l' => \$_local,
151                           'fetch-all|all' => \$_fetch_all,
152                           %fc_opts } ],
153         'commit-diff' => [ \&cmd_commit_diff,
154                            'Commit a diff between two trees',
155                         { 'message|m=s' => \$_message,
156                           'file|F=s' => \$_file,
157                           'revision|r=s' => \$_revision,
158                         %cmt_opts } ],
159 );
161 my $cmd;
162 for (my $i = 0; $i < @ARGV; $i++) {
163         if (defined $cmd{$ARGV[$i]}) {
164                 $cmd = $ARGV[$i];
165                 splice @ARGV, $i, 1;
166                 last;
167         }
168 };
170 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
172 read_repo_config(\%opts);
173 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
174 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
175                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
176                     'id|i=s' => \$Git::SVN::default_ref_id,
177                     'svn-remote|remote|R=s' => sub {
178                        $Git::SVN::no_reuse_existing = 1;
179                        $Git::SVN::default_repo_id = $_[1] });
180 exit 1 if (!$rv && $cmd && $cmd ne 'log');
182 usage(0) if $_help;
183 version() if $_version;
184 usage(1) unless defined $cmd;
185 load_authors() if $_authors;
187 # make sure we're always running
188 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
189         unless (-d $ENV{GIT_DIR}) {
190                 if ($git_dir_user_set) {
191                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
192                             "but it is not a directory\n";
193                 }
194                 my $git_dir = delete $ENV{GIT_DIR};
195                 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
196                 unless (length $cdup) {
197                         die "Already at toplevel, but $git_dir ",
198                             "not found '$cdup'\n";
199                 }
200                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
201                 unless (-d $git_dir) {
202                         die "$git_dir still not found after going to ",
203                             "'$cdup'\n";
204                 }
205                 $ENV{GIT_DIR} = $git_dir;
206         }
208 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
209         Git::SVN::Migration::migration_check();
211 Git::SVN::init_vars();
212 eval {
213         Git::SVN::verify_remotes_sanity();
214         $cmd{$cmd}->[0]->(@ARGV);
215 };
216 fatal $@ if $@;
217 post_fetch_checkout();
218 exit 0;
220 ####################### primary functions ######################
221 sub usage {
222         my $exit = shift || 0;
223         my $fd = $exit ? \*STDERR : \*STDOUT;
224         print $fd <<"";
225 git-svn - bidirectional operations between a single Subversion tree and git
226 Usage: $0 <command> [options] [arguments]\n
228         print $fd "Available commands:\n" unless $cmd;
230         foreach (sort keys %cmd) {
231                 next if $cmd && $cmd ne $_;
232                 next if /^multi-/; # don't show deprecated commands
233                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
234                 foreach (keys %{$cmd{$_}->[2]}) {
235                         # mixed-case options are for .git/config only
236                         next if /[A-Z]/ && /^[a-z]+$/i;
237                         # prints out arguments as they should be passed:
238                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
239                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
240                                                         "--$_" : "-$_" }
241                                                 split /\|/,$_)," $x\n";
242                 }
243         }
244         print $fd <<"";
245 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
246 arbitrary identifier if you're tracking multiple SVN branches/repositories in
247 one git repository and want to keep them separate.  See git-svn(1) for more
248 information.
250         exit $exit;
253 sub version {
254         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
255         exit 0;
258 sub do_git_init_db {
259         unless (-d $ENV{GIT_DIR}) {
260                 my @init_db = ('init');
261                 push @init_db, "--template=$_template" if defined $_template;
262                 if (defined $_shared) {
263                         if ($_shared =~ /[a-z]/) {
264                                 push @init_db, "--shared=$_shared";
265                         } else {
266                                 push @init_db, "--shared";
267                         }
268                 }
269                 command_noisy(@init_db);
270         }
271         my $set;
272         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
273         foreach my $i (keys %icv) {
274                 die "'$set' and '$i' cannot both be set\n" if $set;
275                 next unless defined $icv{$i};
276                 command_noisy('config', "$pfx.$i", $icv{$i});
277                 $set = $i;
278         }
281 sub init_subdir {
282         my $repo_path = shift or return;
283         mkpath([$repo_path]) unless -d $repo_path;
284         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
285         $ENV{GIT_DIR} = '.git';
288 sub cmd_clone {
289         my ($url, $path) = @_;
290         if (!defined $path &&
291             (defined $_trunk || defined $_branches || defined $_tags) &&
292             $url !~ m#^[a-z\+]+://#) {
293                 $path = $url;
294         }
295         $path = basename($url) if !defined $path || !length $path;
296         cmd_init($url, $path);
297         Git::SVN::fetch_all($Git::SVN::default_repo_id);
300 sub cmd_init {
301         if (defined $_trunk || defined $_branches || defined $_tags) {
302                 return cmd_multi_init(@_);
303         }
304         my $url = shift or die "SVN repository location required ",
305                                "as a command-line argument\n";
306         init_subdir(@_);
307         do_git_init_db();
309         Git::SVN->init($url);
312 sub cmd_fetch {
313         if (grep /^\d+=./, @_) {
314                 die "'<rev>=<commit>' fetch arguments are ",
315                     "no longer supported.\n";
316         }
317         my ($remote) = @_;
318         if (@_ > 1) {
319                 die "Usage: $0 fetch [--all] [svn-remote]\n";
320         }
321         $remote ||= $Git::SVN::default_repo_id;
322         if ($_fetch_all) {
323                 cmd_multi_fetch();
324         } else {
325                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
326         }
329 sub cmd_set_tree {
330         my (@commits) = @_;
331         if ($_stdin || !@commits) {
332                 print "Reading from stdin...\n";
333                 @commits = ();
334                 while (<STDIN>) {
335                         if (/\b($sha1_short)\b/o) {
336                                 unshift @commits, $1;
337                         }
338                 }
339         }
340         my @revs;
341         foreach my $c (@commits) {
342                 my @tmp = command('rev-parse',$c);
343                 if (scalar @tmp == 1) {
344                         push @revs, $tmp[0];
345                 } elsif (scalar @tmp > 1) {
346                         push @revs, reverse(command('rev-list',@tmp));
347                 } else {
348                         fatal "Failed to rev-parse $c\n";
349                 }
350         }
351         my $gs = Git::SVN->new;
352         my ($r_last, $cmt_last) = $gs->last_rev_commit;
353         $gs->fetch;
354         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
355                 fatal "There are new revisions that were fetched ",
356                       "and need to be merged (or acknowledged) ",
357                       "before committing.\nlast rev: $r_last\n",
358                       " current: $gs->{last_rev}\n";
359         }
360         $gs->set_tree($_) foreach @revs;
361         print "Done committing ",scalar @revs," revisions to SVN\n";
364 sub cmd_dcommit {
365         my $head = shift;
366         $head ||= 'HEAD';
367         my @refs;
368         my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
369         unless ($gs) {
370                 die "Unable to determine upstream SVN information from ",
371                     "$head history\n";
372         }
373         my $c = $refs[-1];
374         my $last_rev;
375         foreach my $d (@refs) {
376                 if (!verify_ref("$d~1")) {
377                         fatal "Commit $d\n",
378                               "has no parent commit, and therefore ",
379                               "nothing to diff against.\n",
380                               "You should be working from a repository ",
381                               "originally created by git-svn\n";
382                 }
383                 unless (defined $last_rev) {
384                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
385                         unless (defined $last_rev) {
386                                 fatal "Unable to extract revision information ",
387                                       "from commit $d~1\n";
388                         }
389                 }
390                 if ($_dry_run) {
391                         print "diff-tree $d~1 $d\n";
392                 } else {
393                         my %ed_opts = ( r => $last_rev,
394                                         log => get_commit_entry($d)->{log},
395                                         ra => Git::SVN::Ra->new($url),
396                                         tree_a => "$d~1",
397                                         tree_b => $d,
398                                         editor_cb => sub {
399                                                print "Committed r$_[0]\n";
400                                                $last_rev = $_[0]; },
401                                         svn_path => '');
402                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
403                                 print "No changes\n$d~1 == $d\n";
404                         }
405                 }
406         }
407         return if $_dry_run;
408         unless ($gs) {
409                 warn "Could not determine fetch information for $url\n",
410                      "Will not attempt to fetch and rebase commits.\n",
411                      "This probably means you have useSvmProps and should\n",
412                      "now resync your SVN::Mirror repository.\n";
413                 return;
414         }
415         $_fetch_all ? $gs->fetch_all : $gs->fetch;
416         # we always want to rebase against the current HEAD, not any
417         # head that was passed to us
418         my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
419         my @finish;
420         if (@diff) {
421                 @finish = rebase_cmd();
422                 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
423                              "using @finish:\n", "@diff";
424         } else {
425                 print "No changes between current HEAD and ",
426                       $gs->refname, "\nResetting to the latest ",
427                       $gs->refname, "\n";
428                 @finish = qw/reset --mixed/;
429         }
430         command_noisy(@finish, $gs->refname);
433 sub cmd_find_rev {
434         my $revision_or_hash = shift;
435         my $result;
436         if ($revision_or_hash =~ /^r\d+$/) {
437                 my $head = shift;
438                 $head ||= 'HEAD';
439                 my @refs;
440                 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
441                 unless ($gs) {
442                         die "Unable to determine upstream SVN information from ",
443                             "$head history\n";
444                 }
445                 my $desired_revision = substr($revision_or_hash, 1);
446                 $result = $gs->rev_db_get($desired_revision);
447         } else {
448                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
449                 $result = $rev;
450         }
451         print "$result\n" if $result;
454 sub cmd_rebase {
455         command_noisy(qw/update-index --refresh/);
456         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
457         unless ($gs) {
458                 die "Unable to determine upstream SVN information from ",
459                     "working tree history\n";
460         }
461         if (command(qw/diff-index HEAD --/)) {
462                 print STDERR "Cannot rebase with uncommited changes:\n";
463                 command_noisy('status');
464                 exit 1;
465         }
466         unless ($_local) {
467                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
468         }
469         command_noisy(rebase_cmd(), $gs->refname);
472 sub cmd_show_ignore {
473         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
474         $gs ||= Git::SVN->new;
475         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
476         $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
479 sub cmd_multi_init {
480         my $url = shift;
481         unless (defined $_trunk || defined $_branches || defined $_tags) {
482                 usage(1);
483         }
484         $_prefix = '' unless defined $_prefix;
485         if (defined $url) {
486                 $url =~ s#/+$##;
487                 init_subdir(@_);
488         }
489         do_git_init_db();
490         if (defined $_trunk) {
491                 my $trunk_ref = $_prefix . 'trunk';
492                 # try both old-style and new-style lookups:
493                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
494                 unless ($gs_trunk) {
495                         my ($trunk_url, $trunk_path) =
496                                               complete_svn_url($url, $_trunk);
497                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
498                                                    undef, $trunk_ref);
499                 }
500         }
501         return unless defined $_branches || defined $_tags;
502         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
503         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
504         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
507 sub cmd_multi_fetch {
508         my $remotes = Git::SVN::read_all_remotes();
509         foreach my $repo_id (sort keys %$remotes) {
510                 if ($remotes->{$repo_id}->{url}) {
511                         Git::SVN::fetch_all($repo_id, $remotes);
512                 }
513         }
516 # this command is special because it requires no metadata
517 sub cmd_commit_diff {
518         my ($ta, $tb, $url) = @_;
519         my $usage = "Usage: $0 commit-diff -r<revision> ".
520                     "<tree-ish> <tree-ish> [<URL>]\n";
521         fatal($usage) if (!defined $ta || !defined $tb);
522         my $svn_path;
523         if (!defined $url) {
524                 my $gs = eval { Git::SVN->new };
525                 if (!$gs) {
526                         fatal("Needed URL or usable git-svn --id in ",
527                               "the command-line\n", $usage);
528                 }
529                 $url = $gs->{url};
530                 $svn_path = $gs->{path};
531         }
532         unless (defined $_revision) {
533                 fatal("-r|--revision is a required argument\n", $usage);
534         }
535         if (defined $_message && defined $_file) {
536                 fatal("Both --message/-m and --file/-F specified ",
537                       "for the commit message.\n",
538                       "I have no idea what you mean\n");
539         }
540         if (defined $_file) {
541                 $_message = file_to_s($_file);
542         } else {
543                 $_message ||= get_commit_entry($tb)->{log};
544         }
545         my $ra ||= Git::SVN::Ra->new($url);
546         $svn_path ||= $ra->{svn_path};
547         my $r = $_revision;
548         if ($r eq 'HEAD') {
549                 $r = $ra->get_latest_revnum;
550         } elsif ($r !~ /^\d+$/) {
551                 die "revision argument: $r not understood by git-svn\n";
552         }
553         my %ed_opts = ( r => $r,
554                         log => $_message,
555                         ra => $ra,
556                         tree_a => $ta,
557                         tree_b => $tb,
558                         editor_cb => sub { print "Committed r$_[0]\n" },
559                         svn_path => $svn_path );
560         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
561                 print "No changes\n$ta == $tb\n";
562         }
565 ########################### utility functions #########################
567 sub rebase_cmd {
568         my @cmd = qw/rebase/;
569         push @cmd, '-v' if $_verbose;
570         push @cmd, qw/--merge/ if $_merge;
571         push @cmd, "--strategy=$_strategy" if $_strategy;
572         @cmd;
575 sub post_fetch_checkout {
576         return if $_no_checkout;
577         my $gs = $Git::SVN::_head or return;
578         return if verify_ref('refs/heads/master^0');
580         my $valid_head = verify_ref('HEAD^0');
581         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
582         return if ($valid_head || !verify_ref('HEAD^0'));
584         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
585         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
586         return if -f $index;
588         chomp(my $bare = `git config --bool --get core.bare`);
589         return if $bare eq 'true';
590         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
591         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
592         print STDERR "Checked out HEAD:\n  ",
593                      $gs->full_url, " r", $gs->last_rev, "\n";
596 sub complete_svn_url {
597         my ($url, $path) = @_;
598         $path =~ s#/+$##;
599         if ($path !~ m#^[a-z\+]+://#) {
600                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
601                         fatal("E: '$path' is not a complete URL ",
602                               "and a separate URL is not specified\n");
603                 }
604                 return ($url, $path);
605         }
606         return ($path, '');
609 sub complete_url_ls_init {
610         my ($ra, $repo_path, $switch, $pfx) = @_;
611         unless ($repo_path) {
612                 print STDERR "W: $switch not specified\n";
613                 return;
614         }
615         $repo_path =~ s#/+$##;
616         if ($repo_path =~ m#^[a-z\+]+://#) {
617                 $ra = Git::SVN::Ra->new($repo_path);
618                 $repo_path = '';
619         } else {
620                 $repo_path =~ s#^/+##;
621                 unless ($ra) {
622                         fatal("E: '$repo_path' is not a complete URL ",
623                               "and a separate URL is not specified\n");
624                 }
625         }
626         my $url = $ra->{url};
627         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
628         my $k = "svn-remote.$gs->{repo_id}.url";
629         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
630         if ($orig_url && ($orig_url ne $gs->{url})) {
631                 die "$k already set: $orig_url\n",
632                     "wanted to set to: $gs->{url}\n";
633         }
634         command_oneline('config', $k, $gs->{url}) unless $orig_url;
635         my $remote_path = "$ra->{svn_path}/$repo_path/*";
636         $remote_path =~ s#/+#/#g;
637         $remote_path =~ s#^/##g;
638         my ($n) = ($switch =~ /^--(\w+)/);
639         if (length $pfx && $pfx !~ m#/$#) {
640                 die "--prefix='$pfx' must have a trailing slash '/'\n";
641         }
642         command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
643                                 "$remote_path:refs/remotes/$pfx*");
646 sub verify_ref {
647         my ($ref) = @_;
648         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
649                                { STDERR => 0 }); };
652 sub get_tree_from_treeish {
653         my ($treeish) = @_;
654         # $treeish can be a symbolic ref, too:
655         my $type = command_oneline(qw/cat-file -t/, $treeish);
656         my $expected;
657         while ($type eq 'tag') {
658                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
659         }
660         if ($type eq 'commit') {
661                 $expected = (grep /^tree /, command(qw/cat-file commit/,
662                                                     $treeish))[0];
663                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
664                 die "Unable to get tree from $treeish\n" unless $expected;
665         } elsif ($type eq 'tree') {
666                 $expected = $treeish;
667         } else {
668                 die "$treeish is a $type, expected tree, tag or commit\n";
669         }
670         return $expected;
673 sub get_commit_entry {
674         my ($treeish) = shift;
675         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
676         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
677         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
678         open my $log_fh, '>', $commit_editmsg or croak $!;
680         my $type = command_oneline(qw/cat-file -t/, $treeish);
681         if ($type eq 'commit' || $type eq 'tag') {
682                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
683                                                          $type, $treeish);
684                 my $in_msg = 0;
685                 while (<$msg_fh>) {
686                         if (!$in_msg) {
687                                 $in_msg = 1 if (/^\s*$/);
688                         } elsif (/^git-svn-id: /) {
689                                 # skip this for now, we regenerate the
690                                 # correct one on re-fetch anyways
691                                 # TODO: set *:merge properties or like...
692                         } else {
693                                 print $log_fh $_ or croak $!;
694                         }
695                 }
696                 command_close_pipe($msg_fh, $ctx);
697         }
698         close $log_fh or croak $!;
700         if ($_edit || ($type eq 'tree')) {
701                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
702                 # TODO: strip out spaces, comments, like git-commit.sh
703                 system($editor, $commit_editmsg);
704         }
705         rename $commit_editmsg, $commit_msg or croak $!;
706         open $log_fh, '<', $commit_msg or croak $!;
707         { local $/; chomp($log_entry{log} = <$log_fh>); }
708         close $log_fh or croak $!;
709         unlink $commit_msg;
710         \%log_entry;
713 sub s_to_file {
714         my ($str, $file, $mode) = @_;
715         open my $fd,'>',$file or croak $!;
716         print $fd $str,"\n" or croak $!;
717         close $fd or croak $!;
718         chmod ($mode &~ umask, $file) if (defined $mode);
721 sub file_to_s {
722         my $file = shift;
723         open my $fd,'<',$file or croak "$!: file: $file\n";
724         local $/;
725         my $ret = <$fd>;
726         close $fd or croak $!;
727         $ret =~ s/\s*$//s;
728         return $ret;
731 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
732 sub load_authors {
733         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
734         my $log = $cmd eq 'log';
735         while (<$authors>) {
736                 chomp;
737                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
738                 my ($user, $name, $email) = ($1, $2, $3);
739                 if ($log) {
740                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
741                 } else {
742                         $users{$user} = [$name, $email];
743                 }
744         }
745         close $authors or croak $!;
748 # convert GetOpt::Long specs for use by git-config
749 sub read_repo_config {
750         return unless -d $ENV{GIT_DIR};
751         my $opts = shift;
752         my @config_only;
753         foreach my $o (keys %$opts) {
754                 # if we have mixedCase and a long option-only, then
755                 # it's a config-only variable that we don't need for
756                 # the command-line.
757                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
758                 my $v = $opts->{$o};
759                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
760                 $key =~ s/-//g;
761                 my $arg = 'git-config';
762                 $arg .= ' --int' if ($o =~ /[:=]i$/);
763                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
764                 if (ref $v eq 'ARRAY') {
765                         chomp(my @tmp = `$arg --get-all svn.$key`);
766                         @$v = @tmp if @tmp;
767                 } else {
768                         chomp(my $tmp = `$arg --get svn.$key`);
769                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
770                                 $$v = $tmp;
771                         }
772                 }
773         }
774         delete @$opts{@config_only} if @config_only;
777 sub extract_metadata {
778         my $id = shift or return (undef, undef, undef);
779         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
780                                                         \s([a-f\d\-]+)$/x);
781         if (!defined $rev || !$uuid || !$url) {
782                 # some of the original repositories I made had
783                 # identifiers like this:
784                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
785         }
786         return ($url, $rev, $uuid);
789 sub cmt_metadata {
790         return extract_metadata((grep(/^git-svn-id: /,
791                 command(qw/cat-file commit/, shift)))[-1]);
794 sub working_head_info {
795         my ($head, $refs) = @_;
796         my ($fh, $ctx) = command_output_pipe('rev-list', $head);
797         while (my $hash = <$fh>) {
798                 chomp($hash);
799                 my ($url, $rev, $uuid) = cmt_metadata($hash);
800                 if (defined $url && defined $rev) {
801                         if (my $gs = Git::SVN->find_by_url($url)) {
802                                 my $c = $gs->rev_db_get($rev);
803                                 if ($c && $c eq $hash) {
804                                         close $fh; # break the pipe
805                                         return ($url, $rev, $uuid, $gs);
806                                 }
807                         }
808                 }
809                 unshift @$refs, $hash if $refs;
810         }
811         command_close_pipe($fh, $ctx);
812         (undef, undef, undef, undef);
815 package Git::SVN;
816 use strict;
817 use warnings;
818 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
819             $_repack $_repack_flags $_use_svm_props $_head
820             $_use_svnsync_props $no_reuse_existing/;
821 use Carp qw/croak/;
822 use File::Path qw/mkpath/;
823 use File::Copy qw/copy/;
824 use IPC::Open3;
826 my $_repack_nr;
827 # properties that we do not log:
828 my %SKIP_PROP;
829 BEGIN {
830         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
831                                         svn:special svn:executable
832                                         svn:entry:committed-rev
833                                         svn:entry:last-author
834                                         svn:entry:uuid
835                                         svn:entry:committed-date/;
837         # some options are read globally, but can be overridden locally
838         # per [svn-remote "..."] section.  Command-line options will *NOT*
839         # override options set in an [svn-remote "..."] section
840         my $e;
841         foreach (qw/follow_parent no_metadata use_svm_props
842                     use_svnsync_props/) {
843                 my $key = $_;
844                 $key =~ tr/_//d;
845                 $e .= "sub $_ {
846                         my (\$self) = \@_;
847                         return \$self->{-$_} if exists \$self->{-$_};
848                         my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
849                         eval { command_oneline(qw/config --get/, \$k) };
850                         if (\$@) {
851                                 \$self->{-$_} = \$Git::SVN::_$_;
852                         } else {
853                                 my \$v = command_oneline(qw/config --bool/,\$k);
854                                 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
855                         }
856                         return \$self->{-$_} }\n";
857         }
858         $e .= "1;\n";
859         eval $e or die $@;
862 my %LOCKFILES;
863 END { unlink keys %LOCKFILES if %LOCKFILES }
865 sub resolve_local_globs {
866         my ($url, $fetch, $glob_spec) = @_;
867         return unless defined $glob_spec;
868         my $ref = $glob_spec->{ref};
869         my $path = $glob_spec->{path};
870         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
871                 next unless m#^refs/remotes/$ref->{regex}$#;
872                 my $p = $1;
873                 my $pathname = $path->full_path($p);
874                 my $refname = $ref->full_path($p);
875                 if (my $existing = $fetch->{$pathname}) {
876                         if ($existing ne $refname) {
877                                 die "Refspec conflict:\n",
878                                     "existing: refs/remotes/$existing\n",
879                                     " globbed: refs/remotes/$refname\n";
880                         }
881                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
882                         $u =~ s!^\Q$url\E(/|$)!! or die
883                           "refs/remotes/$refname: '$url' not found in '$u'\n";
884                         if ($pathname ne $u) {
885                                 warn "W: Refspec glob conflict ",
886                                      "(ref: refs/remotes/$refname):\n",
887                                      "expected path: $pathname\n",
888                                      "    real path: $u\n",
889                                      "Continuing ahead with $u\n";
890                                 next;
891                         }
892                 } else {
893                         $fetch->{$pathname} = $refname;
894                 }
895         }
898 sub parse_revision_argument {
899         my ($base, $head) = @_;
900         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
901                 return ($base, $head);
902         }
903         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
904         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
905         return ($head, $head) if ($::_revision eq 'HEAD');
906         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
907         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
908         die "revision argument: $::_revision not understood by git-svn\n";
911 sub fetch_all {
912         my ($repo_id, $remotes) = @_;
913         if (ref $repo_id) {
914                 my $gs = $repo_id;
915                 $repo_id = undef;
916                 $repo_id = $gs->{repo_id};
917         }
918         $remotes ||= read_all_remotes();
919         my $remote = $remotes->{$repo_id} or
920                      die "[svn-remote \"$repo_id\"] unknown\n";
921         my $fetch = $remote->{fetch};
922         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
923         my (@gs, @globs);
924         my $ra = Git::SVN::Ra->new($url);
925         my $uuid = $ra->get_uuid;
926         my $head = $ra->get_latest_revnum;
927         my $base = defined $fetch ? $head : 0;
929         # read the max revs for wildcard expansion (branches/*, tags/*)
930         foreach my $t (qw/branches tags/) {
931                 defined $remote->{$t} or next;
932                 push @globs, $remote->{$t};
933                 my $max_rev = eval { tmp_config(qw/--int --get/,
934                                          "svn-remote.$repo_id.${t}-maxRev") };
935                 if (defined $max_rev && ($max_rev < $base)) {
936                         $base = $max_rev;
937                 } elsif (!defined $max_rev) {
938                         $base = 0;
939                 }
940         }
942         if ($fetch) {
943                 foreach my $p (sort keys %$fetch) {
944                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
945                         my $lr = $gs->rev_db_max;
946                         if (defined $lr) {
947                                 $base = $lr if ($lr < $base);
948                         }
949                         push @gs, $gs;
950                 }
951         }
953         ($base, $head) = parse_revision_argument($base, $head);
954         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
957 sub read_all_remotes {
958         my $r = {};
959         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
960                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
961                         $r->{$1}->{fetch}->{$2} = $3;
962                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
963                         $r->{$1}->{url} = $2;
964                 } elsif (m!^(.+)\.(branches|tags)=
965                            (.*):refs/remotes/(.+)\s*$/!x) {
966                         my ($p, $g) = ($3, $4);
967                         my $rs = $r->{$1}->{$2} = {
968                                           t => $2,
969                                           remote => $1,
970                                           path => Git::SVN::GlobSpec->new($p),
971                                           ref => Git::SVN::GlobSpec->new($g) };
972                         if (length($rs->{ref}->{right}) != 0) {
973                                 die "The '*' glob character must be the last ",
974                                     "character of '$g'\n";
975                         }
976                 }
977         }
978         $r;
981 sub init_vars {
982         if (defined $_repack) {
983                 $_repack = 1000 if ($_repack <= 0);
984                 $_repack_nr = $_repack;
985                 $_repack_flags ||= '-d';
986         }
989 sub verify_remotes_sanity {
990         return unless -d $ENV{GIT_DIR};
991         my %seen;
992         foreach (command(qw/config -l/)) {
993                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
994                         if ($seen{$1}) {
995                                 die "Remote ref refs/remote/$1 is tracked by",
996                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
997                                     "Please resolve this ambiguity in ",
998                                     "your git configuration file before ",
999                                     "continuing\n";
1000                         }
1001                         $seen{$1} = $_;
1002                 }
1003         }
1006 # we allow more chars than remotes2config.sh...
1007 sub sanitize_remote_name {
1008         my ($name) = @_;
1009         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1010         $name;
1013 sub find_existing_remote {
1014         my ($url, $remotes) = @_;
1015         return undef if $no_reuse_existing;
1016         my $existing;
1017         foreach my $repo_id (keys %$remotes) {
1018                 my $u = $remotes->{$repo_id}->{url} or next;
1019                 next if $u ne $url;
1020                 $existing = $repo_id;
1021                 last;
1022         }
1023         $existing;
1026 sub init_remote_config {
1027         my ($self, $url, $no_write) = @_;
1028         $url =~ s!/+$!!; # strip trailing slash
1029         my $r = read_all_remotes();
1030         my $existing = find_existing_remote($url, $r);
1031         if ($existing) {
1032                 unless ($no_write) {
1033                         print STDERR "Using existing ",
1034                                      "[svn-remote \"$existing\"]\n";
1035                 }
1036                 $self->{repo_id} = $existing;
1037         } else {
1038                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1039                 $existing = find_existing_remote($min_url, $r);
1040                 if ($existing) {
1041                         unless ($no_write) {
1042                                 print STDERR "Using existing ",
1043                                              "[svn-remote \"$existing\"]\n";
1044                         }
1045                         $self->{repo_id} = $existing;
1046                 }
1047                 if ($min_url ne $url) {
1048                         unless ($no_write) {
1049                                 print STDERR "Using higher level of URL: ",
1050                                              "$url => $min_url\n";
1051                         }
1052                         my $old_path = $self->{path};
1053                         $self->{path} = $url;
1054                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1055                         if (length $old_path) {
1056                                 $self->{path} .= "/$old_path";
1057                         }
1058                         $url = $min_url;
1059                 }
1060         }
1061         my $orig_url;
1062         if (!$existing) {
1063                 # verify that we aren't overwriting anything:
1064                 $orig_url = eval {
1065                         command_oneline('config', '--get',
1066                                         "svn-remote.$self->{repo_id}.url")
1067                 };
1068                 if ($orig_url && ($orig_url ne $url)) {
1069                         die "svn-remote.$self->{repo_id}.url already set: ",
1070                             "$orig_url\nwanted to set to: $url\n";
1071                 }
1072         }
1073         my ($xrepo_id, $xpath) = find_ref($self->refname);
1074         if (defined $xpath) {
1075                 die "svn-remote.$xrepo_id.fetch already set to track ",
1076                     "$xpath:refs/remotes/", $self->refname, "\n";
1077         }
1078         unless ($no_write) {
1079                 command_noisy('config',
1080                               "svn-remote.$self->{repo_id}.url", $url);
1081                 command_noisy('config', '--add',
1082                               "svn-remote.$self->{repo_id}.fetch",
1083                               "$self->{path}:".$self->refname);
1084         }
1085         $self->{url} = $url;
1088 sub find_by_url { # repos_root and, path are optional
1089         my ($class, $full_url, $repos_root, $path) = @_;
1091         return undef unless defined $full_url;
1092         remove_username($full_url);
1093         remove_username($repos_root) if defined $repos_root;
1094         my $remotes = read_all_remotes();
1095         if (defined $full_url && defined $repos_root && !defined $path) {
1096                 $path = $full_url;
1097                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1098         }
1099         foreach my $repo_id (keys %$remotes) {
1100                 my $u = $remotes->{$repo_id}->{url} or next;
1101                 remove_username($u);
1102                 next if defined $repos_root && $repos_root ne $u;
1104                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1105                 foreach (qw/branches tags/) {
1106                         resolve_local_globs($u, $fetch,
1107                                             $remotes->{$repo_id}->{$_});
1108                 }
1109                 my $p = $path;
1110                 unless (defined $p) {
1111                         $p = $full_url;
1112                         $p =~ s#^\Q$u\E(?:/|$)## or next;
1113                 }
1114                 foreach my $f (keys %$fetch) {
1115                         next if $f ne $p;
1116                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1117                 }
1118         }
1119         undef;
1122 sub init {
1123         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1124         my $self = _new($class, $repo_id, $ref_id, $path);
1125         if (defined $url) {
1126                 $self->init_remote_config($url, $no_write);
1127         }
1128         $self;
1131 sub find_ref {
1132         my ($ref_id) = @_;
1133         foreach (command(qw/config -l/)) {
1134                 next unless m!^svn-remote\.(.+)\.fetch=
1135                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1136                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1137                 if ($ref eq $ref_id) {
1138                         $path = '' if ($path =~ m#^\./?#);
1139                         return ($repo_id, $path);
1140                 }
1141         }
1142         (undef, undef, undef);
1145 sub new {
1146         my ($class, $ref_id, $repo_id, $path) = @_;
1147         if (defined $ref_id && !defined $repo_id && !defined $path) {
1148                 ($repo_id, $path) = find_ref($ref_id);
1149                 if (!defined $repo_id) {
1150                         die "Could not find a \"svn-remote.*.fetch\" key ",
1151                             "in the repository configuration matching: ",
1152                             "refs/remotes/$ref_id\n";
1153                 }
1154         }
1155         my $self = _new($class, $repo_id, $ref_id, $path);
1156         if (!defined $self->{path} || !length $self->{path}) {
1157                 my $fetch = command_oneline('config', '--get',
1158                                             "svn-remote.$repo_id.fetch",
1159                                             ":refs/remotes/$ref_id\$") or
1160                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1161                          "\":refs/remotes/$ref_id\$\" in config\n";
1162                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1163         }
1164         $self->{url} = command_oneline('config', '--get',
1165                                        "svn-remote.$repo_id.url") or
1166                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1167         $self->rebuild;
1168         $self;
1171 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1173 sub svm_uuid {
1174         my ($self) = @_;
1175         return $self->{svm}->{uuid} if $self->svm;
1176         $self->ra;
1177         unless ($self->{svm}) {
1178                 die "SVM UUID not cached, and reading remotely failed\n";
1179         }
1180         $self->{svm}->{uuid};
1183 sub svm {
1184         my ($self) = @_;
1185         return $self->{svm} if $self->{svm};
1186         my $svm;
1187         # see if we have it in our config, first:
1188         eval {
1189                 my $section = "svn-remote.$self->{repo_id}";
1190                 $svm = {
1191                   source => tmp_config('--get', "$section.svm-source"),
1192                   uuid => tmp_config('--get', "$section.svm-uuid"),
1193                   replace => tmp_config('--get', "$section.svm-replace"),
1194                 }
1195         };
1196         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1197                 $self->{svm} = $svm;
1198         }
1199         $self->{svm};
1202 sub _set_svm_vars {
1203         my ($self, $ra) = @_;
1204         return $ra if $self->svm;
1206         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1207                     "(svm:source, svm:uuid) ",
1208                     "from the following URLs:\n" );
1209         sub read_svm_props {
1210                 my ($self, $ra, $path, $r) = @_;
1211                 my $props = ($ra->get_dir($path, $r))[2];
1212                 my $src = $props->{'svm:source'};
1213                 my $uuid = $props->{'svm:uuid'};
1214                 return undef if (!$src || !$uuid);
1216                 chomp($src, $uuid);
1218                 $uuid =~ m{^[0-9a-f\-]{30,}$}
1219                     or die "doesn't look right - svm:uuid is '$uuid'\n";
1221                 # the '!' is used to mark the repos_root!/relative/path
1222                 $src =~ s{/?!/?}{/};
1223                 $src =~ s{/+$}{}; # no trailing slashes please
1224                 # username is of no interest
1225                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1227                 my $replace = $ra->{url};
1228                 $replace .= "/$path" if length $path;
1230                 my $section = "svn-remote.$self->{repo_id}";
1231                 tmp_config("$section.svm-source", $src);
1232                 tmp_config("$section.svm-replace", $replace);
1233                 tmp_config("$section.svm-uuid", $uuid);
1234                 $self->{svm} = {
1235                         source => $src,
1236                         uuid => $uuid,
1237                         replace => $replace
1238                 };
1239         }
1241         my $r = $ra->get_latest_revnum;
1242         my $path = $self->{path};
1243         my %tried;
1244         while (length $path) {
1245                 unless ($tried{"$self->{url}/$path"}) {
1246                         return $ra if $self->read_svm_props($ra, $path, $r);
1247                         $tried{"$self->{url}/$path"} = 1;
1248                 }
1249                 $path =~ s#/?[^/]+$##;
1250         }
1251         die "Path: '$path' should be ''\n" if $path ne '';
1252         return $ra if $self->read_svm_props($ra, $path, $r);
1253         $tried{"$self->{url}/$path"} = 1;
1255         if ($ra->{repos_root} eq $self->{url}) {
1256                 die @err, (map { "  $_\n" } keys %tried), "\n";
1257         }
1259         # nope, make sure we're connected to the repository root:
1260         my $ok;
1261         my @tried_b;
1262         $path = $ra->{svn_path};
1263         $ra = Git::SVN::Ra->new($ra->{repos_root});
1264         while (length $path) {
1265                 unless ($tried{"$ra->{url}/$path"}) {
1266                         $ok = $self->read_svm_props($ra, $path, $r);
1267                         last if $ok;
1268                         $tried{"$ra->{url}/$path"} = 1;
1269                 }
1270                 $path =~ s#/?[^/]+$##;
1271         }
1272         die "Path: '$path' should be ''\n" if $path ne '';
1273         $ok ||= $self->read_svm_props($ra, $path, $r);
1274         $tried{"$ra->{url}/$path"} = 1;
1275         if (!$ok) {
1276                 die @err, (map { "  $_\n" } keys %tried), "\n";
1277         }
1278         Git::SVN::Ra->new($self->{url});
1281 sub svnsync {
1282         my ($self) = @_;
1283         return $self->{svnsync} if $self->{svnsync};
1285         if ($self->no_metadata) {
1286                 die "Can't have both 'noMetadata' and ",
1287                     "'useSvnsyncProps' options set!\n";
1288         }
1289         if ($self->rewrite_root) {
1290                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1291                     "options set!\n";
1292         }
1294         my $svnsync;
1295         # see if we have it in our config, first:
1296         eval {
1297                 my $section = "svn-remote.$self->{repo_id}";
1298                 $svnsync = {
1299                   url => tmp_config('--get', "$section.svnsync-url"),
1300                   uuid => tmp_config('--get', "$section.svnsync-uuid"),
1301                 }
1302         };
1303         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1304                 return $self->{svnsync} = $svnsync;
1305         }
1307         my $err = "useSvnsyncProps set, but failed to read " .
1308                   "svnsync property: svn:sync-from-";
1309         my $rp = $self->ra->rev_proplist(0);
1311         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1312         $url =~ m{^[a-z\+]+://} or
1313                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1315         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1316         $uuid =~ m{^[0-9a-f\-]{30,}$} or
1317                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1319         my $section = "svn-remote.$self->{repo_id}";
1320         tmp_config('--add', "$section.svnsync-uuid", $uuid);
1321         tmp_config('--add', "$section.svnsync-url", $url);
1322         return $self->{svnsync} = { url => $url, uuid => $uuid };
1325 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1326 # remote lookup (useful for 'git svn log').
1327 sub ra_uuid {
1328         my ($self) = @_;
1329         unless ($self->{ra_uuid}) {
1330                 my $key = "svn-remote.$self->{repo_id}.uuid";
1331                 my $uuid = eval { tmp_config('--get', $key) };
1332                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1333                         $self->{ra_uuid} = $uuid;
1334                 } else {
1335                         die "ra_uuid called without URL\n" unless $self->{url};
1336                         $self->{ra_uuid} = $self->ra->get_uuid;
1337                         tmp_config('--add', $key, $self->{ra_uuid});
1338                 }
1339         }
1340         $self->{ra_uuid};
1343 sub ra {
1344         my ($self) = shift;
1345         my $ra = Git::SVN::Ra->new($self->{url});
1346         if ($self->use_svm_props && !$self->{svm}) {
1347                 if ($self->no_metadata) {
1348                         die "Can't have both 'noMetadata' and ",
1349                             "'useSvmProps' options set!\n";
1350                 } elsif ($self->use_svnsync_props) {
1351                         die "Can't have both 'useSvnsyncProps' and ",
1352                             "'useSvmProps' options set!\n";
1353                 }
1354                 $ra = $self->_set_svm_vars($ra);
1355                 $self->{-want_revprops} = 1;
1356         }
1357         $ra;
1360 sub rel_path {
1361         my ($self) = @_;
1362         my $repos_root = $self->ra->{repos_root};
1363         return $self->{path} if ($self->{url} eq $repos_root);
1364         my $url = $self->{url} .
1365                   (length $self->{path} ? "/$self->{path}" : $self->{path});
1366         $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1367         $url;
1370 sub traverse_ignore {
1371         my ($self, $fh, $path, $r) = @_;
1372         $path =~ s#^/+##g;
1373         my $ra = $self->ra;
1374         my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1375         my $p = $path;
1376         $p =~ s#^\Q$self->{path}\E(/|$)##;
1377         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1378         if (my $s = $props->{'svn:ignore'}) {
1379                 $s =~ s/[\r\n]+/\n/g;
1380                 chomp $s;
1381                 if (length $p == 0) {
1382                         $s =~ s#\n#\n/$p#g;
1383                         print $fh "/$s\n";
1384                 } else {
1385                         $s =~ s#\n#\n/$p/#g;
1386                         print $fh "/$p/$s\n";
1387                 }
1388         }
1389         foreach (sort keys %$dirent) {
1390                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1391                 $self->traverse_ignore($fh, "$path/$_", $r);
1392         }
1395 sub last_rev { ($_[0]->last_rev_commit)[0] }
1396 sub last_commit { ($_[0]->last_rev_commit)[1] }
1398 # returns the newest SVN revision number and newest commit SHA1
1399 sub last_rev_commit {
1400         my ($self) = @_;
1401         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1402                 return ($self->{last_rev}, $self->{last_commit});
1403         }
1404         my $c = ::verify_ref($self->refname.'^0');
1405         if ($c && !$self->use_svm_props && !$self->no_metadata) {
1406                 my $rev = (::cmt_metadata($c))[1];
1407                 if (defined $rev) {
1408                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1409                         return ($rev, $c);
1410                 }
1411         }
1412         my $db_path = $self->db_path;
1413         unless (-e $db_path) {
1414                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1415                 return (undef, undef);
1416         }
1417         my $offset = -41; # from tail
1418         my $rl;
1419         open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1420         sysseek($fh, $offset, 2); # don't care for errors
1421         sysread($fh, $rl, 41) == 41 or return (undef, undef);
1422         chomp $rl;
1423         while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1424                 $offset -= 41;
1425                 sysseek($fh, $offset, 2); # don't care for errors
1426                 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1427                 chomp $rl;
1428         }
1429         if ($c && $c ne $rl) {
1430                 die "$db_path and ", $self->refname,
1431                     " inconsistent!:\n$c != $rl\n";
1432         }
1433         my $rev = sysseek($fh, 0, 1) or croak $!;
1434         $rev =  ($rev - 41) / 41;
1435         close $fh or croak $!;
1436         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1437         return ($rev, $c);
1440 sub get_fetch_range {
1441         my ($self, $min, $max) = @_;
1442         $max ||= $self->ra->get_latest_revnum;
1443         $min ||= $self->rev_db_max;
1444         (++$min, $max);
1447 sub tmp_config {
1448         my (@args) = @_;
1449         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1450         my $config = "$ENV{GIT_DIR}/svn/.metadata";
1451         if (-e $old_def_config && ! -e $config) {
1452                 rename $old_def_config, $config or
1453                        die "Failed rename $old_def_config => $config: $!\n";
1454         }
1455         my $old_config = $ENV{GIT_CONFIG};
1456         $ENV{GIT_CONFIG} = $config;
1457         $@ = undef;
1458         my @ret = eval {
1459                 unless (-f $config) {
1460                         mkfile($config);
1461                         open my $fh, '>', $config or
1462                             die "Can't open $config: $!\n";
1463                         print $fh "; This file is used internally by ",
1464                                   "git-svn\n" or die
1465                                   "Couldn't write to $config: $!\n";
1466                         print $fh "; You should not have to edit it\n" or
1467                               die "Couldn't write to $config: $!\n";
1468                         close $fh or die "Couldn't close $config: $!\n";
1469                 }
1470                 command('config', @args);
1471         };
1472         my $err = $@;
1473         if (defined $old_config) {
1474                 $ENV{GIT_CONFIG} = $old_config;
1475         } else {
1476                 delete $ENV{GIT_CONFIG};
1477         }
1478         die $err if $err;
1479         wantarray ? @ret : $ret[0];
1482 sub tmp_index_do {
1483         my ($self, $sub) = @_;
1484         my $old_index = $ENV{GIT_INDEX_FILE};
1485         $ENV{GIT_INDEX_FILE} = $self->{index};
1486         $@ = undef;
1487         my @ret = eval {
1488                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1489                 mkpath([$dir]) unless -d $dir;
1490                 &$sub;
1491         };
1492         my $err = $@;
1493         if (defined $old_index) {
1494                 $ENV{GIT_INDEX_FILE} = $old_index;
1495         } else {
1496                 delete $ENV{GIT_INDEX_FILE};
1497         }
1498         die $err if $err;
1499         wantarray ? @ret : $ret[0];
1502 sub assert_index_clean {
1503         my ($self, $treeish) = @_;
1505         $self->tmp_index_do(sub {
1506                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1507                 my $x = command_oneline('write-tree');
1508                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1509                            /^tree ($::sha1)/mo);
1510                 return if $y eq $x;
1512                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1513                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1514                 command_noisy('read-tree', $treeish);
1515                 $x = command_oneline('write-tree');
1516                 if ($y ne $x) {
1517                         ::fatal "trees ($treeish) $y != $x\n",
1518                                 "Something is seriously wrong...\n";
1519                 }
1520         });
1523 sub get_commit_parents {
1524         my ($self, $log_entry) = @_;
1525         my (%seen, @ret, @tmp);
1526         # legacy support for 'set-tree'; this is only used by set_tree_cb:
1527         if (my $ip = $self->{inject_parents}) {
1528                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1529                         push @tmp, $commit;
1530                 }
1531         }
1532         if (my $cur = ::verify_ref($self->refname.'^0')) {
1533                 push @tmp, $cur;
1534         }
1535         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1536         while (my $p = shift @tmp) {
1537                 next if $seen{$p};
1538                 $seen{$p} = 1;
1539                 push @ret, $p;
1540                 # MAXPARENT is defined to 16 in commit-tree.c:
1541                 last if @ret >= 16;
1542         }
1543         if (@tmp) {
1544                 die "r$log_entry->{revision}: No room for parents:\n\t",
1545                     join("\n\t", @tmp), "\n";
1546         }
1547         @ret;
1550 sub rewrite_root {
1551         my ($self) = @_;
1552         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1553         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1554         my $rwr = eval { command_oneline(qw/config --get/, $k) };
1555         if ($rwr) {
1556                 $rwr =~ s#/+$##;
1557                 if ($rwr !~ m#^[a-z\+]+://#) {
1558                         die "$rwr is not a valid URL (key: $k)\n";
1559                 }
1560         }
1561         $self->{-rewrite_root} = $rwr;
1564 sub metadata_url {
1565         my ($self) = @_;
1566         ($self->rewrite_root || $self->{url}) .
1567            (length $self->{path} ? '/' . $self->{path} : '');
1570 sub full_url {
1571         my ($self) = @_;
1572         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1575 sub do_git_commit {
1576         my ($self, $log_entry) = @_;
1577         my $lr = $self->last_rev;
1578         if (defined $lr && $lr >= $log_entry->{revision}) {
1579                 die "Last fetched revision of ", $self->refname,
1580                     " was r$lr, but we are about to fetch: ",
1581                     "r$log_entry->{revision}!\n";
1582         }
1583         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1584                 croak "$log_entry->{revision} = $c already exists! ",
1585                       "Why are we refetching it?\n";
1586         }
1587         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1588         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1589                                                           $log_entry->{email};
1590         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1592         my $tree = $log_entry->{tree};
1593         if (!defined $tree) {
1594                 $tree = $self->tmp_index_do(sub {
1595                                             command_oneline('write-tree') });
1596         }
1597         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1599         my @exec = ('git-commit-tree', $tree);
1600         foreach ($self->get_commit_parents($log_entry)) {
1601                 push @exec, '-p', $_;
1602         }
1603         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1604                                                                    or croak $!;
1605         print $msg_fh $log_entry->{log} or croak $!;
1606         unless ($self->no_metadata) {
1607                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1608                               or croak $!;
1609         }
1610         $msg_fh->flush == 0 or croak $!;
1611         close $msg_fh or croak $!;
1612         chomp(my $commit = do { local $/; <$out_fh> });
1613         close $out_fh or croak $!;
1614         waitpid $pid, 0;
1615         croak $? if $?;
1616         if ($commit !~ /^$::sha1$/o) {
1617                 die "Failed to commit, invalid sha1: $commit\n";
1618         }
1620         $self->rev_db_set($log_entry->{revision}, $commit, 1);
1622         $self->{last_rev} = $log_entry->{revision};
1623         $self->{last_commit} = $commit;
1624         print "r$log_entry->{revision}";
1625         if (defined $log_entry->{svm_revision}) {
1626                  print " (\@$log_entry->{svm_revision})";
1627                  $self->rev_db_set($log_entry->{svm_revision}, $commit,
1628                                    0, $self->svm_uuid);
1629         }
1630         print " = $commit ($self->{ref_id})\n";
1631         if (defined $_repack && (--$_repack_nr == 0)) {
1632                 $_repack_nr = $_repack;
1633                 # repack doesn't use any arguments with spaces in them, does it?
1634                 print "Running git repack $_repack_flags ...\n";
1635                 command_noisy('repack', split(/\s+/, $_repack_flags));
1636                 print "Done repacking\n";
1637         }
1638         return $commit;
1641 sub match_paths {
1642         my ($self, $paths, $r) = @_;
1643         return 1 if $self->{path} eq '';
1644         if (my $path = $paths->{"/$self->{path}"}) {
1645                 return ($path->{action} eq 'D') ? 0 : 1;
1646         }
1647         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1648         if (grep /$self->{path_regex}/, keys %$paths) {
1649                 return 1;
1650         }
1651         my $c = '';
1652         foreach (split m#/#, $self->{path}) {
1653                 $c .= "/$_";
1654                 next unless ($paths->{$c} &&
1655                              ($paths->{$c}->{action} =~ /^[AR]$/));
1656                 if ($self->ra->check_path($self->{path}, $r) ==
1657                     $SVN::Node::dir) {
1658                         return 1;
1659                 }
1660         }
1661         return 0;
1664 sub find_parent_branch {
1665         my ($self, $paths, $rev) = @_;
1666         return undef unless $self->follow_parent;
1667         unless (defined $paths) {
1668                 my $err_handler = $SVN::Error::handler;
1669                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1670                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1671                                    $paths =
1672                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1673                 $SVN::Error::handler = $err_handler;
1674         }
1675         return undef unless defined $paths;
1677         # look for a parent from another branch:
1678         my @b_path_components = split m#/#, $self->rel_path;
1679         my @a_path_components;
1680         my $i;
1681         while (@b_path_components) {
1682                 $i = $paths->{'/'.join('/', @b_path_components)};
1683                 last if $i && defined $i->{copyfrom_path};
1684                 unshift(@a_path_components, pop(@b_path_components));
1685         }
1686         return undef unless defined $i && defined $i->{copyfrom_path};
1687         my $branch_from = $i->{copyfrom_path};
1688         if (@a_path_components) {
1689                 print STDERR "branch_from: $branch_from => ";
1690                 $branch_from .= '/'.join('/', @a_path_components);
1691                 print STDERR $branch_from, "\n";
1692         }
1693         my $r = $i->{copyfrom_rev};
1694         my $repos_root = $self->ra->{repos_root};
1695         my $url = $self->ra->{url};
1696         my $new_url = $repos_root . $branch_from;
1697         print STDERR  "Found possible branch point: ",
1698                       "$new_url => ", $self->full_url, ", $r\n";
1699         $branch_from =~ s#^/##;
1700         my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1701         unless ($gs) {
1702                 my $ref_id = $self->{ref_id};
1703                 $ref_id =~ s/\@\d+$//;
1704                 $ref_id .= "\@$r";
1705                 # just grow a tail if we're not unique enough :x
1706                 $ref_id .= '-' while find_ref($ref_id);
1707                 print STDERR "Initializing parent: $ref_id\n";
1708                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1709         }
1710         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1711         if (!defined $r0 || !defined $parent) {
1712                 my ($base, $head) = parse_revision_argument(0, $r);
1713                 if ($base <= $r) {
1714                         $gs->fetch($base, $r);
1715                 }
1716                 ($r0, $parent) = $gs->last_rev_commit;
1717         }
1718         if (defined $r0 && defined $parent) {
1719                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1720                 my $ed;
1721                 if ($self->ra->can_do_switch) {
1722                         $self->assert_index_clean($parent);
1723                         print STDERR "Following parent with do_switch\n";
1724                         # do_switch works with svn/trunk >= r22312, but that
1725                         # is not included with SVN 1.4.3 (the latest version
1726                         # at the moment), so we can't rely on it
1727                         $self->{last_commit} = $parent;
1728                         $ed = SVN::Git::Fetcher->new($self);
1729                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1730                                               $self->full_url, $ed)
1731                           or die "SVN connection failed somewhere...\n";
1732                 } else {
1733                         print STDERR "Following parent with do_update\n";
1734                         $ed = SVN::Git::Fetcher->new($self);
1735                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1736                           or die "SVN connection failed somewhere...\n";
1737                 }
1738                 print STDERR "Successfully followed parent\n";
1739                 return $self->make_log_entry($rev, [$parent], $ed);
1740         }
1741         return undef;
1744 sub do_fetch {
1745         my ($self, $paths, $rev) = @_;
1746         my $ed;
1747         my ($last_rev, @parents);
1748         if (my $lc = $self->last_commit) {
1749                 # we can have a branch that was deleted, then re-added
1750                 # under the same name but copied from another path, in
1751                 # which case we'll have multiple parents (we don't
1752                 # want to break the original ref, nor lose copypath info):
1753                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1754                         push @{$log_entry->{parents}}, $lc;
1755                         return $log_entry;
1756                 }
1757                 $ed = SVN::Git::Fetcher->new($self);
1758                 $last_rev = $self->{last_rev};
1759                 $ed->{c} = $lc;
1760                 @parents = ($lc);
1761         } else {
1762                 $last_rev = $rev;
1763                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1764                         return $log_entry;
1765                 }
1766                 $ed = SVN::Git::Fetcher->new($self);
1767         }
1768         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1769                 die "SVN connection failed somewhere...\n";
1770         }
1771         $self->make_log_entry($rev, \@parents, $ed);
1774 sub get_untracked {
1775         my ($self, $ed) = @_;
1776         my @out;
1777         my $h = $ed->{empty};
1778         foreach (sort keys %$h) {
1779                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1780                 push @out, "  $act: " . uri_encode($_);
1781                 warn "W: $act: $_\n";
1782         }
1783         foreach my $t (qw/dir_prop file_prop/) {
1784                 $h = $ed->{$t} or next;
1785                 foreach my $path (sort keys %$h) {
1786                         my $ppath = $path eq '' ? '.' : $path;
1787                         foreach my $prop (sort keys %{$h->{$path}}) {
1788                                 next if $SKIP_PROP{$prop};
1789                                 my $v = $h->{$path}->{$prop};
1790                                 my $t_ppath_prop = "$t: " .
1791                                                     uri_encode($ppath) . ' ' .
1792                                                     uri_encode($prop);
1793                                 if (defined $v) {
1794                                         push @out, "  +$t_ppath_prop " .
1795                                                    uri_encode($v);
1796                                 } else {
1797                                         push @out, "  -$t_ppath_prop";
1798                                 }
1799                         }
1800                 }
1801         }
1802         foreach my $t (qw/absent_file absent_directory/) {
1803                 $h = $ed->{$t} or next;
1804                 foreach my $parent (sort keys %$h) {
1805                         foreach my $path (sort @{$h->{$parent}}) {
1806                                 push @out, "  $t: " .
1807                                            uri_encode("$parent/$path");
1808                                 warn "W: $t: $parent/$path ",
1809                                      "Insufficient permissions?\n";
1810                         }
1811                 }
1812         }
1813         \@out;
1816 sub parse_svn_date {
1817         my $date = shift || return '+0000 1970-01-01 00:00:00';
1818         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1819                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1820                                          croak "Unable to parse date: $date\n";
1821         "+0000 $Y-$m-$d $H:$M:$S";
1824 sub check_author {
1825         my ($author) = @_;
1826         if (!defined $author || length $author == 0) {
1827                 $author = '(no author)';
1828         }
1829         if (defined $::_authors && ! defined $::users{$author}) {
1830                 die "Author: $author not defined in $::_authors file\n";
1831         }
1832         $author;
1835 sub make_log_entry {
1836         my ($self, $rev, $parents, $ed) = @_;
1837         my $untracked = $self->get_untracked($ed);
1839         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1840         print $un "r$rev\n" or croak $!;
1841         print $un $_, "\n" foreach @$untracked;
1842         my %log_entry = ( parents => $parents || [], revision => $rev,
1843                           log => '');
1845         my $headrev;
1846         my $logged = delete $self->{logged_rev_props};
1847         if (!$logged || $self->{-want_revprops}) {
1848                 my $rp = $self->ra->rev_proplist($rev);
1849                 foreach (sort keys %$rp) {
1850                         my $v = $rp->{$_};
1851                         if (/^svn:(author|date|log)$/) {
1852                                 $log_entry{$1} = $v;
1853                         } elsif ($_ eq 'svm:headrev') {
1854                                 $headrev = $v;
1855                         } else {
1856                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1857                                           uri_encode($v), "\n";
1858                         }
1859                 }
1860         } else {
1861                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1862         }
1863         close $un or croak $!;
1865         $log_entry{date} = parse_svn_date($log_entry{date});
1866         $log_entry{log} .= "\n";
1867         my $author = $log_entry{author} = check_author($log_entry{author});
1868         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1869                                                        : ($author, undef);
1870         if (defined $headrev && $self->use_svm_props) {
1871                 if ($self->rewrite_root) {
1872                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1873                             "options set!\n";
1874                 }
1875                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1876                 # we don't want "SVM: initializing mirror for junk" ...
1877                 return undef if $r == 0;
1878                 my $svm = $self->svm;
1879                 if ($uuid ne $svm->{uuid}) {
1880                         die "UUID mismatch on SVM path:\n",
1881                             "expected: $svm->{uuid}\n",
1882                             "     got: $uuid\n";
1883                 }
1884                 my $full_url = $self->full_url;
1885                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1886                              die "Failed to replace '$svm->{replace}' with ",
1887                                  "'$svm->{source}' in $full_url\n";
1888                 # throw away username for storing in records
1889                 remove_username($full_url);
1890                 $log_entry{metadata} = "$full_url\@$r $uuid";
1891                 $log_entry{svm_revision} = $r;
1892                 $email ||= "$author\@$uuid"
1893         } elsif ($self->use_svnsync_props) {
1894                 my $full_url = $self->svnsync->{url};
1895                 $full_url .= "/$self->{path}" if length $self->{path};
1896                 remove_username($full_url);
1897                 my $uuid = $self->svnsync->{uuid};
1898                 $log_entry{metadata} = "$full_url\@$rev $uuid";
1899                 $email ||= "$author\@$uuid"
1900         } else {
1901                 my $url = $self->metadata_url;
1902                 remove_username($url);
1903                 $log_entry{metadata} = "$url\@$rev " .
1904                                        $self->ra->get_uuid;
1905                 $email ||= "$author\@" . $self->ra->get_uuid;
1906         }
1907         $log_entry{name} = $name;
1908         $log_entry{email} = $email;
1909         \%log_entry;
1912 sub fetch {
1913         my ($self, $min_rev, $max_rev, @parents) = @_;
1914         my ($last_rev, $last_commit) = $self->last_rev_commit;
1915         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1916         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1919 sub set_tree_cb {
1920         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1921         $self->{inject_parents} = { $rev => $tree };
1922         $self->fetch(undef, undef);
1925 sub set_tree {
1926         my ($self, $tree) = (shift, shift);
1927         my $log_entry = ::get_commit_entry($tree);
1928         unless ($self->{last_rev}) {
1929                 fatal("Must have an existing revision to commit\n");
1930         }
1931         my %ed_opts = ( r => $self->{last_rev},
1932                         log => $log_entry->{log},
1933                         ra => $self->ra,
1934                         tree_a => $self->{last_commit},
1935                         tree_b => $tree,
1936                         editor_cb => sub {
1937                                $self->set_tree_cb($log_entry, $tree, @_) },
1938                         svn_path => $self->{path} );
1939         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1940                 print "No changes\nr$self->{last_rev} = $tree\n";
1941         }
1944 sub rebuild {
1945         my ($self) = @_;
1946         my $db_path = $self->db_path;
1947         return if (-e $db_path && ! -z $db_path);
1948         return unless ::verify_ref($self->refname.'^0');
1949         if (-f $self->{db_root}) {
1950                 rename $self->{db_root}, $db_path or die
1951                      "rename $self->{db_root} => $db_path failed: $!\n";
1952                 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1953                 symlink $base, $self->{db_root} or die
1954                      "symlink $base => $self->{db_root} failed: $!\n";
1955                 return;
1956         }
1957         print "Rebuilding $db_path ...\n";
1958         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1959         my $latest;
1960         my $full_url = $self->full_url;
1961         remove_username($full_url);
1962         my $svn_uuid;
1963         while (<$rev_list>) {
1964                 chomp;
1965                 my $c = $_;
1966                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1967                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1968                 remove_username($url);
1970                 # ignore merges (from set-tree)
1971                 next if (!defined $rev || !$uuid);
1973                 # if we merged or otherwise started elsewhere, this is
1974                 # how we break out of it
1975                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1976                     ($full_url && $url && ($url ne $full_url))) {
1977                         next;
1978                 }
1979                 $latest ||= $rev;
1980                 $svn_uuid ||= $uuid;
1982                 $self->rev_db_set($rev, $c);
1983                 print "r$rev = $c\n";
1984         }
1985         command_close_pipe($rev_list, $ctx);
1986         print "Done rebuilding $db_path\n";
1989 # rev_db:
1990 # Tie::File seems to be prone to offset errors if revisions get sparse,
1991 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1992 # one of my favorite modules is out :<  Next up would be one of the DBM
1993 # modules, but I'm not sure which is most portable...  So I'll just
1994 # go with something that's plain-text, but still capable of
1995 # being randomly accessed.  So here's my ultra-simple fixed-width
1996 # database.  All records are 40 characters + "\n", so it's easy to seek
1997 # to a revision: (41 * rev) is the byte offset.
1998 # A record of 40 0s denotes an empty revision.
1999 # And yes, it's still pretty fast (faster than Tie::File).
2000 # These files are disposable unless noMetadata or useSvmProps is set
2002 sub _rev_db_set {
2003         my ($fh, $rev, $commit) = @_;
2004         my $offset = $rev * 41;
2005         # assume that append is the common case:
2006         seek $fh, 0, 2 or croak $!;
2007         my $pos = tell $fh;
2008         if ($pos < $offset) {
2009                 for (1 .. (($offset - $pos) / 41)) {
2010                         print $fh (('0' x 40),"\n") or croak $!;
2011                 }
2012         }
2013         seek $fh, $offset, 0 or croak $!;
2014         print $fh $commit,"\n" or croak $!;
2017 sub mkfile {
2018         my ($path) = @_;
2019         unless (-e $path) {
2020                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2021                 mkpath([$dir]) unless -d $dir;
2022                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2023                 close $fh or die "Couldn't close (create) $path: $!\n";
2024         }
2027 sub rev_db_set {
2028         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2029         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2030         my $db = $self->db_path($uuid);
2031         my $db_lock = "$db.lock";
2032         my $sig;
2033         if ($update_ref) {
2034                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2035                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2036         }
2037         mkfile($db);
2039         $LOCKFILES{$db_lock} = 1;
2040         my $sync;
2041         # both of these options make our .rev_db file very, very important
2042         # and we can't afford to lose it because rebuild() won't work
2043         if ($self->use_svm_props || $self->no_metadata) {
2044                 $sync = 1;
2045                 copy($db, $db_lock) or die "rev_db_set(@_): ",
2046                                            "Failed to copy: ",
2047                                            "$db => $db_lock ($!)\n";
2048         } else {
2049                 rename $db, $db_lock or die "rev_db_set(@_): ",
2050                                             "Failed to rename: ",
2051                                             "$db => $db_lock ($!)\n";
2052         }
2053         open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2054         _rev_db_set($fh, $rev, $commit);
2055         if ($sync) {
2056                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2057                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2058         }
2059         close $fh or croak $!;
2060         if ($update_ref) {
2061                 $_head = $self;
2062                 command_noisy('update-ref', '-m', "r$rev",
2063                               $self->refname, $commit);
2064         }
2065         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2066                                     "$db_lock => $db ($!)\n";
2067         delete $LOCKFILES{$db_lock};
2068         if ($update_ref) {
2069                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2070                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2071                 kill $sig, $$ if defined $sig;
2072         }
2075 sub rev_db_max {
2076         my ($self) = @_;
2077         $self->rebuild;
2078         my $db_path = $self->db_path;
2079         my @stat = stat $db_path or return 0;
2080         ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2081         my $max = $stat[7] / 41;
2082         (($max > 0) ? $max - 1 : 0);
2085 sub rev_db_get {
2086         my ($self, $rev, $uuid) = @_;
2087         my $ret;
2088         my $offset = $rev * 41;
2089         my $db_path = $self->db_path($uuid);
2090         return undef unless -e $db_path;
2091         open my $fh, '<', $db_path or croak $!;
2092         if (sysseek($fh, $offset, 0) == $offset) {
2093                 my $read = sysread($fh, $ret, 40);
2094                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2095         }
2096         close $fh or croak $!;
2097         $ret;
2100 sub find_rev_before {
2101         my ($self, $rev, $eq_ok) = @_;
2102         --$rev unless $eq_ok;
2103         while ($rev > 0) {
2104                 if (my $c = $self->rev_db_get($rev)) {
2105                         return ($rev, $c);
2106                 }
2107                 --$rev;
2108         }
2109         return (undef, undef);
2112 sub _new {
2113         my ($class, $repo_id, $ref_id, $path) = @_;
2114         unless (defined $repo_id && length $repo_id) {
2115                 $repo_id = $Git::SVN::default_repo_id;
2116         }
2117         unless (defined $ref_id && length $ref_id) {
2118                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2119         }
2120         $_[1] = $repo_id = sanitize_remote_name($repo_id);
2121         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2122         $_[3] = $path = '' unless (defined $path);
2123         mkpath(["$ENV{GIT_DIR}/svn"]);
2124         bless {
2125                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2126                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2127                 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2130 sub db_path {
2131         my ($self, $uuid) = @_;
2132         $uuid ||= $self->ra_uuid;
2133         "$self->{db_root}.$uuid";
2136 sub uri_encode {
2137         my ($f) = @_;
2138         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2139         $f
2142 sub remove_username {
2143         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2146 package Git::SVN::Prompt;
2147 use strict;
2148 use warnings;
2149 require SVN::Core;
2150 use vars qw/$_no_auth_cache $_username/;
2152 sub simple {
2153         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2154         $may_save = undef if $_no_auth_cache;
2155         $default_username = $_username if defined $_username;
2156         if (defined $default_username && length $default_username) {
2157                 if (defined $realm && length $realm) {
2158                         print STDERR "Authentication realm: $realm\n";
2159                         STDERR->flush;
2160                 }
2161                 $cred->username($default_username);
2162         } else {
2163                 username($cred, $realm, $may_save, $pool);
2164         }
2165         $cred->password(_read_password("Password for '" .
2166                                        $cred->username . "': ", $realm));
2167         $cred->may_save($may_save);
2168         $SVN::_Core::SVN_NO_ERROR;
2171 sub ssl_server_trust {
2172         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2173         $may_save = undef if $_no_auth_cache;
2174         print STDERR "Error validating server certificate for '$realm':\n";
2175         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2176                 print STDERR " - The certificate is not issued by a trusted ",
2177                       "authority. Use the\n",
2178                       "   fingerprint to validate the certificate manually!\n";
2179         }
2180         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2181                 print STDERR " - The certificate hostname does not match.\n";
2182         }
2183         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2184                 print STDERR " - The certificate is not yet valid.\n";
2185         }
2186         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2187                 print STDERR " - The certificate has expired.\n";
2188         }
2189         if ($failures & $SVN::Auth::SSL::OTHER) {
2190                 print STDERR " - The certificate has an unknown error.\n";
2191         }
2192         printf STDERR
2193                 "Certificate information:\n".
2194                 " - Hostname: %s\n".
2195                 " - Valid: from %s until %s\n".
2196                 " - Issuer: %s\n".
2197                 " - Fingerprint: %s\n",
2198                 map $cert_info->$_, qw(hostname valid_from valid_until
2199                                        issuer_dname fingerprint);
2200         my $choice;
2201 prompt:
2202         print STDERR $may_save ?
2203               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2204               "(R)eject or accept (t)emporarily? ";
2205         STDERR->flush;
2206         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2207         if ($choice =~ /^t$/i) {
2208                 $cred->may_save(undef);
2209         } elsif ($choice =~ /^r$/i) {
2210                 return -1;
2211         } elsif ($may_save && $choice =~ /^p$/i) {
2212                 $cred->may_save($may_save);
2213         } else {
2214                 goto prompt;
2215         }
2216         $cred->accepted_failures($failures);
2217         $SVN::_Core::SVN_NO_ERROR;
2220 sub ssl_client_cert {
2221         my ($cred, $realm, $may_save, $pool) = @_;
2222         $may_save = undef if $_no_auth_cache;
2223         print STDERR "Client certificate filename: ";
2224         STDERR->flush;
2225         chomp(my $filename = <STDIN>);
2226         $cred->cert_file($filename);
2227         $cred->may_save($may_save);
2228         $SVN::_Core::SVN_NO_ERROR;
2231 sub ssl_client_cert_pw {
2232         my ($cred, $realm, $may_save, $pool) = @_;
2233         $may_save = undef if $_no_auth_cache;
2234         $cred->password(_read_password("Password: ", $realm));
2235         $cred->may_save($may_save);
2236         $SVN::_Core::SVN_NO_ERROR;
2239 sub username {
2240         my ($cred, $realm, $may_save, $pool) = @_;
2241         $may_save = undef if $_no_auth_cache;
2242         if (defined $realm && length $realm) {
2243                 print STDERR "Authentication realm: $realm\n";
2244         }
2245         my $username;
2246         if (defined $_username) {
2247                 $username = $_username;
2248         } else {
2249                 print STDERR "Username: ";
2250                 STDERR->flush;
2251                 chomp($username = <STDIN>);
2252         }
2253         $cred->username($username);
2254         $cred->may_save($may_save);
2255         $SVN::_Core::SVN_NO_ERROR;
2258 sub _read_password {
2259         my ($prompt, $realm) = @_;
2260         print STDERR $prompt;
2261         STDERR->flush;
2262         require Term::ReadKey;
2263         Term::ReadKey::ReadMode('noecho');
2264         my $password = '';
2265         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2266                 last if $key =~ /[\012\015]/; # \n\r
2267                 $password .= $key;
2268         }
2269         Term::ReadKey::ReadMode('restore');
2270         print STDERR "\n";
2271         STDERR->flush;
2272         $password;
2275 package main;
2278         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2279                                 $SVN::Node::dir.$SVN::Node::unknown.
2280                                 $SVN::Node::none.$SVN::Node::file.
2281                                 $SVN::Node::dir.$SVN::Node::unknown.
2282                                 $SVN::Auth::SSL::CNMISMATCH.
2283                                 $SVN::Auth::SSL::NOTYETVALID.
2284                                 $SVN::Auth::SSL::EXPIRED.
2285                                 $SVN::Auth::SSL::UNKNOWNCA.
2286                                 $SVN::Auth::SSL::OTHER;
2289 package SVN::Git::Fetcher;
2290 use vars qw/@ISA/;
2291 use strict;
2292 use warnings;
2293 use Carp qw/croak/;
2294 use IO::File qw//;
2295 use Digest::MD5;
2297 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2298 sub new {
2299         my ($class, $git_svn) = @_;
2300         my $self = SVN::Delta::Editor->new;
2301         bless $self, $class;
2302         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2303         $self->{empty} = {};
2304         $self->{dir_prop} = {};
2305         $self->{file_prop} = {};
2306         $self->{absent_dir} = {};
2307         $self->{absent_file} = {};
2308         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2309         $self;
2312 sub set_path_strip {
2313         my ($self, $path) = @_;
2314         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2317 sub open_root {
2318         { path => '' };
2321 sub open_directory {
2322         my ($self, $path, $pb, $rev) = @_;
2323         { path => $path };
2326 sub git_path {
2327         my ($self, $path) = @_;
2328         if ($self->{path_strip}) {
2329                 $path =~ s!$self->{path_strip}!! or
2330                   die "Failed to strip path '$path' ($self->{path_strip})\n";
2331         }
2332         $path;
2335 sub delete_entry {
2336         my ($self, $path, $rev, $pb) = @_;
2338         my $gpath = $self->git_path($path);
2339         return undef if ($gpath eq '');
2341         # remove entire directories.
2342         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2343                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2344                                                      -r --name-only -z/,
2345                                                      $self->{c}, '--', $gpath);
2346                 local $/ = "\0";
2347                 while (<$ls>) {
2348                         chomp;
2349                         $self->{gii}->remove($_);
2350                         print "\tD\t$_\n" unless $::_q;
2351                 }
2352                 print "\tD\t$gpath/\n" unless $::_q;
2353                 command_close_pipe($ls, $ctx);
2354                 $self->{empty}->{$path} = 0
2355         } else {
2356                 $self->{gii}->remove($gpath);
2357                 print "\tD\t$gpath\n" unless $::_q;
2358         }
2359         undef;
2362 sub open_file {
2363         my ($self, $path, $pb, $rev) = @_;
2364         my $gpath = $self->git_path($path);
2365         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2366                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2367         unless (defined $mode && defined $blob) {
2368                 die "$path was not found in commit $self->{c} (r$rev)\n";
2369         }
2370         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2371           pool => SVN::Pool->new, action => 'M' };
2374 sub add_file {
2375         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2376         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2377         delete $self->{empty}->{$dir};
2378         { path => $path, mode_a => 100644, mode_b => 100644,
2379           pool => SVN::Pool->new, action => 'A' };
2382 sub add_directory {
2383         my ($self, $path, $cp_path, $cp_rev) = @_;
2384         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2385         delete $self->{empty}->{$dir};
2386         $self->{empty}->{$path} = 1;
2387         { path => $path };
2390 sub change_dir_prop {
2391         my ($self, $db, $prop, $value) = @_;
2392         $self->{dir_prop}->{$db->{path}} ||= {};
2393         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2394         undef;
2397 sub absent_directory {
2398         my ($self, $path, $pb) = @_;
2399         $self->{absent_dir}->{$pb->{path}} ||= [];
2400         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2401         undef;
2404 sub absent_file {
2405         my ($self, $path, $pb) = @_;
2406         $self->{absent_file}->{$pb->{path}} ||= [];
2407         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2408         undef;
2411 sub change_file_prop {
2412         my ($self, $fb, $prop, $value) = @_;
2413         if ($prop eq 'svn:executable') {
2414                 if ($fb->{mode_b} != 120000) {
2415                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2416                 }
2417         } elsif ($prop eq 'svn:special') {
2418                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2419         } else {
2420                 $self->{file_prop}->{$fb->{path}} ||= {};
2421                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2422         }
2423         undef;
2426 sub apply_textdelta {
2427         my ($self, $fb, $exp) = @_;
2428         my $fh = IO::File->new_tmpfile;
2429         $fh->autoflush(1);
2430         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2431         # (but $base does not,) so dup() it for reading in close_file
2432         open my $dup, '<&', $fh or croak $!;
2433         my $base = IO::File->new_tmpfile;
2434         $base->autoflush(1);
2435         if ($fb->{blob}) {
2436                 defined (my $pid = fork) or croak $!;
2437                 if (!$pid) {
2438                         open STDOUT, '>&', $base or croak $!;
2439                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2440                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2441                 }
2442                 waitpid $pid, 0;
2443                 croak $? if $?;
2445                 if (defined $exp) {
2446                         seek $base, 0, 0 or croak $!;
2447                         my $md5 = Digest::MD5->new;
2448                         $md5->addfile($base);
2449                         my $got = $md5->hexdigest;
2450                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2451                             "expected: $exp\n",
2452                             "     got: $got\n" if ($got ne $exp);
2453                 }
2454         }
2455         seek $base, 0, 0 or croak $!;
2456         $fb->{fh} = $dup;
2457         $fb->{base} = $base;
2458         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2461 sub close_file {
2462         my ($self, $fb, $exp) = @_;
2463         my $hash;
2464         my $path = $self->git_path($fb->{path});
2465         if (my $fh = $fb->{fh}) {
2466                 seek($fh, 0, 0) or croak $!;
2467                 my $md5 = Digest::MD5->new;
2468                 $md5->addfile($fh);
2469                 my $got = $md5->hexdigest;
2470                 die "Checksum mismatch: $path\n",
2471                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2472                 sysseek($fh, 0, 0) or croak $!;
2473                 if ($fb->{mode_b} == 120000) {
2474                         sysread($fh, my $buf, 5) == 5 or croak $!;
2475                         $buf eq 'link ' or die "$path has mode 120000",
2476                                                "but is not a link\n";
2477                 }
2478                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2479                 if (!$pid) {
2480                         open STDIN, '<&', $fh or croak $!;
2481                         exec qw/git-hash-object -w --stdin/ or croak $!;
2482                 }
2483                 chomp($hash = do { local $/; <$out> });
2484                 close $out or croak $!;
2485                 close $fh or croak $!;
2486                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2487                 close $fb->{base} or croak $!;
2488         } else {
2489                 $hash = $fb->{blob} or die "no blob information\n";
2490         }
2491         $fb->{pool}->clear;
2492         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2493         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2494         undef;
2497 sub abort_edit {
2498         my $self = shift;
2499         $self->{nr} = $self->{gii}->{nr};
2500         delete $self->{gii};
2501         $self->SUPER::abort_edit(@_);
2504 sub close_edit {
2505         my $self = shift;
2506         $self->{git_commit_ok} = 1;
2507         $self->{nr} = $self->{gii}->{nr};
2508         delete $self->{gii};
2509         $self->SUPER::close_edit(@_);
2512 package SVN::Git::Editor;
2513 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2514 use strict;
2515 use warnings;
2516 use Carp qw/croak/;
2517 use IO::File;
2518 use Digest::MD5;
2520 sub new {
2521         my ($class, $opts) = @_;
2522         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2523                 die "$_ required!\n" unless (defined $opts->{$_});
2524         }
2526         my $pool = SVN::Pool->new;
2527         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2528         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2529                                      $opts->{r}, $mods);
2531         # $opts->{ra} functions should not be used after this:
2532         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
2533                                                 $opts->{editor_cb}, $pool);
2534         my $self = SVN::Delta::Editor->new(@ce, $pool);
2535         bless $self, $class;
2536         foreach (qw/svn_path r tree_a tree_b/) {
2537                 $self->{$_} = $opts->{$_};
2538         }
2539         $self->{url} = $opts->{ra}->{url};
2540         $self->{mods} = $mods;
2541         $self->{types} = $types;
2542         $self->{pool} = $pool;
2543         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2544         $self->{rm} = { };
2545         $self->{path_prefix} = length $self->{svn_path} ?
2546                                "$self->{svn_path}/" : '';
2547         return $self;
2550 sub generate_diff {
2551         my ($tree_a, $tree_b) = @_;
2552         my @diff_tree = qw(diff-tree -z -r);
2553         if ($_cp_similarity) {
2554                 push @diff_tree, "-C$_cp_similarity";
2555         } else {
2556                 push @diff_tree, '-C';
2557         }
2558         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2559         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2560         push @diff_tree, $tree_a, $tree_b;
2561         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2562         local $/ = "\0";
2563         my $state = 'meta';
2564         my @mods;
2565         while (<$diff_fh>) {
2566                 chomp $_; # this gets rid of the trailing "\0"
2567                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2568                                         $::sha1\s($::sha1)\s
2569                                         ([MTCRAD])\d*$/xo) {
2570                         push @mods, {   mode_a => $1, mode_b => $2,
2571                                         sha1_b => $3, chg => $4 };
2572                         if ($4 =~ /^(?:C|R)$/) {
2573                                 $state = 'file_a';
2574                         } else {
2575                                 $state = 'file_b';
2576                         }
2577                 } elsif ($state eq 'file_a') {
2578                         my $x = $mods[$#mods] or croak "Empty array\n";
2579                         if ($x->{chg} !~ /^(?:C|R)$/) {
2580                                 croak "Error parsing $_, $x->{chg}\n";
2581                         }
2582                         $x->{file_a} = $_;
2583                         $state = 'file_b';
2584                 } elsif ($state eq 'file_b') {
2585                         my $x = $mods[$#mods] or croak "Empty array\n";
2586                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2587                                 croak "Error parsing $_, $x->{chg}\n";
2588                         }
2589                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2590                                 croak "Error parsing $_, $x->{chg}\n";
2591                         }
2592                         $x->{file_b} = $_;
2593                         $state = 'meta';
2594                 } else {
2595                         croak "Error parsing $_\n";
2596                 }
2597         }
2598         command_close_pipe($diff_fh, $ctx);
2599         \@mods;
2602 sub check_diff_paths {
2603         my ($ra, $pfx, $rev, $mods) = @_;
2604         my %types;
2605         $pfx .= '/' if length $pfx;
2607         sub type_diff_paths {
2608                 my ($ra, $types, $path, $rev) = @_;
2609                 my @p = split m#/+#, $path;
2610                 my $c = shift @p;
2611                 unless (defined $types->{$c}) {
2612                         $types->{$c} = $ra->check_path($c, $rev);
2613                 }
2614                 while (@p) {
2615                         $c .= '/' . shift @p;
2616                         next if defined $types->{$c};
2617                         $types->{$c} = $ra->check_path($c, $rev);
2618                 }
2619         }
2621         foreach my $m (@$mods) {
2622                 foreach my $f (qw/file_a file_b/) {
2623                         next unless defined $m->{$f};
2624                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2625                         if (length $pfx.$dir && ! defined $types{$dir}) {
2626                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2627                         }
2628                 }
2629         }
2630         \%types;
2633 sub split_path {
2634         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2637 sub repo_path {
2638         my ($self, $path) = @_;
2639         $self->{path_prefix}.(defined $path ? $path : '');
2642 sub url_path {
2643         my ($self, $path) = @_;
2644         $self->{url} . '/' . $self->repo_path($path);
2647 sub rmdirs {
2648         my ($self) = @_;
2649         my $rm = $self->{rm};
2650         delete $rm->{''}; # we never delete the url we're tracking
2651         return unless %$rm;
2653         foreach (keys %$rm) {
2654                 my @d = split m#/#, $_;
2655                 my $c = shift @d;
2656                 $rm->{$c} = 1;
2657                 while (@d) {
2658                         $c .= '/' . shift @d;
2659                         $rm->{$c} = 1;
2660                 }
2661         }
2662         delete $rm->{$self->{svn_path}};
2663         delete $rm->{''}; # we never delete the url we're tracking
2664         return unless %$rm;
2666         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2667                                              $self->{tree_b});
2668         local $/ = "\0";
2669         while (<$fh>) {
2670                 chomp;
2671                 my @dn = split m#/#, $_;
2672                 while (pop @dn) {
2673                         delete $rm->{join '/', @dn};
2674                 }
2675                 unless (%$rm) {
2676                         close $fh;
2677                         return;
2678                 }
2679         }
2680         command_close_pipe($fh, $ctx);
2682         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2683         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2684                 $self->close_directory($bat->{$d}, $p);
2685                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2686                 print "\tD+\t$d/\n" unless $::_q;
2687                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2688                 delete $bat->{$d};
2689         }
2692 sub open_or_add_dir {
2693         my ($self, $full_path, $baton) = @_;
2694         my $t = $self->{types}->{$full_path};
2695         if (!defined $t) {
2696                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2697         }
2698         if ($t == $SVN::Node::none) {
2699                 return $self->add_directory($full_path, $baton,
2700                                                 undef, -1, $self->{pool});
2701         } elsif ($t == $SVN::Node::dir) {
2702                 return $self->open_directory($full_path, $baton,
2703                                                 $self->{r}, $self->{pool});
2704         }
2705         print STDERR "$full_path already exists in repository at ",
2706                 "r$self->{r} and it is not a directory (",
2707                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2708         exit 1;
2711 sub ensure_path {
2712         my ($self, $path) = @_;
2713         my $bat = $self->{bat};
2714         my $repo_path = $self->repo_path($path);
2715         return $bat->{''} unless (length $repo_path);
2716         my @p = split m#/+#, $repo_path;
2717         my $c = shift @p;
2718         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2719         while (@p) {
2720                 my $c0 = $c;
2721                 $c .= '/' . shift @p;
2722                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2723         }
2724         return $bat->{$c};
2727 sub A {
2728         my ($self, $m) = @_;
2729         my ($dir, $file) = split_path($m->{file_b});
2730         my $pbat = $self->ensure_path($dir);
2731         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2732                                         undef, -1);
2733         print "\tA\t$m->{file_b}\n" unless $::_q;
2734         $self->chg_file($fbat, $m);
2735         $self->close_file($fbat,undef,$self->{pool});
2738 sub C {
2739         my ($self, $m) = @_;
2740         my ($dir, $file) = split_path($m->{file_b});
2741         my $pbat = $self->ensure_path($dir);
2742         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2743                                 $self->url_path($m->{file_a}), $self->{r});
2744         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2745         $self->chg_file($fbat, $m);
2746         $self->close_file($fbat,undef,$self->{pool});
2749 sub delete_entry {
2750         my ($self, $path, $pbat) = @_;
2751         my $rpath = $self->repo_path($path);
2752         my ($dir, $file) = split_path($rpath);
2753         $self->{rm}->{$dir} = 1;
2754         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2757 sub R {
2758         my ($self, $m) = @_;
2759         my ($dir, $file) = split_path($m->{file_b});
2760         my $pbat = $self->ensure_path($dir);
2761         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2762                                 $self->url_path($m->{file_a}), $self->{r});
2763         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2764         $self->chg_file($fbat, $m);
2765         $self->close_file($fbat,undef,$self->{pool});
2767         ($dir, $file) = split_path($m->{file_a});
2768         $pbat = $self->ensure_path($dir);
2769         $self->delete_entry($m->{file_a}, $pbat);
2772 sub M {
2773         my ($self, $m) = @_;
2774         my ($dir, $file) = split_path($m->{file_b});
2775         my $pbat = $self->ensure_path($dir);
2776         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2777                                 $pbat,$self->{r},$self->{pool});
2778         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2779         $self->chg_file($fbat, $m);
2780         $self->close_file($fbat,undef,$self->{pool});
2783 sub T { shift->M(@_) }
2785 sub change_file_prop {
2786         my ($self, $fbat, $pname, $pval) = @_;
2787         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2790 sub chg_file {
2791         my ($self, $fbat, $m) = @_;
2792         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2793                 $self->change_file_prop($fbat,'svn:executable','*');
2794         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2795                 $self->change_file_prop($fbat,'svn:executable',undef);
2796         }
2797         my $fh = IO::File->new_tmpfile or croak $!;
2798         if ($m->{mode_b} =~ /^120/) {
2799                 print $fh 'link ' or croak $!;
2800                 $self->change_file_prop($fbat,'svn:special','*');
2801         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2802                 $self->change_file_prop($fbat,'svn:special',undef);
2803         }
2804         defined(my $pid = fork) or croak $!;
2805         if (!$pid) {
2806                 open STDOUT, '>&', $fh or croak $!;
2807                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2808         }
2809         waitpid $pid, 0;
2810         croak $? if $?;
2811         $fh->flush == 0 or croak $!;
2812         seek $fh, 0, 0 or croak $!;
2814         my $md5 = Digest::MD5->new;
2815         $md5->addfile($fh) or croak $!;
2816         seek $fh, 0, 0 or croak $!;
2818         my $exp = $md5->hexdigest;
2819         my $pool = SVN::Pool->new;
2820         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2821         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2822         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2823         $pool->clear;
2825         close $fh or croak $!;
2828 sub D {
2829         my ($self, $m) = @_;
2830         my ($dir, $file) = split_path($m->{file_b});
2831         my $pbat = $self->ensure_path($dir);
2832         print "\tD\t$m->{file_b}\n" unless $::_q;
2833         $self->delete_entry($m->{file_b}, $pbat);
2836 sub close_edit {
2837         my ($self) = @_;
2838         my ($p,$bat) = ($self->{pool}, $self->{bat});
2839         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2840                 $self->close_directory($bat->{$_}, $p);
2841         }
2842         $self->SUPER::close_edit($p);
2843         $p->clear;
2846 sub abort_edit {
2847         my ($self) = @_;
2848         $self->SUPER::abort_edit($self->{pool});
2851 sub DESTROY {
2852         my $self = shift;
2853         $self->SUPER::DESTROY(@_);
2854         $self->{pool}->clear;
2857 # this drives the editor
2858 sub apply_diff {
2859         my ($self) = @_;
2860         my $mods = $self->{mods};
2861         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2862         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2863                 my $f = $m->{chg};
2864                 if (defined $o{$f}) {
2865                         $self->$f($m);
2866                 } else {
2867                         fatal("Invalid change type: $f\n");
2868                 }
2869         }
2870         $self->rmdirs if $_rmdir;
2871         if (@$mods == 0) {
2872                 $self->abort_edit;
2873         } else {
2874                 $self->close_edit;
2875         }
2876         return scalar @$mods;
2879 package Git::SVN::Ra;
2880 use vars qw/@ISA $config_dir $_log_window_size/;
2881 use strict;
2882 use warnings;
2883 my ($can_do_switch, %ignored_err, $RA);
2885 BEGIN {
2886         # enforce temporary pool usage for some simple functions
2887         my $e;
2888         foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2889                 $e .= "sub $_ {
2890                         my \$self = shift;
2891                         my \$pool = SVN::Pool->new;
2892                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2893                         \$pool->clear;
2894                         wantarray ? \@ret : \$ret[0]; }\n";
2895         }
2897         # get_dir needs $pool held in cache for dirents to work,
2898         # check_path is cacheable and rev_proplist is close enough
2899         # for our purposes.
2900         foreach (qw/check_path get_dir rev_proplist/) {
2901                 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2902                         my \$self = shift;
2903                         my \$r = pop;
2904                         my \$k = join(\"\\0\", \@_);
2905                         if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2906                                 return wantarray ? \@\$x : \$x->[0];
2907                         }
2908                         my \$pool = SVN::Pool->new;
2909                         my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2910                         if (\$r != \$${_}_rev) {
2911                                 \%${_}_cache = ( pool => [] );
2912                                 \$${_}_rev = \$r;
2913                         }
2914                         \$${_}_cache{\$r}->{\$k} = \\\@ret;
2915                         push \@{\$${_}_cache{pool}}, \$pool;
2916                         wantarray ? \@ret : \$ret[0]; }\n";
2917         }
2918         $e .= "\n1;";
2919         eval $e or die $@;
2922 sub new {
2923         my ($class, $url) = @_;
2924         $url =~ s!/+$!!;
2925         return $RA if ($RA && $RA->{url} eq $url);
2926         $RA->{pool}->clear if $RA;
2928         SVN::_Core::svn_config_ensure($config_dir, undef);
2929         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2930             SVN::Client::get_simple_provider(),
2931             SVN::Client::get_ssl_server_trust_file_provider(),
2932             SVN::Client::get_simple_prompt_provider(
2933               \&Git::SVN::Prompt::simple, 2),
2934             SVN::Client::get_ssl_client_cert_prompt_provider(
2935               \&Git::SVN::Prompt::ssl_client_cert, 2),
2936             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2937               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2938             SVN::Client::get_username_provider(),
2939             SVN::Client::get_ssl_server_trust_prompt_provider(
2940               \&Git::SVN::Prompt::ssl_server_trust),
2941             SVN::Client::get_username_prompt_provider(
2942               \&Git::SVN::Prompt::username, 2),
2943           ]);
2944         my $config = SVN::Core::config_get_config($config_dir);
2945         my $self = SVN::Ra->new(url => $url, auth => $baton,
2946                               config => $config,
2947                               pool => SVN::Pool->new,
2948                               auth_provider_callbacks => $callbacks);
2949         $self->{svn_path} = $url;
2950         $self->{repos_root} = $self->get_repos_root;
2951         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2952         $RA = bless $self, $class;
2955 sub DESTROY {
2956         # do not call the real DESTROY since we store ourselves in $RA
2959 sub get_log {
2960         my ($self, @args) = @_;
2961         my $pool = SVN::Pool->new;
2962         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2963         my $ret = $self->SUPER::get_log(@args, $pool);
2964         $pool->clear;
2965         $ret;
2968 sub get_commit_editor {
2969         my ($self, $log, $cb, $pool) = @_;
2970         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2971         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2974 sub gs_do_update {
2975         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2976         my $new = ($rev_a == $rev_b);
2977         my $path = $gs->{path};
2979         if ($new && -e $gs->{index}) {
2980                 unlink $gs->{index} or die
2981                   "Couldn't unlink index: $gs->{index}: $!\n";
2982         }
2983         my $pool = SVN::Pool->new;
2984         $editor->set_path_strip($path);
2985         my (@pc) = split m#/#, $path;
2986         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2987                                         1, $editor, $pool);
2988         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2990         # Since we can't rely on svn_ra_reparent being available, we'll
2991         # just have to do some magic with set_path to make it so
2992         # we only want a partial path.
2993         my $sp = '';
2994         my $final = join('/', @pc);
2995         while (@pc) {
2996                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2997                 $sp .= '/' if length $sp;
2998                 $sp .= shift @pc;
2999         }
3000         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3002         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3004         $reporter->finish_report($pool);
3005         $pool->clear;
3006         $editor->{git_commit_ok};
3009 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3010 # svn_ra_reparent didn't work before 1.4)
3011 sub gs_do_switch {
3012         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3013         my $path = $gs->{path};
3014         my $pool = SVN::Pool->new;
3016         my $full_url = $self->{url};
3017         my $old_url = $full_url;
3018         $full_url .= "/$path" if length $path;
3019         my ($ra, $reparented);
3020         if ($old_url ne $full_url) {
3021                 if ($old_url !~ m#^svn(\+ssh)?://#) {
3022                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3023                                                   $pool);
3024                         $self->{url} = $full_url;
3025                         $reparented = 1;
3026                 } else {
3027                         $ra = Git::SVN::Ra->new($full_url);
3028                 }
3029         }
3030         $ra ||= $self;
3031         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3032         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3033         $reporter->set_path('', $rev_a, 0, @lock, $pool);
3034         $reporter->finish_report($pool);
3036         if ($reparented) {
3037                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3038                 $self->{url} = $old_url;
3039         }
3041         $pool->clear;
3042         $editor->{git_commit_ok};
3045 sub gs_fetch_loop_common {
3046         my ($self, $base, $head, $gsv, $globs) = @_;
3047         return if ($base > $head);
3048         my $inc = $_log_window_size;
3049         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3050         my %common;
3051         my $common_max = scalar @$gsv;
3053         foreach my $gs (@$gsv) {
3054                 my @tmp = split m#/#, $gs->{path};
3055                 my $p = '';
3056                 foreach (@tmp) {
3057                         $p .= length($p) ? "/$_" : $_;
3058                         $common{$p} ||= 0;
3059                         $common{$p}++;
3060                 }
3061         }
3062         $globs ||= [];
3063         $common_max += scalar @$globs;
3064         foreach my $glob (@$globs) {
3065                 my @tmp = split m#/#, $glob->{path}->{left};
3066                 my $p = '';
3067                 foreach (@tmp) {
3068                         $p .= length($p) ? "/$_" : $_;
3069                         $common{$p} ||= 0;
3070                         $common{$p}++;
3071                 }
3072         }
3074         my $longest_path = '';
3075         foreach (sort {length $b <=> length $a} keys %common) {
3076                 if ($common{$_} == $common_max) {
3077                         $longest_path = $_;
3078                         last;
3079                 }
3080         }
3081         while (1) {
3082                 my %revs;
3083                 my $err;
3084                 my $err_handler = $SVN::Error::handler;
3085                 $SVN::Error::handler = sub {
3086                         ($err) = @_;
3087                         skip_unknown_revs($err);
3088                 };
3089                 sub _cb {
3090                         my ($paths, $r, $author, $date, $log) = @_;
3091                         [ dup_changed_paths($paths),
3092                           { author => $author, date => $date, log => $log } ];
3093                 }
3094                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3095                                sub { $revs{$_[1]} = _cb(@_) });
3096                 if ($err && $max >= $head) {
3097                         print STDERR "Path '$longest_path' ",
3098                                      "was probably deleted:\n",
3099                                      $err->expanded_message,
3100                                      "\nWill attempt to follow ",
3101                                      "revisions r$min .. r$max ",
3102                                      "committed before the deletion\n";
3103                         my $hi = $max;
3104                         while (--$hi >= $min) {
3105                                 my $ok;
3106                                 $self->get_log([$longest_path], $min, $hi,
3107                                                0, 1, 1, sub {
3108                                                $ok ||= $_[1];
3109                                                $revs{$_[1]} = _cb(@_) });
3110                                 if ($ok) {
3111                                         print STDERR "r$min .. r$ok OK\n";
3112                                         last;
3113                                 }
3114                         }
3115                 }
3116                 $SVN::Error::handler = $err_handler;
3118                 my %exists = map { $_->{path} => $_ } @$gsv;
3119                 foreach my $r (sort {$a <=> $b} keys %revs) {
3120                         my ($paths, $logged) = @{$revs{$r}};
3122                         foreach my $gs ($self->match_globs(\%exists, $paths,
3123                                                            $globs, $r)) {
3124                                 if ($gs->rev_db_max >= $r) {
3125                                         next;
3126                                 }
3127                                 next unless $gs->match_paths($paths, $r);
3128                                 $gs->{logged_rev_props} = $logged;
3129                                 if (my $last_commit = $gs->last_commit) {
3130                                         $gs->assert_index_clean($last_commit);
3131                                 }
3132                                 my $log_entry = $gs->do_fetch($paths, $r);
3133                                 if ($log_entry) {
3134                                         $gs->do_git_commit($log_entry);
3135                                 }
3136                         }
3137                         foreach my $g (@$globs) {
3138                                 my $k = "svn-remote.$g->{remote}." .
3139                                         "$g->{t}-maxRev";
3140                                 Git::SVN::tmp_config($k, $r);
3141                         }
3142                 }
3143                 # pre-fill the .rev_db since it'll eventually get filled in
3144                 # with '0' x40 if something new gets committed
3145                 foreach my $gs (@$gsv) {
3146                         next if defined $gs->rev_db_get($max);
3147                         $gs->rev_db_set($max, 0 x40);
3148                 }
3149                 foreach my $g (@$globs) {
3150                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3151                         Git::SVN::tmp_config($k, $max);
3152                 }
3153                 last if $max >= $head;
3154                 $min = $max + 1;
3155                 $max += $inc;
3156                 $max = $head if ($max > $head);
3157         }
3160 sub match_globs {
3161         my ($self, $exists, $paths, $globs, $r) = @_;
3163         sub get_dir_check {
3164                 my ($self, $exists, $g, $r) = @_;
3165                 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3166                 return unless scalar @x == 3;
3167                 my $dirents = $x[0];
3168                 foreach my $de (keys %$dirents) {
3169                         next if $dirents->{$de}->kind != $SVN::Node::dir;
3170                         my $p = $g->{path}->full_path($de);
3171                         next if $exists->{$p};
3172                         next if (length $g->{path}->{right} &&
3173                                  ($self->check_path($p, $r) !=
3174                                   $SVN::Node::dir));
3175                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3176                                          $g->{ref}->full_path($de), 1);
3177                 }
3178         }
3179         foreach my $g (@$globs) {
3180                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3181                         if ($path->{action} =~ /^[AR]$/) {
3182                                 get_dir_check($self, $exists, $g, $r);
3183                         }
3184                 }
3185                 foreach (keys %$paths) {
3186                         if (/$g->{path}->{left_regex}/ &&
3187                             !/$g->{path}->{regex}/) {
3188                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
3189                                 get_dir_check($self, $exists, $g, $r);
3190                         }
3191                         next unless /$g->{path}->{regex}/;
3192                         my $p = $1;
3193                         my $pathname = $g->{path}->full_path($p);
3194                         next if $exists->{$pathname};
3195                         next if ($self->check_path($pathname, $r) !=
3196                                  $SVN::Node::dir);
3197                         $exists->{$pathname} = Git::SVN->init(
3198                                               $self->{url}, $pathname, undef,
3199                                               $g->{ref}->full_path($p), 1);
3200                 }
3201                 my $c = '';
3202                 foreach (split m#/#, $g->{path}->{left}) {
3203                         $c .= "/$_";
3204                         next unless ($paths->{$c} &&
3205                                      ($paths->{$c}->{action} =~ /^[AR]$/));
3206                         get_dir_check($self, $exists, $g, $r);
3207                 }
3208         }
3209         values %$exists;
3212 sub minimize_url {
3213         my ($self) = @_;
3214         return $self->{url} if ($self->{url} eq $self->{repos_root});
3215         my $url = $self->{repos_root};
3216         my @components = split(m!/!, $self->{svn_path});
3217         my $c = '';
3218         do {
3219                 $url .= "/$c" if length $c;
3220                 eval { (ref $self)->new($url)->get_latest_revnum };
3221         } while ($@ && ($c = shift @components));
3222         $url;
3225 sub can_do_switch {
3226         my $self = shift;
3227         unless (defined $can_do_switch) {
3228                 my $pool = SVN::Pool->new;
3229                 my $rep = eval {
3230                         $self->do_switch(1, '', 0, $self->{url},
3231                                          SVN::Delta::Editor->new, $pool);
3232                 };
3233                 if ($@) {
3234                         $can_do_switch = 0;
3235                 } else {
3236                         $rep->abort_report($pool);
3237                         $can_do_switch = 1;
3238                 }
3239                 $pool->clear;
3240         }
3241         $can_do_switch;
3244 sub skip_unknown_revs {
3245         my ($err) = @_;
3246         my $errno = $err->apr_err();
3247         # Maybe the branch we're tracking didn't
3248         # exist when the repo started, so it's
3249         # not an error if it doesn't, just continue
3250         #
3251         # Wonderfully consistent library, eh?
3252         # 160013 - svn:// and file://
3253         # 175002 - http(s)://
3254         # 175007 - http(s):// (this repo required authorization, too...)
3255         #   More codes may be discovered later...
3256         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3257                 my $err_key = $err->expanded_message;
3258                 # revision numbers change every time, filter them out
3259                 $err_key =~ s/\d+/\0/g;
3260                 $err_key = "$errno\0$err_key";
3261                 unless ($ignored_err{$err_key}) {
3262                         warn "W: Ignoring error from SVN, path probably ",
3263                              "does not exist: ($errno): ",
3264                              $err->expanded_message,"\n";
3265                         $ignored_err{$err_key} = 1;
3266                 }
3267                 return;
3268         }
3269         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3272 # svn_log_changed_path_t objects passed to get_log are likely to be
3273 # overwritten even if only the refs are copied to an external variable,
3274 # so we should dup the structures in their entirety.  Using an externally
3275 # passed pool (instead of our temporary and quickly cleared pool in
3276 # Git::SVN::Ra) does not help matters at all...
3277 sub dup_changed_paths {
3278         my ($paths) = @_;
3279         return undef unless $paths;
3280         my %ret;
3281         foreach my $p (keys %$paths) {
3282                 my $i = $paths->{$p};
3283                 my %s = map { $_ => $i->$_ }
3284                               qw/copyfrom_path copyfrom_rev action/;
3285                 $ret{$p} = \%s;
3286         }
3287         \%ret;
3290 package Git::SVN::Log;
3291 use strict;
3292 use warnings;
3293 use POSIX qw/strftime/;
3294 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3295             %rusers $show_commit $incremental/;
3296 my $l_fmt;
3298 sub cmt_showable {
3299         my ($c) = @_;
3300         return 1 if defined $c->{r};
3302         # big commit message got truncated by the 16k pretty buffer in rev-list
3303         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3304                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3305                 @{$c->{l}} = ();
3306                 my @log = command(qw/cat-file commit/, $c->{c});
3308                 # shift off the headers
3309                 shift @log while ($log[0] ne '');
3310                 shift @log;
3312                 # TODO: make $c->{l} not have a trailing newline in the future
3313                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3315                 (undef, $c->{r}, undef) = ::extract_metadata(
3316                                 (grep(/^git-svn-id: /, @log))[-1]);
3317         }
3318         return defined $c->{r};
3321 sub log_use_color {
3322         return 1 if $color;
3323         my ($dc, $dcvar);
3324         $dcvar = 'color.diff';
3325         $dc = `git-config --get $dcvar`;
3326         if ($dc eq '') {
3327                 # nothing at all; fallback to "diff.color"
3328                 $dcvar = 'diff.color';
3329                 $dc = `git-config --get $dcvar`;
3330         }
3331         chomp($dc);
3332         if ($dc eq 'auto') {
3333                 my $pc;
3334                 $pc = `git-config --get color.pager`;
3335                 if ($pc eq '') {
3336                         # does not have it -- fallback to pager.color
3337                         $pc = `git-config --bool --get pager.color`;
3338                 }
3339                 else {
3340                         $pc = `git-config --bool --get color.pager`;
3341                         if ($?) {
3342                                 $pc = 'false';
3343                         }
3344                 }
3345                 chomp($pc);
3346                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3347                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3348                 }
3349                 return 0;
3350         }
3351         return 0 if $dc eq 'never';
3352         return 1 if $dc eq 'always';
3353         chomp($dc = `git-config --bool --get $dcvar`);
3354         return ($dc eq 'true');
3357 sub git_svn_log_cmd {
3358         my ($r_min, $r_max, @args) = @_;
3359         my $head = 'HEAD';
3360         foreach my $x (@args) {
3361                 last if $x eq '--';
3362                 next unless ::verify_ref("$x^0");
3363                 $head = $x;
3364                 last;
3365         }
3367         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3368         $gs ||= Git::SVN->_new;
3369         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3370                    $gs->refname);
3371         push @cmd, '-r' unless $non_recursive;
3372         push @cmd, qw/--raw --name-status/ if $verbose;
3373         push @cmd, '--color' if log_use_color();
3374         return @cmd unless defined $r_max;
3375         if ($r_max == $r_min) {
3376                 push @cmd, '--max-count=1';
3377                 if (my $c = $gs->rev_db_get($r_max)) {
3378                         push @cmd, $c;
3379                 }
3380         } else {
3381                 my ($c_min, $c_max);
3382                 $c_max = $gs->rev_db_get($r_max);
3383                 $c_min = $gs->rev_db_get($r_min);
3384                 if (defined $c_min && defined $c_max) {
3385                         if ($r_max > $r_max) {
3386                                 push @cmd, "$c_min..$c_max";
3387                         } else {
3388                                 push @cmd, "$c_max..$c_min";
3389                         }
3390                 } elsif ($r_max > $r_min) {
3391                         push @cmd, $c_max;
3392                 } else {
3393                         push @cmd, $c_min;
3394                 }
3395         }
3396         return @cmd;
3399 # adapted from pager.c
3400 sub config_pager {
3401         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3402         if (!defined $pager) {
3403                 $pager = 'less';
3404         } elsif (length $pager == 0 || $pager eq 'cat') {
3405                 $pager = undef;
3406         }
3409 sub run_pager {
3410         return unless -t *STDOUT;
3411         pipe my $rfd, my $wfd or return;
3412         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3413         if (!$pid) {
3414                 open STDOUT, '>&', $wfd or
3415                                      ::fatal "Can't redirect to stdout: $!\n";
3416                 return;
3417         }
3418         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3419         $ENV{LESS} ||= 'FRSX';
3420         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3423 sub tz_to_s_offset {
3424         my ($tz) = @_;
3425         $tz =~ s/(\d\d)$//;
3426         return ($1 * 60) + ($tz * 3600);
3429 sub get_author_info {
3430         my ($dest, $author, $t, $tz) = @_;
3431         $author =~ s/(?:^\s*|\s*$)//g;
3432         $dest->{a_raw} = $author;
3433         my $au;
3434         if ($::_authors) {
3435                 $au = $rusers{$author} || undef;
3436         }
3437         if (!$au) {
3438                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3439         }
3440         $dest->{t} = $t;
3441         $dest->{tz} = $tz;
3442         $dest->{a} = $au;
3443         # Date::Parse isn't in the standard Perl distro :(
3444         if ($tz =~ s/^\+//) {
3445                 $t += tz_to_s_offset($tz);
3446         } elsif ($tz =~ s/^\-//) {
3447                 $t -= tz_to_s_offset($tz);
3448         }
3449         $dest->{t_utc} = $t;
3452 sub process_commit {
3453         my ($c, $r_min, $r_max, $defer) = @_;
3454         if (defined $r_min && defined $r_max) {
3455                 if ($r_min == $c->{r} && $r_min == $r_max) {
3456                         show_commit($c);
3457                         return 0;
3458                 }
3459                 return 1 if $r_min == $r_max;
3460                 if ($r_min < $r_max) {
3461                         # we need to reverse the print order
3462                         return 0 if (defined $limit && --$limit < 0);
3463                         push @$defer, $c;
3464                         return 1;
3465                 }
3466                 if ($r_min != $r_max) {
3467                         return 1 if ($r_min < $c->{r});
3468                         return 1 if ($r_max > $c->{r});
3469                 }
3470         }
3471         return 0 if (defined $limit && --$limit < 0);
3472         show_commit($c);
3473         return 1;
3476 sub show_commit {
3477         my $c = shift;
3478         if ($oneline) {
3479                 my $x = "\n";
3480                 if (my $l = $c->{l}) {
3481                         while ($l->[0] =~ /^\s*$/) { shift @$l }
3482                         $x = $l->[0];
3483                 }
3484                 $l_fmt ||= 'A' . length($c->{r});
3485                 print 'r',pack($l_fmt, $c->{r}),' | ';
3486                 print "$c->{c} | " if $show_commit;
3487                 print $x;
3488         } else {
3489                 show_commit_normal($c);
3490         }
3493 sub show_commit_changed_paths {
3494         my ($c) = @_;
3495         return unless $c->{changed};
3496         print "Changed paths:\n", @{$c->{changed}};
3499 sub show_commit_normal {
3500         my ($c) = @_;
3501         print '-' x72, "\nr$c->{r} | ";
3502         print "$c->{c} | " if $show_commit;
3503         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3504                                  localtime($c->{t_utc})), ' | ';
3505         my $nr_line = 0;
3507         if (my $l = $c->{l}) {
3508                 while ($l->[$#$l] eq "\n" && $#$l > 0
3509                                           && $l->[($#$l - 1)] eq "\n") {
3510                         pop @$l;
3511                 }
3512                 $nr_line = scalar @$l;
3513                 if (!$nr_line) {
3514                         print "1 line\n\n\n";
3515                 } else {
3516                         if ($nr_line == 1) {
3517                                 $nr_line = '1 line';
3518                         } else {
3519                                 $nr_line .= ' lines';
3520                         }
3521                         print $nr_line, "\n";
3522                         show_commit_changed_paths($c);
3523                         print "\n";
3524                         print $_ foreach @$l;
3525                 }
3526         } else {
3527                 print "1 line\n";
3528                 show_commit_changed_paths($c);
3529                 print "\n";
3531         }
3532         foreach my $x (qw/raw stat diff/) {
3533                 if ($c->{$x}) {
3534                         print "\n";
3535                         print $_ foreach @{$c->{$x}}
3536                 }
3537         }
3540 sub cmd_show_log {
3541         my (@args) = @_;
3542         my ($r_min, $r_max);
3543         my $r_last = -1; # prevent dupes
3544         if (defined $TZ) {
3545                 $ENV{TZ} = $TZ;
3546         } else {
3547                 delete $ENV{TZ};
3548         }
3549         if (defined $::_revision) {
3550                 if ($::_revision =~ /^(\d+):(\d+)$/) {
3551                         ($r_min, $r_max) = ($1, $2);
3552                 } elsif ($::_revision =~ /^\d+$/) {
3553                         $r_min = $r_max = $::_revision;
3554                 } else {
3555                         ::fatal "-r$::_revision is not supported, use ",
3556                                 "standard \'git log\' arguments instead\n";
3557                 }
3558         }
3560         config_pager();
3561         @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3562         my $log = command_output_pipe(@args);
3563         run_pager();
3564         my (@k, $c, $d, $stat);
3565         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3566         while (<$log>) {
3567                 if (/^${esc_color}commit ($::sha1_short)/o) {
3568                         my $cmt = $1;
3569                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3570                                 $r_last = $c->{r};
3571                                 process_commit($c, $r_min, $r_max, \@k) or
3572                                                                 goto out;
3573                         }
3574                         $d = undef;
3575                         $c = { c => $cmt };
3576                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3577                         get_author_info($c, $1, $2, $3);
3578                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3579                         # ignore
3580                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3581                         push @{$c->{raw}}, $_;
3582                 } elsif (/^${esc_color}[ACRMDT]\t/) {
3583                         # we could add $SVN->{svn_path} here, but that requires
3584                         # remote access at the moment (repo_path_split)...
3585                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3586                         push @{$c->{changed}}, $_;
3587                 } elsif (/^${esc_color}diff /o) {
3588                         $d = 1;
3589                         push @{$c->{diff}}, $_;
3590                 } elsif ($d) {
3591                         push @{$c->{diff}}, $_;
3592                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3593                           $esc_color*[\+\-]*$esc_color$/x) {
3594                         $stat = 1;
3595                         push @{$c->{stat}}, $_;
3596                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3597                         push @{$c->{stat}}, $_;
3598                         $stat = undef;
3599                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3600                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3601                 } elsif (s/^${esc_color}    //o) {
3602                         push @{$c->{l}}, $_;
3603                 }
3604         }
3605         if ($c && defined $c->{r} && $c->{r} != $r_last) {
3606                 $r_last = $c->{r};
3607                 process_commit($c, $r_min, $r_max, \@k);
3608         }
3609         if (@k) {
3610                 my $swap = $r_max;
3611                 $r_max = $r_min;
3612                 $r_min = $swap;
3613                 process_commit($_, $r_min, $r_max) foreach reverse @k;
3614         }
3615 out:
3616         close $log;
3617         print '-' x72,"\n" unless $incremental || $oneline;
3620 package Git::SVN::Migration;
3621 # these version numbers do NOT correspond to actual version numbers
3622 # of git nor git-svn.  They are just relative.
3624 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3626 # v1 layout: .git/$id/info/url, refs/remotes/$id
3628 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3630 # v3 layout: .git/svn/$id, refs/remotes/$id
3631 #            - info/url may remain for backwards compatibility
3632 #            - this is what we migrate up to this layout automatically,
3633 #            - this will be used by git svn init on single branches
3634 # v3.1 layout (auto migrated):
3635 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3636 #              for backwards compatibility
3638 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3639 #            - this is only created for newly multi-init-ed
3640 #              repositories.  Similar in spirit to the
3641 #              --use-separate-remotes option in git-clone (now default)
3642 #            - we do not automatically migrate to this (following
3643 #              the example set by core git)
3644 use strict;
3645 use warnings;
3646 use Carp qw/croak/;
3647 use File::Path qw/mkpath/;
3648 use File::Basename qw/dirname basename/;
3649 use vars qw/$_minimize/;
3651 sub migrate_from_v0 {
3652         my $git_dir = $ENV{GIT_DIR};
3653         return undef unless -d $git_dir;
3654         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3655         my $migrated = 0;
3656         while (<$fh>) {
3657                 chomp;
3658                 my ($id, $orig_ref) = ($_, $_);
3659                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3660                 next unless -f "$git_dir/$id/info/url";
3661                 my $new_ref = "refs/remotes/$id";
3662                 if (::verify_ref("$new_ref^0")) {
3663                         print STDERR "W: $orig_ref is probably an old ",
3664                                      "branch used by an ancient version of ",
3665                                      "git-svn.\n",
3666                                      "However, $new_ref also exists.\n",
3667                                      "We will not be able ",
3668                                      "to use this branch until this ",
3669                                      "ambiguity is resolved.\n";
3670                         next;
3671                 }
3672                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3673                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3674                 command_noisy('update-ref', $new_ref, $orig_ref);
3675                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3676                 $migrated++;
3677         }
3678         command_close_pipe($fh, $ctx);
3679         print STDERR "Done migrating from v0 layout...\n" if $migrated;
3680         $migrated;
3683 sub migrate_from_v1 {
3684         my $git_dir = $ENV{GIT_DIR};
3685         my $migrated = 0;
3686         return $migrated unless -d $git_dir;
3687         my $svn_dir = "$git_dir/svn";
3689         # just in case somebody used 'svn' as their $id at some point...
3690         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3692         print STDERR "Migrating from a git-svn v1 layout...\n";
3693         mkpath([$svn_dir]);
3694         print STDERR "Data from a previous version of git-svn exists, but\n\t",
3695                      "$svn_dir\n\t(required for this version ",
3696                      "($::VERSION) of git-svn) does not. exist\n";
3697         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3698         while (<$fh>) {
3699                 my $x = $_;
3700                 next unless $x =~ s#^refs/remotes/##;
3701                 chomp $x;
3702                 next unless -f "$git_dir/$x/info/url";
3703                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3704                 next unless $u;
3705                 my $dn = dirname("$git_dir/svn/$x");
3706                 mkpath([$dn]) unless -d $dn;
3707                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3708                         mkpath(["$git_dir/svn/svn"]);
3709                         print STDERR " - $git_dir/$x/info => ",
3710                                         "$git_dir/svn/$x/info\n";
3711                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3712                                croak "$!: $x";
3713                         # don't worry too much about these, they probably
3714                         # don't exist with repos this old (save for index,
3715                         # and we can easily regenerate that)
3716                         foreach my $f (qw/unhandled.log index .rev_db/) {
3717                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3718                         }
3719                 } else {
3720                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3721                         rename "$git_dir/$x", "$git_dir/svn/$x" or
3722                                croak "$!: $x";
3723                 }
3724                 $migrated++;
3725         }
3726         command_close_pipe($fh, $ctx);
3727         print STDERR "Done migrating from a git-svn v1 layout\n";
3728         $migrated;
3731 sub read_old_urls {
3732         my ($l_map, $pfx, $path) = @_;
3733         my @dir;
3734         foreach (<$path/*>) {
3735                 if (-r "$_/info/url") {
3736                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3737                         my $ref_id = $pfx . basename $_;
3738                         my $url = ::file_to_s("$_/info/url");
3739                         $l_map->{$ref_id} = $url;
3740                 } elsif (-d $_) {
3741                         push @dir, $_;
3742                 }
3743         }
3744         foreach (@dir) {
3745                 my $x = $_;
3746                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3747                 read_old_urls($l_map, $x, $_);
3748         }
3751 sub migrate_from_v2 {
3752         my @cfg = command(qw/config -l/);
3753         return if grep /^svn-remote\..+\.url=/, @cfg;
3754         my %l_map;
3755         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3756         my $migrated = 0;
3758         foreach my $ref_id (sort keys %l_map) {
3759                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3760                 if ($@) {
3761                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3762                 }
3763                 $migrated++;
3764         }
3765         $migrated;
3768 sub minimize_connections {
3769         my $r = Git::SVN::read_all_remotes();
3770         my $new_urls = {};
3771         my $root_repos = {};
3772         foreach my $repo_id (keys %$r) {
3773                 my $url = $r->{$repo_id}->{url} or next;
3774                 my $fetch = $r->{$repo_id}->{fetch} or next;
3775                 my $ra = Git::SVN::Ra->new($url);
3777                 # skip existing cases where we already connect to the root
3778                 if (($ra->{url} eq $ra->{repos_root}) ||
3779                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3780                      $repo_id)) {
3781                         $root_repos->{$ra->{url}} = $repo_id;
3782                         next;
3783                 }
3785                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3786                 my $root_path = $ra->{url};
3787                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3788                 foreach my $path (keys %$fetch) {
3789                         my $ref_id = $fetch->{$path};
3790                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3792                         # make sure we can read when connecting to
3793                         # a higher level of a repository
3794                         my ($last_rev, undef) = $gs->last_rev_commit;
3795                         if (!defined $last_rev) {
3796                                 $last_rev = eval {
3797                                         $root_ra->get_latest_revnum;
3798                                 };
3799                                 next if $@;
3800                         }
3801                         my $new = $root_path;
3802                         $new .= length $path ? "/$path" : '';
3803                         eval {
3804                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3805                                                   0, 0, 1, sub { });
3806                         };
3807                         next if $@;
3808                         $new_urls->{$ra->{repos_root}}->{$new} =
3809                                 { ref_id => $ref_id,
3810                                   old_repo_id => $repo_id,
3811                                   old_path => $path };
3812                 }
3813         }
3815         my @emptied;
3816         foreach my $url (keys %$new_urls) {
3817                 # see if we can re-use an existing [svn-remote "repo_id"]
3818                 # instead of creating a(n ugly) new section:
3819                 my $repo_id = $root_repos->{$url} ||
3820                               Git::SVN::sanitize_remote_name($url);
3822                 my $fetch = $new_urls->{$url};
3823                 foreach my $path (keys %$fetch) {
3824                         my $x = $fetch->{$path};
3825                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3826                         my $pfx = "svn-remote.$x->{old_repo_id}";
3828                         my $old_fetch = quotemeta("$x->{old_path}:".
3829                                                   "refs/remotes/$x->{ref_id}");
3830                         command_noisy(qw/config --unset/,
3831                                       "$pfx.fetch", '^'. $old_fetch . '$');
3832                         delete $r->{$x->{old_repo_id}}->
3833                                {fetch}->{$x->{old_path}};
3834                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3835                                 command_noisy(qw/config --unset/,
3836                                               "$pfx.url");
3837                                 push @emptied, $x->{old_repo_id}
3838                         }
3839                 }
3840         }
3841         if (@emptied) {
3842                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3843                            "$ENV{GIT_DIR}/config";
3844                 print STDERR <<EOF;
3845 The following [svn-remote] sections in your config file ($file) are empty
3846 and can be safely removed:
3847 EOF
3848                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3849         }
3852 sub migration_check {
3853         migrate_from_v0();
3854         migrate_from_v1();
3855         migrate_from_v2();
3856         minimize_connections() if $_minimize;
3859 package Git::IndexInfo;
3860 use strict;
3861 use warnings;
3862 use Git qw/command_input_pipe command_close_pipe/;
3864 sub new {
3865         my ($class) = @_;
3866         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3867         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3870 sub remove {
3871         my ($self, $path) = @_;
3872         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3873                 return ++$self->{nr};
3874         }
3875         undef;
3878 sub update {
3879         my ($self, $mode, $hash, $path) = @_;
3880         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3881                 return ++$self->{nr};
3882         }
3883         undef;
3886 sub DESTROY {
3887         my ($self) = @_;
3888         command_close_pipe($self->{gui}, $self->{ctx});
3891 package Git::SVN::GlobSpec;
3892 use strict;
3893 use warnings;
3895 sub new {
3896         my ($class, $glob) = @_;
3897         my $re = $glob;
3898         $re =~ s!/+$!!g; # no need for trailing slashes
3899         my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3900         my ($left, $right) = ($1, $2);
3901         if ($nr > 1) {
3902                 die "Only one '*' wildcard expansion ",
3903                     "is supported (got $nr): '$glob'\n";
3904         } elsif ($nr == 0) {
3905                 die "One '*' is needed for glob: '$glob'\n";
3906         }
3907         $re = quotemeta($left) . $re . quotemeta($right);
3908         if (length $left && !($left =~ s!/+$!!g)) {
3909                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3910         }
3911         if (length $right && !($right =~ s!^/+!!g)) {
3912                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3913         }
3914         my $left_re = qr/^\/\Q$left\E(\/|$)/;
3915         bless { left => $left, right => $right, left_regex => $left_re,
3916                 regex => qr/$re/, glob => $glob }, $class;
3919 sub full_path {
3920         my ($self, $path) = @_;
3921         return (length $self->{left} ? "$self->{left}/" : '') .
3922                $path . (length $self->{right} ? "/$self->{right}" : '');
3925 __END__
3927 Data structures:
3930 $remotes = { # returned by read_all_remotes()
3931         'svn' => {
3932                 # svn-remote.svn.url=https://svn.musicpd.org
3933                 url => 'https://svn.musicpd.org',
3934                 # svn-remote.svn.fetch=mpd/trunk:trunk
3935                 fetch => {
3936                         'mpd/trunk' => 'trunk',
3937                 },
3938                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3939                 tags => {
3940                         path => {
3941                                 left => 'mpd/tags',
3942                                 right => '',
3943                                 regex => qr!mpd/tags/([^/]+)$!,
3944                                 glob => 'tags/*',
3945                         },
3946                         ref => {
3947                                 left => 'tags',
3948                                 right => '',
3949                                 regex => qr!tags/([^/]+)$!,
3950                                 glob => 'tags/*',
3951                         },
3952                 }
3953         }
3954 };
3956 $log_entry hashref as returned by libsvn_log_entry()
3958         log => 'whitespace-formatted log entry
3959 ',                                              # trailing newline is preserved
3960         revision => '8',                        # integer
3961         date => '2004-02-24T17:01:44.108345Z',  # commit date
3962         author => 'committer name'
3963 };
3966 # this is generated by generate_diff();
3967 @mods = array of diff-index line hashes, each element represents one line
3968         of diff-index output
3970 diff-index line ($m hash)
3972         mode_a => first column of diff-index output, no leading ':',
3973         mode_b => second column of diff-index output,
3974         sha1_b => sha1sum of the final blob,
3975         chg => change type [MCRADT],
3976         file_a => original file name of a file (iff chg is 'C' or 'R')
3977         file_b => new/current file name of a file (any chg)
3981 # retval of read_url_paths{,_all}();
3982 $l_map = {
3983         # repository root url
3984         'https://svn.musicpd.org' => {
3985                 # repository path               # GIT_SVN_ID
3986                 'mpd/trunk'             =>      'trunk',
3987                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3988         },
3991 Notes:
3992         I don't trust the each() function on unless I created %hash myself
3993         because the internal iterator may not have started at base.