Code

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