Code

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