Code

70159204cef7368a9c198ba668498e8712c51d92
[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 $_repository
8                 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
33 }
34 my $can_compress = eval { require Compress::Zlib; 1};
35 push @Git::SVN::Ra::ISA, 'SVN::Ra';
36 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
37 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
38 use Carp qw/croak/;
39 use Digest::MD5;
40 use IO::File qw//;
41 use File::Basename qw/dirname basename/;
42 use File::Path qw/mkpath/;
43 use File::Spec;
44 use File::Find;
45 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
46 use IPC::Open3;
47 use Git;
49 BEGIN {
50         # import functions from Git into our packages, en masse
51         no strict 'refs';
52         foreach (qw/command command_oneline command_noisy command_output_pipe
53                     command_input_pipe command_close_pipe
54                     command_bidi_pipe command_close_bidi_pipe/) {
55                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
56                         Git::SVN::Migration Git::SVN::Log Git::SVN),
57                         __PACKAGE__) {
58                         *{"${package}::$_"} = \&{"Git::$_"};
59                 }
60         }
61 }
63 my ($SVN);
65 $sha1 = qr/[a-f\d]{40}/;
66 $sha1_short = qr/[a-f\d]{4,40}/;
67 my ($_stdin, $_help, $_edit,
68         $_message, $_file, $_branch_dest,
69         $_template, $_shared,
70         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
71         $_merge, $_strategy, $_dry_run, $_local,
72         $_prefix, $_no_checkout, $_url, $_verbose,
73         $_git_format, $_commit_url, $_tag);
74 $Git::SVN::_follow_parent = 1;
75 $_q ||= 0;
76 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
77                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
78                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
79                     'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
80 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
81                 'authors-file|A=s' => \$_authors,
82                 'authors-prog=s' => \$_authors_prog,
83                 'repack:i' => \$Git::SVN::_repack,
84                 'noMetadata' => \$Git::SVN::_no_metadata,
85                 'useSvmProps' => \$Git::SVN::_use_svm_props,
86                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
87                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
88                 'no-checkout' => \$_no_checkout,
89                 'quiet|q+' => \$_q,
90                 'repack-flags|repack-args|repack-opts=s' =>
91                    \$Git::SVN::_repack_flags,
92                 'use-log-author' => \$Git::SVN::_use_log_author,
93                 'add-author-from' => \$Git::SVN::_add_author_from,
94                 'localtime' => \$Git::SVN::_localtime,
95                 %remote_opts );
97 my ($_trunk, @_tags, @_branches, $_stdlayout);
98 my %icv;
99 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
100                   'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
101                   'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
102                   'stdlayout|s' => \$_stdlayout,
103                   'minimize-url|m' => \$Git::SVN::_minimize_url,
104                   'no-metadata' => sub { $icv{noMetadata} = 1 },
105                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
106                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
107                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
108                   %remote_opts );
109 my %cmt_opts = ( 'edit|e' => \$_edit,
110                 'rmdir' => \$SVN::Git::Editor::_rmdir,
111                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
112                 'l=i' => \$SVN::Git::Editor::_rename_limit,
113                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 );
116 my %cmd = (
117         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
118                         { 'revision|r=s' => \$_revision,
119                           'fetch-all|all' => \$_fetch_all,
120                           'parent|p' => \$_fetch_parent,
121                            %fc_opts } ],
122         clone => [ \&cmd_clone, "Initialize and fetch revisions",
123                         { 'revision|r=s' => \$_revision,
124                            %fc_opts, %init_opts } ],
125         init => [ \&cmd_init, "Initialize a repo for tracking" .
126                           " (requires URL argument)",
127                           \%init_opts ],
128         'multi-init' => [ \&cmd_multi_init,
129                           "Deprecated alias for ".
130                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
131                           \%init_opts ],
132         dcommit => [ \&cmd_dcommit,
133                      'Commit several diffs to merge with upstream',
134                         { 'merge|m|M' => \$_merge,
135                           'strategy|s=s' => \$_strategy,
136                           'verbose|v' => \$_verbose,
137                           'dry-run|n' => \$_dry_run,
138                           'fetch-all|all' => \$_fetch_all,
139                           'commit-url=s' => \$_commit_url,
140                           'revision|r=i' => \$_revision,
141                           'no-rebase' => \$_no_rebase,
142                         %cmt_opts, %fc_opts } ],
143         branch => [ \&cmd_branch,
144                     'Create a branch in the SVN repository',
145                     { 'message|m=s' => \$_message,
146                       'destination|d=s' => \$_branch_dest,
147                       'dry-run|n' => \$_dry_run,
148                       'tag|t' => \$_tag } ],
149         tag => [ sub { $_tag = 1; cmd_branch(@_) },
150                  'Create a tag in the SVN repository',
151                  { 'message|m=s' => \$_message,
152                    'destination|d=s' => \$_branch_dest,
153                    'dry-run|n' => \$_dry_run } ],
154         'set-tree' => [ \&cmd_set_tree,
155                         "Set an SVN repository to a git tree-ish",
156                         { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
157         'create-ignore' => [ \&cmd_create_ignore,
158                              'Create a .gitignore per svn:ignore',
159                              { 'revision|r=i' => \$_revision
160                              } ],
161         'propget' => [ \&cmd_propget,
162                        'Print the value of a property on a file or directory',
163                        { 'revision|r=i' => \$_revision } ],
164         'proplist' => [ \&cmd_proplist,
165                        'List all properties of a file or directory',
166                        { 'revision|r=i' => \$_revision } ],
167         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
168                         { 'revision|r=i' => \$_revision
169                         } ],
170         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
171                         { 'revision|r=i' => \$_revision
172                         } ],
173         'multi-fetch' => [ \&cmd_multi_fetch,
174                            "Deprecated alias for $0 fetch --all",
175                            { 'revision|r=s' => \$_revision, %fc_opts } ],
176         'migrate' => [ sub { },
177                        # no-op, we automatically run this anyways,
178                        'Migrate configuration/metadata/layout from
179                         previous versions of git-svn',
180                        { 'minimize' => \$Git::SVN::Migration::_minimize,
181                          %remote_opts } ],
182         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
183                         { 'limit=i' => \$Git::SVN::Log::limit,
184                           'revision|r=s' => \$_revision,
185                           'verbose|v' => \$Git::SVN::Log::verbose,
186                           'incremental' => \$Git::SVN::Log::incremental,
187                           'oneline' => \$Git::SVN::Log::oneline,
188                           'show-commit' => \$Git::SVN::Log::show_commit,
189                           'non-recursive' => \$Git::SVN::Log::non_recursive,
190                           'authors-file|A=s' => \$_authors,
191                           'color' => \$Git::SVN::Log::color,
192                           'pager=s' => \$Git::SVN::Log::pager
193                         } ],
194         'find-rev' => [ \&cmd_find_rev,
195                         "Translate between SVN revision numbers and tree-ish",
196                         {} ],
197         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
198                         { 'merge|m|M' => \$_merge,
199                           'verbose|v' => \$_verbose,
200                           'strategy|s=s' => \$_strategy,
201                           'local|l' => \$_local,
202                           'fetch-all|all' => \$_fetch_all,
203                           'dry-run|n' => \$_dry_run,
204                           %fc_opts } ],
205         'commit-diff' => [ \&cmd_commit_diff,
206                            'Commit a diff between two trees',
207                         { 'message|m=s' => \$_message,
208                           'file|F=s' => \$_file,
209                           'revision|r=s' => \$_revision,
210                         %cmt_opts } ],
211         'info' => [ \&cmd_info,
212                     "Show info about the latest SVN revision
213                      on the current branch",
214                     { 'url' => \$_url, } ],
215         'blame' => [ \&Git::SVN::Log::cmd_blame,
216                     "Show what revision and author last modified each line of a file",
217                     { 'git-format' => \$_git_format } ],
218         'reset' => [ \&cmd_reset,
219                      "Undo fetches back to the specified SVN revision",
220                      { 'revision|r=s' => \$_revision,
221                        'parent|p' => \$_fetch_parent } ],
222         'gc' => [ \&cmd_gc,
223                   "Compress unhandled.log files in .git/svn and remove " .
224                   "index files in .git/svn",
225                 {} ],
226 );
228 my $cmd;
229 for (my $i = 0; $i < @ARGV; $i++) {
230         if (defined $cmd{$ARGV[$i]}) {
231                 $cmd = $ARGV[$i];
232                 splice @ARGV, $i, 1;
233                 last;
234         } elsif ($ARGV[$i] eq 'help') {
235                 $cmd = $ARGV[$i+1];
236                 usage(0);
237         }
238 };
240 # make sure we're always running at the top-level working directory
241 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
242         unless (-d $ENV{GIT_DIR}) {
243                 if ($git_dir_user_set) {
244                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
245                             "but it is not a directory\n";
246                 }
247                 my $git_dir = delete $ENV{GIT_DIR};
248                 my $cdup = undef;
249                 git_cmd_try {
250                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
251                         $git_dir = '.' unless ($cdup);
252                         chomp $cdup if ($cdup);
253                         $cdup = "." unless ($cdup && length $cdup);
254                 } "Already at toplevel, but $git_dir not found\n";
255                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
256                 unless (-d $git_dir) {
257                         die "$git_dir still not found after going to ",
258                             "'$cdup'\n";
259                 }
260                 $ENV{GIT_DIR} = $git_dir;
261         }
262         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
265 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
267 read_repo_config(\%opts);
268 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
269         Getopt::Long::Configure('pass_through');
271 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
272                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
273                     'id|i=s' => \$Git::SVN::default_ref_id,
274                     'svn-remote|remote|R=s' => sub {
275                        $Git::SVN::no_reuse_existing = 1;
276                        $Git::SVN::default_repo_id = $_[1] });
277 exit 1 if (!$rv && $cmd && $cmd ne 'log');
279 usage(0) if $_help;
280 version() if $_version;
281 usage(1) unless defined $cmd;
282 load_authors() if $_authors;
283 if (defined $_authors_prog) {
284         $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
287 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
288         Git::SVN::Migration::migration_check();
290 Git::SVN::init_vars();
291 eval {
292         Git::SVN::verify_remotes_sanity();
293         $cmd{$cmd}->[0]->(@ARGV);
294 };
295 fatal $@ if $@;
296 post_fetch_checkout();
297 exit 0;
299 ####################### primary functions ######################
300 sub usage {
301         my $exit = shift || 0;
302         my $fd = $exit ? \*STDERR : \*STDOUT;
303         print $fd <<"";
304 git-svn - bidirectional operations between a single Subversion tree and git
305 Usage: git svn <command> [options] [arguments]\n
307         print $fd "Available commands:\n" unless $cmd;
309         foreach (sort keys %cmd) {
310                 next if $cmd && $cmd ne $_;
311                 next if /^multi-/; # don't show deprecated commands
312                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
313                 foreach (sort keys %{$cmd{$_}->[2]}) {
314                         # mixed-case options are for .git/config only
315                         next if /[A-Z]/ && /^[a-z]+$/i;
316                         # prints out arguments as they should be passed:
317                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
318                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
319                                                         "--$_" : "-$_" }
320                                                 split /\|/,$_)," $x\n";
321                 }
322         }
323         print $fd <<"";
324 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
325 arbitrary identifier if you're tracking multiple SVN branches/repositories in
326 one git repository and want to keep them separate.  See git-svn(1) for more
327 information.
329         exit $exit;
332 sub version {
333         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
334         exit 0;
337 sub do_git_init_db {
338         unless (-d $ENV{GIT_DIR}) {
339                 my @init_db = ('init');
340                 push @init_db, "--template=$_template" if defined $_template;
341                 if (defined $_shared) {
342                         if ($_shared =~ /[a-z]/) {
343                                 push @init_db, "--shared=$_shared";
344                         } else {
345                                 push @init_db, "--shared";
346                         }
347                 }
348                 command_noisy(@init_db);
349                 $_repository = Git->repository(Repository => ".git");
350         }
351         command_noisy('config', 'core.autocrlf', 'false');
352         my $set;
353         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
354         foreach my $i (keys %icv) {
355                 die "'$set' and '$i' cannot both be set\n" if $set;
356                 next unless defined $icv{$i};
357                 command_noisy('config', "$pfx.$i", $icv{$i});
358                 $set = $i;
359         }
360         my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
361         command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
362                 if defined $$ignore_regex;
365 sub init_subdir {
366         my $repo_path = shift or return;
367         mkpath([$repo_path]) unless -d $repo_path;
368         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
369         $ENV{GIT_DIR} = '.git';
370         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
373 sub cmd_clone {
374         my ($url, $path) = @_;
375         if (!defined $path &&
376             (defined $_trunk || @_branches || @_tags ||
377              defined $_stdlayout) &&
378             $url !~ m#^[a-z\+]+://#) {
379                 $path = $url;
380         }
381         $path = basename($url) if !defined $path || !length $path;
382         cmd_init($url, $path);
383         Git::SVN::fetch_all($Git::SVN::default_repo_id);
384         command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
387 sub cmd_init {
388         if (defined $_stdlayout) {
389                 $_trunk = 'trunk' if (!defined $_trunk);
390                 @_tags = 'tags' if (! @_tags);
391                 @_branches = 'branches' if (! @_branches);
392         }
393         if (defined $_trunk || @_branches || @_tags) {
394                 return cmd_multi_init(@_);
395         }
396         my $url = shift or die "SVN repository location required ",
397                                "as a command-line argument\n";
398         $url = canonicalize_url($url);
399         init_subdir(@_);
400         do_git_init_db();
402         Git::SVN->init($url);
405 sub cmd_fetch {
406         if (grep /^\d+=./, @_) {
407                 die "'<rev>=<commit>' fetch arguments are ",
408                     "no longer supported.\n";
409         }
410         my ($remote) = @_;
411         if (@_ > 1) {
412                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
413         }
414         if ($_fetch_parent) {
415                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
416                 unless ($gs) {
417                         die "Unable to determine upstream SVN information from ",
418                             "working tree history\n";
419                 }
420                 # just fetch, don't checkout.
421                 $_no_checkout = 'true';
422                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
423         } elsif ($_fetch_all) {
424                 cmd_multi_fetch();
425         } else {
426                 $remote ||= $Git::SVN::default_repo_id;
427                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
428         }
431 sub cmd_set_tree {
432         my (@commits) = @_;
433         if ($_stdin || !@commits) {
434                 print "Reading from stdin...\n";
435                 @commits = ();
436                 while (<STDIN>) {
437                         if (/\b($sha1_short)\b/o) {
438                                 unshift @commits, $1;
439                         }
440                 }
441         }
442         my @revs;
443         foreach my $c (@commits) {
444                 my @tmp = command('rev-parse',$c);
445                 if (scalar @tmp == 1) {
446                         push @revs, $tmp[0];
447                 } elsif (scalar @tmp > 1) {
448                         push @revs, reverse(command('rev-list',@tmp));
449                 } else {
450                         fatal "Failed to rev-parse $c";
451                 }
452         }
453         my $gs = Git::SVN->new;
454         my ($r_last, $cmt_last) = $gs->last_rev_commit;
455         $gs->fetch;
456         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
457                 fatal "There are new revisions that were fetched ",
458                       "and need to be merged (or acknowledged) ",
459                       "before committing.\nlast rev: $r_last\n",
460                       " current: $gs->{last_rev}";
461         }
462         $gs->set_tree($_) foreach @revs;
463         print "Done committing ",scalar @revs," revisions to SVN\n";
464         unlink $gs->{index};
467 sub cmd_dcommit {
468         my $head = shift;
469         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
470                 'Cannot dcommit with a dirty index.  Commit your changes first, '
471                 . "or stash them with `git stash'.\n";
472         $head ||= 'HEAD';
474         my $old_head;
475         if ($head ne 'HEAD') {
476                 $old_head = eval {
477                         command_oneline([qw/symbolic-ref -q HEAD/])
478                 };
479                 if ($old_head) {
480                         $old_head =~ s{^refs/heads/}{};
481                 } else {
482                         $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
483                 }
484                 command(['checkout', $head], STDERR => 0);
485         }
487         my @refs;
488         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
489         unless ($gs) {
490                 die "Unable to determine upstream SVN information from ",
491                     "$head history.\nPerhaps the repository is empty.";
492         }
494         if (defined $_commit_url) {
495                 $url = $_commit_url;
496         } else {
497                 $url = eval { command_oneline('config', '--get',
498                               "svn-remote.$gs->{repo_id}.commiturl") };
499                 if (!$url) {
500                         $url = $gs->full_url
501                 }
502         }
504         my $last_rev = $_revision if defined $_revision;
505         if ($url) {
506                 print "Committing to $url ...\n";
507         }
508         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
509         if ($_no_rebase && scalar(@$linear_refs) > 1) {
510                 warn "Attempting to commit more than one change while ",
511                      "--no-rebase is enabled.\n",
512                      "If these changes depend on each other, re-running ",
513                      "without --no-rebase may be required."
514         }
515         my $expect_url = $url;
516         Git::SVN::remove_username($expect_url);
517         while (1) {
518                 my $d = shift @$linear_refs or last;
519                 unless (defined $last_rev) {
520                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
521                         unless (defined $last_rev) {
522                                 fatal "Unable to extract revision information ",
523                                       "from commit $d~1";
524                         }
525                 }
526                 if ($_dry_run) {
527                         print "diff-tree $d~1 $d\n";
528                 } else {
529                         my $cmt_rev;
530                         my %ed_opts = ( r => $last_rev,
531                                         log => get_commit_entry($d)->{log},
532                                         ra => Git::SVN::Ra->new($url),
533                                         config => SVN::Core::config_get_config(
534                                                 $Git::SVN::Ra::config_dir
535                                         ),
536                                         tree_a => "$d~1",
537                                         tree_b => $d,
538                                         editor_cb => sub {
539                                                print "Committed r$_[0]\n";
540                                                $cmt_rev = $_[0];
541                                         },
542                                         svn_path => '');
543                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
544                                 print "No changes\n$d~1 == $d\n";
545                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
546                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
547                                                                $parents->{$d};
548                         }
549                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
550                         $last_rev = $cmt_rev;
551                         next if $_no_rebase;
553                         # we always want to rebase against the current HEAD,
554                         # not any head that was passed to us
555                         my @diff = command('diff-tree', $d,
556                                            $gs->refname, '--');
557                         my @finish;
558                         if (@diff) {
559                                 @finish = rebase_cmd();
560                                 print STDERR "W: $d and ", $gs->refname,
561                                              " differ, using @finish:\n",
562                                              join("\n", @diff), "\n";
563                         } else {
564                                 print "No changes between current HEAD and ",
565                                       $gs->refname,
566                                       "\nResetting to the latest ",
567                                       $gs->refname, "\n";
568                                 @finish = qw/reset --mixed/;
569                         }
570                         command_noisy(@finish, $gs->refname);
571                         if (@diff) {
572                                 @refs = ();
573                                 my ($url_, $rev_, $uuid_, $gs_) =
574                                               working_head_info('HEAD', \@refs);
575                                 my ($linear_refs_, $parents_) =
576                                               linearize_history($gs_, \@refs);
577                                 if (scalar(@$linear_refs) !=
578                                     scalar(@$linear_refs_)) {
579                                         fatal "# of revisions changed ",
580                                           "\nbefore:\n",
581                                           join("\n", @$linear_refs),
582                                           "\n\nafter:\n",
583                                           join("\n", @$linear_refs_), "\n",
584                                           'If you are attempting to commit ',
585                                           "merges, try running:\n\t",
586                                           'git rebase --interactive',
587                                           '--preserve-merges ',
588                                           $gs->refname,
589                                           "\nBefore dcommitting";
590                                 }
591                                 if ($url_ ne $expect_url) {
592                                         fatal "URL mismatch after rebase: ",
593                                               "$url_ != $expect_url";
594                                 }
595                                 if ($uuid_ ne $uuid) {
596                                         fatal "uuid mismatch after rebase: ",
597                                               "$uuid_ != $uuid";
598                                 }
599                                 # remap parents
600                                 my (%p, @l, $i);
601                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
602                                         my $new = $linear_refs_->[$i] or next;
603                                         $p{$new} =
604                                                 $parents->{$linear_refs->[$i]};
605                                         push @l, $new;
606                                 }
607                                 $parents = \%p;
608                                 $linear_refs = \@l;
609                         }
610                 }
611         }
613         if ($old_head) {
614                 my $new_head = command_oneline(qw/rev-parse HEAD/);
615                 my $new_is_symbolic = eval {
616                         command_oneline(qw/symbolic-ref -q HEAD/);
617                 };
618                 if ($new_is_symbolic) {
619                         print "dcommitted the branch ", $head, "\n";
620                 } else {
621                         print "dcommitted on a detached HEAD because you gave ",
622                               "a revision argument.\n",
623                               "The rewritten commit is: ", $new_head, "\n";
624                 }
625                 command(['checkout', $old_head], STDERR => 0);
626         }
628         unlink $gs->{index};
631 sub cmd_branch {
632         my ($branch_name, $head) = @_;
634         unless (defined $branch_name && length $branch_name) {
635                 die(($_tag ? "tag" : "branch") . " name required\n");
636         }
637         $head ||= 'HEAD';
639         my ($src, $rev, undef, $gs) = working_head_info($head);
641         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
642         my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
643         my $glob;
644         if ($#{$allglobs} == 0) {
645                 $glob = $allglobs->[0];
646         } else {
647                 unless(defined $_branch_dest) {
648                         die "Multiple ",
649                             $_tag ? "tag" : "branch",
650                             " paths defined for Subversion repository.\n",
651                             "You must specify where you want to create the ",
652                             $_tag ? "tag" : "branch",
653                             " with the --destination argument.\n";
654                 }
655                 foreach my $g (@{$allglobs}) {
656                         # SVN::Git::Editor could probably be moved to Git.pm..
657                         my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
658                         if ($_branch_dest =~ /$re/) {
659                                 $glob = $g;
660                                 last;
661                         }
662                 }
663                 unless (defined $glob) {
664                         die "Unknown ",
665                             $_tag ? "tag" : "branch",
666                             " destination $_branch_dest\n";
667                 }
668         }
669         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
670         my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
672         my $ctx = SVN::Client->new(
673                 auth    => Git::SVN::Ra::_auth_providers(),
674                 log_msg => sub {
675                         ${ $_[0] } = defined $_message
676                                 ? $_message
677                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
678                                 . $branch_name;
679                 },
680         );
682         eval {
683                 $ctx->ls($dst, 'HEAD', 0);
684         } and die "branch ${branch_name} already exists\n";
686         print "Copying ${src} at r${rev} to ${dst}...\n";
687         $ctx->copy($src, $rev, $dst)
688                 unless $_dry_run;
690         $gs->fetch_all;
693 sub cmd_find_rev {
694         my $revision_or_hash = shift or die "SVN or git revision required ",
695                                             "as a command-line argument\n";
696         my $result;
697         if ($revision_or_hash =~ /^r\d+$/) {
698                 my $head = shift;
699                 $head ||= 'HEAD';
700                 my @refs;
701                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
702                 unless ($gs) {
703                         die "Unable to determine upstream SVN information from ",
704                             "$head history\n";
705                 }
706                 my $desired_revision = substr($revision_or_hash, 1);
707                 $result = $gs->rev_map_get($desired_revision, $uuid);
708         } else {
709                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
710                 $result = $rev;
711         }
712         print "$result\n" if $result;
715 sub cmd_rebase {
716         command_noisy(qw/update-index --refresh/);
717         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
718         unless ($gs) {
719                 die "Unable to determine upstream SVN information from ",
720                     "working tree history\n";
721         }
722         if ($_dry_run) {
723                 print "Remote Branch: " . $gs->refname . "\n";
724                 print "SVN URL: " . $url . "\n";
725                 return;
726         }
727         if (command(qw/diff-index HEAD --/)) {
728                 print STDERR "Cannot rebase with uncommited changes:\n";
729                 command_noisy('status');
730                 exit 1;
731         }
732         unless ($_local) {
733                 # rebase will checkout for us, so no need to do it explicitly
734                 $_no_checkout = 'true';
735                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
736         }
737         command_noisy(rebase_cmd(), $gs->refname);
740 sub cmd_show_ignore {
741         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
742         $gs ||= Git::SVN->new;
743         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
744         $gs->prop_walk($gs->{path}, $r, sub {
745                 my ($gs, $path, $props) = @_;
746                 print STDOUT "\n# $path\n";
747                 my $s = $props->{'svn:ignore'} or return;
748                 $s =~ s/[\r\n]+/\n/g;
749                 chomp $s;
750                 $s =~ s#^#$path#gm;
751                 print STDOUT "$s\n";
752         });
755 sub cmd_show_externals {
756         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
757         $gs ||= Git::SVN->new;
758         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
759         $gs->prop_walk($gs->{path}, $r, sub {
760                 my ($gs, $path, $props) = @_;
761                 print STDOUT "\n# $path\n";
762                 my $s = $props->{'svn:externals'} or return;
763                 $s =~ s/[\r\n]+/\n/g;
764                 chomp $s;
765                 $s =~ s#^#$path#gm;
766                 print STDOUT "$s\n";
767         });
770 sub cmd_create_ignore {
771         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
772         $gs ||= Git::SVN->new;
773         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
774         $gs->prop_walk($gs->{path}, $r, sub {
775                 my ($gs, $path, $props) = @_;
776                 # $path is of the form /path/to/dir/
777                 $path = '.' . $path;
778                 # SVN can have attributes on empty directories,
779                 # which git won't track
780                 mkpath([$path]) unless -d $path;
781                 my $ignore = $path . '.gitignore';
782                 my $s = $props->{'svn:ignore'} or return;
783                 open(GITIGNORE, '>', $ignore)
784                   or fatal("Failed to open `$ignore' for writing: $!");
785                 $s =~ s/[\r\n]+/\n/g;
786                 chomp $s;
787                 # Prefix all patterns so that the ignore doesn't apply
788                 # to sub-directories.
789                 $s =~ s#^#/#gm;
790                 print GITIGNORE "$s\n";
791                 close(GITIGNORE)
792                   or fatal("Failed to close `$ignore': $!");
793                 command_noisy('add', '-f', $ignore);
794         });
797 sub canonicalize_path {
798         my ($path) = @_;
799         my $dot_slash_added = 0;
800         if (substr($path, 0, 1) ne "/") {
801                 $path = "./" . $path;
802                 $dot_slash_added = 1;
803         }
804         # File::Spec->canonpath doesn't collapse x/../y into y (for a
805         # good reason), so let's do this manually.
806         $path =~ s#/+#/#g;
807         $path =~ s#/\.(?:/|$)#/#g;
808         $path =~ s#/[^/]+/\.\.##g;
809         $path =~ s#/$##g;
810         $path =~ s#^\./## if $dot_slash_added;
811         $path =~ s#^/##;
812         $path =~ s#^\.$##;
813         return $path;
816 sub canonicalize_url {
817         my ($url) = @_;
818         $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
819         return $url;
822 # get_svnprops(PATH)
823 # ------------------
824 # Helper for cmd_propget and cmd_proplist below.
825 sub get_svnprops {
826         my $path = shift;
827         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
828         $gs ||= Git::SVN->new;
830         # prefix THE PATH by the sub-directory from which the user
831         # invoked us.
832         $path = $cmd_dir_prefix . $path;
833         fatal("No such file or directory: $path") unless -e $path;
834         my $is_dir = -d $path ? 1 : 0;
835         $path = $gs->{path} . '/' . $path;
837         # canonicalize the path (otherwise libsvn will abort or fail to
838         # find the file)
839         $path = canonicalize_path($path);
841         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
842         my $props;
843         if ($is_dir) {
844                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
845         }
846         else {
847                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
848         }
849         return $props;
852 # cmd_propget (PROP, PATH)
853 # ------------------------
854 # Print the SVN property PROP for PATH.
855 sub cmd_propget {
856         my ($prop, $path) = @_;
857         $path = '.' if not defined $path;
858         usage(1) if not defined $prop;
859         my $props = get_svnprops($path);
860         if (not defined $props->{$prop}) {
861                 fatal("`$path' does not have a `$prop' SVN property.");
862         }
863         print $props->{$prop} . "\n";
866 # cmd_proplist (PATH)
867 # -------------------
868 # Print the list of SVN properties for PATH.
869 sub cmd_proplist {
870         my $path = shift;
871         $path = '.' if not defined $path;
872         my $props = get_svnprops($path);
873         print "Properties on '$path':\n";
874         foreach (sort keys %{$props}) {
875                 print "  $_\n";
876         }
879 sub cmd_multi_init {
880         my $url = shift;
881         unless (defined $_trunk || @_branches || @_tags) {
882                 usage(1);
883         }
885         $_prefix = '' unless defined $_prefix;
886         if (defined $url) {
887                 $url = canonicalize_url($url);
888                 init_subdir(@_);
889         }
890         do_git_init_db();
891         if (defined $_trunk) {
892                 my $trunk_ref = $_prefix . 'trunk';
893                 # try both old-style and new-style lookups:
894                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
895                 unless ($gs_trunk) {
896                         my ($trunk_url, $trunk_path) =
897                                               complete_svn_url($url, $_trunk);
898                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
899                                                    undef, $trunk_ref);
900                 }
901         }
902         return unless @_branches || @_tags;
903         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
904         foreach my $path (@_branches) {
905                 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
906         }
907         foreach my $path (@_tags) {
908                 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
909         }
912 sub cmd_multi_fetch {
913         my $remotes = Git::SVN::read_all_remotes();
914         foreach my $repo_id (sort keys %$remotes) {
915                 if ($remotes->{$repo_id}->{url}) {
916                         Git::SVN::fetch_all($repo_id, $remotes);
917                 }
918         }
921 # this command is special because it requires no metadata
922 sub cmd_commit_diff {
923         my ($ta, $tb, $url) = @_;
924         my $usage = "Usage: $0 commit-diff -r<revision> ".
925                     "<tree-ish> <tree-ish> [<URL>]";
926         fatal($usage) if (!defined $ta || !defined $tb);
927         my $svn_path = '';
928         if (!defined $url) {
929                 my $gs = eval { Git::SVN->new };
930                 if (!$gs) {
931                         fatal("Needed URL or usable git-svn --id in ",
932                               "the command-line\n", $usage);
933                 }
934                 $url = $gs->{url};
935                 $svn_path = $gs->{path};
936         }
937         unless (defined $_revision) {
938                 fatal("-r|--revision is a required argument\n", $usage);
939         }
940         if (defined $_message && defined $_file) {
941                 fatal("Both --message/-m and --file/-F specified ",
942                       "for the commit message.\n",
943                       "I have no idea what you mean");
944         }
945         if (defined $_file) {
946                 $_message = file_to_s($_file);
947         } else {
948                 $_message ||= get_commit_entry($tb)->{log};
949         }
950         my $ra ||= Git::SVN::Ra->new($url);
951         my $r = $_revision;
952         if ($r eq 'HEAD') {
953                 $r = $ra->get_latest_revnum;
954         } elsif ($r !~ /^\d+$/) {
955                 die "revision argument: $r not understood by git-svn\n";
956         }
957         my %ed_opts = ( r => $r,
958                         log => $_message,
959                         ra => $ra,
960                         tree_a => $ta,
961                         tree_b => $tb,
962                         editor_cb => sub { print "Committed r$_[0]\n" },
963                         svn_path => $svn_path );
964         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
965                 print "No changes\n$ta == $tb\n";
966         }
969 sub escape_uri_only {
970         my ($uri) = @_;
971         my @tmp;
972         foreach (split m{/}, $uri) {
973                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
974                 push @tmp, $_;
975         }
976         join('/', @tmp);
979 sub escape_url {
980         my ($url) = @_;
981         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
982                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
983                 $url = "$scheme://$domain$uri";
984         }
985         $url;
988 sub cmd_info {
989         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
990         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
991         if (exists $_[1]) {
992                 die "Too many arguments specified\n";
993         }
995         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
997         if (!$file_type && !$diff_status) {
998                 print STDERR "svn: '$path' is not under version control\n";
999                 exit 1;
1000         }
1002         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1003         unless ($gs) {
1004                 die "Unable to determine upstream SVN information from ",
1005                     "working tree history\n";
1006         }
1008         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1009         $path = "." if $path eq "";
1011         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1013         if ($_url) {
1014                 print escape_url($full_url), "\n";
1015                 return;
1016         }
1018         my $result = "Path: $path\n";
1019         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1020         $result .= "URL: " . escape_url($full_url) . "\n";
1022         eval {
1023                 my $repos_root = $gs->repos_root;
1024                 Git::SVN::remove_username($repos_root);
1025                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1026         };
1027         if ($@) {
1028                 $result .= "Repository Root: (offline)\n";
1029         }
1030         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1031                 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1032         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1034         $result .= "Node Kind: " .
1035                    ($file_type eq "dir" ? "directory" : "file") . "\n";
1037         my $schedule = $diff_status eq "A"
1038                        ? "add"
1039                        : ($diff_status eq "D" ? "delete" : "normal");
1040         $result .= "Schedule: $schedule\n";
1042         if ($diff_status eq "A") {
1043                 print $result, "\n";
1044                 return;
1045         }
1047         my ($lc_author, $lc_rev, $lc_date_utc);
1048         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1049         my $log = command_output_pipe(@args);
1050         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1051         while (<$log>) {
1052                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1053                         $lc_author = $1;
1054                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1055                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1056                         (undef, $lc_rev, undef) = ::extract_metadata($1);
1057                 }
1058         }
1059         close $log;
1061         Git::SVN::Log::set_local_timezone();
1063         $result .= "Last Changed Author: $lc_author\n";
1064         $result .= "Last Changed Rev: $lc_rev\n";
1065         $result .= "Last Changed Date: " .
1066                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1068         if ($file_type ne "dir") {
1069                 my $text_last_updated_date =
1070                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1071                 $result .=
1072                     "Text Last Updated: " .
1073                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
1074                     "\n";
1075                 my $checksum;
1076                 if ($diff_status eq "D") {
1077                         my ($fh, $ctx) =
1078                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
1079                         if ($file_type eq "link") {
1080                                 my $file_name = <$fh>;
1081                                 $checksum = md5sum("link $file_name");
1082                         } else {
1083                                 $checksum = md5sum($fh);
1084                         }
1085                         command_close_pipe($fh, $ctx);
1086                 } elsif ($file_type eq "link") {
1087                         my $file_name =
1088                             command(qw(cat-file blob), "HEAD:$path");
1089                         $checksum =
1090                             md5sum("link " . $file_name);
1091                 } else {
1092                         open FILE, "<", $path or die $!;
1093                         $checksum = md5sum(\*FILE);
1094                         close FILE or die $!;
1095                 }
1096                 $result .= "Checksum: " . $checksum . "\n";
1097         }
1099         print $result, "\n";
1102 sub cmd_reset {
1103         my $target = shift || $_revision or die "SVN revision required\n";
1104         $target = $1 if $target =~ /^r(\d+)$/;
1105         $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1106         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1107         unless ($gs) {
1108                 die "Unable to determine upstream SVN information from ".
1109                     "history\n";
1110         }
1111         my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1112         $gs->rev_map_set($r, $c, 'reset', $uuid);
1113         print "r$r = $c ($gs->{ref_id})\n";
1116 sub cmd_gc {
1117         if (!$can_compress) {
1118                 warn "Compress::Zlib could not be found; unhandled.log " .
1119                      "files will not be compressed.\n";
1120         }
1121         find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1124 ########################### utility functions #########################
1126 sub rebase_cmd {
1127         my @cmd = qw/rebase/;
1128         push @cmd, '-v' if $_verbose;
1129         push @cmd, qw/--merge/ if $_merge;
1130         push @cmd, "--strategy=$_strategy" if $_strategy;
1131         @cmd;
1134 sub post_fetch_checkout {
1135         return if $_no_checkout;
1136         my $gs = $Git::SVN::_head or return;
1137         return if verify_ref('refs/heads/master^0');
1139         my $valid_head = verify_ref('HEAD^0');
1140         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1141         return if ($valid_head || !verify_ref('HEAD^0'));
1143         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1144         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1145         return if -f $index;
1147         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1148         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1149         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1150         print STDERR "Checked out HEAD:\n  ",
1151                      $gs->full_url, " r", $gs->last_rev, "\n";
1154 sub complete_svn_url {
1155         my ($url, $path) = @_;
1156         $path =~ s#/+$##;
1157         if ($path !~ m#^[a-z\+]+://#) {
1158                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1159                         fatal("E: '$path' is not a complete URL ",
1160                               "and a separate URL is not specified");
1161                 }
1162                 return ($url, $path);
1163         }
1164         return ($path, '');
1167 sub complete_url_ls_init {
1168         my ($ra, $repo_path, $switch, $pfx) = @_;
1169         unless ($repo_path) {
1170                 print STDERR "W: $switch not specified\n";
1171                 return;
1172         }
1173         $repo_path =~ s#/+$##;
1174         if ($repo_path =~ m#^[a-z\+]+://#) {
1175                 $ra = Git::SVN::Ra->new($repo_path);
1176                 $repo_path = '';
1177         } else {
1178                 $repo_path =~ s#^/+##;
1179                 unless ($ra) {
1180                         fatal("E: '$repo_path' is not a complete URL ",
1181                               "and a separate URL is not specified");
1182                 }
1183         }
1184         my $url = $ra->{url};
1185         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1186         my $k = "svn-remote.$gs->{repo_id}.url";
1187         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1188         if ($orig_url && ($orig_url ne $gs->{url})) {
1189                 die "$k already set: $orig_url\n",
1190                     "wanted to set to: $gs->{url}\n";
1191         }
1192         command_oneline('config', $k, $gs->{url}) unless $orig_url;
1193         my $remote_path = "$gs->{path}/$repo_path";
1194         $remote_path =~ s#/+#/#g;
1195         $remote_path =~ s#^/##g;
1196         $remote_path .= "/*" if $remote_path !~ /\*/;
1197         my ($n) = ($switch =~ /^--(\w+)/);
1198         if (length $pfx && $pfx !~ m#/$#) {
1199                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1200         }
1201         command_noisy('config',
1202                       '--add',
1203                       "svn-remote.$gs->{repo_id}.$n",
1204                       "$remote_path:refs/remotes/$pfx*" .
1205                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1208 sub verify_ref {
1209         my ($ref) = @_;
1210         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1211                                { STDERR => 0 }); };
1214 sub get_tree_from_treeish {
1215         my ($treeish) = @_;
1216         # $treeish can be a symbolic ref, too:
1217         my $type = command_oneline(qw/cat-file -t/, $treeish);
1218         my $expected;
1219         while ($type eq 'tag') {
1220                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1221         }
1222         if ($type eq 'commit') {
1223                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1224                                                     $treeish))[0];
1225                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1226                 die "Unable to get tree from $treeish\n" unless $expected;
1227         } elsif ($type eq 'tree') {
1228                 $expected = $treeish;
1229         } else {
1230                 die "$treeish is a $type, expected tree, tag or commit\n";
1231         }
1232         return $expected;
1235 sub get_commit_entry {
1236         my ($treeish) = shift;
1237         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1238         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1239         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1240         open my $log_fh, '>', $commit_editmsg or croak $!;
1242         my $type = command_oneline(qw/cat-file -t/, $treeish);
1243         if ($type eq 'commit' || $type eq 'tag') {
1244                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1245                                                          $type, $treeish);
1246                 my $in_msg = 0;
1247                 my $author;
1248                 my $saw_from = 0;
1249                 my $msgbuf = "";
1250                 while (<$msg_fh>) {
1251                         if (!$in_msg) {
1252                                 $in_msg = 1 if (/^\s*$/);
1253                                 $author = $1 if (/^author (.*>)/);
1254                         } elsif (/^git-svn-id: /) {
1255                                 # skip this for now, we regenerate the
1256                                 # correct one on re-fetch anyways
1257                                 # TODO: set *:merge properties or like...
1258                         } else {
1259                                 if (/^From:/ || /^Signed-off-by:/) {
1260                                         $saw_from = 1;
1261                                 }
1262                                 $msgbuf .= $_;
1263                         }
1264                 }
1265                 $msgbuf =~ s/\s+$//s;
1266                 if ($Git::SVN::_add_author_from && defined($author)
1267                     && !$saw_from) {
1268                         $msgbuf .= "\n\nFrom: $author";
1269                 }
1270                 print $log_fh $msgbuf or croak $!;
1271                 command_close_pipe($msg_fh, $ctx);
1272         }
1273         close $log_fh or croak $!;
1275         if ($_edit || ($type eq 'tree')) {
1276                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1277                 # TODO: strip out spaces, comments, like git-commit.sh
1278                 system($editor, $commit_editmsg);
1279         }
1280         rename $commit_editmsg, $commit_msg or croak $!;
1281         {
1282                 require Encode;
1283                 # SVN requires messages to be UTF-8 when entering the repo
1284                 local $/;
1285                 open $log_fh, '<', $commit_msg or croak $!;
1286                 binmode $log_fh;
1287                 chomp($log_entry{log} = <$log_fh>);
1289                 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1290                 my $msg = $log_entry{log};
1292                 eval { $msg = Encode::decode($enc, $msg, 1) };
1293                 if ($@) {
1294                         die "Could not decode as $enc:\n", $msg,
1295                             "\nPerhaps you need to set i18n.commitencoding\n";
1296                 }
1298                 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1299                 die "Could not encode as UTF-8:\n$msg\n" if $@;
1301                 $log_entry{log} = $msg;
1303                 close $log_fh or croak $!;
1304         }
1305         unlink $commit_msg;
1306         \%log_entry;
1309 sub s_to_file {
1310         my ($str, $file, $mode) = @_;
1311         open my $fd,'>',$file or croak $!;
1312         print $fd $str,"\n" or croak $!;
1313         close $fd or croak $!;
1314         chmod ($mode &~ umask, $file) if (defined $mode);
1317 sub file_to_s {
1318         my $file = shift;
1319         open my $fd,'<',$file or croak "$!: file: $file\n";
1320         local $/;
1321         my $ret = <$fd>;
1322         close $fd or croak $!;
1323         $ret =~ s/\s*$//s;
1324         return $ret;
1327 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1328 sub load_authors {
1329         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1330         my $log = $cmd eq 'log';
1331         while (<$authors>) {
1332                 chomp;
1333                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1334                 my ($user, $name, $email) = ($1, $2, $3);
1335                 if ($log) {
1336                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1337                 } else {
1338                         $users{$user} = [$name, $email];
1339                 }
1340         }
1341         close $authors or croak $!;
1344 # convert GetOpt::Long specs for use by git-config
1345 sub read_repo_config {
1346         return unless -d $ENV{GIT_DIR};
1347         my $opts = shift;
1348         my @config_only;
1349         foreach my $o (keys %$opts) {
1350                 # if we have mixedCase and a long option-only, then
1351                 # it's a config-only variable that we don't need for
1352                 # the command-line.
1353                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1354                 my $v = $opts->{$o};
1355                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1356                 $key =~ s/-//g;
1357                 my $arg = 'git config';
1358                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1359                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1360                 if (ref $v eq 'ARRAY') {
1361                         chomp(my @tmp = `$arg --get-all svn.$key`);
1362                         @$v = @tmp if @tmp;
1363                 } else {
1364                         chomp(my $tmp = `$arg --get svn.$key`);
1365                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1366                                 $$v = $tmp;
1367                         }
1368                 }
1369         }
1370         delete @$opts{@config_only} if @config_only;
1373 sub extract_metadata {
1374         my $id = shift or return (undef, undef, undef);
1375         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1376                                                         \s([a-f\d\-]+)$/ix);
1377         if (!defined $rev || !$uuid || !$url) {
1378                 # some of the original repositories I made had
1379                 # identifiers like this:
1380                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1381         }
1382         return ($url, $rev, $uuid);
1385 sub cmt_metadata {
1386         return extract_metadata((grep(/^git-svn-id: /,
1387                 command(qw/cat-file commit/, shift)))[-1]);
1390 sub cmt_sha2rev_batch {
1391         my %s2r;
1392         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1393         my $list = shift;
1395         foreach my $sha (@{$list}) {
1396                 my $first = 1;
1397                 my $size = 0;
1398                 print $out $sha, "\n";
1400                 while (my $line = <$in>) {
1401                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1402                                 last;
1403                         } elsif ($first &&
1404                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1405                                 $first = 0;
1406                                 $size = $1;
1407                                 next;
1408                         } elsif ($line =~ /^(git-svn-id: )/) {
1409                                 my (undef, $rev, undef) =
1410                                                       extract_metadata($line);
1411                                 $s2r{$sha} = $rev;
1412                         }
1414                         $size -= length($line);
1415                         last if ($size == 0);
1416                 }
1417         }
1419         command_close_bidi_pipe($pid, $in, $out, $ctx);
1421         return \%s2r;
1424 sub working_head_info {
1425         my ($head, $refs) = @_;
1426         my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1427         my ($fh, $ctx) = command_output_pipe(@args, $head);
1428         my $hash;
1429         my %max;
1430         while (<$fh>) {
1431                 if ( m{^commit ($::sha1)$} ) {
1432                         unshift @$refs, $hash if $hash and $refs;
1433                         $hash = $1;
1434                         next;
1435                 }
1436                 next unless s{^\s*(git-svn-id:)}{$1};
1437                 my ($url, $rev, $uuid) = extract_metadata($_);
1438                 if (defined $url && defined $rev) {
1439                         next if $max{$url} and $max{$url} < $rev;
1440                         if (my $gs = Git::SVN->find_by_url($url)) {
1441                                 my $c = $gs->rev_map_get($rev, $uuid);
1442                                 if ($c && $c eq $hash) {
1443                                         close $fh; # break the pipe
1444                                         return ($url, $rev, $uuid, $gs);
1445                                 } else {
1446                                         $max{$url} ||= $gs->rev_map_max;
1447                                 }
1448                         }
1449                 }
1450         }
1451         command_close_pipe($fh, $ctx);
1452         (undef, undef, undef, undef);
1455 sub read_commit_parents {
1456         my ($parents, $c) = @_;
1457         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1458         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1459         @{$parents->{$c}} = split(/ /, $p);
1462 sub linearize_history {
1463         my ($gs, $refs) = @_;
1464         my %parents;
1465         foreach my $c (@$refs) {
1466                 read_commit_parents(\%parents, $c);
1467         }
1469         my @linear_refs;
1470         my %skip = ();
1471         my $last_svn_commit = $gs->last_commit;
1472         foreach my $c (reverse @$refs) {
1473                 next if $c eq $last_svn_commit;
1474                 last if $skip{$c};
1476                 unshift @linear_refs, $c;
1477                 $skip{$c} = 1;
1479                 # we only want the first parent to diff against for linear
1480                 # history, we save the rest to inject when we finalize the
1481                 # svn commit
1482                 my $fp_a = verify_ref("$c~1");
1483                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1484                 if (!$fp_a || !$fp_b) {
1485                         die "Commit $c\n",
1486                             "has no parent commit, and therefore ",
1487                             "nothing to diff against.\n",
1488                             "You should be working from a repository ",
1489                             "originally created by git-svn\n";
1490                 }
1491                 if ($fp_a ne $fp_b) {
1492                         die "$c~1 = $fp_a, however parsing commit $c ",
1493                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1494                 }
1496                 foreach my $p (@{$parents{$c}}) {
1497                         $skip{$p} = 1;
1498                 }
1499         }
1500         (\@linear_refs, \%parents);
1503 sub find_file_type_and_diff_status {
1504         my ($path) = @_;
1505         return ('dir', '') if $path eq '';
1507         my $diff_output =
1508             command_oneline(qw(diff --cached --name-status --), $path) || "";
1509         my $diff_status = (split(' ', $diff_output))[0] || "";
1511         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1513         return (undef, undef) if !$diff_status && !$ls_tree;
1515         if ($diff_status eq "A") {
1516                 return ("link", $diff_status) if -l $path;
1517                 return ("dir", $diff_status) if -d $path;
1518                 return ("file", $diff_status);
1519         }
1521         my $mode = (split(' ', $ls_tree))[0] || "";
1523         return ("link", $diff_status) if $mode eq "120000";
1524         return ("dir", $diff_status) if $mode eq "040000";
1525         return ("file", $diff_status);
1528 sub md5sum {
1529         my $arg = shift;
1530         my $ref = ref $arg;
1531         my $md5 = Digest::MD5->new();
1532         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1533                 $md5->addfile($arg) or croak $!;
1534         } elsif ($ref eq 'SCALAR') {
1535                 $md5->add($$arg) or croak $!;
1536         } elsif (!$ref) {
1537                 $md5->add($arg) or croak $!;
1538         } else {
1539                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1540         }
1541         return $md5->hexdigest();
1544 sub gc_directory {
1545         if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1546                 my $out_filename = $_ . ".gz";
1547                 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1548                 binmode $in_fh;
1549                 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1550                                 die "Unable to open $out_filename: $!\n";
1552                 my $res;
1553                 while ($res = sysread($in_fh, my $str, 1024)) {
1554                         $gz->gzwrite($str) or
1555                                 die "Unable to write: ".$gz->gzerror()."!\n";
1556                 }
1557                 unlink $_ or die "unlink $File::Find::name: $!\n";
1558         } elsif (-f $_ && basename($_) eq "index") {
1559                 unlink $_ or die "unlink $_: $!\n";
1560         }
1563 package Git::SVN;
1564 use strict;
1565 use warnings;
1566 use Fcntl qw/:DEFAULT :seek/;
1567 use constant rev_map_fmt => 'NH40';
1568 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1569             $_repack $_repack_flags $_use_svm_props $_head
1570             $_use_svnsync_props $no_reuse_existing $_minimize_url
1571             $_use_log_author $_add_author_from $_localtime/;
1572 use Carp qw/croak/;
1573 use File::Path qw/mkpath/;
1574 use File::Copy qw/copy/;
1575 use IPC::Open3;
1577 my ($_gc_nr, $_gc_period);
1579 # properties that we do not log:
1580 my %SKIP_PROP;
1581 BEGIN {
1582         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1583                                         svn:special svn:executable
1584                                         svn:entry:committed-rev
1585                                         svn:entry:last-author
1586                                         svn:entry:uuid
1587                                         svn:entry:committed-date/;
1589         # some options are read globally, but can be overridden locally
1590         # per [svn-remote "..."] section.  Command-line options will *NOT*
1591         # override options set in an [svn-remote "..."] section
1592         no strict 'refs';
1593         for my $option (qw/follow_parent no_metadata use_svm_props
1594                            use_svnsync_props/) {
1595                 my $key = $option;
1596                 $key =~ tr/_//d;
1597                 my $prop = "-$option";
1598                 *$option = sub {
1599                         my ($self) = @_;
1600                         return $self->{$prop} if exists $self->{$prop};
1601                         my $k = "svn-remote.$self->{repo_id}.$key";
1602                         eval { command_oneline(qw/config --get/, $k) };
1603                         if ($@) {
1604                                 $self->{$prop} = ${"Git::SVN::_$option"};
1605                         } else {
1606                                 my $v = command_oneline(qw/config --bool/,$k);
1607                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1608                         }
1609                         return $self->{$prop};
1610                 }
1611         }
1615 my (%LOCKFILES, %INDEX_FILES);
1616 END {
1617         unlink keys %LOCKFILES if %LOCKFILES;
1618         unlink keys %INDEX_FILES if %INDEX_FILES;
1621 sub resolve_local_globs {
1622         my ($url, $fetch, $glob_spec) = @_;
1623         return unless defined $glob_spec;
1624         my $ref = $glob_spec->{ref};
1625         my $path = $glob_spec->{path};
1626         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1627                 next unless m#^refs/remotes/$ref->{regex}$#;
1628                 my $p = $1;
1629                 my $pathname = desanitize_refname($path->full_path($p));
1630                 my $refname = desanitize_refname($ref->full_path($p));
1631                 if (my $existing = $fetch->{$pathname}) {
1632                         if ($existing ne $refname) {
1633                                 die "Refspec conflict:\n",
1634                                     "existing: refs/remotes/$existing\n",
1635                                     " globbed: refs/remotes/$refname\n";
1636                         }
1637                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1638                         $u =~ s!^\Q$url\E(/|$)!! or die
1639                           "refs/remotes/$refname: '$url' not found in '$u'\n";
1640                         if ($pathname ne $u) {
1641                                 warn "W: Refspec glob conflict ",
1642                                      "(ref: refs/remotes/$refname):\n",
1643                                      "expected path: $pathname\n",
1644                                      "    real path: $u\n",
1645                                      "Continuing ahead with $u\n";
1646                                 next;
1647                         }
1648                 } else {
1649                         $fetch->{$pathname} = $refname;
1650                 }
1651         }
1654 sub parse_revision_argument {
1655         my ($base, $head) = @_;
1656         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1657                 return ($base, $head);
1658         }
1659         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1660         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1661         return ($head, $head) if ($::_revision eq 'HEAD');
1662         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1663         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1664         die "revision argument: $::_revision not understood by git-svn\n";
1667 sub fetch_all {
1668         my ($repo_id, $remotes) = @_;
1669         if (ref $repo_id) {
1670                 my $gs = $repo_id;
1671                 $repo_id = undef;
1672                 $repo_id = $gs->{repo_id};
1673         }
1674         $remotes ||= read_all_remotes();
1675         my $remote = $remotes->{$repo_id} or
1676                      die "[svn-remote \"$repo_id\"] unknown\n";
1677         my $fetch = $remote->{fetch};
1678         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1679         my (@gs, @globs);
1680         my $ra = Git::SVN::Ra->new($url);
1681         my $uuid = $ra->get_uuid;
1682         my $head = $ra->get_latest_revnum;
1683         $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1684         my $base = defined $fetch ? $head : 0;
1686         # read the max revs for wildcard expansion (branches/*, tags/*)
1687         foreach my $t (qw/branches tags/) {
1688                 defined $remote->{$t} or next;
1689                 push @globs, @{$remote->{$t}};
1691                 my $max_rev = eval { tmp_config(qw/--int --get/,
1692                                          "svn-remote.$repo_id.${t}-maxRev") };
1693                 if (defined $max_rev && ($max_rev < $base)) {
1694                         $base = $max_rev;
1695                 } elsif (!defined $max_rev) {
1696                         $base = 0;
1697                 }
1698         }
1700         if ($fetch) {
1701                 foreach my $p (sort keys %$fetch) {
1702                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1703                         my $lr = $gs->rev_map_max;
1704                         if (defined $lr) {
1705                                 $base = $lr if ($lr < $base);
1706                         }
1707                         push @gs, $gs;
1708                 }
1709         }
1711         ($base, $head) = parse_revision_argument($base, $head);
1712         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1715 sub read_all_remotes {
1716         my $r = {};
1717         my $use_svm_props = eval { command_oneline(qw/config --bool
1718             svn.useSvmProps/) };
1719         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1720         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1721                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1722                         my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1723                         die("svn-remote.$remote: remote ref '$_remote_ref' "
1724                             . "must start with 'refs/remotes/'\n")
1725                                 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1726                         my $remote_ref = $1;
1727                         $local_ref =~ s{^/}{};
1728                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1729                         $r->{$remote}->{svm} = {} if $use_svm_props;
1730                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1731                         $r->{$1}->{svm} = {};
1732                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1733                         $r->{$1}->{url} = $2;
1734                 } elsif (m!^(.+)\.(branches|tags)=
1735                            (.*):refs/remotes/(.+)\s*$/!x) {
1736                         my ($p, $g) = ($3, $4);
1737                         my $rs = {
1738                             t => $2,
1739                             remote => $1,
1740                             path => Git::SVN::GlobSpec->new($p),
1741                             ref => Git::SVN::GlobSpec->new($g) };
1742                         if (length($rs->{ref}->{right}) != 0) {
1743                                 die "The '*' glob character must be the last ",
1744                                     "character of '$g'\n";
1745                         }
1746                         push @{ $r->{$1}->{$2} }, $rs;
1747                 }
1748         }
1750         map {
1751                 if (defined $r->{$_}->{svm}) {
1752                         my $svm;
1753                         eval {
1754                                 my $section = "svn-remote.$_";
1755                                 $svm = {
1756                                         source => tmp_config('--get',
1757                                             "$section.svm-source"),
1758                                         replace => tmp_config('--get',
1759                                             "$section.svm-replace"),
1760                                 }
1761                         };
1762                         $r->{$_}->{svm} = $svm;
1763                 }
1764         } keys %$r;
1766         $r;
1769 sub init_vars {
1770         $_gc_nr = $_gc_period = 1000;
1771         if (defined $_repack || defined $_repack_flags) {
1772                warn "Repack options are obsolete; they have no effect.\n";
1773         }
1776 sub verify_remotes_sanity {
1777         return unless -d $ENV{GIT_DIR};
1778         my %seen;
1779         foreach (command(qw/config -l/)) {
1780                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1781                         if ($seen{$1}) {
1782                                 die "Remote ref refs/remote/$1 is tracked by",
1783                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1784                                     "Please resolve this ambiguity in ",
1785                                     "your git configuration file before ",
1786                                     "continuing\n";
1787                         }
1788                         $seen{$1} = $_;
1789                 }
1790         }
1793 sub find_existing_remote {
1794         my ($url, $remotes) = @_;
1795         return undef if $no_reuse_existing;
1796         my $existing;
1797         foreach my $repo_id (keys %$remotes) {
1798                 my $u = $remotes->{$repo_id}->{url} or next;
1799                 next if $u ne $url;
1800                 $existing = $repo_id;
1801                 last;
1802         }
1803         $existing;
1806 sub init_remote_config {
1807         my ($self, $url, $no_write) = @_;
1808         $url =~ s!/+$!!; # strip trailing slash
1809         my $r = read_all_remotes();
1810         my $existing = find_existing_remote($url, $r);
1811         if ($existing) {
1812                 unless ($no_write) {
1813                         print STDERR "Using existing ",
1814                                      "[svn-remote \"$existing\"]\n";
1815                 }
1816                 $self->{repo_id} = $existing;
1817         } elsif ($_minimize_url) {
1818                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1819                 $existing = find_existing_remote($min_url, $r);
1820                 if ($existing) {
1821                         unless ($no_write) {
1822                                 print STDERR "Using existing ",
1823                                              "[svn-remote \"$existing\"]\n";
1824                         }
1825                         $self->{repo_id} = $existing;
1826                 }
1827                 if ($min_url ne $url) {
1828                         unless ($no_write) {
1829                                 print STDERR "Using higher level of URL: ",
1830                                              "$url => $min_url\n";
1831                         }
1832                         my $old_path = $self->{path};
1833                         $self->{path} = $url;
1834                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1835                         if (length $old_path) {
1836                                 $self->{path} .= "/$old_path";
1837                         }
1838                         $url = $min_url;
1839                 }
1840         }
1841         my $orig_url;
1842         if (!$existing) {
1843                 # verify that we aren't overwriting anything:
1844                 $orig_url = eval {
1845                         command_oneline('config', '--get',
1846                                         "svn-remote.$self->{repo_id}.url")
1847                 };
1848                 if ($orig_url && ($orig_url ne $url)) {
1849                         die "svn-remote.$self->{repo_id}.url already set: ",
1850                             "$orig_url\nwanted to set to: $url\n";
1851                 }
1852         }
1853         my ($xrepo_id, $xpath) = find_ref($self->refname);
1854         if (defined $xpath) {
1855                 die "svn-remote.$xrepo_id.fetch already set to track ",
1856                     "$xpath:refs/remotes/", $self->refname, "\n";
1857         }
1858         unless ($no_write) {
1859                 command_noisy('config',
1860                               "svn-remote.$self->{repo_id}.url", $url);
1861                 $self->{path} =~ s{^/}{};
1862                 command_noisy('config', '--add',
1863                               "svn-remote.$self->{repo_id}.fetch",
1864                               "$self->{path}:".$self->refname);
1865         }
1866         $self->{url} = $url;
1869 sub find_by_url { # repos_root and, path are optional
1870         my ($class, $full_url, $repos_root, $path) = @_;
1872         return undef unless defined $full_url;
1873         remove_username($full_url);
1874         remove_username($repos_root) if defined $repos_root;
1875         my $remotes = read_all_remotes();
1876         if (defined $full_url && defined $repos_root && !defined $path) {
1877                 $path = $full_url;
1878                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1879         }
1880         foreach my $repo_id (keys %$remotes) {
1881                 my $u = $remotes->{$repo_id}->{url} or next;
1882                 remove_username($u);
1883                 next if defined $repos_root && $repos_root ne $u;
1885                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1886                 foreach my $t (qw/branches tags/) {
1887                         foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1888                                 resolve_local_globs($u, $fetch, $globspec);
1889                         }
1890                 }
1891                 my $p = $path;
1892                 my $rwr = rewrite_root({repo_id => $repo_id});
1893                 my $svm = $remotes->{$repo_id}->{svm}
1894                         if defined $remotes->{$repo_id}->{svm};
1895                 unless (defined $p) {
1896                         $p = $full_url;
1897                         my $z = $u;
1898                         my $prefix = '';
1899                         if ($rwr) {
1900                                 $z = $rwr;
1901                                 remove_username($z);
1902                         } elsif (defined $svm) {
1903                                 $z = $svm->{source};
1904                                 $prefix = $svm->{replace};
1905                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
1906                                 $prefix =~ s#/$##;
1907                         }
1908                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1909                 }
1910                 foreach my $f (keys %$fetch) {
1911                         next if $f ne $p;
1912                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1913                 }
1914         }
1915         undef;
1918 sub init {
1919         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1920         my $self = _new($class, $repo_id, $ref_id, $path);
1921         if (defined $url) {
1922                 $self->init_remote_config($url, $no_write);
1923         }
1924         $self;
1927 sub find_ref {
1928         my ($ref_id) = @_;
1929         foreach (command(qw/config -l/)) {
1930                 next unless m!^svn-remote\.(.+)\.fetch=
1931                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1932                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1933                 if ($ref eq $ref_id) {
1934                         $path = '' if ($path =~ m#^\./?#);
1935                         return ($repo_id, $path);
1936                 }
1937         }
1938         (undef, undef, undef);
1941 sub new {
1942         my ($class, $ref_id, $repo_id, $path) = @_;
1943         if (defined $ref_id && !defined $repo_id && !defined $path) {
1944                 ($repo_id, $path) = find_ref($ref_id);
1945                 if (!defined $repo_id) {
1946                         die "Could not find a \"svn-remote.*.fetch\" key ",
1947                             "in the repository configuration matching: ",
1948                             "refs/remotes/$ref_id\n";
1949                 }
1950         }
1951         my $self = _new($class, $repo_id, $ref_id, $path);
1952         if (!defined $self->{path} || !length $self->{path}) {
1953                 my $fetch = command_oneline('config', '--get',
1954                                             "svn-remote.$repo_id.fetch",
1955                                             ":refs/remotes/$ref_id\$") or
1956                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1957                          "\":refs/remotes/$ref_id\$\" in config\n";
1958                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1959         }
1960         $self->{url} = command_oneline('config', '--get',
1961                                        "svn-remote.$repo_id.url") or
1962                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1963         $self->rebuild;
1964         $self;
1967 sub refname {
1968         my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1970         # It cannot end with a slash /, we'll throw up on this because
1971         # SVN can't have directories with a slash in their name, either:
1972         if ($refname =~ m{/$}) {
1973                 die "ref: '$refname' ends with a trailing slash, this is ",
1974                     "not permitted by git nor Subversion\n";
1975         }
1977         # It cannot have ASCII control character space, tilde ~, caret ^,
1978         # colon :, question-mark ?, asterisk *, space, or open bracket [
1979         # anywhere.
1980         #
1981         # Additionally, % must be escaped because it is used for escaping
1982         # and we want our escaped refname to be reversible
1983         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1985         # no slash-separated component can begin with a dot .
1986         # /.* becomes /%2E*
1987         $refname =~ s{/\.}{/%2E}g;
1989         # It cannot have two consecutive dots .. anywhere
1990         # .. becomes %2E%2E
1991         $refname =~ s{\.\.}{%2E%2E}g;
1993         return $refname;
1996 sub desanitize_refname {
1997         my ($refname) = @_;
1998         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1999         return $refname;
2002 sub svm_uuid {
2003         my ($self) = @_;
2004         return $self->{svm}->{uuid} if $self->svm;
2005         $self->ra;
2006         unless ($self->{svm}) {
2007                 die "SVM UUID not cached, and reading remotely failed\n";
2008         }
2009         $self->{svm}->{uuid};
2012 sub svm {
2013         my ($self) = @_;
2014         return $self->{svm} if $self->{svm};
2015         my $svm;
2016         # see if we have it in our config, first:
2017         eval {
2018                 my $section = "svn-remote.$self->{repo_id}";
2019                 $svm = {
2020                   source => tmp_config('--get', "$section.svm-source"),
2021                   uuid => tmp_config('--get', "$section.svm-uuid"),
2022                   replace => tmp_config('--get', "$section.svm-replace"),
2023                 }
2024         };
2025         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2026                 $self->{svm} = $svm;
2027         }
2028         $self->{svm};
2031 sub _set_svm_vars {
2032         my ($self, $ra) = @_;
2033         return $ra if $self->svm;
2035         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2036                     "(svm:source, svm:uuid) ",
2037                     "from the following URLs:\n" );
2038         sub read_svm_props {
2039                 my ($self, $ra, $path, $r) = @_;
2040                 my $props = ($ra->get_dir($path, $r))[2];
2041                 my $src = $props->{'svm:source'};
2042                 my $uuid = $props->{'svm:uuid'};
2043                 return undef if (!$src || !$uuid);
2045                 chomp($src, $uuid);
2047                 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2048                     or die "doesn't look right - svm:uuid is '$uuid'\n";
2050                 # the '!' is used to mark the repos_root!/relative/path
2051                 $src =~ s{/?!/?}{/};
2052                 $src =~ s{/+$}{}; # no trailing slashes please
2053                 # username is of no interest
2054                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2056                 my $replace = $ra->{url};
2057                 $replace .= "/$path" if length $path;
2059                 my $section = "svn-remote.$self->{repo_id}";
2060                 tmp_config("$section.svm-source", $src);
2061                 tmp_config("$section.svm-replace", $replace);
2062                 tmp_config("$section.svm-uuid", $uuid);
2063                 $self->{svm} = {
2064                         source => $src,
2065                         uuid => $uuid,
2066                         replace => $replace
2067                 };
2068         }
2070         my $r = $ra->get_latest_revnum;
2071         my $path = $self->{path};
2072         my %tried;
2073         while (length $path) {
2074                 unless ($tried{"$self->{url}/$path"}) {
2075                         return $ra if $self->read_svm_props($ra, $path, $r);
2076                         $tried{"$self->{url}/$path"} = 1;
2077                 }
2078                 $path =~ s#/?[^/]+$##;
2079         }
2080         die "Path: '$path' should be ''\n" if $path ne '';
2081         return $ra if $self->read_svm_props($ra, $path, $r);
2082         $tried{"$self->{url}/$path"} = 1;
2084         if ($ra->{repos_root} eq $self->{url}) {
2085                 die @err, (map { "  $_\n" } keys %tried), "\n";
2086         }
2088         # nope, make sure we're connected to the repository root:
2089         my $ok;
2090         my @tried_b;
2091         $path = $ra->{svn_path};
2092         $ra = Git::SVN::Ra->new($ra->{repos_root});
2093         while (length $path) {
2094                 unless ($tried{"$ra->{url}/$path"}) {
2095                         $ok = $self->read_svm_props($ra, $path, $r);
2096                         last if $ok;
2097                         $tried{"$ra->{url}/$path"} = 1;
2098                 }
2099                 $path =~ s#/?[^/]+$##;
2100         }
2101         die "Path: '$path' should be ''\n" if $path ne '';
2102         $ok ||= $self->read_svm_props($ra, $path, $r);
2103         $tried{"$ra->{url}/$path"} = 1;
2104         if (!$ok) {
2105                 die @err, (map { "  $_\n" } keys %tried), "\n";
2106         }
2107         Git::SVN::Ra->new($self->{url});
2110 sub svnsync {
2111         my ($self) = @_;
2112         return $self->{svnsync} if $self->{svnsync};
2114         if ($self->no_metadata) {
2115                 die "Can't have both 'noMetadata' and ",
2116                     "'useSvnsyncProps' options set!\n";
2117         }
2118         if ($self->rewrite_root) {
2119                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2120                     "options set!\n";
2121         }
2123         my $svnsync;
2124         # see if we have it in our config, first:
2125         eval {
2126                 my $section = "svn-remote.$self->{repo_id}";
2128                 my $url = tmp_config('--get', "$section.svnsync-url");
2129                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2130                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2132                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2133                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2134                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2136                 $svnsync = { url => $url, uuid => $uuid }
2137         };
2138         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2139                 return $self->{svnsync} = $svnsync;
2140         }
2142         my $err = "useSvnsyncProps set, but failed to read " .
2143                   "svnsync property: svn:sync-from-";
2144         my $rp = $self->ra->rev_proplist(0);
2146         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2147         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2148                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2150         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2151         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2152                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2154         my $section = "svn-remote.$self->{repo_id}";
2155         tmp_config('--add', "$section.svnsync-uuid", $uuid);
2156         tmp_config('--add', "$section.svnsync-url", $url);
2157         return $self->{svnsync} = { url => $url, uuid => $uuid };
2160 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2161 # remote lookup (useful for 'git svn log').
2162 sub ra_uuid {
2163         my ($self) = @_;
2164         unless ($self->{ra_uuid}) {
2165                 my $key = "svn-remote.$self->{repo_id}.uuid";
2166                 my $uuid = eval { tmp_config('--get', $key) };
2167                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2168                         $self->{ra_uuid} = $uuid;
2169                 } else {
2170                         die "ra_uuid called without URL\n" unless $self->{url};
2171                         $self->{ra_uuid} = $self->ra->get_uuid;
2172                         tmp_config('--add', $key, $self->{ra_uuid});
2173                 }
2174         }
2175         $self->{ra_uuid};
2178 sub _set_repos_root {
2179         my ($self, $repos_root) = @_;
2180         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2181         $repos_root ||= $self->ra->{repos_root};
2182         tmp_config($k, $repos_root);
2183         $repos_root;
2186 sub repos_root {
2187         my ($self) = @_;
2188         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2189         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2192 sub ra {
2193         my ($self) = shift;
2194         my $ra = Git::SVN::Ra->new($self->{url});
2195         $self->_set_repos_root($ra->{repos_root});
2196         if ($self->use_svm_props && !$self->{svm}) {
2197                 if ($self->no_metadata) {
2198                         die "Can't have both 'noMetadata' and ",
2199                             "'useSvmProps' options set!\n";
2200                 } elsif ($self->use_svnsync_props) {
2201                         die "Can't have both 'useSvnsyncProps' and ",
2202                             "'useSvmProps' options set!\n";
2203                 }
2204                 $ra = $self->_set_svm_vars($ra);
2205                 $self->{-want_revprops} = 1;
2206         }
2207         $ra;
2210 # prop_walk(PATH, REV, SUB)
2211 # -------------------------
2212 # Recursively traverse PATH at revision REV and invoke SUB for each
2213 # directory that contains a SVN property.  SUB will be invoked as
2214 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
2215 # Git::SVN, `path' the path to the directory where the properties
2216 # `props' were found.  The `path' will be relative to point of checkout,
2217 # that is, if url://repo/trunk is the current Git branch, and that
2218 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2219 # as `path' (note the trailing `/').
2220 sub prop_walk {
2221         my ($self, $path, $rev, $sub) = @_;
2223         $path =~ s#^/##;
2224         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2225         $path =~ s#^/*#/#g;
2226         my $p = $path;
2227         # Strip the irrelevant part of the path.
2228         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2229         # Ensure the path is terminated by a `/'.
2230         $p =~ s#/*$#/#;
2232         # The properties contain all the internal SVN stuff nobody
2233         # (usually) cares about.
2234         my $interesting_props = 0;
2235         foreach (keys %{$props}) {
2236                 # If it doesn't start with `svn:', it must be a
2237                 # user-defined property.
2238                 ++$interesting_props and next if $_ !~ /^svn:/;
2239                 # FIXME: Fragile, if SVN adds new public properties,
2240                 # this needs to be updated.
2241                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2242                                                  |eol-style|mime-type
2243                                                  |externals|needs-lock)$/x;
2244         }
2245         &$sub($self, $p, $props) if $interesting_props;
2247         foreach (sort keys %$dirent) {
2248                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2249                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2250         }
2253 sub last_rev { ($_[0]->last_rev_commit)[0] }
2254 sub last_commit { ($_[0]->last_rev_commit)[1] }
2256 # returns the newest SVN revision number and newest commit SHA1
2257 sub last_rev_commit {
2258         my ($self) = @_;
2259         if (defined $self->{last_rev} && defined $self->{last_commit}) {
2260                 return ($self->{last_rev}, $self->{last_commit});
2261         }
2262         my $c = ::verify_ref($self->refname.'^0');
2263         if ($c && !$self->use_svm_props && !$self->no_metadata) {
2264                 my $rev = (::cmt_metadata($c))[1];
2265                 if (defined $rev) {
2266                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2267                         return ($rev, $c);
2268                 }
2269         }
2270         my $map_path = $self->map_path;
2271         unless (-e $map_path) {
2272                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2273                 return (undef, undef);
2274         }
2275         my ($rev, $commit) = $self->rev_map_max(1);
2276         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2277         return ($rev, $commit);
2280 sub get_fetch_range {
2281         my ($self, $min, $max) = @_;
2282         $max ||= $self->ra->get_latest_revnum;
2283         $min ||= $self->rev_map_max;
2284         (++$min, $max);
2287 sub tmp_config {
2288         my (@args) = @_;
2289         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2290         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2291         if (! -f $config && -f $old_def_config) {
2292                 rename $old_def_config, $config or
2293                        die "Failed rename $old_def_config => $config: $!\n";
2294         }
2295         my $old_config = $ENV{GIT_CONFIG};
2296         $ENV{GIT_CONFIG} = $config;
2297         $@ = undef;
2298         my @ret = eval {
2299                 unless (-f $config) {
2300                         mkfile($config);
2301                         open my $fh, '>', $config or
2302                             die "Can't open $config: $!\n";
2303                         print $fh "; This file is used internally by ",
2304                                   "git-svn\n" or die
2305                                   "Couldn't write to $config: $!\n";
2306                         print $fh "; You should not have to edit it\n" or
2307                               die "Couldn't write to $config: $!\n";
2308                         close $fh or die "Couldn't close $config: $!\n";
2309                 }
2310                 command('config', @args);
2311         };
2312         my $err = $@;
2313         if (defined $old_config) {
2314                 $ENV{GIT_CONFIG} = $old_config;
2315         } else {
2316                 delete $ENV{GIT_CONFIG};
2317         }
2318         die $err if $err;
2319         wantarray ? @ret : $ret[0];
2322 sub tmp_index_do {
2323         my ($self, $sub) = @_;
2324         my $old_index = $ENV{GIT_INDEX_FILE};
2325         $ENV{GIT_INDEX_FILE} = $self->{index};
2326         $@ = undef;
2327         my @ret = eval {
2328                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2329                 mkpath([$dir]) unless -d $dir;
2330                 &$sub;
2331         };
2332         my $err = $@;
2333         if (defined $old_index) {
2334                 $ENV{GIT_INDEX_FILE} = $old_index;
2335         } else {
2336                 delete $ENV{GIT_INDEX_FILE};
2337         }
2338         die $err if $err;
2339         wantarray ? @ret : $ret[0];
2342 sub assert_index_clean {
2343         my ($self, $treeish) = @_;
2345         $self->tmp_index_do(sub {
2346                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2347                 my $x = command_oneline('write-tree');
2348                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2349                            /^tree ($::sha1)/mo);
2350                 return if $y eq $x;
2352                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2353                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2354                 command_noisy('read-tree', $treeish);
2355                 $x = command_oneline('write-tree');
2356                 if ($y ne $x) {
2357                         ::fatal "trees ($treeish) $y != $x\n",
2358                                 "Something is seriously wrong...";
2359                 }
2360         });
2363 sub get_commit_parents {
2364         my ($self, $log_entry) = @_;
2365         my (%seen, @ret, @tmp);
2366         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2367         if (my $ip = $self->{inject_parents}) {
2368                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2369                         push @tmp, $commit;
2370                 }
2371         }
2372         if (my $cur = ::verify_ref($self->refname.'^0')) {
2373                 push @tmp, $cur;
2374         }
2375         if (my $ipd = $self->{inject_parents_dcommit}) {
2376                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2377                         push @tmp, @$commit;
2378                 }
2379         }
2380         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2381         while (my $p = shift @tmp) {
2382                 next if $seen{$p};
2383                 $seen{$p} = 1;
2384                 push @ret, $p;
2385                 # MAXPARENT is defined to 16 in commit-tree.c:
2386                 last if @ret >= 16;
2387         }
2388         if (@tmp) {
2389                 die "r$log_entry->{revision}: No room for parents:\n\t",
2390                     join("\n\t", @tmp), "\n";
2391         }
2392         @ret;
2395 sub rewrite_root {
2396         my ($self) = @_;
2397         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2398         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2399         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2400         if ($rwr) {
2401                 $rwr =~ s#/+$##;
2402                 if ($rwr !~ m#^[a-z\+]+://#) {
2403                         die "$rwr is not a valid URL (key: $k)\n";
2404                 }
2405         }
2406         $self->{-rewrite_root} = $rwr;
2409 sub metadata_url {
2410         my ($self) = @_;
2411         ($self->rewrite_root || $self->{url}) .
2412            (length $self->{path} ? '/' . $self->{path} : '');
2415 sub full_url {
2416         my ($self) = @_;
2417         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2421 sub set_commit_header_env {
2422         my ($log_entry) = @_;
2423         my %env;
2424         foreach my $ned (qw/NAME EMAIL DATE/) {
2425                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2426                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2427                 }
2428         }
2430         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2431         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2432         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2434         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2435                                                 ? $log_entry->{commit_name}
2436                                                 : $log_entry->{name};
2437         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2438                                                 ? $log_entry->{commit_email}
2439                                                 : $log_entry->{email};
2440         \%env;
2443 sub restore_commit_header_env {
2444         my ($env) = @_;
2445         foreach my $ned (qw/NAME EMAIL DATE/) {
2446                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2447                         my $k = "GIT_${ac}_${ned}";
2448                         if (defined $env->{$k}) {
2449                                 $ENV{$k} = $env->{$k};
2450                         } else {
2451                                 delete $ENV{$k};
2452                         }
2453                 }
2454         }
2457 sub gc {
2458         command_noisy('gc', '--auto');
2459 };
2461 sub do_git_commit {
2462         my ($self, $log_entry) = @_;
2463         my $lr = $self->last_rev;
2464         if (defined $lr && $lr >= $log_entry->{revision}) {
2465                 die "Last fetched revision of ", $self->refname,
2466                     " was r$lr, but we are about to fetch: ",
2467                     "r$log_entry->{revision}!\n";
2468         }
2469         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2470                 croak "$log_entry->{revision} = $c already exists! ",
2471                       "Why are we refetching it?\n";
2472         }
2473         my $old_env = set_commit_header_env($log_entry);
2474         my $tree = $log_entry->{tree};
2475         if (!defined $tree) {
2476                 $tree = $self->tmp_index_do(sub {
2477                                             command_oneline('write-tree') });
2478         }
2479         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2481         my @exec = ('git', 'commit-tree', $tree);
2482         foreach ($self->get_commit_parents($log_entry)) {
2483                 push @exec, '-p', $_;
2484         }
2485         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2486                                                                    or croak $!;
2487         binmode $msg_fh;
2489         # we always get UTF-8 from SVN, but we may want our commits in
2490         # a different encoding.
2491         if (my $enc = Git::config('i18n.commitencoding')) {
2492                 require Encode;
2493                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2494         }
2495         print $msg_fh $log_entry->{log} or croak $!;
2496         restore_commit_header_env($old_env);
2497         unless ($self->no_metadata) {
2498                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2499                               or croak $!;
2500         }
2501         $msg_fh->flush == 0 or croak $!;
2502         close $msg_fh or croak $!;
2503         chomp(my $commit = do { local $/; <$out_fh> });
2504         close $out_fh or croak $!;
2505         waitpid $pid, 0;
2506         croak $? if $?;
2507         if ($commit !~ /^$::sha1$/o) {
2508                 die "Failed to commit, invalid sha1: $commit\n";
2509         }
2511         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2513         $self->{last_rev} = $log_entry->{revision};
2514         $self->{last_commit} = $commit;
2515         print "r$log_entry->{revision}" unless $::_q > 1;
2516         if (defined $log_entry->{svm_revision}) {
2517                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2518                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2519                                    0, $self->svm_uuid);
2520         }
2521         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2522         if (--$_gc_nr == 0) {
2523                 $_gc_nr = $_gc_period;
2524                 gc();
2525         }
2526         return $commit;
2529 sub match_paths {
2530         my ($self, $paths, $r) = @_;
2531         return 1 if $self->{path} eq '';
2532         if (my $path = $paths->{"/$self->{path}"}) {
2533                 return ($path->{action} eq 'D') ? 0 : 1;
2534         }
2535         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2536         if (grep /$self->{path_regex}/, keys %$paths) {
2537                 return 1;
2538         }
2539         my $c = '';
2540         foreach (split m#/#, $self->{path}) {
2541                 $c .= "/$_";
2542                 next unless ($paths->{$c} &&
2543                              ($paths->{$c}->{action} =~ /^[AR]$/));
2544                 if ($self->ra->check_path($self->{path}, $r) ==
2545                     $SVN::Node::dir) {
2546                         return 1;
2547                 }
2548         }
2549         return 0;
2552 sub find_parent_branch {
2553         my ($self, $paths, $rev) = @_;
2554         return undef unless $self->follow_parent;
2555         unless (defined $paths) {
2556                 my $err_handler = $SVN::Error::handler;
2557                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2558                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2559                                    sub { $paths = $_[0] });
2560                 $SVN::Error::handler = $err_handler;
2561         }
2562         return undef unless defined $paths;
2564         # look for a parent from another branch:
2565         my @b_path_components = split m#/#, $self->{path};
2566         my @a_path_components;
2567         my $i;
2568         while (@b_path_components) {
2569                 $i = $paths->{'/'.join('/', @b_path_components)};
2570                 last if $i && defined $i->{copyfrom_path};
2571                 unshift(@a_path_components, pop(@b_path_components));
2572         }
2573         return undef unless defined $i && defined $i->{copyfrom_path};
2574         my $branch_from = $i->{copyfrom_path};
2575         if (@a_path_components) {
2576                 print STDERR "branch_from: $branch_from => ";
2577                 $branch_from .= '/'.join('/', @a_path_components);
2578                 print STDERR $branch_from, "\n";
2579         }
2580         my $r = $i->{copyfrom_rev};
2581         my $repos_root = $self->ra->{repos_root};
2582         my $url = $self->ra->{url};
2583         my $new_url = $url . $branch_from;
2584         print STDERR  "Found possible branch point: ",
2585                       "$new_url => ", $self->full_url, ", $r\n";
2586         $branch_from =~ s#^/##;
2587         my $gs = $self->other_gs($new_url, $url,
2588                                  $branch_from, $r, $self->{ref_id});
2589         my ($r0, $parent) = $gs->find_rev_before($r, 1);
2590         {
2591                 my ($base, $head);
2592                 if (!defined $r0 || !defined $parent) {
2593                         ($base, $head) = parse_revision_argument(0, $r);
2594                 } else {
2595                         if ($r0 < $r) {
2596                                 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2597                                         0, 1, sub { $base = $_[1] - 1 });
2598                         }
2599                 }
2600                 if (defined $base && $base <= $r) {
2601                         $gs->fetch($base, $r);
2602                 }
2603                 ($r0, $parent) = $gs->find_rev_before($r, 1);
2604         }
2605         if (defined $r0 && defined $parent) {
2606                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2607                 my $ed;
2608                 if ($self->ra->can_do_switch) {
2609                         $self->assert_index_clean($parent);
2610                         print STDERR "Following parent with do_switch\n";
2611                         # do_switch works with svn/trunk >= r22312, but that
2612                         # is not included with SVN 1.4.3 (the latest version
2613                         # at the moment), so we can't rely on it
2614                         $self->{last_rev} = $r0;
2615                         $self->{last_commit} = $parent;
2616                         $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2617                         $gs->ra->gs_do_switch($r0, $rev, $gs,
2618                                               $self->full_url, $ed)
2619                           or die "SVN connection failed somewhere...\n";
2620                 } elsif ($self->ra->trees_match($new_url, $r0,
2621                                                 $self->full_url, $rev)) {
2622                         print STDERR "Trees match:\n",
2623                                      "  $new_url\@$r0\n",
2624                                      "  ${\$self->full_url}\@$rev\n",
2625                                      "Following parent with no changes\n";
2626                         $self->tmp_index_do(sub {
2627                             command_noisy('read-tree', $parent);
2628                         });
2629                         $self->{last_commit} = $parent;
2630                 } else {
2631                         print STDERR "Following parent with do_update\n";
2632                         $ed = SVN::Git::Fetcher->new($self);
2633                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
2634                           or die "SVN connection failed somewhere...\n";
2635                 }
2636                 print STDERR "Successfully followed parent\n";
2637                 return $self->make_log_entry($rev, [$parent], $ed);
2638         }
2639         return undef;
2642 sub do_fetch {
2643         my ($self, $paths, $rev) = @_;
2644         my $ed;
2645         my ($last_rev, @parents);
2646         if (my $lc = $self->last_commit) {
2647                 # we can have a branch that was deleted, then re-added
2648                 # under the same name but copied from another path, in
2649                 # which case we'll have multiple parents (we don't
2650                 # want to break the original ref, nor lose copypath info):
2651                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2652                         push @{$log_entry->{parents}}, $lc;
2653                         return $log_entry;
2654                 }
2655                 $ed = SVN::Git::Fetcher->new($self);
2656                 $last_rev = $self->{last_rev};
2657                 $ed->{c} = $lc;
2658                 @parents = ($lc);
2659         } else {
2660                 $last_rev = $rev;
2661                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2662                         return $log_entry;
2663                 }
2664                 $ed = SVN::Git::Fetcher->new($self);
2665         }
2666         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2667                 die "SVN connection failed somewhere...\n";
2668         }
2669         $self->make_log_entry($rev, \@parents, $ed);
2672 sub get_untracked {
2673         my ($self, $ed) = @_;
2674         my @out;
2675         my $h = $ed->{empty};
2676         foreach (sort keys %$h) {
2677                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2678                 push @out, "  $act: " . uri_encode($_);
2679                 warn "W: $act: $_\n";
2680         }
2681         foreach my $t (qw/dir_prop file_prop/) {
2682                 $h = $ed->{$t} or next;
2683                 foreach my $path (sort keys %$h) {
2684                         my $ppath = $path eq '' ? '.' : $path;
2685                         foreach my $prop (sort keys %{$h->{$path}}) {
2686                                 next if $SKIP_PROP{$prop};
2687                                 my $v = $h->{$path}->{$prop};
2688                                 my $t_ppath_prop = "$t: " .
2689                                                     uri_encode($ppath) . ' ' .
2690                                                     uri_encode($prop);
2691                                 if (defined $v) {
2692                                         push @out, "  +$t_ppath_prop " .
2693                                                    uri_encode($v);
2694                                 } else {
2695                                         push @out, "  -$t_ppath_prop";
2696                                 }
2697                         }
2698                 }
2699         }
2700         foreach my $t (qw/absent_file absent_directory/) {
2701                 $h = $ed->{$t} or next;
2702                 foreach my $parent (sort keys %$h) {
2703                         foreach my $path (sort @{$h->{$parent}}) {
2704                                 push @out, "  $t: " .
2705                                            uri_encode("$parent/$path");
2706                                 warn "W: $t: $parent/$path ",
2707                                      "Insufficient permissions?\n";
2708                         }
2709                 }
2710         }
2711         \@out;
2714 # parse_svn_date(DATE)
2715 # --------------------
2716 # Given a date (in UTC) from Subversion, return a string in the format
2717 # "<TZ Offset> <local date/time>" that Git will use.
2719 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2720 # is true we'll convert it to the local timezone instead.
2721 sub parse_svn_date {
2722         my $date = shift || return '+0000 1970-01-01 00:00:00';
2723         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2724                                             (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2725                                          croak "Unable to parse date: $date\n";
2726         my $parsed_date;    # Set next.
2728         if ($Git::SVN::_localtime) {
2729                 # Translate the Subversion datetime to an epoch time.
2730                 # Begin by switching ourselves to $date's timezone, UTC.
2731                 my $old_env_TZ = $ENV{TZ};
2732                 $ENV{TZ} = 'UTC';
2734                 my $epoch_in_UTC =
2735                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2737                 # Determine our local timezone (including DST) at the
2738                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
2739                 # value of TZ, if any, at the time we were run.
2740                 if (defined $Git::SVN::Log::TZ) {
2741                         $ENV{TZ} = $Git::SVN::Log::TZ;
2742                 } else {
2743                         delete $ENV{TZ};
2744                 }
2746                 my $our_TZ =
2747                     POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2749                 # This converts $epoch_in_UTC into our local timezone.
2750                 my ($sec, $min, $hour, $mday, $mon, $year,
2751                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2753                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2754                                        $our_TZ, $year + 1900, $mon + 1,
2755                                        $mday, $hour, $min, $sec);
2757                 # Reset us to the timezone in effect when we entered
2758                 # this routine.
2759                 if (defined $old_env_TZ) {
2760                         $ENV{TZ} = $old_env_TZ;
2761                 } else {
2762                         delete $ENV{TZ};
2763                 }
2764         } else {
2765                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2766         }
2768         return $parsed_date;
2771 sub other_gs {
2772         my ($self, $new_url, $url,
2773             $branch_from, $r, $old_ref_id) = @_;
2774         my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2775         unless ($gs) {
2776                 my $ref_id = $old_ref_id;
2777                 $ref_id =~ s/\@\d+$//;
2778                 $ref_id .= "\@$r";
2779                 # just grow a tail if we're not unique enough :x
2780                 $ref_id .= '-' while find_ref($ref_id);
2781                 print STDERR "Initializing parent: $ref_id\n";
2782                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2783                 if ($u =~ s#^\Q$url\E(/|$)##) {
2784                         $p = $u;
2785                         $u = $url;
2786                         $repo_id = $self->{repo_id};
2787                 }
2788                 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2789         }
2790         $gs
2793 sub call_authors_prog {
2794         my ($orig_author) = @_;
2795         my $author = `$::_authors_prog $orig_author`;
2796         if ($? != 0) {
2797                 die "$::_authors_prog failed with exit code $?\n"
2798         }
2799         if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2800                 my ($name, $email) = ($1, $2);
2801                 $email = undef if length $2 == 0;
2802                 return [$name, $email];
2803         } else {
2804                 die "Author: $orig_author: $::_authors_prog returned "
2805                         . "invalid author format: $author\n";
2806         }
2809 sub check_author {
2810         my ($author) = @_;
2811         if (!defined $author || length $author == 0) {
2812                 $author = '(no author)';
2813         }
2814         if (!defined $::users{$author}) {
2815                 if (defined $::_authors_prog) {
2816                         $::users{$author} = call_authors_prog($author);
2817                 } elsif (defined $::_authors) {
2818                         die "Author: $author not defined in $::_authors file\n";
2819                 }
2820         }
2821         $author;
2824 sub make_log_entry {
2825         my ($self, $rev, $parents, $ed) = @_;
2826         my $untracked = $self->get_untracked($ed);
2828         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2829         print $un "r$rev\n" or croak $!;
2830         print $un $_, "\n" foreach @$untracked;
2831         my %log_entry = ( parents => $parents || [], revision => $rev,
2832                           log => '');
2834         my $headrev;
2835         my $logged = delete $self->{logged_rev_props};
2836         if (!$logged || $self->{-want_revprops}) {
2837                 my $rp = $self->ra->rev_proplist($rev);
2838                 foreach (sort keys %$rp) {
2839                         my $v = $rp->{$_};
2840                         if (/^svn:(author|date|log)$/) {
2841                                 $log_entry{$1} = $v;
2842                         } elsif ($_ eq 'svm:headrev') {
2843                                 $headrev = $v;
2844                         } else {
2845                                 print $un "  rev_prop: ", uri_encode($_), ' ',
2846                                           uri_encode($v), "\n";
2847                         }
2848                 }
2849         } else {
2850                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2851         }
2852         close $un or croak $!;
2854         $log_entry{date} = parse_svn_date($log_entry{date});
2855         $log_entry{log} .= "\n";
2856         my $author = $log_entry{author} = check_author($log_entry{author});
2857         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2858                                                        : ($author, undef);
2860         my ($commit_name, $commit_email) = ($name, $email);
2861         if ($_use_log_author) {
2862                 my $name_field;
2863                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2864                         $name_field = $1;
2865                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2866                         $name_field = $1;
2867                 }
2868                 if (!defined $name_field) {
2869                         if (!defined $email) {
2870                                 $email = $name;
2871                         }
2872                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2873                         ($name, $email) = ($1, $2);
2874                 } elsif ($name_field =~ /(.*)@/) {
2875                         ($name, $email) = ($1, $name_field);
2876                 } else {
2877                         ($name, $email) = ($name_field, $name_field);
2878                 }
2879         }
2880         if (defined $headrev && $self->use_svm_props) {
2881                 if ($self->rewrite_root) {
2882                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2883                             "options set!\n";
2884                 }
2885                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2886                 # we don't want "SVM: initializing mirror for junk" ...
2887                 return undef if $r == 0;
2888                 my $svm = $self->svm;
2889                 if ($uuid ne $svm->{uuid}) {
2890                         die "UUID mismatch on SVM path:\n",
2891                             "expected: $svm->{uuid}\n",
2892                             "     got: $uuid\n";
2893                 }
2894                 my $full_url = $self->full_url;
2895                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2896                              die "Failed to replace '$svm->{replace}' with ",
2897                                  "'$svm->{source}' in $full_url\n";
2898                 # throw away username for storing in records
2899                 remove_username($full_url);
2900                 $log_entry{metadata} = "$full_url\@$r $uuid";
2901                 $log_entry{svm_revision} = $r;
2902                 $email ||= "$author\@$uuid";
2903                 $commit_email ||= "$author\@$uuid";
2904         } elsif ($self->use_svnsync_props) {
2905                 my $full_url = $self->svnsync->{url};
2906                 $full_url .= "/$self->{path}" if length $self->{path};
2907                 remove_username($full_url);
2908                 my $uuid = $self->svnsync->{uuid};
2909                 $log_entry{metadata} = "$full_url\@$rev $uuid";
2910                 $email ||= "$author\@$uuid";
2911                 $commit_email ||= "$author\@$uuid";
2912         } else {
2913                 my $url = $self->metadata_url;
2914                 remove_username($url);
2915                 $log_entry{metadata} = "$url\@$rev " .
2916                                        $self->ra->get_uuid;
2917                 $email ||= "$author\@" . $self->ra->get_uuid;
2918                 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2919         }
2920         $log_entry{name} = $name;
2921         $log_entry{email} = $email;
2922         $log_entry{commit_name} = $commit_name;
2923         $log_entry{commit_email} = $commit_email;
2924         \%log_entry;
2927 sub fetch {
2928         my ($self, $min_rev, $max_rev, @parents) = @_;
2929         my ($last_rev, $last_commit) = $self->last_rev_commit;
2930         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2931         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2934 sub set_tree_cb {
2935         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2936         $self->{inject_parents} = { $rev => $tree };
2937         $self->fetch(undef, undef);
2940 sub set_tree {
2941         my ($self, $tree) = (shift, shift);
2942         my $log_entry = ::get_commit_entry($tree);
2943         unless ($self->{last_rev}) {
2944                 ::fatal("Must have an existing revision to commit");
2945         }
2946         my %ed_opts = ( r => $self->{last_rev},
2947                         log => $log_entry->{log},
2948                         ra => $self->ra,
2949                         tree_a => $self->{last_commit},
2950                         tree_b => $tree,
2951                         editor_cb => sub {
2952                                $self->set_tree_cb($log_entry, $tree, @_) },
2953                         svn_path => $self->{path} );
2954         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2955                 print "No changes\nr$self->{last_rev} = $tree\n";
2956         }
2959 sub rebuild_from_rev_db {
2960         my ($self, $path) = @_;
2961         my $r = -1;
2962         open my $fh, '<', $path or croak "open: $!";
2963         binmode $fh or croak "binmode: $!";
2964         while (<$fh>) {
2965                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2966                 chomp($_);
2967                 ++$r;
2968                 next if $_ eq ('0' x 40);
2969                 $self->rev_map_set($r, $_);
2970                 print "r$r = $_\n";
2971         }
2972         close $fh or croak "close: $!";
2973         unlink $path or croak "unlink: $!";
2976 sub rebuild {
2977         my ($self) = @_;
2978         my $map_path = $self->map_path;
2979         my $partial = (-e $map_path && ! -z $map_path);
2980         return unless ::verify_ref($self->refname.'^0');
2981         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2982                 my $rev_db = $self->rev_db_path;
2983                 $self->rebuild_from_rev_db($rev_db);
2984                 if ($self->use_svm_props) {
2985                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2986                         $self->rebuild_from_rev_db($svm_rev_db);
2987                 }
2988                 $self->unlink_rev_db_symlink;
2989                 return;
2990         }
2991         print "Rebuilding $map_path ...\n" if (!$partial);
2992         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2993                 (undef, undef));
2994         my ($log, $ctx) =
2995             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2996                                 ($head ? "$head.." : "") . $self->refname,
2997                                 '--');
2998         my $metadata_url = $self->metadata_url;
2999         remove_username($metadata_url);
3000         my $svn_uuid = $self->ra_uuid;
3001         my $c;
3002         while (<$log>) {
3003                 if ( m{^commit ($::sha1)$} ) {
3004                         $c = $1;
3005                         next;
3006                 }
3007                 next unless s{^\s*(git-svn-id:)}{$1};
3008                 my ($url, $rev, $uuid) = ::extract_metadata($_);
3009                 remove_username($url);
3011                 # ignore merges (from set-tree)
3012                 next if (!defined $rev || !$uuid);
3014                 # if we merged or otherwise started elsewhere, this is
3015                 # how we break out of it
3016                 if (($uuid ne $svn_uuid) ||
3017                     ($metadata_url && $url && ($url ne $metadata_url))) {
3018                         next;
3019                 }
3020                 if ($partial && $head) {
3021                         print "Partial-rebuilding $map_path ...\n";
3022                         print "Currently at $base_rev = $head\n";
3023                         $head = undef;
3024                 }
3026                 $self->rev_map_set($rev, $c);
3027                 print "r$rev = $c\n";
3028         }
3029         command_close_pipe($log, $ctx);
3030         print "Done rebuilding $map_path\n" if (!$partial || !$head);
3031         my $rev_db_path = $self->rev_db_path;
3032         if (-f $self->rev_db_path) {
3033                 unlink $self->rev_db_path or croak "unlink: $!";
3034         }
3035         $self->unlink_rev_db_symlink;
3038 # rev_map:
3039 # Tie::File seems to be prone to offset errors if revisions get sparse,
3040 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3041 # one of my favorite modules is out :<  Next up would be one of the DBM
3042 # modules, but I'm not sure which is most portable...
3044 # This is the replacement for the rev_db format, which was too big
3045 # and inefficient for large repositories with a lot of sparse history
3046 # (mainly tags)
3048 # The format is this:
3049 #   - 24 bytes for every record,
3050 #     * 4 bytes for the integer representing an SVN revision number
3051 #     * 20 bytes representing the sha1 of a git commit
3052 #   - No empty padding records like the old format
3053 #     (except the last record, which can be overwritten)
3054 #   - new records are written append-only since SVN revision numbers
3055 #     increase monotonically
3056 #   - lookups on SVN revision number are done via a binary search
3057 #   - Piping the file to xxd -c24 is a good way of dumping it for
3058 #     viewing or editing (piped back through xxd -r), should the need
3059 #     ever arise.
3060 #   - The last record can be padding revision with an all-zero sha1
3061 #     This is used to optimize fetch performance when using multiple
3062 #     "fetch" directives in .git/config
3064 # These files are disposable unless noMetadata or useSvmProps is set
3066 sub _rev_map_set {
3067         my ($fh, $rev, $commit) = @_;
3069         binmode $fh or croak "binmode: $!";
3070         my $size = (stat($fh))[7];
3071         ($size % 24) == 0 or croak "inconsistent size: $size";
3073         my $wr_offset = 0;
3074         if ($size > 0) {
3075                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3076                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3077                 $read == 24 or croak "read only $read bytes (!= 24)";
3078                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3079                 if ($last_commit eq ('0' x40)) {
3080                         if ($size >= 48) {
3081                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3082                                 $read = sysread($fh, $buf, 24) or
3083                                     croak "read: $!";
3084                                 $read == 24 or
3085                                     croak "read only $read bytes (!= 24)";
3086                                 ($last_rev, $last_commit) =
3087                                     unpack(rev_map_fmt, $buf);
3088                                 if ($last_commit eq ('0' x40)) {
3089                                         croak "inconsistent .rev_map\n";
3090                                 }
3091                         }
3092                         if ($last_rev >= $rev) {
3093                                 croak "last_rev is higher!: $last_rev >= $rev";
3094                         }
3095                         $wr_offset = -24;
3096                 }
3097         }
3098         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3099         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3100           croak "write: $!";
3103 sub _rev_map_reset {
3104         my ($fh, $rev, $commit) = @_;
3105         my $c = _rev_map_get($fh, $rev);
3106         $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3107         my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3108         truncate $fh, $offset or croak "truncate: $!";
3111 sub mkfile {
3112         my ($path) = @_;
3113         unless (-e $path) {
3114                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3115                 mkpath([$dir]) unless -d $dir;
3116                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3117                 close $fh or die "Couldn't close (create) $path: $!\n";
3118         }
3121 sub rev_map_set {
3122         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3123         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3124         my $db = $self->map_path($uuid);
3125         my $db_lock = "$db.lock";
3126         my $sig;
3127         $update_ref ||= 0;
3128         if ($update_ref) {
3129                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3130                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3131         }
3132         mkfile($db);
3134         $LOCKFILES{$db_lock} = 1;
3135         my $sync;
3136         # both of these options make our .rev_db file very, very important
3137         # and we can't afford to lose it because rebuild() won't work
3138         if ($self->use_svm_props || $self->no_metadata) {
3139                 $sync = 1;
3140                 copy($db, $db_lock) or die "rev_map_set(@_): ",
3141                                            "Failed to copy: ",
3142                                            "$db => $db_lock ($!)\n";
3143         } else {
3144                 rename $db, $db_lock or die "rev_map_set(@_): ",
3145                                             "Failed to rename: ",
3146                                             "$db => $db_lock ($!)\n";
3147         }
3149         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3150              or croak "Couldn't open $db_lock: $!\n";
3151         $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3152                                  _rev_map_set($fh, $rev, $commit);
3153         if ($sync) {
3154                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3155                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3156         }
3157         close $fh or croak $!;
3158         if ($update_ref) {
3159                 $_head = $self;
3160                 my $note = "";
3161                 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3162                 command_noisy('update-ref', '-m', "r$rev$note",
3163                               $self->refname, $commit);
3164         }
3165         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3166                                     "$db_lock => $db ($!)\n";
3167         delete $LOCKFILES{$db_lock};
3168         if ($update_ref) {
3169                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3170                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3171                 kill $sig, $$ if defined $sig;
3172         }
3175 # If want_commit, this will return an array of (rev, commit) where
3176 # commit _must_ be a valid commit in the archive.
3177 # Otherwise, it'll return the max revision (whether or not the
3178 # commit is valid or just a 0x40 placeholder).
3179 sub rev_map_max {
3180         my ($self, $want_commit) = @_;
3181         $self->rebuild;
3182         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3183         $want_commit ? ($r, $c) : $r;
3186 sub rev_map_max_norebuild {
3187         my ($self, $want_commit) = @_;
3188         my $map_path = $self->map_path;
3189         stat $map_path or return $want_commit ? (0, undef) : 0;
3190         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3191         binmode $fh or croak "binmode: $!";
3192         my $size = (stat($fh))[7];
3193         ($size % 24) == 0 or croak "inconsistent size: $size";
3195         if ($size == 0) {
3196                 close $fh or croak "close: $!";
3197                 return $want_commit ? (0, undef) : 0;
3198         }
3200         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3201         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3202         my ($r, $c) = unpack(rev_map_fmt, $buf);
3203         if ($want_commit && $c eq ('0' x40)) {
3204                 if ($size < 48) {
3205                         return $want_commit ? (0, undef) : 0;
3206                 }
3207                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3208                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3209                 ($r, $c) = unpack(rev_map_fmt, $buf);
3210                 if ($c eq ('0'x40)) {
3211                         croak "Penultimate record is all-zeroes in $map_path";
3212                 }
3213         }
3214         close $fh or croak "close: $!";
3215         $want_commit ? ($r, $c) : $r;
3218 sub rev_map_get {
3219         my ($self, $rev, $uuid) = @_;
3220         my $map_path = $self->map_path($uuid);
3221         return undef unless -e $map_path;
3223         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3224         my $c = _rev_map_get($fh, $rev);
3225         close($fh) or croak "close: $!";
3226         $c
3229 sub _rev_map_get {
3230         my ($fh, $rev) = @_;
3232         binmode $fh or croak "binmode: $!";
3233         my $size = (stat($fh))[7];
3234         ($size % 24) == 0 or croak "inconsistent size: $size";
3236         if ($size == 0) {
3237                 return undef;
3238         }
3240         my ($l, $u) = (0, $size - 24);
3241         my ($r, $c, $buf);
3243         while ($l <= $u) {
3244                 my $i = int(($l/24 + $u/24) / 2) * 24;
3245                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3246                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3247                 my ($r, $c) = unpack('NH40', $buf);
3249                 if ($r < $rev) {
3250                         $l = $i + 24;
3251                 } elsif ($r > $rev) {
3252                         $u = $i - 24;
3253                 } else { # $r == $rev
3254                         return $c eq ('0' x 40) ? undef : $c;
3255                 }
3256         }
3257         undef;
3260 # Finds the first svn revision that exists on (if $eq_ok is true) or
3261 # before $rev for the current branch.  It will not search any lower
3262 # than $min_rev.  Returns the git commit hash and svn revision number
3263 # if found, else (undef, undef).
3264 sub find_rev_before {
3265         my ($self, $rev, $eq_ok, $min_rev) = @_;
3266         --$rev unless $eq_ok;
3267         $min_rev ||= 1;
3268         my $max_rev = $self->rev_map_max;
3269         $rev = $max_rev if ($rev > $max_rev);
3270         while ($rev >= $min_rev) {
3271                 if (my $c = $self->rev_map_get($rev)) {
3272                         return ($rev, $c);
3273                 }
3274                 --$rev;
3275         }
3276         return (undef, undef);
3279 # Finds the first svn revision that exists on (if $eq_ok is true) or
3280 # after $rev for the current branch.  It will not search any higher
3281 # than $max_rev.  Returns the git commit hash and svn revision number
3282 # if found, else (undef, undef).
3283 sub find_rev_after {
3284         my ($self, $rev, $eq_ok, $max_rev) = @_;
3285         ++$rev unless $eq_ok;
3286         $max_rev ||= $self->rev_map_max;
3287         while ($rev <= $max_rev) {
3288                 if (my $c = $self->rev_map_get($rev)) {
3289                         return ($rev, $c);
3290                 }
3291                 ++$rev;
3292         }
3293         return (undef, undef);
3296 sub _new {
3297         my ($class, $repo_id, $ref_id, $path) = @_;
3298         unless (defined $repo_id && length $repo_id) {
3299                 $repo_id = $Git::SVN::default_repo_id;
3300         }
3301         unless (defined $ref_id && length $ref_id) {
3302                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3303         }
3304         $_[1] = $repo_id;
3305         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3306         $_[3] = $path = '' unless (defined $path);
3307         mkpath(["$ENV{GIT_DIR}/svn"]);
3308         bless {
3309                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3310                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3311                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3314 # for read-only access of old .rev_db formats
3315 sub unlink_rev_db_symlink {
3316         my ($self) = @_;
3317         my $link = $self->rev_db_path;
3318         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3319         if (-l $link) {
3320                 unlink $link or croak "unlink: $link failed!";
3321         }
3324 sub rev_db_path {
3325         my ($self, $uuid) = @_;
3326         my $db_path = $self->map_path($uuid);
3327         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3328             or croak "map_path: $db_path does not contain '/.rev_map.' !";
3329         $db_path;
3332 # the new replacement for .rev_db
3333 sub map_path {
3334         my ($self, $uuid) = @_;
3335         $uuid ||= $self->ra_uuid;
3336         "$self->{map_root}.$uuid";
3339 sub uri_encode {
3340         my ($f) = @_;
3341         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3342         $f
3345 sub remove_username {
3346         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3349 package Git::SVN::Prompt;
3350 use strict;
3351 use warnings;
3352 require SVN::Core;
3353 use vars qw/$_no_auth_cache $_username/;
3355 sub simple {
3356         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3357         $may_save = undef if $_no_auth_cache;
3358         $default_username = $_username if defined $_username;
3359         if (defined $default_username && length $default_username) {
3360                 if (defined $realm && length $realm) {
3361                         print STDERR "Authentication realm: $realm\n";
3362                         STDERR->flush;
3363                 }
3364                 $cred->username($default_username);
3365         } else {
3366                 username($cred, $realm, $may_save, $pool);
3367         }
3368         $cred->password(_read_password("Password for '" .
3369                                        $cred->username . "': ", $realm));
3370         $cred->may_save($may_save);
3371         $SVN::_Core::SVN_NO_ERROR;
3374 sub ssl_server_trust {
3375         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3376         $may_save = undef if $_no_auth_cache;
3377         print STDERR "Error validating server certificate for '$realm':\n";
3378         {
3379                 no warnings 'once';
3380                 # All variables SVN::Auth::SSL::* are used only once,
3381                 # so we're shutting up Perl warnings about this.
3382                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3383                         print STDERR " - The certificate is not issued ",
3384                             "by a trusted authority. Use the\n",
3385                             "   fingerprint to validate ",
3386                             "the certificate manually!\n";
3387                 }
3388                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3389                         print STDERR " - The certificate hostname ",
3390                             "does not match.\n";
3391                 }
3392                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3393                         print STDERR " - The certificate is not yet valid.\n";
3394                 }
3395                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3396                         print STDERR " - The certificate has expired.\n";
3397                 }
3398                 if ($failures & $SVN::Auth::SSL::OTHER) {
3399                         print STDERR " - The certificate has ",
3400                             "an unknown error.\n";
3401                 }
3402         } # no warnings 'once'
3403         printf STDERR
3404                 "Certificate information:\n".
3405                 " - Hostname: %s\n".
3406                 " - Valid: from %s until %s\n".
3407                 " - Issuer: %s\n".
3408                 " - Fingerprint: %s\n",
3409                 map $cert_info->$_, qw(hostname valid_from valid_until
3410                                        issuer_dname fingerprint);
3411         my $choice;
3412 prompt:
3413         print STDERR $may_save ?
3414               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3415               "(R)eject or accept (t)emporarily? ";
3416         STDERR->flush;
3417         $choice = lc(substr(<STDIN> || 'R', 0, 1));
3418         if ($choice =~ /^t$/i) {
3419                 $cred->may_save(undef);
3420         } elsif ($choice =~ /^r$/i) {
3421                 return -1;
3422         } elsif ($may_save && $choice =~ /^p$/i) {
3423                 $cred->may_save($may_save);
3424         } else {
3425                 goto prompt;
3426         }
3427         $cred->accepted_failures($failures);
3428         $SVN::_Core::SVN_NO_ERROR;
3431 sub ssl_client_cert {
3432         my ($cred, $realm, $may_save, $pool) = @_;
3433         $may_save = undef if $_no_auth_cache;
3434         print STDERR "Client certificate filename: ";
3435         STDERR->flush;
3436         chomp(my $filename = <STDIN>);
3437         $cred->cert_file($filename);
3438         $cred->may_save($may_save);
3439         $SVN::_Core::SVN_NO_ERROR;
3442 sub ssl_client_cert_pw {
3443         my ($cred, $realm, $may_save, $pool) = @_;
3444         $may_save = undef if $_no_auth_cache;
3445         $cred->password(_read_password("Password: ", $realm));
3446         $cred->may_save($may_save);
3447         $SVN::_Core::SVN_NO_ERROR;
3450 sub username {
3451         my ($cred, $realm, $may_save, $pool) = @_;
3452         $may_save = undef if $_no_auth_cache;
3453         if (defined $realm && length $realm) {
3454                 print STDERR "Authentication realm: $realm\n";
3455         }
3456         my $username;
3457         if (defined $_username) {
3458                 $username = $_username;
3459         } else {
3460                 print STDERR "Username: ";
3461                 STDERR->flush;
3462                 chomp($username = <STDIN>);
3463         }
3464         $cred->username($username);
3465         $cred->may_save($may_save);
3466         $SVN::_Core::SVN_NO_ERROR;
3469 sub _read_password {
3470         my ($prompt, $realm) = @_;
3471         print STDERR $prompt;
3472         STDERR->flush;
3473         require Term::ReadKey;
3474         Term::ReadKey::ReadMode('noecho');
3475         my $password = '';
3476         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3477                 last if $key =~ /[\012\015]/; # \n\r
3478                 $password .= $key;
3479         }
3480         Term::ReadKey::ReadMode('restore');
3481         print STDERR "\n";
3482         STDERR->flush;
3483         $password;
3486 package SVN::Git::Fetcher;
3487 use vars qw/@ISA/;
3488 use strict;
3489 use warnings;
3490 use Carp qw/croak/;
3491 use File::Temp qw/tempfile/;
3492 use IO::File qw//;
3493 use vars qw/$_ignore_regex/;
3495 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3496 sub new {
3497         my ($class, $git_svn, $switch_path) = @_;
3498         my $self = SVN::Delta::Editor->new;
3499         bless $self, $class;
3500         if (exists $git_svn->{last_commit}) {
3501                 $self->{c} = $git_svn->{last_commit};
3502                 $self->{empty_symlinks} =
3503                                   _mark_empty_symlinks($git_svn, $switch_path);
3504         }
3505         $self->{ignore_regex} = eval { command_oneline('config', '--get',
3506                              "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3507         $self->{empty} = {};
3508         $self->{dir_prop} = {};
3509         $self->{file_prop} = {};
3510         $self->{absent_dir} = {};
3511         $self->{absent_file} = {};
3512         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3513         $self;
3516 # this uses the Ra object, so it must be called before do_{switch,update},
3517 # not inside them (when the Git::SVN::Fetcher object is passed) to
3518 # do_{switch,update}
3519 sub _mark_empty_symlinks {
3520         my ($git_svn, $switch_path) = @_;
3521         my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3522         return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3524         my %ret;
3525         my ($rev, $cmt) = $git_svn->last_rev_commit;
3526         return {} unless ($rev && $cmt);
3528         # allow the warning to be printed for each revision we fetch to
3529         # ensure the user sees it.  The user can also disable the workaround
3530         # on the repository even while git svn is running and the next
3531         # revision fetched will skip this expensive function.
3532         my $printed_warning;
3533         chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3534         my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3535         local $/ = "\0";
3536         my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3537         $pfx .= '/' if length($pfx);
3538         while (<$ls>) {
3539                 chomp;
3540                 s/\A100644 blob $empty_blob\t//o or next;
3541                 unless ($printed_warning) {
3542                         print STDERR "Scanning for empty symlinks, ",
3543                                      "this may take a while if you have ",
3544                                      "many empty files\n",
3545                                      "You may disable this with `",
3546                                      "git config svn.brokenSymlinkWorkaround ",
3547                                      "false'.\n",
3548                                      "This may be done in a different ",
3549                                      "terminal without restarting ",
3550                                      "git svn\n";
3551                         $printed_warning = 1;
3552                 }
3553                 my $path = $_;
3554                 my (undef, $props) =
3555                                $git_svn->ra->get_file($pfx.$path, $rev, undef);
3556                 if ($props->{'svn:special'}) {
3557                         $ret{$path} = 1;
3558                 }
3559         }
3560         command_close_pipe($ls, $ctx);
3561         \%ret;
3564 # returns true if a given path is inside a ".git" directory
3565 sub in_dot_git {
3566         $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3569 # return value: 0 -- don't ignore, 1 -- ignore
3570 sub is_path_ignored {
3571         my ($self, $path) = @_;
3572         return 1 if in_dot_git($path);
3573         return 1 if defined($self->{ignore_regex}) &&
3574                     $path =~ m!$self->{ignore_regex}!;
3575         return 0 unless defined($_ignore_regex);
3576         return 1 if $path =~ m!$_ignore_regex!o;
3577         return 0;
3580 sub set_path_strip {
3581         my ($self, $path) = @_;
3582         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3585 sub open_root {
3586         { path => '' };
3589 sub open_directory {
3590         my ($self, $path, $pb, $rev) = @_;
3591         { path => $path };
3594 sub git_path {
3595         my ($self, $path) = @_;
3596         if ($self->{path_strip}) {
3597                 $path =~ s!$self->{path_strip}!! or
3598                   die "Failed to strip path '$path' ($self->{path_strip})\n";
3599         }
3600         $path;
3603 sub delete_entry {
3604         my ($self, $path, $rev, $pb) = @_;
3605         return undef if $self->is_path_ignored($path);
3607         my $gpath = $self->git_path($path);
3608         return undef if ($gpath eq '');
3610         # remove entire directories.
3611         my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3612                          =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3613         if ($tree) {
3614                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3615                                                      -r --name-only -z/,
3616                                                      $tree);
3617                 local $/ = "\0";
3618                 while (<$ls>) {
3619                         chomp;
3620                         my $rmpath = "$gpath/$_";
3621                         $self->{gii}->remove($rmpath);
3622                         print "\tD\t$rmpath\n" unless $::_q;
3623                 }
3624                 print "\tD\t$gpath/\n" unless $::_q;
3625                 command_close_pipe($ls, $ctx);
3626                 $self->{empty}->{$path} = 0
3627         } else {
3628                 $self->{gii}->remove($gpath);
3629                 print "\tD\t$gpath\n" unless $::_q;
3630         }
3631         undef;
3634 sub open_file {
3635         my ($self, $path, $pb, $rev) = @_;
3636         my ($mode, $blob);
3638         goto out if $self->is_path_ignored($path);
3640         my $gpath = $self->git_path($path);
3641         ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3642                              =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3643         unless (defined $mode && defined $blob) {
3644                 die "$path was not found in commit $self->{c} (r$rev)\n";
3645         }
3646         if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3647                 $mode = '120000';
3648         }
3649 out:
3650         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3651           pool => SVN::Pool->new, action => 'M' };
3654 sub add_file {
3655         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3656         my $mode;
3658         if (!$self->is_path_ignored($path)) {
3659                 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3660                 delete $self->{empty}->{$dir};
3661                 $mode = '100644';
3662         }
3663         { path => $path, mode_a => $mode, mode_b => $mode,
3664           pool => SVN::Pool->new, action => 'A' };
3667 sub add_directory {
3668         my ($self, $path, $cp_path, $cp_rev) = @_;
3669         goto out if $self->is_path_ignored($path);
3670         my $gpath = $self->git_path($path);
3671         if ($gpath eq '') {
3672                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3673                                                      -r --name-only -z/,
3674                                                      $self->{c});
3675                 local $/ = "\0";
3676                 while (<$ls>) {
3677                         chomp;
3678                         $self->{gii}->remove($_);
3679                         print "\tD\t$_\n" unless $::_q;
3680                 }
3681                 command_close_pipe($ls, $ctx);
3682                 $self->{empty}->{$path} = 0;
3683         }
3684         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3685         delete $self->{empty}->{$dir};
3686         $self->{empty}->{$path} = 1;
3687 out:
3688         { path => $path };
3691 sub change_dir_prop {
3692         my ($self, $db, $prop, $value) = @_;
3693         return undef if $self->is_path_ignored($db->{path});
3694         $self->{dir_prop}->{$db->{path}} ||= {};
3695         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3696         undef;
3699 sub absent_directory {
3700         my ($self, $path, $pb) = @_;
3701         return undef if $self->is_path_ignored($path);
3702         $self->{absent_dir}->{$pb->{path}} ||= [];
3703         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3704         undef;
3707 sub absent_file {
3708         my ($self, $path, $pb) = @_;
3709         return undef if $self->is_path_ignored($path);
3710         $self->{absent_file}->{$pb->{path}} ||= [];
3711         push @{$self->{absent_file}->{$pb->{path}}}, $path;
3712         undef;
3715 sub change_file_prop {
3716         my ($self, $fb, $prop, $value) = @_;
3717         return undef if $self->is_path_ignored($fb->{path});
3718         if ($prop eq 'svn:executable') {
3719                 if ($fb->{mode_b} != 120000) {
3720                         $fb->{mode_b} = defined $value ? 100755 : 100644;
3721                 }
3722         } elsif ($prop eq 'svn:special') {
3723                 $fb->{mode_b} = defined $value ? 120000 : 100644;
3724         } else {
3725                 $self->{file_prop}->{$fb->{path}} ||= {};
3726                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3727         }
3728         undef;
3731 sub apply_textdelta {
3732         my ($self, $fb, $exp) = @_;
3733         return undef if $self->is_path_ignored($fb->{path});
3734         my $fh = $::_repository->temp_acquire('svn_delta');
3735         # $fh gets auto-closed() by SVN::TxDelta::apply(),
3736         # (but $base does not,) so dup() it for reading in close_file
3737         open my $dup, '<&', $fh or croak $!;
3738         my $base = $::_repository->temp_acquire('git_blob');
3740         if ($fb->{blob}) {
3741                 my ($base_is_link, $size);
3743                 if ($fb->{mode_a} eq '120000' &&
3744                     ! $self->{empty_symlinks}->{$fb->{path}}) {
3745                         print $base 'link ' or die "print $!\n";
3746                         $base_is_link = 1;
3747                 }
3748         retry:
3749                 $size = $::_repository->cat_blob($fb->{blob}, $base);
3750                 die "Failed to read object $fb->{blob}" if ($size < 0);
3752                 if (defined $exp) {
3753                         seek $base, 0, 0 or croak $!;
3754                         my $got = ::md5sum($base);
3755                         if ($got ne $exp) {
3756                                 my $err = "Checksum mismatch: ".
3757                                        "$fb->{path} $fb->{blob}\n" .
3758                                        "expected: $exp\n" .
3759                                        "     got: $got\n";
3760                                 if ($base_is_link) {
3761                                         warn $err,
3762                                              "Retrying... (possibly ",
3763                                              "a bad symlink from SVN)\n";
3764                                         $::_repository->temp_reset($base);
3765                                         $base_is_link = 0;
3766                                         goto retry;
3767                                 }
3768                                 die $err;
3769                         }
3770                 }
3771         }
3772         seek $base, 0, 0 or croak $!;
3773         $fb->{fh} = $fh;
3774         $fb->{base} = $base;
3775         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3778 sub close_file {
3779         my ($self, $fb, $exp) = @_;
3780         return undef if $self->is_path_ignored($fb->{path});
3782         my $hash;
3783         my $path = $self->git_path($fb->{path});
3784         if (my $fh = $fb->{fh}) {
3785                 if (defined $exp) {
3786                         seek($fh, 0, 0) or croak $!;
3787                         my $got = ::md5sum($fh);
3788                         if ($got ne $exp) {
3789                                 die "Checksum mismatch: $path\n",
3790                                     "expected: $exp\n    got: $got\n";
3791                         }
3792                 }
3793                 if ($fb->{mode_b} == 120000) {
3794                         sysseek($fh, 0, 0) or croak $!;
3795                         my $rd = sysread($fh, my $buf, 5);
3797                         if (!defined $rd) {
3798                                 croak "sysread: $!\n";
3799                         } elsif ($rd == 0) {
3800                                 warn "$path has mode 120000",
3801                                      " but it points to nothing\n",
3802                                      "converting to an empty file with mode",
3803                                      " 100644\n";
3804                                 $fb->{mode_b} = '100644';
3805                         } elsif ($buf ne 'link ') {
3806                                 warn "$path has mode 120000",
3807                                      " but is not a link\n";
3808                         } else {
3809                                 my $tmp_fh = $::_repository->temp_acquire(
3810                                         'svn_hash');
3811                                 my $res;
3812                                 while ($res = sysread($fh, my $str, 1024)) {
3813                                         my $out = syswrite($tmp_fh, $str, $res);
3814                                         defined($out) && $out == $res
3815                                                 or croak("write ",
3816                                                         Git::temp_path($tmp_fh),
3817                                                         ": $!\n");
3818                                 }
3819                                 defined $res or croak $!;
3821                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3822                                 Git::temp_release($tmp_fh, 1);
3823                         }
3824                 }
3826                 $hash = $::_repository->hash_and_insert_object(
3827                                 Git::temp_path($fh));
3828                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3830                 Git::temp_release($fb->{base}, 1);
3831                 Git::temp_release($fh, 1);
3832         } else {
3833                 $hash = $fb->{blob} or die "no blob information\n";
3834         }
3835         $fb->{pool}->clear;
3836         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3837         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3838         undef;
3841 sub abort_edit {
3842         my $self = shift;
3843         $self->{nr} = $self->{gii}->{nr};
3844         delete $self->{gii};
3845         $self->SUPER::abort_edit(@_);
3848 sub close_edit {
3849         my $self = shift;
3850         $self->{git_commit_ok} = 1;
3851         $self->{nr} = $self->{gii}->{nr};
3852         delete $self->{gii};
3853         $self->SUPER::close_edit(@_);
3856 package SVN::Git::Editor;
3857 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3858 use strict;
3859 use warnings;
3860 use Carp qw/croak/;
3861 use IO::File;
3863 sub new {
3864         my ($class, $opts) = @_;
3865         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3866                 die "$_ required!\n" unless (defined $opts->{$_});
3867         }
3869         my $pool = SVN::Pool->new;
3870         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3871         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3872                                      $opts->{r}, $mods);
3874         # $opts->{ra} functions should not be used after this:
3875         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
3876                                                 $opts->{editor_cb}, $pool);
3877         my $self = SVN::Delta::Editor->new(@ce, $pool);
3878         bless $self, $class;
3879         foreach (qw/svn_path r tree_a tree_b/) {
3880                 $self->{$_} = $opts->{$_};
3881         }
3882         $self->{url} = $opts->{ra}->{url};
3883         $self->{mods} = $mods;
3884         $self->{types} = $types;
3885         $self->{pool} = $pool;
3886         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3887         $self->{rm} = { };
3888         $self->{path_prefix} = length $self->{svn_path} ?
3889                                "$self->{svn_path}/" : '';
3890         $self->{config} = $opts->{config};
3891         return $self;
3894 sub generate_diff {
3895         my ($tree_a, $tree_b) = @_;
3896         my @diff_tree = qw(diff-tree -z -r);
3897         if ($_cp_similarity) {
3898                 push @diff_tree, "-C$_cp_similarity";
3899         } else {
3900                 push @diff_tree, '-C';
3901         }
3902         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3903         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3904         push @diff_tree, $tree_a, $tree_b;
3905         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3906         local $/ = "\0";
3907         my $state = 'meta';
3908         my @mods;
3909         while (<$diff_fh>) {
3910                 chomp $_; # this gets rid of the trailing "\0"
3911                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3912                                         ($::sha1)\s($::sha1)\s
3913                                         ([MTCRAD])\d*$/xo) {
3914                         push @mods, {   mode_a => $1, mode_b => $2,
3915                                         sha1_a => $3, sha1_b => $4,
3916                                         chg => $5 };
3917                         if ($5 =~ /^(?:C|R)$/) {
3918                                 $state = 'file_a';
3919                         } else {
3920                                 $state = 'file_b';
3921                         }
3922                 } elsif ($state eq 'file_a') {
3923                         my $x = $mods[$#mods] or croak "Empty array\n";
3924                         if ($x->{chg} !~ /^(?:C|R)$/) {
3925                                 croak "Error parsing $_, $x->{chg}\n";
3926                         }
3927                         $x->{file_a} = $_;
3928                         $state = 'file_b';
3929                 } elsif ($state eq 'file_b') {
3930                         my $x = $mods[$#mods] or croak "Empty array\n";
3931                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3932                                 croak "Error parsing $_, $x->{chg}\n";
3933                         }
3934                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3935                                 croak "Error parsing $_, $x->{chg}\n";
3936                         }
3937                         $x->{file_b} = $_;
3938                         $state = 'meta';
3939                 } else {
3940                         croak "Error parsing $_\n";
3941                 }
3942         }
3943         command_close_pipe($diff_fh, $ctx);
3944         \@mods;
3947 sub check_diff_paths {
3948         my ($ra, $pfx, $rev, $mods) = @_;
3949         my %types;
3950         $pfx .= '/' if length $pfx;
3952         sub type_diff_paths {
3953                 my ($ra, $types, $path, $rev) = @_;
3954                 my @p = split m#/+#, $path;
3955                 my $c = shift @p;
3956                 unless (defined $types->{$c}) {
3957                         $types->{$c} = $ra->check_path($c, $rev);
3958                 }
3959                 while (@p) {
3960                         $c .= '/' . shift @p;
3961                         next if defined $types->{$c};
3962                         $types->{$c} = $ra->check_path($c, $rev);
3963                 }
3964         }
3966         foreach my $m (@$mods) {
3967                 foreach my $f (qw/file_a file_b/) {
3968                         next unless defined $m->{$f};
3969                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3970                         if (length $pfx.$dir && ! defined $types{$dir}) {
3971                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3972                         }
3973                 }
3974         }
3975         \%types;
3978 sub split_path {
3979         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3982 sub repo_path {
3983         my ($self, $path) = @_;
3984         $self->{path_prefix}.(defined $path ? $path : '');
3987 sub url_path {
3988         my ($self, $path) = @_;
3989         if ($self->{url} =~ m#^https?://#) {
3990                 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3991         }
3992         $self->{url} . '/' . $self->repo_path($path);
3995 sub rmdirs {
3996         my ($self) = @_;
3997         my $rm = $self->{rm};
3998         delete $rm->{''}; # we never delete the url we're tracking
3999         return unless %$rm;
4001         foreach (keys %$rm) {
4002                 my @d = split m#/#, $_;
4003                 my $c = shift @d;
4004                 $rm->{$c} = 1;
4005                 while (@d) {
4006                         $c .= '/' . shift @d;
4007                         $rm->{$c} = 1;
4008                 }
4009         }
4010         delete $rm->{$self->{svn_path}};
4011         delete $rm->{''}; # we never delete the url we're tracking
4012         return unless %$rm;
4014         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4015                                              $self->{tree_b});
4016         local $/ = "\0";
4017         while (<$fh>) {
4018                 chomp;
4019                 my @dn = split m#/#, $_;
4020                 while (pop @dn) {
4021                         delete $rm->{join '/', @dn};
4022                 }
4023                 unless (%$rm) {
4024                         close $fh;
4025                         return;
4026                 }
4027         }
4028         command_close_pipe($fh, $ctx);
4030         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4031         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4032                 $self->close_directory($bat->{$d}, $p);
4033                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4034                 print "\tD+\t$d/\n" unless $::_q;
4035                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4036                 delete $bat->{$d};
4037         }
4040 sub open_or_add_dir {
4041         my ($self, $full_path, $baton) = @_;
4042         my $t = $self->{types}->{$full_path};
4043         if (!defined $t) {
4044                 die "$full_path not known in r$self->{r} or we have a bug!\n";
4045         }
4046         {
4047                 no warnings 'once';
4048                 # SVN::Node::none and SVN::Node::file are used only once,
4049                 # so we're shutting up Perl's warnings about them.
4050                 if ($t == $SVN::Node::none) {
4051                         return $self->add_directory($full_path, $baton,
4052                             undef, -1, $self->{pool});
4053                 } elsif ($t == $SVN::Node::dir) {
4054                         return $self->open_directory($full_path, $baton,
4055                             $self->{r}, $self->{pool});
4056                 } # no warnings 'once'
4057                 print STDERR "$full_path already exists in repository at ",
4058                     "r$self->{r} and it is not a directory (",
4059                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4060         } # no warnings 'once'
4061         exit 1;
4064 sub ensure_path {
4065         my ($self, $path) = @_;
4066         my $bat = $self->{bat};
4067         my $repo_path = $self->repo_path($path);
4068         return $bat->{''} unless (length $repo_path);
4069         my @p = split m#/+#, $repo_path;
4070         my $c = shift @p;
4071         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4072         while (@p) {
4073                 my $c0 = $c;
4074                 $c .= '/' . shift @p;
4075                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4076         }
4077         return $bat->{$c};
4080 # Subroutine to convert a globbing pattern to a regular expression.
4081 # From perl cookbook.
4082 sub glob2pat {
4083         my $globstr = shift;
4084         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4085         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4086         return '^' . $globstr . '$';
4089 sub check_autoprop {
4090         my ($self, $pattern, $properties, $file, $fbat) = @_;
4091         # Convert the globbing pattern to a regular expression.
4092         my $regex = glob2pat($pattern);
4093         # Check if the pattern matches the file name.
4094         if($file =~ m/($regex)/) {
4095                 # Parse the list of properties to set.
4096                 my @props = split(/;/, $properties);
4097                 foreach my $prop (@props) {
4098                         # Parse 'name=value' syntax and set the property.
4099                         if ($prop =~ /([^=]+)=(.*)/) {
4100                                 my ($n,$v) = ($1,$2);
4101                                 for ($n, $v) {
4102                                         s/^\s+//; s/\s+$//;
4103                                 }
4104                                 $self->change_file_prop($fbat, $n, $v);
4105                         }
4106                 }
4107         }
4110 sub apply_autoprops {
4111         my ($self, $file, $fbat) = @_;
4112         my $conf_t = ${$self->{config}}{'config'};
4113         no warnings 'once';
4114         # Check [miscellany]/enable-auto-props in svn configuration.
4115         if (SVN::_Core::svn_config_get_bool(
4116                 $conf_t,
4117                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4118                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4119                 0)) {
4120                 # Auto-props are enabled.  Enumerate them to look for matches.
4121                 my $callback = sub {
4122                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
4123                 };
4124                 SVN::_Core::svn_config_enumerate(
4125                         $conf_t,
4126                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4127                         $callback);
4128         }
4131 sub A {
4132         my ($self, $m) = @_;
4133         my ($dir, $file) = split_path($m->{file_b});
4134         my $pbat = $self->ensure_path($dir);
4135         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4136                                         undef, -1);
4137         print "\tA\t$m->{file_b}\n" unless $::_q;
4138         $self->apply_autoprops($file, $fbat);
4139         $self->chg_file($fbat, $m);
4140         $self->close_file($fbat,undef,$self->{pool});
4143 sub C {
4144         my ($self, $m) = @_;
4145         my ($dir, $file) = split_path($m->{file_b});
4146         my $pbat = $self->ensure_path($dir);
4147         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4148                                 $self->url_path($m->{file_a}), $self->{r});
4149         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4150         $self->chg_file($fbat, $m);
4151         $self->close_file($fbat,undef,$self->{pool});
4154 sub delete_entry {
4155         my ($self, $path, $pbat) = @_;
4156         my $rpath = $self->repo_path($path);
4157         my ($dir, $file) = split_path($rpath);
4158         $self->{rm}->{$dir} = 1;
4159         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4162 sub R {
4163         my ($self, $m) = @_;
4164         my ($dir, $file) = split_path($m->{file_b});
4165         my $pbat = $self->ensure_path($dir);
4166         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4167                                 $self->url_path($m->{file_a}), $self->{r});
4168         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4169         $self->apply_autoprops($file, $fbat);
4170         $self->chg_file($fbat, $m);
4171         $self->close_file($fbat,undef,$self->{pool});
4173         ($dir, $file) = split_path($m->{file_a});
4174         $pbat = $self->ensure_path($dir);
4175         $self->delete_entry($m->{file_a}, $pbat);
4178 sub M {
4179         my ($self, $m) = @_;
4180         my ($dir, $file) = split_path($m->{file_b});
4181         my $pbat = $self->ensure_path($dir);
4182         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4183                                 $pbat,$self->{r},$self->{pool});
4184         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4185         $self->chg_file($fbat, $m);
4186         $self->close_file($fbat,undef,$self->{pool});
4189 sub T { shift->M(@_) }
4191 sub change_file_prop {
4192         my ($self, $fbat, $pname, $pval) = @_;
4193         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4196 sub _chg_file_get_blob ($$$$) {
4197         my ($self, $fbat, $m, $which) = @_;
4198         my $fh = $::_repository->temp_acquire("git_blob_$which");
4199         if ($m->{"mode_$which"} =~ /^120/) {
4200                 print $fh 'link ' or croak $!;
4201                 $self->change_file_prop($fbat,'svn:special','*');
4202         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4203                 $self->change_file_prop($fbat,'svn:special',undef);
4204         }
4205         my $blob = $m->{"sha1_$which"};
4206         return ($fh,) if ($blob =~ /^0{40}$/);
4207         my $size = $::_repository->cat_blob($blob, $fh);
4208         croak "Failed to read object $blob" if ($size < 0);
4209         $fh->flush == 0 or croak $!;
4210         seek $fh, 0, 0 or croak $!;
4212         my $exp = ::md5sum($fh);
4213         seek $fh, 0, 0 or croak $!;
4214         return ($fh, $exp);
4217 sub chg_file {
4218         my ($self, $fbat, $m) = @_;
4219         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4220                 $self->change_file_prop($fbat,'svn:executable','*');
4221         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4222                 $self->change_file_prop($fbat,'svn:executable',undef);
4223         }
4224         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4225         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4226         my $pool = SVN::Pool->new;
4227         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4228         if (-s $fh_a) {
4229                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4230                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4231                 if (defined $res) {
4232                         die "Unexpected result from send_txstream: $res\n",
4233                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4234                 }
4235         } else {
4236                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4237                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4238                     if ($got ne $exp_b);
4239         }
4240         Git::temp_release($fh_b, 1);
4241         Git::temp_release($fh_a, 1);
4242         $pool->clear;
4245 sub D {
4246         my ($self, $m) = @_;
4247         my ($dir, $file) = split_path($m->{file_b});
4248         my $pbat = $self->ensure_path($dir);
4249         print "\tD\t$m->{file_b}\n" unless $::_q;
4250         $self->delete_entry($m->{file_b}, $pbat);
4253 sub close_edit {
4254         my ($self) = @_;
4255         my ($p,$bat) = ($self->{pool}, $self->{bat});
4256         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4257                 next if $_ eq '';
4258                 $self->close_directory($bat->{$_}, $p);
4259         }
4260         $self->close_directory($bat->{''}, $p);
4261         $self->SUPER::close_edit($p);
4262         $p->clear;
4265 sub abort_edit {
4266         my ($self) = @_;
4267         $self->SUPER::abort_edit($self->{pool});
4270 sub DESTROY {
4271         my $self = shift;
4272         $self->SUPER::DESTROY(@_);
4273         $self->{pool}->clear;
4276 # this drives the editor
4277 sub apply_diff {
4278         my ($self) = @_;
4279         my $mods = $self->{mods};
4280         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4281         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4282                 my $f = $m->{chg};
4283                 if (defined $o{$f}) {
4284                         $self->$f($m);
4285                 } else {
4286                         fatal("Invalid change type: $f");
4287                 }
4288         }
4289         $self->rmdirs if $_rmdir;
4290         if (@$mods == 0) {
4291                 $self->abort_edit;
4292         } else {
4293                 $self->close_edit;
4294         }
4295         return scalar @$mods;
4298 package Git::SVN::Ra;
4299 use vars qw/@ISA $config_dir $_log_window_size/;
4300 use strict;
4301 use warnings;
4302 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4304 BEGIN {
4305         # enforce temporary pool usage for some simple functions
4306         no strict 'refs';
4307         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4308                       get_file/) {
4309                 my $SUPER = "SUPER::$f";
4310                 *$f = sub {
4311                         my $self = shift;
4312                         my $pool = SVN::Pool->new;
4313                         my @ret = $self->$SUPER(@_,$pool);
4314                         $pool->clear;
4315                         wantarray ? @ret : $ret[0];
4316                 };
4317         }
4320 sub _auth_providers () {
4321         [
4322           SVN::Client::get_simple_provider(),
4323           SVN::Client::get_ssl_server_trust_file_provider(),
4324           SVN::Client::get_simple_prompt_provider(
4325             \&Git::SVN::Prompt::simple, 2),
4326           SVN::Client::get_ssl_client_cert_file_provider(),
4327           SVN::Client::get_ssl_client_cert_prompt_provider(
4328             \&Git::SVN::Prompt::ssl_client_cert, 2),
4329           SVN::Client::get_ssl_client_cert_pw_file_provider(),
4330           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4331             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4332           SVN::Client::get_username_provider(),
4333           SVN::Client::get_ssl_server_trust_prompt_provider(
4334             \&Git::SVN::Prompt::ssl_server_trust),
4335           SVN::Client::get_username_prompt_provider(
4336             \&Git::SVN::Prompt::username, 2)
4337         ]
4340 sub escape_uri_only {
4341         my ($uri) = @_;
4342         my @tmp;
4343         foreach (split m{/}, $uri) {
4344                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4345                 push @tmp, $_;
4346         }
4347         join('/', @tmp);
4350 sub escape_url {
4351         my ($url) = @_;
4352         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4353                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4354                 $url = "$scheme://$domain$uri";
4355         }
4356         $url;
4359 sub new {
4360         my ($class, $url) = @_;
4361         $url =~ s!/+$!!;
4362         return $RA if ($RA && $RA->{url} eq $url);
4364         SVN::_Core::svn_config_ensure($config_dir, undef);
4365         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4366         my $config = SVN::Core::config_get_config($config_dir);
4367         $RA = undef;
4368         my $dont_store_passwords = 1;
4369         my $conf_t = ${$config}{'config'};
4370         {
4371                 no warnings 'once';
4372                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4373                 # produces warnings that variables are used only once.
4374                 # I had not found the better way to shut them up, so
4375                 # the warnings of type 'once' are disabled in this block.
4376                 if (SVN::_Core::svn_config_get_bool($conf_t,
4377                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4378                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4379                     1) == 0) {
4380                         SVN::_Core::svn_auth_set_parameter($baton,
4381                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4382                             bless (\$dont_store_passwords, "_p_void"));
4383                 }
4384                 if (SVN::_Core::svn_config_get_bool($conf_t,
4385                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4386                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4387                     1) == 0) {
4388                         $Git::SVN::Prompt::_no_auth_cache = 1;
4389                 }
4390         } # no warnings 'once'
4391         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4392                               config => $config,
4393                               pool => SVN::Pool->new,
4394                               auth_provider_callbacks => $callbacks);
4395         $self->{url} = $url;
4396         $self->{svn_path} = $url;
4397         $self->{repos_root} = $self->get_repos_root;
4398         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4399         $self->{cache} = { check_path => { r => 0, data => {} },
4400                            get_dir => { r => 0, data => {} } };
4401         $RA = bless $self, $class;
4404 sub check_path {
4405         my ($self, $path, $r) = @_;
4406         my $cache = $self->{cache}->{check_path};
4407         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4408                 return $cache->{data}->{$path};
4409         }
4410         my $pool = SVN::Pool->new;
4411         my $t = $self->SUPER::check_path($path, $r, $pool);
4412         $pool->clear;
4413         if ($r != $cache->{r}) {
4414                 %{$cache->{data}} = ();
4415                 $cache->{r} = $r;
4416         }
4417         $cache->{data}->{$path} = $t;
4420 sub get_dir {
4421         my ($self, $dir, $r) = @_;
4422         my $cache = $self->{cache}->{get_dir};
4423         if ($r == $cache->{r}) {
4424                 if (my $x = $cache->{data}->{$dir}) {
4425                         return wantarray ? @$x : $x->[0];
4426                 }
4427         }
4428         my $pool = SVN::Pool->new;
4429         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4430         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4431         $pool->clear;
4432         if ($r != $cache->{r}) {
4433                 %{$cache->{data}} = ();
4434                 $cache->{r} = $r;
4435         }
4436         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4437         wantarray ? (\%dirents, $r, $props) : \%dirents;
4440 sub DESTROY {
4441         # do not call the real DESTROY since we store ourselves in $RA
4444 # get_log(paths, start, end, limit,
4445 #         discover_changed_paths, strict_node_history, receiver)
4446 sub get_log {
4447         my ($self, @args) = @_;
4448         my $pool = SVN::Pool->new;
4450         # svn_log_changed_path_t objects passed to get_log are likely to be
4451         # overwritten even if only the refs are copied to an external variable,
4452         # so we should dup the structures in their entirety.  Using an
4453         # externally passed pool (instead of our temporary and quickly cleared
4454         # pool in Git::SVN::Ra) does not help matters at all...
4455         my $receiver = pop @args;
4456         my $prefix = "/".$self->{svn_path};
4457         $prefix =~ s#/+($)##;
4458         my $prefix_regex = qr#^\Q$prefix\E#;
4459         push(@args, sub {
4460                 my ($paths) = $_[0];
4461                 return &$receiver(@_) unless $paths;
4462                 $_[0] = ();
4463                 foreach my $p (keys %$paths) {
4464                         my $i = $paths->{$p};
4465                         # Make path relative to our url, not repos_root
4466                         $p =~ s/$prefix_regex//;
4467                         my %s = map { $_ => $i->$_; }
4468                                 qw/copyfrom_path copyfrom_rev action/;
4469                         if ($s{'copyfrom_path'}) {
4470                                 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4471                         }
4472                         $_[0]{$p} = \%s;
4473                 }
4474                 &$receiver(@_);
4475         });
4478         # the limit parameter was not supported in SVN 1.1.x, so we
4479         # drop it.  Therefore, the receiver callback passed to it
4480         # is made aware of this limitation by being wrapped if
4481         # the limit passed to is being wrapped.
4482         if ($SVN::Core::VERSION le '1.2.0') {
4483                 my $limit = splice(@args, 3, 1);
4484                 if ($limit > 0) {
4485                         my $receiver = pop @args;
4486                         push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4487                 }
4488         }
4489         my $ret = $self->SUPER::get_log(@args, $pool);
4490         $pool->clear;
4491         $ret;
4494 sub trees_match {
4495         my ($self, $url1, $rev1, $url2, $rev2) = @_;
4496         my $ctx = SVN::Client->new(auth => _auth_providers);
4497         my $out = IO::File->new_tmpfile;
4499         # older SVN (1.1.x) doesn't take $pool as the last parameter for
4500         # $ctx->diff(), so we'll create a default one
4501         my $pool = SVN::Pool->new_default_sub;
4503         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4504         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4505         $out->flush;
4506         my $ret = (($out->stat)[7] == 0);
4507         close $out or croak $!;
4509         $ret;
4512 sub get_commit_editor {
4513         my ($self, $log, $cb, $pool) = @_;
4514         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4515         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4518 sub gs_do_update {
4519         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4520         my $new = ($rev_a == $rev_b);
4521         my $path = $gs->{path};
4523         if ($new && -e $gs->{index}) {
4524                 unlink $gs->{index} or die
4525                   "Couldn't unlink index: $gs->{index}: $!\n";
4526         }
4527         my $pool = SVN::Pool->new;
4528         $editor->set_path_strip($path);
4529         my (@pc) = split m#/#, $path;
4530         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4531                                         1, $editor, $pool);
4532         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4534         # Since we can't rely on svn_ra_reparent being available, we'll
4535         # just have to do some magic with set_path to make it so
4536         # we only want a partial path.
4537         my $sp = '';
4538         my $final = join('/', @pc);
4539         while (@pc) {
4540                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4541                 $sp .= '/' if length $sp;
4542                 $sp .= shift @pc;
4543         }
4544         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4546         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4548         $reporter->finish_report($pool);
4549         $pool->clear;
4550         $editor->{git_commit_ok};
4553 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4554 # svn_ra_reparent didn't work before 1.4)
4555 sub gs_do_switch {
4556         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4557         my $path = $gs->{path};
4558         my $pool = SVN::Pool->new;
4560         my $full_url = $self->{url};
4561         my $old_url = $full_url;
4562         $full_url .= '/' . $path if length $path;
4563         my ($ra, $reparented);
4565         if ($old_url =~ m#^svn(\+ssh)?://# ||
4566             ($full_url =~ m#^https?://# &&
4567              escape_url($full_url) ne $full_url)) {
4568                 $_[0] = undef;
4569                 $self = undef;
4570                 $RA = undef;
4571                 $ra = Git::SVN::Ra->new($full_url);
4572                 $ra_invalid = 1;
4573         } elsif ($old_url ne $full_url) {
4574                 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4575                 $self->{url} = $full_url;
4576                 $reparented = 1;
4577         }
4579         $ra ||= $self;
4580         $url_b = escape_url($url_b);
4581         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4582         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4583         $reporter->set_path('', $rev_a, 0, @lock, $pool);
4584         $reporter->finish_report($pool);
4586         if ($reparented) {
4587                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4588                 $self->{url} = $old_url;
4589         }
4591         $pool->clear;
4592         $editor->{git_commit_ok};
4595 sub longest_common_path {
4596         my ($gsv, $globs) = @_;
4597         my %common;
4598         my $common_max = scalar @$gsv;
4600         foreach my $gs (@$gsv) {
4601                 my @tmp = split m#/#, $gs->{path};
4602                 my $p = '';
4603                 foreach (@tmp) {
4604                         $p .= length($p) ? "/$_" : $_;
4605                         $common{$p} ||= 0;
4606                         $common{$p}++;
4607                 }
4608         }
4609         $globs ||= [];
4610         $common_max += scalar @$globs;
4611         foreach my $glob (@$globs) {
4612                 my @tmp = split m#/#, $glob->{path}->{left};
4613                 my $p = '';
4614                 foreach (@tmp) {
4615                         $p .= length($p) ? "/$_" : $_;
4616                         $common{$p} ||= 0;
4617                         $common{$p}++;
4618                 }
4619         }
4621         my $longest_path = '';
4622         foreach (sort {length $b <=> length $a} keys %common) {
4623                 if ($common{$_} == $common_max) {
4624                         $longest_path = $_;
4625                         last;
4626                 }
4627         }
4628         $longest_path;
4631 sub gs_fetch_loop_common {
4632         my ($self, $base, $head, $gsv, $globs) = @_;
4633         return if ($base > $head);
4634         my $inc = $_log_window_size;
4635         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4636         my $longest_path = longest_common_path($gsv, $globs);
4637         my $ra_url = $self->{url};
4638         my $find_trailing_edge;
4639         while (1) {
4640                 my %revs;
4641                 my $err;
4642                 my $err_handler = $SVN::Error::handler;
4643                 $SVN::Error::handler = sub {
4644                         ($err) = @_;
4645                         skip_unknown_revs($err);
4646                 };
4647                 sub _cb {
4648                         my ($paths, $r, $author, $date, $log) = @_;
4649                         [ $paths,
4650                           { author => $author, date => $date, log => $log } ];
4651                 }
4652                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4653                                sub { $revs{$_[1]} = _cb(@_) });
4654                 if ($err) {
4655                         print "Checked through r$max\r";
4656                 } else {
4657                         $find_trailing_edge = 1;
4658                 }
4659                 if ($err and $find_trailing_edge) {
4660                         print STDERR "Path '$longest_path' ",
4661                                      "was probably deleted:\n",
4662                                      $err->expanded_message,
4663                                      "\nWill attempt to follow ",
4664                                      "revisions r$min .. r$max ",
4665                                      "committed before the deletion\n";
4666                         my $hi = $max;
4667                         while (--$hi >= $min) {
4668                                 my $ok;
4669                                 $self->get_log([$longest_path], $min, $hi,
4670                                                0, 1, 1, sub {
4671                                                $ok = $_[1];
4672                                                $revs{$_[1]} = _cb(@_) });
4673                                 if ($ok) {
4674                                         print STDERR "r$min .. r$ok OK\n";
4675                                         last;
4676                                 }
4677                         }
4678                         $find_trailing_edge = 0;
4679                 }
4680                 $SVN::Error::handler = $err_handler;
4682                 my %exists = map { $_->{path} => $_ } @$gsv;
4683                 foreach my $r (sort {$a <=> $b} keys %revs) {
4684                         my ($paths, $logged) = @{$revs{$r}};
4686                         foreach my $gs ($self->match_globs(\%exists, $paths,
4687                                                            $globs, $r)) {
4688                                 if ($gs->rev_map_max >= $r) {
4689                                         next;
4690                                 }
4691                                 next unless $gs->match_paths($paths, $r);
4692                                 $gs->{logged_rev_props} = $logged;
4693                                 if (my $last_commit = $gs->last_commit) {
4694                                         $gs->assert_index_clean($last_commit);
4695                                 }
4696                                 my $log_entry = $gs->do_fetch($paths, $r);
4697                                 if ($log_entry) {
4698                                         $gs->do_git_commit($log_entry);
4699                                 }
4700                                 $INDEX_FILES{$gs->{index}} = 1;
4701                         }
4702                         foreach my $g (@$globs) {
4703                                 my $k = "svn-remote.$g->{remote}." .
4704                                         "$g->{t}-maxRev";
4705                                 Git::SVN::tmp_config($k, $r);
4706                         }
4707                         if ($ra_invalid) {
4708                                 $_[0] = undef;
4709                                 $self = undef;
4710                                 $RA = undef;
4711                                 $self = Git::SVN::Ra->new($ra_url);
4712                                 $ra_invalid = undef;
4713                         }
4714                 }
4715                 # pre-fill the .rev_db since it'll eventually get filled in
4716                 # with '0' x40 if something new gets committed
4717                 foreach my $gs (@$gsv) {
4718                         next if $gs->rev_map_max >= $max;
4719                         next if defined $gs->rev_map_get($max);
4720                         $gs->rev_map_set($max, 0 x40);
4721                 }
4722                 foreach my $g (@$globs) {
4723                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4724                         Git::SVN::tmp_config($k, $max);
4725                 }
4726                 last if $max >= $head;
4727                 $min = $max + 1;
4728                 $max += $inc;
4729                 $max = $head if ($max > $head);
4730         }
4731         Git::SVN::gc();
4734 sub get_dir_globbed {
4735         my ($self, $left, $depth, $r) = @_;
4737         my @x = eval { $self->get_dir($left, $r) };
4738         return unless scalar @x == 3;
4739         my $dirents = $x[0];
4740         my @finalents;
4741         foreach my $de (keys %$dirents) {
4742                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4743                 if ($depth > 1) {
4744                         my @args = ("$left/$de", $depth - 1, $r);
4745                         foreach my $dir ($self->get_dir_globbed(@args)) {
4746                                 push @finalents, "$de/$dir";
4747                         }
4748                 } else {
4749                         push @finalents, $de;
4750                 }
4751         }
4752         @finalents;
4755 sub match_globs {
4756         my ($self, $exists, $paths, $globs, $r) = @_;
4758         sub get_dir_check {
4759                 my ($self, $exists, $g, $r) = @_;
4761                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4762                                                   $g->{path}->{depth},
4763                                                   $r);
4765                 foreach my $de (@dirs) {
4766                         my $p = $g->{path}->full_path($de);
4767                         next if $exists->{$p};
4768                         next if (length $g->{path}->{right} &&
4769                                  ($self->check_path($p, $r) !=
4770                                   $SVN::Node::dir));
4771                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4772                                          $g->{ref}->full_path($de), 1);
4773                 }
4774         }
4775         foreach my $g (@$globs) {
4776                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4777                         if ($path->{action} =~ /^[AR]$/) {
4778                                 get_dir_check($self, $exists, $g, $r);
4779                         }
4780                 }
4781                 foreach (keys %$paths) {
4782                         if (/$g->{path}->{left_regex}/ &&
4783                             !/$g->{path}->{regex}/) {
4784                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
4785                                 get_dir_check($self, $exists, $g, $r);
4786                         }
4787                         next unless /$g->{path}->{regex}/;
4788                         my $p = $1;
4789                         my $pathname = $g->{path}->full_path($p);
4790                         next if $exists->{$pathname};
4791                         next if ($self->check_path($pathname, $r) !=
4792                                  $SVN::Node::dir);
4793                         $exists->{$pathname} = Git::SVN->init(
4794                                               $self->{url}, $pathname, undef,
4795                                               $g->{ref}->full_path($p), 1);
4796                 }
4797                 my $c = '';
4798                 foreach (split m#/#, $g->{path}->{left}) {
4799                         $c .= "/$_";
4800                         next unless ($paths->{$c} &&
4801                                      ($paths->{$c}->{action} =~ /^[AR]$/));
4802                         get_dir_check($self, $exists, $g, $r);
4803                 }
4804         }
4805         values %$exists;
4808 sub minimize_url {
4809         my ($self) = @_;
4810         return $self->{url} if ($self->{url} eq $self->{repos_root});
4811         my $url = $self->{repos_root};
4812         my @components = split(m!/!, $self->{svn_path});
4813         my $c = '';
4814         do {
4815                 $url .= "/$c" if length $c;
4816                 eval { (ref $self)->new($url)->get_latest_revnum };
4817         } while ($@ && ($c = shift @components));
4818         $url;
4821 sub can_do_switch {
4822         my $self = shift;
4823         unless (defined $can_do_switch) {
4824                 my $pool = SVN::Pool->new;
4825                 my $rep = eval {
4826                         $self->do_switch(1, '', 0, $self->{url},
4827                                          SVN::Delta::Editor->new, $pool);
4828                 };
4829                 if ($@) {
4830                         $can_do_switch = 0;
4831                 } else {
4832                         $rep->abort_report($pool);
4833                         $can_do_switch = 1;
4834                 }
4835                 $pool->clear;
4836         }
4837         $can_do_switch;
4840 sub skip_unknown_revs {
4841         my ($err) = @_;
4842         my $errno = $err->apr_err();
4843         # Maybe the branch we're tracking didn't
4844         # exist when the repo started, so it's
4845         # not an error if it doesn't, just continue
4846         #
4847         # Wonderfully consistent library, eh?
4848         # 160013 - svn:// and file://
4849         # 175002 - http(s)://
4850         # 175007 - http(s):// (this repo required authorization, too...)
4851         #   More codes may be discovered later...
4852         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4853                 my $err_key = $err->expanded_message;
4854                 # revision numbers change every time, filter them out
4855                 $err_key =~ s/\d+/\0/g;
4856                 $err_key = "$errno\0$err_key";
4857                 unless ($ignored_err{$err_key}) {
4858                         warn "W: Ignoring error from SVN, path probably ",
4859                              "does not exist: ($errno): ",
4860                              $err->expanded_message,"\n";
4861                         warn "W: Do not be alarmed at the above message ",
4862                              "git-svn is just searching aggressively for ",
4863                              "old history.\n",
4864                              "This may take a while on large repositories\n";
4865                         $ignored_err{$err_key} = 1;
4866                 }
4867                 return;
4868         }
4869         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4872 package Git::SVN::Log;
4873 use strict;
4874 use warnings;
4875 use POSIX qw/strftime/;
4876 use Time::Local;
4877 use constant commit_log_separator => ('-' x 72) . "\n";
4878 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4879             %rusers $show_commit $incremental/;
4880 my $l_fmt;
4882 sub cmt_showable {
4883         my ($c) = @_;
4884         return 1 if defined $c->{r};
4886         # big commit message got truncated by the 16k pretty buffer in rev-list
4887         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4888                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4889                 @{$c->{l}} = ();
4890                 my @log = command(qw/cat-file commit/, $c->{c});
4892                 # shift off the headers
4893                 shift @log while ($log[0] ne '');
4894                 shift @log;
4896                 # TODO: make $c->{l} not have a trailing newline in the future
4897                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4899                 (undef, $c->{r}, undef) = ::extract_metadata(
4900                                 (grep(/^git-svn-id: /, @log))[-1]);
4901         }
4902         return defined $c->{r};
4905 sub log_use_color {
4906         return $color || Git->repository->get_colorbool('color.diff');
4909 sub git_svn_log_cmd {
4910         my ($r_min, $r_max, @args) = @_;
4911         my $head = 'HEAD';
4912         my (@files, @log_opts);
4913         foreach my $x (@args) {
4914                 if ($x eq '--' || @files) {
4915                         push @files, $x;
4916                 } else {
4917                         if (::verify_ref("$x^0")) {
4918                                 $head = $x;
4919                         } else {
4920                                 push @log_opts, $x;
4921                         }
4922                 }
4923         }
4925         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4926         $gs ||= Git::SVN->_new;
4927         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4928                    $gs->refname);
4929         push @cmd, '-r' unless $non_recursive;
4930         push @cmd, qw/--raw --name-status/ if $verbose;
4931         push @cmd, '--color' if log_use_color();
4932         push @cmd, @log_opts;
4933         if (defined $r_max && $r_max == $r_min) {
4934                 push @cmd, '--max-count=1';
4935                 if (my $c = $gs->rev_map_get($r_max)) {
4936                         push @cmd, $c;
4937                 }
4938         } elsif (defined $r_max) {
4939                 if ($r_max < $r_min) {
4940                         ($r_min, $r_max) = ($r_max, $r_min);
4941                 }
4942                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4943                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4944                 # If there are no commits in the range, both $c_max and $c_min
4945                 # will be undefined.  If there is at least 1 commit in the
4946                 # range, both will be defined.
4947                 return () if !defined $c_min || !defined $c_max;
4948                 if ($c_min eq $c_max) {
4949                         push @cmd, '--max-count=1', $c_min;
4950                 } else {
4951                         push @cmd, '--boundary', "$c_min..$c_max";
4952                 }
4953         }
4954         return (@cmd, @files);
4957 # adapted from pager.c
4958 sub config_pager {
4959         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4960         if (!defined $pager) {
4961                 $pager = 'less';
4962         } elsif (length $pager == 0 || $pager eq 'cat') {
4963                 $pager = undef;
4964         }
4965         $ENV{GIT_PAGER_IN_USE} = defined($pager);
4968 sub run_pager {
4969         return unless -t *STDOUT && defined $pager;
4970         pipe my ($rfd, $wfd) or return;
4971         defined(my $pid = fork) or ::fatal "Can't fork: $!";
4972         if (!$pid) {
4973                 open STDOUT, '>&', $wfd or
4974                                      ::fatal "Can't redirect to stdout: $!";
4975                 return;
4976         }
4977         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4978         $ENV{LESS} ||= 'FRSX';
4979         exec $pager or ::fatal "Can't run pager: $! ($pager)";
4982 sub format_svn_date {
4983         # some systmes don't handle or mishandle %z, so be creative.
4984         my $t = shift || time;
4985         my $gm = timelocal(gmtime($t));
4986         my $sign = qw( + + - )[ $t <=> $gm ];
4987         my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4988         return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4991 sub parse_git_date {
4992         my ($t, $tz) = @_;
4993         # Date::Parse isn't in the standard Perl distro :(
4994         if ($tz =~ s/^\+//) {
4995                 $t += tz_to_s_offset($tz);
4996         } elsif ($tz =~ s/^\-//) {
4997                 $t -= tz_to_s_offset($tz);
4998         }
4999         return $t;
5002 sub set_local_timezone {
5003         if (defined $TZ) {
5004                 $ENV{TZ} = $TZ;
5005         } else {
5006                 delete $ENV{TZ};
5007         }
5010 sub tz_to_s_offset {
5011         my ($tz) = @_;
5012         $tz =~ s/(\d\d)$//;
5013         return ($1 * 60) + ($tz * 3600);
5016 sub get_author_info {
5017         my ($dest, $author, $t, $tz) = @_;
5018         $author =~ s/(?:^\s*|\s*$)//g;
5019         $dest->{a_raw} = $author;
5020         my $au;
5021         if ($::_authors) {
5022                 $au = $rusers{$author} || undef;
5023         }
5024         if (!$au) {
5025                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5026         }
5027         $dest->{t} = $t;
5028         $dest->{tz} = $tz;
5029         $dest->{a} = $au;
5030         $dest->{t_utc} = parse_git_date($t, $tz);
5033 sub process_commit {
5034         my ($c, $r_min, $r_max, $defer) = @_;
5035         if (defined $r_min && defined $r_max) {
5036                 if ($r_min == $c->{r} && $r_min == $r_max) {
5037                         show_commit($c);
5038                         return 0;
5039                 }
5040                 return 1 if $r_min == $r_max;
5041                 if ($r_min < $r_max) {
5042                         # we need to reverse the print order
5043                         return 0 if (defined $limit && --$limit < 0);
5044                         push @$defer, $c;
5045                         return 1;
5046                 }
5047                 if ($r_min != $r_max) {
5048                         return 1 if ($r_min < $c->{r});
5049                         return 1 if ($r_max > $c->{r});
5050                 }
5051         }
5052         return 0 if (defined $limit && --$limit < 0);
5053         show_commit($c);
5054         return 1;
5057 sub show_commit {
5058         my $c = shift;
5059         if ($oneline) {
5060                 my $x = "\n";
5061                 if (my $l = $c->{l}) {
5062                         while ($l->[0] =~ /^\s*$/) { shift @$l }
5063                         $x = $l->[0];
5064                 }
5065                 $l_fmt ||= 'A' . length($c->{r});
5066                 print 'r',pack($l_fmt, $c->{r}),' | ';
5067                 print "$c->{c} | " if $show_commit;
5068                 print $x;
5069         } else {
5070                 show_commit_normal($c);
5071         }
5074 sub show_commit_changed_paths {
5075         my ($c) = @_;
5076         return unless $c->{changed};
5077         print "Changed paths:\n", @{$c->{changed}};
5080 sub show_commit_normal {
5081         my ($c) = @_;
5082         print commit_log_separator, "r$c->{r} | ";
5083         print "$c->{c} | " if $show_commit;
5084         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5085         my $nr_line = 0;
5087         if (my $l = $c->{l}) {
5088                 while ($l->[$#$l] eq "\n" && $#$l > 0
5089                                           && $l->[($#$l - 1)] eq "\n") {
5090                         pop @$l;
5091                 }
5092                 $nr_line = scalar @$l;
5093                 if (!$nr_line) {
5094                         print "1 line\n\n\n";
5095                 } else {
5096                         if ($nr_line == 1) {
5097                                 $nr_line = '1 line';
5098                         } else {
5099                                 $nr_line .= ' lines';
5100                         }
5101                         print $nr_line, "\n";
5102                         show_commit_changed_paths($c);
5103                         print "\n";
5104                         print $_ foreach @$l;
5105                 }
5106         } else {
5107                 print "1 line\n";
5108                 show_commit_changed_paths($c);
5109                 print "\n";
5111         }
5112         foreach my $x (qw/raw stat diff/) {
5113                 if ($c->{$x}) {
5114                         print "\n";
5115                         print $_ foreach @{$c->{$x}}
5116                 }
5117         }
5120 sub cmd_show_log {
5121         my (@args) = @_;
5122         my ($r_min, $r_max);
5123         my $r_last = -1; # prevent dupes
5124         set_local_timezone();
5125         if (defined $::_revision) {
5126                 if ($::_revision =~ /^(\d+):(\d+)$/) {
5127                         ($r_min, $r_max) = ($1, $2);
5128                 } elsif ($::_revision =~ /^\d+$/) {
5129                         $r_min = $r_max = $::_revision;
5130                 } else {
5131                         ::fatal "-r$::_revision is not supported, use ",
5132                                 "standard 'git log' arguments instead";
5133                 }
5134         }
5136         config_pager();
5137         @args = git_svn_log_cmd($r_min, $r_max, @args);
5138         if (!@args) {
5139                 print commit_log_separator unless $incremental || $oneline;
5140                 return;
5141         }
5142         my $log = command_output_pipe(@args);
5143         run_pager();
5144         my (@k, $c, $d, $stat);
5145         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5146         while (<$log>) {
5147                 if (/^${esc_color}commit -?($::sha1_short)/o) {
5148                         my $cmt = $1;
5149                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5150                                 $r_last = $c->{r};
5151                                 process_commit($c, $r_min, $r_max, \@k) or
5152                                                                 goto out;
5153                         }
5154                         $d = undef;
5155                         $c = { c => $cmt };
5156                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5157                         get_author_info($c, $1, $2, $3);
5158                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5159                         # ignore
5160                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5161                         push @{$c->{raw}}, $_;
5162                 } elsif (/^${esc_color}[ACRMDT]\t/) {
5163                         # we could add $SVN->{svn_path} here, but that requires
5164                         # remote access at the moment (repo_path_split)...
5165                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
5166                         push @{$c->{changed}}, $_;
5167                 } elsif (/^${esc_color}diff /o) {
5168                         $d = 1;
5169                         push @{$c->{diff}}, $_;
5170                 } elsif ($d) {
5171                         push @{$c->{diff}}, $_;
5172                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5173                           $esc_color*[\+\-]*$esc_color$/x) {
5174                         $stat = 1;
5175                         push @{$c->{stat}}, $_;
5176                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5177                         push @{$c->{stat}}, $_;
5178                         $stat = undef;
5179                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
5180                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5181                 } elsif (s/^${esc_color}    //o) {
5182                         push @{$c->{l}}, $_;
5183                 }
5184         }
5185         if ($c && defined $c->{r} && $c->{r} != $r_last) {
5186                 $r_last = $c->{r};
5187                 process_commit($c, $r_min, $r_max, \@k);
5188         }
5189         if (@k) {
5190                 ($r_min, $r_max) = ($r_max, $r_min);
5191                 process_commit($_, $r_min, $r_max) foreach reverse @k;
5192         }
5193 out:
5194         close $log;
5195         print commit_log_separator unless $incremental || $oneline;
5198 sub cmd_blame {
5199         my $path = pop;
5201         config_pager();
5202         run_pager();
5204         my ($fh, $ctx, $rev);
5206         if ($_git_format) {
5207                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5208                 while (my $line = <$fh>) {
5209                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5210                                 # Uncommitted edits show up as a rev ID of
5211                                 # all zeros, which we can't look up with
5212                                 # cmt_metadata
5213                                 if ($1 !~ /^0+$/) {
5214                                         (undef, $rev, undef) =
5215                                                 ::cmt_metadata($1);
5216                                         $rev = '0' if (!$rev);
5217                                 } else {
5218                                         $rev = '0';
5219                                 }
5220                                 $rev = sprintf('%-10s', $rev);
5221                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5222                         }
5223                         print $line;
5224                 }
5225         } else {
5226                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5227                                                   '--', $path);
5228                 my ($sha1);
5229                 my %authors;
5230                 my @buffer;
5231                 my %dsha; #distinct sha keys
5233                 while (my $line = <$fh>) {
5234                         push @buffer, $line;
5235                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5236                                 $dsha{$1} = 1;
5237                         }
5238                 }
5240                 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5242                 foreach my $line (@buffer) {
5243                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5244                                 $rev = $s2r->{$1};
5245                                 $rev = '0' if (!$rev)
5246                         }
5247                         elsif ($line =~ /^author (.*)/) {
5248                                 $authors{$rev} = $1;
5249                                 $authors{$rev} =~ s/\s/_/g;
5250                         }
5251                         elsif ($line =~ /^\t(.*)$/) {
5252                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5253                         }
5254                 }
5255         }
5256         command_close_pipe($fh, $ctx);
5259 package Git::SVN::Migration;
5260 # these version numbers do NOT correspond to actual version numbers
5261 # of git nor git-svn.  They are just relative.
5263 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5265 # v1 layout: .git/$id/info/url, refs/remotes/$id
5267 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5269 # v3 layout: .git/svn/$id, refs/remotes/$id
5270 #            - info/url may remain for backwards compatibility
5271 #            - this is what we migrate up to this layout automatically,
5272 #            - this will be used by git svn init on single branches
5273 # v3.1 layout (auto migrated):
5274 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5275 #              for backwards compatibility
5277 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5278 #            - this is only created for newly multi-init-ed
5279 #              repositories.  Similar in spirit to the
5280 #              --use-separate-remotes option in git-clone (now default)
5281 #            - we do not automatically migrate to this (following
5282 #              the example set by core git)
5284 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5285 #            - newer, more-efficient format that uses 24-bytes per record
5286 #              with no filler space.
5287 #            - use xxd -c24 < .rev_map.$UUID to view and debug
5288 #            - This is a one-way migration, repositories updated to the
5289 #              new format will not be able to use old git-svn without
5290 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
5291 #              possible if noMetadata or useSvmProps are set; but should
5292 #              be no problem for users that use the (sensible) defaults.
5293 use strict;
5294 use warnings;
5295 use Carp qw/croak/;
5296 use File::Path qw/mkpath/;
5297 use File::Basename qw/dirname basename/;
5298 use vars qw/$_minimize/;
5300 sub migrate_from_v0 {
5301         my $git_dir = $ENV{GIT_DIR};
5302         return undef unless -d $git_dir;
5303         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5304         my $migrated = 0;
5305         while (<$fh>) {
5306                 chomp;
5307                 my ($id, $orig_ref) = ($_, $_);
5308                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5309                 next unless -f "$git_dir/$id/info/url";
5310                 my $new_ref = "refs/remotes/$id";
5311                 if (::verify_ref("$new_ref^0")) {
5312                         print STDERR "W: $orig_ref is probably an old ",
5313                                      "branch used by an ancient version of ",
5314                                      "git-svn.\n",
5315                                      "However, $new_ref also exists.\n",
5316                                      "We will not be able ",
5317                                      "to use this branch until this ",
5318                                      "ambiguity is resolved.\n";
5319                         next;
5320                 }
5321                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5322                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5323                 command_noisy('update-ref', $new_ref, $orig_ref);
5324                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5325                 $migrated++;
5326         }
5327         command_close_pipe($fh, $ctx);
5328         print STDERR "Done migrating from v0 layout...\n" if $migrated;
5329         $migrated;
5332 sub migrate_from_v1 {
5333         my $git_dir = $ENV{GIT_DIR};
5334         my $migrated = 0;
5335         return $migrated unless -d $git_dir;
5336         my $svn_dir = "$git_dir/svn";
5338         # just in case somebody used 'svn' as their $id at some point...
5339         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5341         print STDERR "Migrating from a git-svn v1 layout...\n";
5342         mkpath([$svn_dir]);
5343         print STDERR "Data from a previous version of git-svn exists, but\n\t",
5344                      "$svn_dir\n\t(required for this version ",
5345                      "($::VERSION) of git-svn) does not exist.\n";
5346         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5347         while (<$fh>) {
5348                 my $x = $_;
5349                 next unless $x =~ s#^refs/remotes/##;
5350                 chomp $x;
5351                 next unless -f "$git_dir/$x/info/url";
5352                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5353                 next unless $u;
5354                 my $dn = dirname("$git_dir/svn/$x");
5355                 mkpath([$dn]) unless -d $dn;
5356                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5357                         mkpath(["$git_dir/svn/svn"]);
5358                         print STDERR " - $git_dir/$x/info => ",
5359                                         "$git_dir/svn/$x/info\n";
5360                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5361                                croak "$!: $x";
5362                         # don't worry too much about these, they probably
5363                         # don't exist with repos this old (save for index,
5364                         # and we can easily regenerate that)
5365                         foreach my $f (qw/unhandled.log index .rev_db/) {
5366                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5367                         }
5368                 } else {
5369                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5370                         rename "$git_dir/$x", "$git_dir/svn/$x" or
5371                                croak "$!: $x";
5372                 }
5373                 $migrated++;
5374         }
5375         command_close_pipe($fh, $ctx);
5376         print STDERR "Done migrating from a git-svn v1 layout\n";
5377         $migrated;
5380 sub read_old_urls {
5381         my ($l_map, $pfx, $path) = @_;
5382         my @dir;
5383         foreach (<$path/*>) {
5384                 if (-r "$_/info/url") {
5385                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5386                         my $ref_id = $pfx . basename $_;
5387                         my $url = ::file_to_s("$_/info/url");
5388                         $l_map->{$ref_id} = $url;
5389                 } elsif (-d $_) {
5390                         push @dir, $_;
5391                 }
5392         }
5393         foreach (@dir) {
5394                 my $x = $_;
5395                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5396                 read_old_urls($l_map, $x, $_);
5397         }
5400 sub migrate_from_v2 {
5401         my @cfg = command(qw/config -l/);
5402         return if grep /^svn-remote\..+\.url=/, @cfg;
5403         my %l_map;
5404         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5405         my $migrated = 0;
5407         foreach my $ref_id (sort keys %l_map) {
5408                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5409                 if ($@) {
5410                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5411                 }
5412                 $migrated++;
5413         }
5414         $migrated;
5417 sub minimize_connections {
5418         my $r = Git::SVN::read_all_remotes();
5419         my $new_urls = {};
5420         my $root_repos = {};
5421         foreach my $repo_id (keys %$r) {
5422                 my $url = $r->{$repo_id}->{url} or next;
5423                 my $fetch = $r->{$repo_id}->{fetch} or next;
5424                 my $ra = Git::SVN::Ra->new($url);
5426                 # skip existing cases where we already connect to the root
5427                 if (($ra->{url} eq $ra->{repos_root}) ||
5428                     ($ra->{repos_root} eq $repo_id)) {
5429                         $root_repos->{$ra->{url}} = $repo_id;
5430                         next;
5431                 }
5433                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5434                 my $root_path = $ra->{url};
5435                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5436                 foreach my $path (keys %$fetch) {
5437                         my $ref_id = $fetch->{$path};
5438                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5440                         # make sure we can read when connecting to
5441                         # a higher level of a repository
5442                         my ($last_rev, undef) = $gs->last_rev_commit;
5443                         if (!defined $last_rev) {
5444                                 $last_rev = eval {
5445                                         $root_ra->get_latest_revnum;
5446                                 };
5447                                 next if $@;
5448                         }
5449                         my $new = $root_path;
5450                         $new .= length $path ? "/$path" : '';
5451                         eval {
5452                                 $root_ra->get_log([$new], $last_rev, $last_rev,
5453                                                   0, 0, 1, sub { });
5454                         };
5455                         next if $@;
5456                         $new_urls->{$ra->{repos_root}}->{$new} =
5457                                 { ref_id => $ref_id,
5458                                   old_repo_id => $repo_id,
5459                                   old_path => $path };
5460                 }
5461         }
5463         my @emptied;
5464         foreach my $url (keys %$new_urls) {
5465                 # see if we can re-use an existing [svn-remote "repo_id"]
5466                 # instead of creating a(n ugly) new section:
5467                 my $repo_id = $root_repos->{$url} || $url;
5469                 my $fetch = $new_urls->{$url};
5470                 foreach my $path (keys %$fetch) {
5471                         my $x = $fetch->{$path};
5472                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5473                         my $pfx = "svn-remote.$x->{old_repo_id}";
5475                         my $old_fetch = quotemeta("$x->{old_path}:".
5476                                                   "refs/remotes/$x->{ref_id}");
5477                         command_noisy(qw/config --unset/,
5478                                       "$pfx.fetch", '^'. $old_fetch . '$');
5479                         delete $r->{$x->{old_repo_id}}->
5480                                {fetch}->{$x->{old_path}};
5481                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5482                                 command_noisy(qw/config --unset/,
5483                                               "$pfx.url");
5484                                 push @emptied, $x->{old_repo_id}
5485                         }
5486                 }
5487         }
5488         if (@emptied) {
5489                 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5490                 print STDERR <<EOF;
5491 The following [svn-remote] sections in your config file ($file) are empty
5492 and can be safely removed:
5493 EOF
5494                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5495         }
5498 sub migration_check {
5499         migrate_from_v0();
5500         migrate_from_v1();
5501         migrate_from_v2();
5502         minimize_connections() if $_minimize;
5505 package Git::IndexInfo;
5506 use strict;
5507 use warnings;
5508 use Git qw/command_input_pipe command_close_pipe/;
5510 sub new {
5511         my ($class) = @_;
5512         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5513         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5516 sub remove {
5517         my ($self, $path) = @_;
5518         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5519                 return ++$self->{nr};
5520         }
5521         undef;
5524 sub update {
5525         my ($self, $mode, $hash, $path) = @_;
5526         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5527                 return ++$self->{nr};
5528         }
5529         undef;
5532 sub DESTROY {
5533         my ($self) = @_;
5534         command_close_pipe($self->{gui}, $self->{ctx});
5537 package Git::SVN::GlobSpec;
5538 use strict;
5539 use warnings;
5541 sub new {
5542         my ($class, $glob) = @_;
5543         my $re = $glob;
5544         $re =~ s!/+$!!g; # no need for trailing slashes
5545         $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5546         my $temp = $re;
5547         my ($left, $right) = ($1, $3);
5548         $re = $2;
5549         my $depth = $re =~ tr/*/*/;
5550         if ($depth != $temp =~ tr/*/*/) {
5551                 die "Only one set of wildcard directories " .
5552                         "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5553         }
5554         if ($depth == 0) {
5555                 die "One '*' is needed for glob: '$glob'\n";
5556         }
5557         $re =~ s!\*!\[^/\]*!g;
5558         $re = quotemeta($left) . "($re)" . quotemeta($right);
5559         if (length $left && !($left =~ s!/+$!!g)) {
5560                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5561         }
5562         if (length $right && !($right =~ s!^/+!!g)) {
5563                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5564         }
5565         my $left_re = qr/^\/\Q$left\E(\/|$)/;
5566         bless { left => $left, right => $right, left_regex => $left_re,
5567                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5570 sub full_path {
5571         my ($self, $path) = @_;
5572         return (length $self->{left} ? "$self->{left}/" : '') .
5573                $path . (length $self->{right} ? "/$self->{right}" : '');
5576 __END__
5578 Data structures:
5581 $remotes = { # returned by read_all_remotes()
5582         'svn' => {
5583                 # svn-remote.svn.url=https://svn.musicpd.org
5584                 url => 'https://svn.musicpd.org',
5585                 # svn-remote.svn.fetch=mpd/trunk:trunk
5586                 fetch => {
5587                         'mpd/trunk' => 'trunk',
5588                 },
5589                 # svn-remote.svn.tags=mpd/tags/*:tags/*
5590                 tags => {
5591                         path => {
5592                                 left => 'mpd/tags',
5593                                 right => '',
5594                                 regex => qr!mpd/tags/([^/]+)$!,
5595                                 glob => 'tags/*',
5596                         },
5597                         ref => {
5598                                 left => 'tags',
5599                                 right => '',
5600                                 regex => qr!tags/([^/]+)$!,
5601                                 glob => 'tags/*',
5602                         },
5603                 }
5604         }
5605 };
5607 $log_entry hashref as returned by libsvn_log_entry()
5609         log => 'whitespace-formatted log entry
5610 ',                                              # trailing newline is preserved
5611         revision => '8',                        # integer
5612         date => '2004-02-24T17:01:44.108345Z',  # commit date
5613         author => 'committer name'
5614 };
5617 # this is generated by generate_diff();
5618 @mods = array of diff-index line hashes, each element represents one line
5619         of diff-index output
5621 diff-index line ($m hash)
5623         mode_a => first column of diff-index output, no leading ':',
5624         mode_b => second column of diff-index output,
5625         sha1_b => sha1sum of the final blob,
5626         chg => change type [MCRADT],
5627         file_a => original file name of a file (iff chg is 'C' or 'R')
5628         file_b => new/current file name of a file (any chg)
5632 # retval of read_url_paths{,_all}();
5633 $l_map = {
5634         # repository root url
5635         'https://svn.musicpd.org' => {
5636                 # repository path               # GIT_SVN_ID
5637                 'mpd/trunk'             =>      'trunk',
5638                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5639         },
5642 Notes:
5643         I don't trust the each() function on unless I created %hash myself
5644         because the internal iterator may not have started at base.