Code

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